blob: c78c01a950491609869abd8944c4c5dea1ba1fe1 [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()) {
Reid Spencerc635f472006-12-31 05:48:39 +0000343 case Type::Int8TyID:
344 case Type::Int16TyID: return Type::Int32Ty;
Chris Lattnere79e8542004-02-23 06:38:22 +0000345 case Type::FloatTyID: return Type::DoubleTy;
346 default: return Ty;
347 }
348}
349
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000350/// getBitCastOperand - If the specified operand is a CastInst or a constant
351/// expression bitcast, return the operand value, otherwise return null.
352static Value *getBitCastOperand(Value *V) {
353 if (BitCastInst *I = dyn_cast<BitCastInst>(V))
Chris Lattner567b81f2005-09-13 00:40:14 +0000354 return I->getOperand(0);
355 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000356 if (CE->getOpcode() == Instruction::BitCast)
Chris Lattner567b81f2005-09-13 00:40:14 +0000357 return CE->getOperand(0);
358 return 0;
359}
360
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000361/// This function is a wrapper around CastInst::isEliminableCastPair. It
362/// simply extracts arguments and returns what that function returns.
363/// @Determine if it is valid to eliminate a Convert pair
364static Instruction::CastOps
365isEliminableCastPair(
366 const CastInst *CI, ///< The first cast instruction
367 unsigned opcode, ///< The opcode of the second cast instruction
368 const Type *DstTy, ///< The target type for the second cast instruction
369 TargetData *TD ///< The target data for pointer size
370) {
371
372 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
373 const Type *MidTy = CI->getType(); // B from above
Chris Lattner1d441ad2006-05-06 09:00:16 +0000374
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000375 // Get the opcodes of the two Cast instructions
376 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
377 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
Chris Lattner1d441ad2006-05-06 09:00:16 +0000378
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000379 return Instruction::CastOps(
380 CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
381 DstTy, TD->getIntPtrType()));
Chris Lattner1d441ad2006-05-06 09:00:16 +0000382}
383
384/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
385/// in any code being generated. It does not require codegen if V is simple
386/// enough or if the cast can be folded into other casts.
Reid Spencer266e42b2006-12-23 06:05:41 +0000387static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
388 const Type *Ty, TargetData *TD) {
Chris Lattner1d441ad2006-05-06 09:00:16 +0000389 if (V->getType() == Ty || isa<Constant>(V)) return false;
390
391 // If this is a noop cast, it isn't real codegen.
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000392 if (V->getType()->canLosslesslyBitCastTo(Ty))
Chris Lattner1d441ad2006-05-06 09:00:16 +0000393 return false;
394
Chris Lattner99155be2006-05-25 23:24:33 +0000395 // If this is another cast that can be eliminated, it isn't codegen either.
Chris Lattner1d441ad2006-05-06 09:00:16 +0000396 if (const CastInst *CI = dyn_cast<CastInst>(V))
Reid Spencer266e42b2006-12-23 06:05:41 +0000397 if (isEliminableCastPair(CI, opcode, Ty, TD))
Chris Lattner1d441ad2006-05-06 09:00:16 +0000398 return false;
399 return true;
400}
401
402/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
403/// InsertBefore instruction. This is specialized a bit to avoid inserting
404/// casts that are known to not do anything...
405///
Reid Spencer13bc5d72006-12-12 09:18:51 +0000406Value *InstCombiner::InsertOperandCastBefore(Instruction::CastOps opcode,
407 Value *V, const Type *DestTy,
Chris Lattner1d441ad2006-05-06 09:00:16 +0000408 Instruction *InsertBefore) {
409 if (V->getType() == DestTy) return V;
410 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencer13bc5d72006-12-12 09:18:51 +0000411 return ConstantExpr::getCast(opcode, C, DestTy);
Chris Lattner1d441ad2006-05-06 09:00:16 +0000412
Reid Spencer13bc5d72006-12-12 09:18:51 +0000413 return InsertCastBefore(opcode, V, DestTy, *InsertBefore);
Chris Lattner1d441ad2006-05-06 09:00:16 +0000414}
415
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000416// SimplifyCommutative - This performs a few simplifications for commutative
417// operators:
Chris Lattner260ab202002-04-18 17:39:14 +0000418//
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000419// 1. Order operands such that they are listed from right (least complex) to
420// left (most complex). This puts constants before unary operators before
421// binary operators.
422//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000423// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
424// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000425//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000426bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000427 bool Changed = false;
428 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
429 Changed = !I.swapOperands();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000430
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000431 if (!I.isAssociative()) return Changed;
432 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattner7fb29e12003-03-11 00:12:48 +0000433 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
434 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
435 if (isa<Constant>(I.getOperand(1))) {
Chris Lattner34428442003-05-27 16:40:51 +0000436 Constant *Folded = ConstantExpr::get(I.getOpcode(),
437 cast<Constant>(I.getOperand(1)),
438 cast<Constant>(Op->getOperand(1)));
Chris Lattner7fb29e12003-03-11 00:12:48 +0000439 I.setOperand(0, Op->getOperand(0));
440 I.setOperand(1, Folded);
441 return true;
442 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
443 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
444 isOnlyUse(Op) && isOnlyUse(Op1)) {
445 Constant *C1 = cast<Constant>(Op->getOperand(1));
446 Constant *C2 = cast<Constant>(Op1->getOperand(1));
447
448 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner34428442003-05-27 16:40:51 +0000449 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000450 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
451 Op1->getOperand(0),
452 Op1->getName(), &I);
453 WorkList.push_back(New);
454 I.setOperand(0, New);
455 I.setOperand(1, Folded);
456 return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000457 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000458 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000459 return Changed;
Chris Lattner260ab202002-04-18 17:39:14 +0000460}
Chris Lattnerca081252001-12-14 16:52:21 +0000461
Reid Spencer266e42b2006-12-23 06:05:41 +0000462/// SimplifyCompare - For a CmpInst this function just orders the operands
463/// so that theyare listed from right (least complex) to left (most complex).
464/// This puts constants before unary operators before binary operators.
465bool InstCombiner::SimplifyCompare(CmpInst &I) {
466 if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
467 return false;
468 I.swapOperands();
469 // Compare instructions are not associative so there's nothing else we can do.
470 return true;
471}
472
Chris Lattnerbb74e222003-03-10 23:06:50 +0000473// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
474// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattner9fa53de2002-05-06 16:49:18 +0000475//
Chris Lattnerbb74e222003-03-10 23:06:50 +0000476static inline Value *dyn_castNegVal(Value *V) {
477 if (BinaryOperator::isNeg(V))
Chris Lattnerd6f636a2005-04-24 07:30:14 +0000478 return BinaryOperator::getNegArgument(V);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000479
Chris Lattner9ad0d552004-12-14 20:08:06 +0000480 // Constants can be considered to be negated values if they can be folded.
481 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
482 return ConstantExpr::getNeg(C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000483 return 0;
Chris Lattner9fa53de2002-05-06 16:49:18 +0000484}
485
Chris Lattnerbb74e222003-03-10 23:06:50 +0000486static inline Value *dyn_castNotVal(Value *V) {
487 if (BinaryOperator::isNot(V))
Chris Lattnerd6f636a2005-04-24 07:30:14 +0000488 return BinaryOperator::getNotArgument(V);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000489
490 // Constants can be considered to be not'ed values...
Chris Lattnerdd65d862003-04-30 22:34:06 +0000491 if (ConstantIntegral *C = dyn_cast<ConstantIntegral>(V))
Chris Lattnerc8e7e292004-06-10 02:12:35 +0000492 return ConstantExpr::getNot(C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000493 return 0;
494}
495
Chris Lattner7fb29e12003-03-11 00:12:48 +0000496// dyn_castFoldableMul - If this value is a multiply that can be folded into
497// other computations (because it has a constant operand), return the
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000498// non-constant operand of the multiply, and set CST to point to the multiplier.
499// Otherwise, return null.
Chris Lattner7fb29e12003-03-11 00:12:48 +0000500//
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000501static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000502 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000503 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattner7fb29e12003-03-11 00:12:48 +0000504 if (I->getOpcode() == Instruction::Mul)
Chris Lattner970136362004-11-15 05:54:07 +0000505 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattner7fb29e12003-03-11 00:12:48 +0000506 return I->getOperand(0);
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000507 if (I->getOpcode() == Instruction::Shl)
Chris Lattner970136362004-11-15 05:54:07 +0000508 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000509 // The multiplier is really 1 << CST.
510 Constant *One = ConstantInt::get(V->getType(), 1);
511 CST = cast<ConstantInt>(ConstantExpr::getShl(One, CST));
512 return I->getOperand(0);
513 }
514 }
Chris Lattner7fb29e12003-03-11 00:12:48 +0000515 return 0;
Chris Lattner3082c5a2003-02-18 19:28:33 +0000516}
Chris Lattner31ae8632002-08-14 17:51:49 +0000517
Chris Lattner0798af32005-01-13 20:14:25 +0000518/// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
519/// expression, return it.
520static User *dyn_castGetElementPtr(Value *V) {
521 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
522 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
523 if (CE->getOpcode() == Instruction::GetElementPtr)
524 return cast<User>(V);
525 return false;
526}
527
Chris Lattner623826c2004-09-28 21:48:02 +0000528// AddOne, SubOne - Add or subtract a constant one from an integer constant...
Chris Lattner6862fbd2004-09-29 17:40:11 +0000529static ConstantInt *AddOne(ConstantInt *C) {
530 return cast<ConstantInt>(ConstantExpr::getAdd(C,
531 ConstantInt::get(C->getType(), 1)));
Chris Lattner623826c2004-09-28 21:48:02 +0000532}
Chris Lattner6862fbd2004-09-29 17:40:11 +0000533static ConstantInt *SubOne(ConstantInt *C) {
534 return cast<ConstantInt>(ConstantExpr::getSub(C,
535 ConstantInt::get(C->getType(), 1)));
Chris Lattner623826c2004-09-28 21:48:02 +0000536}
537
Chris Lattner0157e7f2006-02-11 09:31:47 +0000538/// GetConstantInType - Return a ConstantInt with the specified type and value.
539///
Chris Lattneree0f2802006-02-12 02:07:56 +0000540static ConstantIntegral *GetConstantInType(const Type *Ty, uint64_t Val) {
Reid Spencerc635f472006-12-31 05:48:39 +0000541 if (Ty->getTypeID() == Type::BoolTyID)
Chris Lattneree0f2802006-02-12 02:07:56 +0000542 return ConstantBool::get(Val);
Reid Spencerc635f472006-12-31 05:48:39 +0000543 return ConstantInt::get(Ty, Val);
Chris Lattner0157e7f2006-02-11 09:31:47 +0000544}
545
546
Chris Lattner4534dd592006-02-09 07:38:58 +0000547/// ComputeMaskedBits - Determine which of the bits specified in Mask are
548/// known to be either zero or one and return them in the KnownZero/KnownOne
549/// bitsets. This code only analyzes bits in Mask, in order to short-circuit
550/// processing.
551static void ComputeMaskedBits(Value *V, uint64_t Mask, uint64_t &KnownZero,
552 uint64_t &KnownOne, unsigned Depth = 0) {
Chris Lattner0b3557f2005-09-24 23:43:33 +0000553 // Note, we cannot consider 'undef' to be "IsZero" here. The problem is that
554 // we cannot optimize based on the assumption that it is zero without changing
Chris Lattnerc3ebf402006-02-07 07:27:52 +0000555 // it to be an explicit zero. If we don't change it to zero, other code could
Chris Lattner0b3557f2005-09-24 23:43:33 +0000556 // optimized based on the contradictory assumption that it is non-zero.
557 // Because instcombine aggressively folds operations with undef args anyway,
558 // this won't lose us code quality.
Chris Lattner4534dd592006-02-09 07:38:58 +0000559 if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(V)) {
560 // We know all of the bits for a constant!
Chris Lattner0157e7f2006-02-11 09:31:47 +0000561 KnownOne = CI->getZExtValue() & Mask;
Chris Lattner4534dd592006-02-09 07:38:58 +0000562 KnownZero = ~KnownOne & Mask;
563 return;
564 }
565
566 KnownZero = KnownOne = 0; // Don't know anything.
Chris Lattner92a68652006-02-07 08:05:22 +0000567 if (Depth == 6 || Mask == 0)
Chris Lattner4534dd592006-02-09 07:38:58 +0000568 return; // Limit search depth.
569
570 uint64_t KnownZero2, KnownOne2;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000571 Instruction *I = dyn_cast<Instruction>(V);
572 if (!I) return;
573
Chris Lattnerfb296922006-05-04 17:33:35 +0000574 Mask &= V->getType()->getIntegralTypeMask();
575
Chris Lattner0157e7f2006-02-11 09:31:47 +0000576 switch (I->getOpcode()) {
577 case Instruction::And:
578 // If either the LHS or the RHS are Zero, the result is zero.
579 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
580 Mask &= ~KnownZero;
581 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
582 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
583 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
584
585 // Output known-1 bits are only known if set in both the LHS & RHS.
586 KnownOne &= KnownOne2;
587 // Output known-0 are known to be clear if zero in either the LHS | RHS.
588 KnownZero |= KnownZero2;
589 return;
590 case Instruction::Or:
591 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
592 Mask &= ~KnownOne;
593 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
594 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
595 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
596
597 // Output known-0 bits are only known if clear in both the LHS & RHS.
598 KnownZero &= KnownZero2;
599 // Output known-1 are known to be set if set in either the LHS | RHS.
600 KnownOne |= KnownOne2;
601 return;
602 case Instruction::Xor: {
603 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
604 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
605 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
606 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
607
608 // Output known-0 bits are known if clear or set in both the LHS & RHS.
609 uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
610 // Output known-1 are known to be set if set in only one of the LHS, RHS.
611 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
612 KnownZero = KnownZeroOut;
613 return;
614 }
615 case Instruction::Select:
616 ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
617 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
618 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
619 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
620
621 // Only known if known in both the LHS and RHS.
622 KnownOne &= KnownOne2;
623 KnownZero &= KnownZero2;
624 return;
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000625 case Instruction::FPTrunc:
626 case Instruction::FPExt:
627 case Instruction::FPToUI:
628 case Instruction::FPToSI:
629 case Instruction::SIToFP:
630 case Instruction::PtrToInt:
631 case Instruction::UIToFP:
632 case Instruction::IntToPtr:
633 return; // Can't work with floating point or pointers
634 case Instruction::Trunc:
635 // All these have integer operands
636 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
637 return;
638 case Instruction::BitCast: {
Chris Lattner0157e7f2006-02-11 09:31:47 +0000639 const Type *SrcTy = I->getOperand(0)->getType();
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000640 if (SrcTy->isIntegral()) {
Chris Lattner0157e7f2006-02-11 09:31:47 +0000641 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
Chris Lattner4534dd592006-02-09 07:38:58 +0000642 return;
643 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000644 break;
645 }
646 case Instruction::ZExt: {
647 // Compute the bits in the result that are not present in the input.
648 const Type *SrcTy = I->getOperand(0)->getType();
Chris Lattner0157e7f2006-02-11 09:31:47 +0000649 uint64_t NotIn = ~SrcTy->getIntegralTypeMask();
650 uint64_t NewBits = I->getType()->getIntegralTypeMask() & NotIn;
Chris Lattner62010c42005-10-09 06:36:35 +0000651
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000652 Mask &= SrcTy->getIntegralTypeMask();
653 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
654 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
655 // The top bits are known to be zero.
656 KnownZero |= NewBits;
657 return;
658 }
659 case Instruction::SExt: {
660 // Compute the bits in the result that are not present in the input.
661 const Type *SrcTy = I->getOperand(0)->getType();
662 uint64_t NotIn = ~SrcTy->getIntegralTypeMask();
663 uint64_t NewBits = I->getType()->getIntegralTypeMask() & NotIn;
664
665 Mask &= SrcTy->getIntegralTypeMask();
666 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
667 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattner92a68652006-02-07 08:05:22 +0000668
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000669 // If the sign bit of the input is known set or clear, then we know the
670 // top bits of the result.
671 uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
672 if (KnownZero & InSignBit) { // Input sign bit known zero
673 KnownZero |= NewBits;
674 KnownOne &= ~NewBits;
675 } else if (KnownOne & InSignBit) { // Input sign bit known set
676 KnownOne |= NewBits;
677 KnownZero &= ~NewBits;
678 } else { // Input sign bit unknown
679 KnownZero &= ~NewBits;
680 KnownOne &= ~NewBits;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000681 }
682 return;
683 }
684 case Instruction::Shl:
685 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
Reid Spencere0fc4df2006-10-20 07:07:24 +0000686 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
687 uint64_t ShiftAmt = SA->getZExtValue();
688 Mask >>= ShiftAmt;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000689 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
690 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Reid Spencere0fc4df2006-10-20 07:07:24 +0000691 KnownZero <<= ShiftAmt;
692 KnownOne <<= ShiftAmt;
693 KnownZero |= (1ULL << ShiftAmt)-1; // low bits known zero.
Chris Lattner0157e7f2006-02-11 09:31:47 +0000694 return;
695 }
696 break;
Reid Spencerfdff9382006-11-08 06:47:33 +0000697 case Instruction::LShr:
Chris Lattner0157e7f2006-02-11 09:31:47 +0000698 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
Reid Spencere0fc4df2006-10-20 07:07:24 +0000699 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Chris Lattner0157e7f2006-02-11 09:31:47 +0000700 // Compute the new bits that are at the top now.
Reid Spencere0fc4df2006-10-20 07:07:24 +0000701 uint64_t ShiftAmt = SA->getZExtValue();
702 uint64_t HighBits = (1ULL << ShiftAmt)-1;
703 HighBits <<= I->getType()->getPrimitiveSizeInBits()-ShiftAmt;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000704
Reid Spencerfdff9382006-11-08 06:47:33 +0000705 // Unsigned shift right.
706 Mask <<= ShiftAmt;
707 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
708 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
709 KnownZero >>= ShiftAmt;
710 KnownOne >>= ShiftAmt;
711 KnownZero |= HighBits; // high bits known zero.
712 return;
713 }
714 break;
715 case Instruction::AShr:
716 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
717 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
718 // Compute the new bits that are at the top now.
719 uint64_t ShiftAmt = SA->getZExtValue();
720 uint64_t HighBits = (1ULL << ShiftAmt)-1;
721 HighBits <<= I->getType()->getPrimitiveSizeInBits()-ShiftAmt;
722
723 // Signed shift right.
724 Mask <<= ShiftAmt;
725 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
726 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
727 KnownZero >>= ShiftAmt;
728 KnownOne >>= ShiftAmt;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000729
Reid Spencerfdff9382006-11-08 06:47:33 +0000730 // Handle the sign bits.
731 uint64_t SignBit = 1ULL << (I->getType()->getPrimitiveSizeInBits()-1);
732 SignBit >>= ShiftAmt; // Adjust to where it is now in the mask.
Chris Lattner0157e7f2006-02-11 09:31:47 +0000733
Reid Spencerfdff9382006-11-08 06:47:33 +0000734 if (KnownZero & SignBit) { // New bits are known zero.
735 KnownZero |= HighBits;
736 } else if (KnownOne & SignBit) { // New bits are known one.
737 KnownOne |= HighBits;
Chris Lattner4534dd592006-02-09 07:38:58 +0000738 }
739 return;
Chris Lattner62010c42005-10-09 06:36:35 +0000740 }
Chris Lattner0157e7f2006-02-11 09:31:47 +0000741 break;
Chris Lattner0b3557f2005-09-24 23:43:33 +0000742 }
Chris Lattner92a68652006-02-07 08:05:22 +0000743}
744
745/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
746/// this predicate to simplify operations downstream. Mask is known to be zero
747/// for bits that V cannot have.
748static bool MaskedValueIsZero(Value *V, uint64_t Mask, unsigned Depth = 0) {
Chris Lattner4534dd592006-02-09 07:38:58 +0000749 uint64_t KnownZero, KnownOne;
750 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
751 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
752 return (KnownZero & Mask) == Mask;
Chris Lattner0b3557f2005-09-24 23:43:33 +0000753}
754
Chris Lattner0157e7f2006-02-11 09:31:47 +0000755/// ShrinkDemandedConstant - Check to see if the specified operand of the
756/// specified instruction is a constant integer. If so, check to see if there
757/// are any bits set in the constant that are not demanded. If so, shrink the
758/// constant and return true.
759static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
760 uint64_t Demanded) {
761 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
762 if (!OpC) return false;
763
764 // If there are no bits set that aren't demanded, nothing to do.
765 if ((~Demanded & OpC->getZExtValue()) == 0)
766 return false;
767
768 // This is producing any bits that are not needed, shrink the RHS.
769 uint64_t Val = Demanded & OpC->getZExtValue();
770 I->setOperand(OpNo, GetConstantInType(OpC->getType(), Val));
771 return true;
772}
773
Chris Lattneree0f2802006-02-12 02:07:56 +0000774// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
775// set of known zero and one bits, compute the maximum and minimum values that
776// could have the specified known zero and known one bits, returning them in
777// min/max.
778static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
779 uint64_t KnownZero,
780 uint64_t KnownOne,
781 int64_t &Min, int64_t &Max) {
782 uint64_t TypeBits = Ty->getIntegralTypeMask();
783 uint64_t UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
784
785 uint64_t SignBit = 1ULL << (Ty->getPrimitiveSizeInBits()-1);
786
787 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
788 // bit if it is unknown.
789 Min = KnownOne;
790 Max = KnownOne|UnknownBits;
791
792 if (SignBit & UnknownBits) { // Sign bit is unknown
793 Min |= SignBit;
794 Max &= ~SignBit;
795 }
796
797 // Sign extend the min/max values.
798 int ShAmt = 64-Ty->getPrimitiveSizeInBits();
799 Min = (Min << ShAmt) >> ShAmt;
800 Max = (Max << ShAmt) >> ShAmt;
801}
802
803// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
804// a set of known zero and one bits, compute the maximum and minimum values that
805// could have the specified known zero and known one bits, returning them in
806// min/max.
807static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
808 uint64_t KnownZero,
809 uint64_t KnownOne,
810 uint64_t &Min,
811 uint64_t &Max) {
812 uint64_t TypeBits = Ty->getIntegralTypeMask();
813 uint64_t UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
814
815 // The minimum value is when the unknown bits are all zeros.
816 Min = KnownOne;
817 // The maximum value is when the unknown bits are all ones.
818 Max = KnownOne|UnknownBits;
819}
Chris Lattner0157e7f2006-02-11 09:31:47 +0000820
821
822/// SimplifyDemandedBits - Look at V. At this point, we know that only the
823/// DemandedMask bits of the result of V are ever used downstream. If we can
824/// use this information to simplify V, do so and return true. Otherwise,
825/// analyze the expression and return a mask of KnownOne and KnownZero bits for
826/// the expression (used to simplify the caller). The KnownZero/One bits may
827/// only be accurate for those bits in the DemandedMask.
828bool InstCombiner::SimplifyDemandedBits(Value *V, uint64_t DemandedMask,
829 uint64_t &KnownZero, uint64_t &KnownOne,
Chris Lattner2590e512006-02-07 06:56:34 +0000830 unsigned Depth) {
Chris Lattner0157e7f2006-02-11 09:31:47 +0000831 if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(V)) {
832 // We know all of the bits for a constant!
833 KnownOne = CI->getZExtValue() & DemandedMask;
834 KnownZero = ~KnownOne & DemandedMask;
835 return false;
836 }
837
838 KnownZero = KnownOne = 0;
Chris Lattner2590e512006-02-07 06:56:34 +0000839 if (!V->hasOneUse()) { // Other users may use these bits.
Chris Lattner0157e7f2006-02-11 09:31:47 +0000840 if (Depth != 0) { // Not at the root.
841 // Just compute the KnownZero/KnownOne bits to simplify things downstream.
842 ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
Chris Lattner2590e512006-02-07 06:56:34 +0000843 return false;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000844 }
Chris Lattner2590e512006-02-07 06:56:34 +0000845 // If this is the root being simplified, allow it to have multiple uses,
Chris Lattner0157e7f2006-02-11 09:31:47 +0000846 // just set the DemandedMask to all bits.
847 DemandedMask = V->getType()->getIntegralTypeMask();
848 } else if (DemandedMask == 0) { // Not demanding any bits from V.
Chris Lattner92a68652006-02-07 08:05:22 +0000849 if (V != UndefValue::get(V->getType()))
850 return UpdateValueUsesWith(V, UndefValue::get(V->getType()));
851 return false;
Chris Lattner2590e512006-02-07 06:56:34 +0000852 } else if (Depth == 6) { // Limit search depth.
853 return false;
854 }
855
856 Instruction *I = dyn_cast<Instruction>(V);
857 if (!I) return false; // Only analyze instructions.
858
Chris Lattnerfb296922006-05-04 17:33:35 +0000859 DemandedMask &= V->getType()->getIntegralTypeMask();
860
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000861 uint64_t KnownZero2 = 0, KnownOne2 = 0;
Chris Lattner2590e512006-02-07 06:56:34 +0000862 switch (I->getOpcode()) {
863 default: break;
864 case Instruction::And:
Chris Lattner0157e7f2006-02-11 09:31:47 +0000865 // If either the LHS or the RHS are Zero, the result is zero.
866 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
867 KnownZero, KnownOne, Depth+1))
868 return true;
869 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
870
871 // If something is known zero on the RHS, the bits aren't demanded on the
872 // LHS.
873 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownZero,
874 KnownZero2, KnownOne2, Depth+1))
875 return true;
876 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
877
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000878 // If all of the demanded bits are known 1 on one side, return the other.
Chris Lattner0157e7f2006-02-11 09:31:47 +0000879 // These bits cannot contribute to the result of the 'and'.
880 if ((DemandedMask & ~KnownZero2 & KnownOne) == (DemandedMask & ~KnownZero2))
881 return UpdateValueUsesWith(I, I->getOperand(0));
882 if ((DemandedMask & ~KnownZero & KnownOne2) == (DemandedMask & ~KnownZero))
883 return UpdateValueUsesWith(I, I->getOperand(1));
Chris Lattner5b2edb12006-02-12 08:02:11 +0000884
885 // If all of the demanded bits in the inputs are known zeros, return zero.
886 if ((DemandedMask & (KnownZero|KnownZero2)) == DemandedMask)
887 return UpdateValueUsesWith(I, Constant::getNullValue(I->getType()));
888
Chris Lattner0157e7f2006-02-11 09:31:47 +0000889 // If the RHS is a constant, see if we can simplify it.
Chris Lattner5b2edb12006-02-12 08:02:11 +0000890 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~KnownZero2))
Chris Lattner0157e7f2006-02-11 09:31:47 +0000891 return UpdateValueUsesWith(I, I);
892
893 // Output known-1 bits are only known if set in both the LHS & RHS.
894 KnownOne &= KnownOne2;
895 // Output known-0 are known to be clear if zero in either the LHS | RHS.
896 KnownZero |= KnownZero2;
897 break;
898 case Instruction::Or:
899 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
900 KnownZero, KnownOne, Depth+1))
901 return true;
902 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
903 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownOne,
904 KnownZero2, KnownOne2, Depth+1))
905 return true;
906 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
907
908 // If all of the demanded bits are known zero on one side, return the other.
909 // These bits cannot contribute to the result of the 'or'.
Jeff Cohen0add83e2006-02-18 03:20:33 +0000910 if ((DemandedMask & ~KnownOne2 & KnownZero) == (DemandedMask & ~KnownOne2))
Chris Lattner0157e7f2006-02-11 09:31:47 +0000911 return UpdateValueUsesWith(I, I->getOperand(0));
Jeff Cohen0add83e2006-02-18 03:20:33 +0000912 if ((DemandedMask & ~KnownOne & KnownZero2) == (DemandedMask & ~KnownOne))
Chris Lattner0157e7f2006-02-11 09:31:47 +0000913 return UpdateValueUsesWith(I, I->getOperand(1));
Chris Lattner5b2edb12006-02-12 08:02:11 +0000914
915 // If all of the potentially set bits on one side are known to be set on
916 // the other side, just use the 'other' side.
917 if ((DemandedMask & (~KnownZero) & KnownOne2) ==
918 (DemandedMask & (~KnownZero)))
919 return UpdateValueUsesWith(I, I->getOperand(0));
Nate Begeman8a77efe2006-02-16 21:11:51 +0000920 if ((DemandedMask & (~KnownZero2) & KnownOne) ==
921 (DemandedMask & (~KnownZero2)))
922 return UpdateValueUsesWith(I, I->getOperand(1));
Chris Lattner0157e7f2006-02-11 09:31:47 +0000923
924 // If the RHS is a constant, see if we can simplify it.
925 if (ShrinkDemandedConstant(I, 1, DemandedMask))
926 return UpdateValueUsesWith(I, I);
927
928 // Output known-0 bits are only known if clear in both the LHS & RHS.
929 KnownZero &= KnownZero2;
930 // Output known-1 are known to be set if set in either the LHS | RHS.
931 KnownOne |= KnownOne2;
932 break;
933 case Instruction::Xor: {
934 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
935 KnownZero, KnownOne, Depth+1))
936 return true;
937 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
938 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
939 KnownZero2, KnownOne2, Depth+1))
940 return true;
941 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
942
943 // If all of the demanded bits are known zero on one side, return the other.
944 // These bits cannot contribute to the result of the 'xor'.
945 if ((DemandedMask & KnownZero) == DemandedMask)
946 return UpdateValueUsesWith(I, I->getOperand(0));
947 if ((DemandedMask & KnownZero2) == DemandedMask)
948 return UpdateValueUsesWith(I, I->getOperand(1));
949
950 // Output known-0 bits are known if clear or set in both the LHS & RHS.
951 uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
952 // Output known-1 are known to be set if set in only one of the LHS, RHS.
953 uint64_t KnownOneOut = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
954
Chris Lattner8e9a7b72006-11-27 19:55:07 +0000955 // If all of the demanded bits are known to be zero on one side or the
956 // other, turn this into an *inclusive* or.
Chris Lattner5b2edb12006-02-12 08:02:11 +0000957 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattner8e9a7b72006-11-27 19:55:07 +0000958 if ((DemandedMask & ~KnownZero & ~KnownZero2) == 0) {
959 Instruction *Or =
960 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
961 I->getName());
962 InsertNewInstBefore(Or, *I);
963 return UpdateValueUsesWith(I, Or);
Chris Lattner2590e512006-02-07 06:56:34 +0000964 }
Chris Lattner0157e7f2006-02-11 09:31:47 +0000965
Chris Lattner5b2edb12006-02-12 08:02:11 +0000966 // If all of the demanded bits on one side are known, and all of the set
967 // bits on that side are also known to be set on the other side, turn this
968 // into an AND, as we know the bits will be cleared.
969 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
970 if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask) { // all known
971 if ((KnownOne & KnownOne2) == KnownOne) {
972 Constant *AndC = GetConstantInType(I->getType(),
973 ~KnownOne & DemandedMask);
974 Instruction *And =
975 BinaryOperator::createAnd(I->getOperand(0), AndC, "tmp");
976 InsertNewInstBefore(And, *I);
977 return UpdateValueUsesWith(I, And);
978 }
979 }
980
Chris Lattner0157e7f2006-02-11 09:31:47 +0000981 // If the RHS is a constant, see if we can simplify it.
982 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
983 if (ShrinkDemandedConstant(I, 1, DemandedMask))
984 return UpdateValueUsesWith(I, I);
985
986 KnownZero = KnownZeroOut;
987 KnownOne = KnownOneOut;
988 break;
989 }
990 case Instruction::Select:
991 if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
992 KnownZero, KnownOne, Depth+1))
993 return true;
994 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
995 KnownZero2, KnownOne2, Depth+1))
996 return true;
997 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
998 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
999
1000 // If the operands are constants, see if we can simplify them.
1001 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1002 return UpdateValueUsesWith(I, I);
1003 if (ShrinkDemandedConstant(I, 2, DemandedMask))
1004 return UpdateValueUsesWith(I, I);
1005
1006 // Only known if known in both the LHS and RHS.
1007 KnownOne &= KnownOne2;
1008 KnownZero &= KnownZero2;
1009 break;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001010 case Instruction::Trunc:
1011 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1012 KnownZero, KnownOne, Depth+1))
1013 return true;
1014 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1015 break;
1016 case Instruction::BitCast:
1017 if (!I->getOperand(0)->getType()->isIntegral())
1018 return false;
Chris Lattner850465d2006-09-16 03:14:10 +00001019
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001020 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1021 KnownZero, KnownOne, Depth+1))
1022 return true;
1023 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1024 break;
1025 case Instruction::ZExt: {
1026 // Compute the bits in the result that are not present in the input.
1027 const Type *SrcTy = I->getOperand(0)->getType();
Chris Lattner0157e7f2006-02-11 09:31:47 +00001028 uint64_t NotIn = ~SrcTy->getIntegralTypeMask();
1029 uint64_t NewBits = I->getType()->getIntegralTypeMask() & NotIn;
1030
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001031 DemandedMask &= SrcTy->getIntegralTypeMask();
1032 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1033 KnownZero, KnownOne, Depth+1))
1034 return true;
1035 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1036 // The top bits are known to be zero.
1037 KnownZero |= NewBits;
1038 break;
1039 }
1040 case Instruction::SExt: {
1041 // Compute the bits in the result that are not present in the input.
1042 const Type *SrcTy = I->getOperand(0)->getType();
1043 uint64_t NotIn = ~SrcTy->getIntegralTypeMask();
1044 uint64_t NewBits = I->getType()->getIntegralTypeMask() & NotIn;
1045
1046 // Get the sign bit for the source type
1047 uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
1048 int64_t InputDemandedBits = DemandedMask & SrcTy->getIntegralTypeMask();
Chris Lattner7d852282006-02-13 22:41:07 +00001049
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001050 // If any of the sign extended bits are demanded, we know that the sign
1051 // bit is demanded.
1052 if (NewBits & DemandedMask)
1053 InputDemandedBits |= InSignBit;
Chris Lattner7d852282006-02-13 22:41:07 +00001054
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001055 if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
1056 KnownZero, KnownOne, Depth+1))
1057 return true;
1058 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattner0157e7f2006-02-11 09:31:47 +00001059
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001060 // If the sign bit of the input is known set or clear, then we know the
1061 // top bits of the result.
Chris Lattner2590e512006-02-07 06:56:34 +00001062
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001063 // If the input sign bit is known zero, or if the NewBits are not demanded
1064 // convert this into a zero extension.
1065 if ((KnownZero & InSignBit) || (NewBits & ~DemandedMask) == NewBits) {
1066 // Convert to ZExt cast
1067 CastInst *NewCast = CastInst::create(
1068 Instruction::ZExt, I->getOperand(0), I->getType(), I->getName(), I);
1069 return UpdateValueUsesWith(I, NewCast);
1070 } else if (KnownOne & InSignBit) { // Input sign bit known set
1071 KnownOne |= NewBits;
1072 KnownZero &= ~NewBits;
1073 } else { // Input sign bit unknown
1074 KnownZero &= ~NewBits;
1075 KnownOne &= ~NewBits;
Chris Lattner2590e512006-02-07 06:56:34 +00001076 }
Chris Lattner0157e7f2006-02-11 09:31:47 +00001077 break;
Chris Lattner2590e512006-02-07 06:56:34 +00001078 }
Chris Lattner6e2c15c2006-11-09 05:12:27 +00001079 case Instruction::Add:
1080 // If there is a constant on the RHS, there are a variety of xformations
1081 // we can do.
1082 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1083 // If null, this should be simplified elsewhere. Some of the xforms here
1084 // won't work if the RHS is zero.
1085 if (RHS->isNullValue())
1086 break;
1087
1088 // Figure out what the input bits are. If the top bits of the and result
1089 // are not demanded, then the add doesn't demand them from its input
1090 // either.
1091
1092 // Shift the demanded mask up so that it's at the top of the uint64_t.
1093 unsigned BitWidth = I->getType()->getPrimitiveSizeInBits();
1094 unsigned NLZ = CountLeadingZeros_64(DemandedMask << (64-BitWidth));
1095
1096 // If the top bit of the output is demanded, demand everything from the
1097 // input. Otherwise, we demand all the input bits except NLZ top bits.
1098 uint64_t InDemandedBits = ~0ULL >> 64-BitWidth+NLZ;
1099
1100 // Find information about known zero/one bits in the input.
1101 if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits,
1102 KnownZero2, KnownOne2, Depth+1))
1103 return true;
1104
1105 // If the RHS of the add has bits set that can't affect the input, reduce
1106 // the constant.
1107 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1108 return UpdateValueUsesWith(I, I);
1109
1110 // Avoid excess work.
1111 if (KnownZero2 == 0 && KnownOne2 == 0)
1112 break;
1113
1114 // Turn it into OR if input bits are zero.
1115 if ((KnownZero2 & RHS->getZExtValue()) == RHS->getZExtValue()) {
1116 Instruction *Or =
1117 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1118 I->getName());
1119 InsertNewInstBefore(Or, *I);
1120 return UpdateValueUsesWith(I, Or);
1121 }
1122
1123 // We can say something about the output known-zero and known-one bits,
1124 // depending on potential carries from the input constant and the
1125 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1126 // bits set and the RHS constant is 0x01001, then we know we have a known
1127 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1128
1129 // To compute this, we first compute the potential carry bits. These are
1130 // the bits which may be modified. I'm not aware of a better way to do
1131 // this scan.
1132 uint64_t RHSVal = RHS->getZExtValue();
1133
1134 bool CarryIn = false;
1135 uint64_t CarryBits = 0;
1136 uint64_t CurBit = 1;
1137 for (unsigned i = 0; i != BitWidth; ++i, CurBit <<= 1) {
1138 // Record the current carry in.
1139 if (CarryIn) CarryBits |= CurBit;
1140
1141 bool CarryOut;
1142
1143 // This bit has a carry out unless it is "zero + zero" or
1144 // "zero + anything" with no carry in.
1145 if ((KnownZero2 & CurBit) && ((RHSVal & CurBit) == 0)) {
1146 CarryOut = false; // 0 + 0 has no carry out, even with carry in.
1147 } else if (!CarryIn &&
1148 ((KnownZero2 & CurBit) || ((RHSVal & CurBit) == 0))) {
1149 CarryOut = false; // 0 + anything has no carry out if no carry in.
1150 } else {
1151 // Otherwise, we have to assume we have a carry out.
1152 CarryOut = true;
1153 }
1154
1155 // This stage's carry out becomes the next stage's carry-in.
1156 CarryIn = CarryOut;
1157 }
1158
1159 // Now that we know which bits have carries, compute the known-1/0 sets.
1160
1161 // Bits are known one if they are known zero in one operand and one in the
1162 // other, and there is no input carry.
1163 KnownOne = ((KnownZero2 & RHSVal) | (KnownOne2 & ~RHSVal)) & ~CarryBits;
1164
1165 // Bits are known zero if they are known zero in both operands and there
1166 // is no input carry.
1167 KnownZero = KnownZero2 & ~RHSVal & ~CarryBits;
1168 }
1169 break;
Chris Lattner2590e512006-02-07 06:56:34 +00001170 case Instruction::Shl:
Reid Spencere0fc4df2006-10-20 07:07:24 +00001171 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1172 uint64_t ShiftAmt = SA->getZExtValue();
1173 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask >> ShiftAmt,
Chris Lattner0157e7f2006-02-11 09:31:47 +00001174 KnownZero, KnownOne, Depth+1))
1175 return true;
1176 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Reid Spencere0fc4df2006-10-20 07:07:24 +00001177 KnownZero <<= ShiftAmt;
1178 KnownOne <<= ShiftAmt;
1179 KnownZero |= (1ULL << ShiftAmt) - 1; // low bits known zero.
Chris Lattner0157e7f2006-02-11 09:31:47 +00001180 }
Chris Lattner2590e512006-02-07 06:56:34 +00001181 break;
Reid Spencerfdff9382006-11-08 06:47:33 +00001182 case Instruction::LShr:
1183 // For a logical shift right
1184 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1185 unsigned ShiftAmt = SA->getZExtValue();
1186
1187 // Compute the new bits that are at the top now.
1188 uint64_t HighBits = (1ULL << ShiftAmt)-1;
1189 HighBits <<= I->getType()->getPrimitiveSizeInBits() - ShiftAmt;
1190 uint64_t TypeMask = I->getType()->getIntegralTypeMask();
1191 // Unsigned shift right.
1192 if (SimplifyDemandedBits(I->getOperand(0),
1193 (DemandedMask << ShiftAmt) & TypeMask,
1194 KnownZero, KnownOne, Depth+1))
1195 return true;
1196 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1197 KnownZero &= TypeMask;
1198 KnownOne &= TypeMask;
1199 KnownZero >>= ShiftAmt;
1200 KnownOne >>= ShiftAmt;
1201 KnownZero |= HighBits; // high bits known zero.
1202 }
1203 break;
1204 case Instruction::AShr:
Chris Lattner420c4bc2006-09-18 04:31:40 +00001205 // If this is an arithmetic shift right and only the low-bit is set, we can
1206 // always convert this into a logical shr, even if the shift amount is
1207 // variable. The low bit of the shift cannot be an input sign bit unless
1208 // the shift amount is >= the size of the datatype, which is undefined.
Reid Spencerfdff9382006-11-08 06:47:33 +00001209 if (DemandedMask == 1) {
1210 // Perform the logical shift right.
1211 Value *NewVal = new ShiftInst(Instruction::LShr, I->getOperand(0),
1212 I->getOperand(1), I->getName());
Reid Spencer00c482b2006-10-26 19:19:06 +00001213 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
Chris Lattner420c4bc2006-09-18 04:31:40 +00001214 return UpdateValueUsesWith(I, NewVal);
1215 }
1216
Reid Spencere0fc4df2006-10-20 07:07:24 +00001217 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1218 unsigned ShiftAmt = SA->getZExtValue();
Chris Lattner0157e7f2006-02-11 09:31:47 +00001219
1220 // Compute the new bits that are at the top now.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001221 uint64_t HighBits = (1ULL << ShiftAmt)-1;
1222 HighBits <<= I->getType()->getPrimitiveSizeInBits() - ShiftAmt;
Chris Lattner68e74752006-02-13 06:09:08 +00001223 uint64_t TypeMask = I->getType()->getIntegralTypeMask();
Reid Spencerfdff9382006-11-08 06:47:33 +00001224 // Signed shift right.
1225 if (SimplifyDemandedBits(I->getOperand(0),
1226 (DemandedMask << ShiftAmt) & TypeMask,
1227 KnownZero, KnownOne, Depth+1))
1228 return true;
1229 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1230 KnownZero &= TypeMask;
1231 KnownOne &= TypeMask;
1232 KnownZero >>= ShiftAmt;
1233 KnownOne >>= ShiftAmt;
Chris Lattner0157e7f2006-02-11 09:31:47 +00001234
Reid Spencerfdff9382006-11-08 06:47:33 +00001235 // Handle the sign bits.
1236 uint64_t SignBit = 1ULL << (I->getType()->getPrimitiveSizeInBits()-1);
1237 SignBit >>= ShiftAmt; // Adjust to where it is now in the mask.
Chris Lattner0157e7f2006-02-11 09:31:47 +00001238
Reid Spencerfdff9382006-11-08 06:47:33 +00001239 // If the input sign bit is known to be zero, or if none of the top bits
1240 // are demanded, turn this into an unsigned shift right.
1241 if ((KnownZero & SignBit) || (HighBits & ~DemandedMask) == HighBits) {
1242 // Perform the logical shift right.
1243 Value *NewVal = new ShiftInst(Instruction::LShr, I->getOperand(0),
1244 SA, I->getName());
1245 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1246 return UpdateValueUsesWith(I, NewVal);
1247 } else if (KnownOne & SignBit) { // New bits are known one.
1248 KnownOne |= HighBits;
Chris Lattner2590e512006-02-07 06:56:34 +00001249 }
Chris Lattner0157e7f2006-02-11 09:31:47 +00001250 }
Chris Lattner2590e512006-02-07 06:56:34 +00001251 break;
1252 }
Chris Lattner0157e7f2006-02-11 09:31:47 +00001253
1254 // If the client is only demanding bits that we know, return the known
1255 // constant.
1256 if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask)
1257 return UpdateValueUsesWith(I, GetConstantInType(I->getType(), KnownOne));
Chris Lattner2590e512006-02-07 06:56:34 +00001258 return false;
1259}
1260
Chris Lattner2deeaea2006-10-05 06:55:50 +00001261
1262/// SimplifyDemandedVectorElts - The specified value producecs a vector with
1263/// 64 or fewer elements. DemandedElts contains the set of elements that are
1264/// actually used by the caller. This method analyzes which elements of the
1265/// operand are undef and returns that information in UndefElts.
1266///
1267/// If the information about demanded elements can be used to simplify the
1268/// operation, the operation is simplified, then the resultant value is
1269/// returned. This returns null if no change was made.
1270Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1271 uint64_t &UndefElts,
1272 unsigned Depth) {
1273 unsigned VWidth = cast<PackedType>(V->getType())->getNumElements();
1274 assert(VWidth <= 64 && "Vector too wide to analyze!");
1275 uint64_t EltMask = ~0ULL >> (64-VWidth);
1276 assert(DemandedElts != EltMask && (DemandedElts & ~EltMask) == 0 &&
1277 "Invalid DemandedElts!");
1278
1279 if (isa<UndefValue>(V)) {
1280 // If the entire vector is undefined, just return this info.
1281 UndefElts = EltMask;
1282 return 0;
1283 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1284 UndefElts = EltMask;
1285 return UndefValue::get(V->getType());
1286 }
1287
1288 UndefElts = 0;
1289 if (ConstantPacked *CP = dyn_cast<ConstantPacked>(V)) {
1290 const Type *EltTy = cast<PackedType>(V->getType())->getElementType();
1291 Constant *Undef = UndefValue::get(EltTy);
1292
1293 std::vector<Constant*> Elts;
1294 for (unsigned i = 0; i != VWidth; ++i)
1295 if (!(DemandedElts & (1ULL << i))) { // If not demanded, set to undef.
1296 Elts.push_back(Undef);
1297 UndefElts |= (1ULL << i);
1298 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1299 Elts.push_back(Undef);
1300 UndefElts |= (1ULL << i);
1301 } else { // Otherwise, defined.
1302 Elts.push_back(CP->getOperand(i));
1303 }
1304
1305 // If we changed the constant, return it.
1306 Constant *NewCP = ConstantPacked::get(Elts);
1307 return NewCP != CP ? NewCP : 0;
1308 } else if (isa<ConstantAggregateZero>(V)) {
1309 // Simplify the CAZ to a ConstantPacked where the non-demanded elements are
1310 // set to undef.
1311 const Type *EltTy = cast<PackedType>(V->getType())->getElementType();
1312 Constant *Zero = Constant::getNullValue(EltTy);
1313 Constant *Undef = UndefValue::get(EltTy);
1314 std::vector<Constant*> Elts;
1315 for (unsigned i = 0; i != VWidth; ++i)
1316 Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1317 UndefElts = DemandedElts ^ EltMask;
1318 return ConstantPacked::get(Elts);
1319 }
1320
1321 if (!V->hasOneUse()) { // Other users may use these bits.
1322 if (Depth != 0) { // Not at the root.
1323 // TODO: Just compute the UndefElts information recursively.
1324 return false;
1325 }
1326 return false;
1327 } else if (Depth == 10) { // Limit search depth.
1328 return false;
1329 }
1330
1331 Instruction *I = dyn_cast<Instruction>(V);
1332 if (!I) return false; // Only analyze instructions.
1333
1334 bool MadeChange = false;
1335 uint64_t UndefElts2;
1336 Value *TmpV;
1337 switch (I->getOpcode()) {
1338 default: break;
1339
1340 case Instruction::InsertElement: {
1341 // If this is a variable index, we don't know which element it overwrites.
1342 // demand exactly the same input as we produce.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001343 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
Chris Lattner2deeaea2006-10-05 06:55:50 +00001344 if (Idx == 0) {
1345 // Note that we can't propagate undef elt info, because we don't know
1346 // which elt is getting updated.
1347 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1348 UndefElts2, Depth+1);
1349 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1350 break;
1351 }
1352
1353 // If this is inserting an element that isn't demanded, remove this
1354 // insertelement.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001355 unsigned IdxNo = Idx->getZExtValue();
Chris Lattner2deeaea2006-10-05 06:55:50 +00001356 if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1357 return AddSoonDeadInstToWorklist(*I, 0);
1358
1359 // Otherwise, the element inserted overwrites whatever was there, so the
1360 // input demanded set is simpler than the output set.
1361 TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1362 DemandedElts & ~(1ULL << IdxNo),
1363 UndefElts, Depth+1);
1364 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1365
1366 // The inserted element is defined.
1367 UndefElts |= 1ULL << IdxNo;
1368 break;
1369 }
1370
1371 case Instruction::And:
1372 case Instruction::Or:
1373 case Instruction::Xor:
1374 case Instruction::Add:
1375 case Instruction::Sub:
1376 case Instruction::Mul:
1377 // div/rem demand all inputs, because they don't want divide by zero.
1378 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1379 UndefElts, Depth+1);
1380 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1381 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1382 UndefElts2, Depth+1);
1383 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1384
1385 // Output elements are undefined if both are undefined. Consider things
1386 // like undef&0. The result is known zero, not undef.
1387 UndefElts &= UndefElts2;
1388 break;
1389
1390 case Instruction::Call: {
1391 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1392 if (!II) break;
1393 switch (II->getIntrinsicID()) {
1394 default: break;
1395
1396 // Binary vector operations that work column-wise. A dest element is a
1397 // function of the corresponding input elements from the two inputs.
1398 case Intrinsic::x86_sse_sub_ss:
1399 case Intrinsic::x86_sse_mul_ss:
1400 case Intrinsic::x86_sse_min_ss:
1401 case Intrinsic::x86_sse_max_ss:
1402 case Intrinsic::x86_sse2_sub_sd:
1403 case Intrinsic::x86_sse2_mul_sd:
1404 case Intrinsic::x86_sse2_min_sd:
1405 case Intrinsic::x86_sse2_max_sd:
1406 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1407 UndefElts, Depth+1);
1408 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1409 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1410 UndefElts2, Depth+1);
1411 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1412
1413 // If only the low elt is demanded and this is a scalarizable intrinsic,
1414 // scalarize it now.
1415 if (DemandedElts == 1) {
1416 switch (II->getIntrinsicID()) {
1417 default: break;
1418 case Intrinsic::x86_sse_sub_ss:
1419 case Intrinsic::x86_sse_mul_ss:
1420 case Intrinsic::x86_sse2_sub_sd:
1421 case Intrinsic::x86_sse2_mul_sd:
1422 // TODO: Lower MIN/MAX/ABS/etc
1423 Value *LHS = II->getOperand(1);
1424 Value *RHS = II->getOperand(2);
1425 // Extract the element as scalars.
1426 LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1427 RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1428
1429 switch (II->getIntrinsicID()) {
1430 default: assert(0 && "Case stmts out of sync!");
1431 case Intrinsic::x86_sse_sub_ss:
1432 case Intrinsic::x86_sse2_sub_sd:
1433 TmpV = InsertNewInstBefore(BinaryOperator::createSub(LHS, RHS,
1434 II->getName()), *II);
1435 break;
1436 case Intrinsic::x86_sse_mul_ss:
1437 case Intrinsic::x86_sse2_mul_sd:
1438 TmpV = InsertNewInstBefore(BinaryOperator::createMul(LHS, RHS,
1439 II->getName()), *II);
1440 break;
1441 }
1442
1443 Instruction *New =
1444 new InsertElementInst(UndefValue::get(II->getType()), TmpV, 0U,
1445 II->getName());
1446 InsertNewInstBefore(New, *II);
1447 AddSoonDeadInstToWorklist(*II, 0);
1448 return New;
1449 }
1450 }
1451
1452 // Output elements are undefined if both are undefined. Consider things
1453 // like undef&0. The result is known zero, not undef.
1454 UndefElts &= UndefElts2;
1455 break;
1456 }
1457 break;
1458 }
1459 }
1460 return MadeChange ? I : 0;
1461}
1462
Reid Spencer266e42b2006-12-23 06:05:41 +00001463/// @returns true if the specified compare instruction is
1464/// true when both operands are equal...
1465/// @brief Determine if the ICmpInst returns true if both operands are equal
1466static bool isTrueWhenEqual(ICmpInst &ICI) {
1467 ICmpInst::Predicate pred = ICI.getPredicate();
1468 return pred == ICmpInst::ICMP_EQ || pred == ICmpInst::ICMP_UGE ||
1469 pred == ICmpInst::ICMP_SGE || pred == ICmpInst::ICMP_ULE ||
1470 pred == ICmpInst::ICMP_SLE;
1471}
1472
1473/// @returns true if the specified compare instruction is
1474/// true when both operands are equal...
1475/// @brief Determine if the FCmpInst returns true if both operands are equal
1476static bool isTrueWhenEqual(FCmpInst &FCI) {
1477 FCmpInst::Predicate pred = FCI.getPredicate();
1478 return pred == FCmpInst::FCMP_OEQ || pred == FCmpInst::FCMP_UEQ ||
1479 pred == FCmpInst::FCMP_OGE || pred == FCmpInst::FCMP_UGE ||
1480 pred == FCmpInst::FCMP_OLE || pred == FCmpInst::FCMP_ULE;
Chris Lattner623826c2004-09-28 21:48:02 +00001481}
Chris Lattnerb8b97502003-08-13 19:01:45 +00001482
1483/// AssociativeOpt - Perform an optimization on an associative operator. This
1484/// function is designed to check a chain of associative operators for a
1485/// potential to apply a certain optimization. Since the optimization may be
1486/// applicable if the expression was reassociated, this checks the chain, then
1487/// reassociates the expression as necessary to expose the optimization
1488/// opportunity. This makes use of a special Functor, which must define
1489/// 'shouldApply' and 'apply' methods.
1490///
1491template<typename Functor>
1492Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1493 unsigned Opcode = Root.getOpcode();
1494 Value *LHS = Root.getOperand(0);
1495
1496 // Quick check, see if the immediate LHS matches...
1497 if (F.shouldApply(LHS))
1498 return F.apply(Root);
1499
1500 // Otherwise, if the LHS is not of the same opcode as the root, return.
1501 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001502 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattnerb8b97502003-08-13 19:01:45 +00001503 // Should we apply this transform to the RHS?
1504 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1505
1506 // If not to the RHS, check to see if we should apply to the LHS...
1507 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1508 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1509 ShouldApply = true;
1510 }
1511
1512 // If the functor wants to apply the optimization to the RHS of LHSI,
1513 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1514 if (ShouldApply) {
1515 BasicBlock *BB = Root.getParent();
Misha Brukmanb1c93172005-04-21 23:48:37 +00001516
Chris Lattnerb8b97502003-08-13 19:01:45 +00001517 // Now all of the instructions are in the current basic block, go ahead
1518 // and perform the reassociation.
1519 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1520
1521 // First move the selected RHS to the LHS of the root...
1522 Root.setOperand(0, LHSI->getOperand(1));
1523
1524 // Make what used to be the LHS of the root be the user of the root...
1525 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner284d3b02004-04-16 18:08:07 +00001526 if (&Root == TmpLHSI) {
Chris Lattner8953b902004-04-05 02:10:19 +00001527 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1528 return 0;
1529 }
Chris Lattner284d3b02004-04-16 18:08:07 +00001530 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattnerb8b97502003-08-13 19:01:45 +00001531 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner284d3b02004-04-16 18:08:07 +00001532 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
1533 BasicBlock::iterator ARI = &Root; ++ARI;
1534 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
1535 ARI = Root;
Chris Lattnerb8b97502003-08-13 19:01:45 +00001536
1537 // Now propagate the ExtraOperand down the chain of instructions until we
1538 // get to LHSI.
1539 while (TmpLHSI != LHSI) {
1540 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner284d3b02004-04-16 18:08:07 +00001541 // Move the instruction to immediately before the chain we are
1542 // constructing to avoid breaking dominance properties.
1543 NextLHSI->getParent()->getInstList().remove(NextLHSI);
1544 BB->getInstList().insert(ARI, NextLHSI);
1545 ARI = NextLHSI;
1546
Chris Lattnerb8b97502003-08-13 19:01:45 +00001547 Value *NextOp = NextLHSI->getOperand(1);
1548 NextLHSI->setOperand(1, ExtraOperand);
1549 TmpLHSI = NextLHSI;
1550 ExtraOperand = NextOp;
1551 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001552
Chris Lattnerb8b97502003-08-13 19:01:45 +00001553 // Now that the instructions are reassociated, have the functor perform
1554 // the transformation...
1555 return F.apply(Root);
1556 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001557
Chris Lattnerb8b97502003-08-13 19:01:45 +00001558 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1559 }
1560 return 0;
1561}
1562
1563
1564// AddRHS - Implements: X + X --> X << 1
1565struct AddRHS {
1566 Value *RHS;
1567 AddRHS(Value *rhs) : RHS(rhs) {}
1568 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1569 Instruction *apply(BinaryOperator &Add) const {
1570 return new ShiftInst(Instruction::Shl, Add.getOperand(0),
Reid Spencerc635f472006-12-31 05:48:39 +00001571 ConstantInt::get(Type::Int8Ty, 1));
Chris Lattnerb8b97502003-08-13 19:01:45 +00001572 }
1573};
1574
1575// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1576// iff C1&C2 == 0
1577struct AddMaskingAnd {
1578 Constant *C2;
1579 AddMaskingAnd(Constant *c) : C2(c) {}
1580 bool shouldApply(Value *LHS) const {
Chris Lattnerd4252a72004-07-30 07:50:03 +00001581 ConstantInt *C1;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001582 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Chris Lattnerd4252a72004-07-30 07:50:03 +00001583 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattnerb8b97502003-08-13 19:01:45 +00001584 }
1585 Instruction *apply(BinaryOperator &Add) const {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001586 return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattnerb8b97502003-08-13 19:01:45 +00001587 }
1588};
1589
Chris Lattner86102b82005-01-01 16:22:27 +00001590static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner183b3362004-04-09 19:05:30 +00001591 InstCombiner *IC) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001592 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
Chris Lattner86102b82005-01-01 16:22:27 +00001593 if (Constant *SOC = dyn_cast<Constant>(SO))
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001594 return ConstantExpr::getCast(CI->getOpcode(), SOC, I.getType());
Misha Brukmanb1c93172005-04-21 23:48:37 +00001595
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001596 return IC->InsertNewInstBefore(CastInst::create(
1597 CI->getOpcode(), SO, I.getType(), SO->getName() + ".cast"), I);
Chris Lattner86102b82005-01-01 16:22:27 +00001598 }
1599
Chris Lattner183b3362004-04-09 19:05:30 +00001600 // Figure out if the constant is the left or the right argument.
Chris Lattner86102b82005-01-01 16:22:27 +00001601 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1602 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattnerb8b97502003-08-13 19:01:45 +00001603
Chris Lattner183b3362004-04-09 19:05:30 +00001604 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1605 if (ConstIsRHS)
Chris Lattner86102b82005-01-01 16:22:27 +00001606 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1607 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner183b3362004-04-09 19:05:30 +00001608 }
1609
1610 Value *Op0 = SO, *Op1 = ConstOperand;
1611 if (!ConstIsRHS)
1612 std::swap(Op0, Op1);
1613 Instruction *New;
Chris Lattner86102b82005-01-01 16:22:27 +00001614 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1615 New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
Reid Spencer266e42b2006-12-23 06:05:41 +00001616 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1617 New = CmpInst::create(CI->getOpcode(), CI->getPredicate(), Op0, Op1,
1618 SO->getName()+".cmp");
Chris Lattner86102b82005-01-01 16:22:27 +00001619 else if (ShiftInst *SI = dyn_cast<ShiftInst>(&I))
1620 New = new ShiftInst(SI->getOpcode(), Op0, Op1, SO->getName()+".sh");
Chris Lattnerf9d96652004-04-10 19:15:56 +00001621 else {
Chris Lattner183b3362004-04-09 19:05:30 +00001622 assert(0 && "Unknown binary instruction type!");
Chris Lattnerf9d96652004-04-10 19:15:56 +00001623 abort();
1624 }
Chris Lattner86102b82005-01-01 16:22:27 +00001625 return IC->InsertNewInstBefore(New, I);
1626}
1627
1628// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1629// constant as the other operand, try to fold the binary operator into the
1630// select arguments. This also works for Cast instructions, which obviously do
1631// not have a second operand.
1632static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1633 InstCombiner *IC) {
1634 // Don't modify shared select instructions
1635 if (!SI->hasOneUse()) return 0;
1636 Value *TV = SI->getOperand(1);
1637 Value *FV = SI->getOperand(2);
1638
1639 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner374e6592005-04-21 05:43:13 +00001640 // Bool selects with constant operands can be folded to logical ops.
1641 if (SI->getType() == Type::BoolTy) return 0;
1642
Chris Lattner86102b82005-01-01 16:22:27 +00001643 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1644 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1645
1646 return new SelectInst(SI->getCondition(), SelectTrueVal,
1647 SelectFalseVal);
1648 }
1649 return 0;
Chris Lattner183b3362004-04-09 19:05:30 +00001650}
1651
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001652
1653/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1654/// node as operand #0, see if we can fold the instruction into the PHI (which
1655/// is only possible if all operands to the PHI are constants).
1656Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1657 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattner7515cab2004-11-14 19:13:23 +00001658 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner04689872006-09-09 22:02:56 +00001659 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001660
Chris Lattner04689872006-09-09 22:02:56 +00001661 // Check to see if all of the operands of the PHI are constants. If there is
1662 // one non-constant value, remember the BB it is. If there is more than one
1663 // bail out.
1664 BasicBlock *NonConstBB = 0;
1665 for (unsigned i = 0; i != NumPHIValues; ++i)
1666 if (!isa<Constant>(PN->getIncomingValue(i))) {
1667 if (NonConstBB) return 0; // More than one non-const value.
1668 NonConstBB = PN->getIncomingBlock(i);
1669
1670 // If the incoming non-constant value is in I's block, we have an infinite
1671 // loop.
1672 if (NonConstBB == I.getParent())
1673 return 0;
1674 }
1675
1676 // If there is exactly one non-constant value, we can insert a copy of the
1677 // operation in that block. However, if this is a critical edge, we would be
1678 // inserting the computation one some other paths (e.g. inside a loop). Only
1679 // do this if the pred block is unconditionally branching into the phi block.
1680 if (NonConstBB) {
1681 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1682 if (!BI || !BI->isUnconditional()) return 0;
1683 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001684
1685 // Okay, we can do the transformation: create the new PHI node.
1686 PHINode *NewPN = new PHINode(I.getType(), I.getName());
1687 I.setName("");
Chris Lattnerd8e20182005-01-29 00:39:08 +00001688 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001689 InsertNewInstBefore(NewPN, *PN);
1690
1691 // Next, add all of the operands to the PHI.
1692 if (I.getNumOperands() == 2) {
1693 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattner7515cab2004-11-14 19:13:23 +00001694 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner04689872006-09-09 22:02:56 +00001695 Value *InV;
1696 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencer266e42b2006-12-23 06:05:41 +00001697 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1698 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
1699 else
1700 InV = ConstantExpr::get(I.getOpcode(), InC, C);
Chris Lattner04689872006-09-09 22:02:56 +00001701 } else {
1702 assert(PN->getIncomingBlock(i) == NonConstBB);
1703 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1704 InV = BinaryOperator::create(BO->getOpcode(),
1705 PN->getIncomingValue(i), C, "phitmp",
1706 NonConstBB->getTerminator());
Reid Spencer266e42b2006-12-23 06:05:41 +00001707 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1708 InV = CmpInst::create(CI->getOpcode(),
1709 CI->getPredicate(),
1710 PN->getIncomingValue(i), C, "phitmp",
1711 NonConstBB->getTerminator());
Chris Lattner04689872006-09-09 22:02:56 +00001712 else if (ShiftInst *SI = dyn_cast<ShiftInst>(&I))
1713 InV = new ShiftInst(SI->getOpcode(),
1714 PN->getIncomingValue(i), C, "phitmp",
1715 NonConstBB->getTerminator());
1716 else
1717 assert(0 && "Unknown binop!");
1718
1719 WorkList.push_back(cast<Instruction>(InV));
1720 }
1721 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001722 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001723 } else {
1724 CastInst *CI = cast<CastInst>(&I);
1725 const Type *RetTy = CI->getType();
Chris Lattner7515cab2004-11-14 19:13:23 +00001726 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner04689872006-09-09 22:02:56 +00001727 Value *InV;
1728 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001729 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Chris Lattner04689872006-09-09 22:02:56 +00001730 } else {
1731 assert(PN->getIncomingBlock(i) == NonConstBB);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001732 InV = CastInst::create(CI->getOpcode(), PN->getIncomingValue(i),
1733 I.getType(), "phitmp",
1734 NonConstBB->getTerminator());
Chris Lattner04689872006-09-09 22:02:56 +00001735 WorkList.push_back(cast<Instruction>(InV));
1736 }
1737 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001738 }
1739 }
1740 return ReplaceInstUsesWith(I, NewPN);
1741}
1742
Chris Lattner113f4f42002-06-25 16:13:24 +00001743Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001744 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00001745 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattner9fa53de2002-05-06 16:49:18 +00001746
Chris Lattnercf4a9962004-04-10 22:01:55 +00001747 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattner81a7a232004-10-16 18:11:37 +00001748 // X + undef -> undef
1749 if (isa<UndefValue>(RHS))
1750 return ReplaceInstUsesWith(I, RHS);
1751
Chris Lattnercf4a9962004-04-10 22:01:55 +00001752 // X + 0 --> X
Chris Lattner7a002fe2006-12-02 00:13:08 +00001753 if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
Chris Lattner7fde91e2005-10-17 17:56:38 +00001754 if (RHSC->isNullValue())
1755 return ReplaceInstUsesWith(I, LHS);
Chris Lattnerda1b1522005-10-17 20:18:38 +00001756 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
1757 if (CFP->isExactlyValue(-0.0))
1758 return ReplaceInstUsesWith(I, LHS);
Chris Lattner7fde91e2005-10-17 17:56:38 +00001759 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001760
Chris Lattnercf4a9962004-04-10 22:01:55 +00001761 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattner6e2c15c2006-11-09 05:12:27 +00001762 // X + (signbit) --> X ^ signbit
Chris Lattner92a68652006-02-07 08:05:22 +00001763 uint64_t Val = CI->getZExtValue();
Chris Lattner77defba2006-02-07 07:00:41 +00001764 if (Val == (1ULL << (CI->getType()->getPrimitiveSizeInBits()-1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001765 return BinaryOperator::createXor(LHS, RHS);
Chris Lattner6e2c15c2006-11-09 05:12:27 +00001766
1767 // See if SimplifyDemandedBits can simplify this. This handles stuff like
1768 // (X & 254)+1 -> (X&254)|1
1769 uint64_t KnownZero, KnownOne;
1770 if (!isa<PackedType>(I.getType()) &&
1771 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
1772 KnownZero, KnownOne))
1773 return &I;
Chris Lattnercf4a9962004-04-10 22:01:55 +00001774 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001775
1776 if (isa<PHINode>(LHS))
1777 if (Instruction *NV = FoldOpIntoPhi(I))
1778 return NV;
Chris Lattner0b3557f2005-09-24 23:43:33 +00001779
Chris Lattner330628a2006-01-06 17:59:59 +00001780 ConstantInt *XorRHS = 0;
1781 Value *XorLHS = 0;
Chris Lattner0b3557f2005-09-24 23:43:33 +00001782 if (match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
1783 unsigned TySizeBits = I.getType()->getPrimitiveSizeInBits();
1784 int64_t RHSSExt = cast<ConstantInt>(RHSC)->getSExtValue();
1785 uint64_t RHSZExt = cast<ConstantInt>(RHSC)->getZExtValue();
1786
1787 uint64_t C0080Val = 1ULL << 31;
1788 int64_t CFF80Val = -C0080Val;
1789 unsigned Size = 32;
1790 do {
1791 if (TySizeBits > Size) {
1792 bool Found = false;
1793 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
1794 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
1795 if (RHSSExt == CFF80Val) {
1796 if (XorRHS->getZExtValue() == C0080Val)
1797 Found = true;
1798 } else if (RHSZExt == C0080Val) {
1799 if (XorRHS->getSExtValue() == CFF80Val)
1800 Found = true;
1801 }
1802 if (Found) {
1803 // This is a sign extend if the top bits are known zero.
Chris Lattner4534dd592006-02-09 07:38:58 +00001804 uint64_t Mask = ~0ULL;
Chris Lattnerc3ebf402006-02-07 07:27:52 +00001805 Mask <<= 64-(TySizeBits-Size);
Chris Lattner4534dd592006-02-09 07:38:58 +00001806 Mask &= XorLHS->getType()->getIntegralTypeMask();
Chris Lattnerc3ebf402006-02-07 07:27:52 +00001807 if (!MaskedValueIsZero(XorLHS, Mask))
Chris Lattner0b3557f2005-09-24 23:43:33 +00001808 Size = 0; // Not a sign ext, but can't be any others either.
1809 goto FoundSExt;
1810 }
1811 }
1812 Size >>= 1;
1813 C0080Val >>= Size;
1814 CFF80Val >>= Size;
1815 } while (Size >= 8);
1816
1817FoundSExt:
1818 const Type *MiddleType = 0;
1819 switch (Size) {
1820 default: break;
Reid Spencerc635f472006-12-31 05:48:39 +00001821 case 32: MiddleType = Type::Int32Ty; break;
1822 case 16: MiddleType = Type::Int16Ty; break;
1823 case 8: MiddleType = Type::Int8Ty; break;
Chris Lattner0b3557f2005-09-24 23:43:33 +00001824 }
1825 if (MiddleType) {
Reid Spencerbb65ebf2006-12-12 23:36:14 +00001826 Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
Chris Lattner0b3557f2005-09-24 23:43:33 +00001827 InsertNewInstBefore(NewTrunc, I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001828 return new SExtInst(NewTrunc, I.getType());
Chris Lattner0b3557f2005-09-24 23:43:33 +00001829 }
1830 }
Chris Lattnercf4a9962004-04-10 22:01:55 +00001831 }
Chris Lattner9fa53de2002-05-06 16:49:18 +00001832
Chris Lattnerb8b97502003-08-13 19:01:45 +00001833 // X + X --> X << 1
Robert Bocchino7b5b86c2004-07-27 21:02:21 +00001834 if (I.getType()->isInteger()) {
Chris Lattnerb8b97502003-08-13 19:01:45 +00001835 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Chris Lattner47060462005-04-07 17:14:51 +00001836
1837 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
1838 if (RHSI->getOpcode() == Instruction::Sub)
1839 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
1840 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
1841 }
1842 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
1843 if (LHSI->getOpcode() == Instruction::Sub)
1844 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
1845 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
1846 }
Robert Bocchino7b5b86c2004-07-27 21:02:21 +00001847 }
Chris Lattnerede3fe02003-08-13 04:18:28 +00001848
Chris Lattner147e9752002-05-08 22:46:53 +00001849 // -A + B --> B - A
Chris Lattnerbb74e222003-03-10 23:06:50 +00001850 if (Value *V = dyn_castNegVal(LHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001851 return BinaryOperator::createSub(RHS, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +00001852
1853 // A + -B --> A - B
Chris Lattnerbb74e222003-03-10 23:06:50 +00001854 if (!isa<Constant>(RHS))
1855 if (Value *V = dyn_castNegVal(RHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001856 return BinaryOperator::createSub(LHS, V);
Chris Lattner260ab202002-04-18 17:39:14 +00001857
Misha Brukmanb1c93172005-04-21 23:48:37 +00001858
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001859 ConstantInt *C2;
1860 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
1861 if (X == RHS) // X*C + X --> X * (C+1)
1862 return BinaryOperator::createMul(RHS, AddOne(C2));
1863
1864 // X*C1 + X*C2 --> X * (C1+C2)
1865 ConstantInt *C1;
1866 if (X == dyn_castFoldableMul(RHS, C1))
1867 return BinaryOperator::createMul(X, ConstantExpr::getAdd(C1, C2));
Chris Lattner57c8d992003-02-18 19:57:07 +00001868 }
1869
1870 // X + X*C --> X * (C+1)
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001871 if (dyn_castFoldableMul(RHS, C2) == LHS)
1872 return BinaryOperator::createMul(LHS, AddOne(C2));
1873
Chris Lattner57c8d992003-02-18 19:57:07 +00001874
Chris Lattnerb8b97502003-08-13 19:01:45 +00001875 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattnerd4252a72004-07-30 07:50:03 +00001876 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattnerb8b97502003-08-13 19:01:45 +00001877 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2))) return R;
Chris Lattner7fb29e12003-03-11 00:12:48 +00001878
Chris Lattnerb9cde762003-10-02 15:11:26 +00001879 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner330628a2006-01-06 17:59:59 +00001880 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00001881 if (match(LHS, m_Not(m_Value(X)))) { // ~X + C --> (C-1) - X
1882 Constant *C= ConstantExpr::getSub(CRHS, ConstantInt::get(I.getType(), 1));
1883 return BinaryOperator::createSub(C, X);
Chris Lattnerb9cde762003-10-02 15:11:26 +00001884 }
Chris Lattnerd4252a72004-07-30 07:50:03 +00001885
Chris Lattnerbff91d92004-10-08 05:07:56 +00001886 // (X & FF00) + xx00 -> (X+xx00) & FF00
1887 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
1888 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
1889 if (Anded == CRHS) {
1890 // See if all bits from the first bit set in the Add RHS up are included
1891 // in the mask. First, get the rightmost bit.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001892 uint64_t AddRHSV = CRHS->getZExtValue();
Chris Lattnerbff91d92004-10-08 05:07:56 +00001893
1894 // Form a mask of all bits from the lowest bit added through the top.
1895 uint64_t AddRHSHighBits = ~((AddRHSV & -AddRHSV)-1);
Chris Lattner77defba2006-02-07 07:00:41 +00001896 AddRHSHighBits &= C2->getType()->getIntegralTypeMask();
Chris Lattnerbff91d92004-10-08 05:07:56 +00001897
1898 // See if the and mask includes all of these bits.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001899 uint64_t AddRHSHighBitsAnd = AddRHSHighBits & C2->getZExtValue();
Misha Brukmanb1c93172005-04-21 23:48:37 +00001900
Chris Lattnerbff91d92004-10-08 05:07:56 +00001901 if (AddRHSHighBits == AddRHSHighBitsAnd) {
1902 // Okay, the xform is safe. Insert the new add pronto.
1903 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
1904 LHS->getName()), I);
1905 return BinaryOperator::createAnd(NewAdd, C2);
1906 }
1907 }
1908 }
1909
Chris Lattnerd4252a72004-07-30 07:50:03 +00001910 // Try to fold constant add into select arguments.
1911 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner86102b82005-01-01 16:22:27 +00001912 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattnerd4252a72004-07-30 07:50:03 +00001913 return R;
Chris Lattnerb9cde762003-10-02 15:11:26 +00001914 }
1915
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001916 // add (cast *A to intptrtype) B ->
1917 // cast (GEP (cast *A to sbyte*) B) ->
1918 // intptrtype
Andrew Lenharth4f339be2006-09-19 18:24:51 +00001919 {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001920 CastInst *CI = dyn_cast<CastInst>(LHS);
1921 Value *Other = RHS;
Andrew Lenharth4f339be2006-09-19 18:24:51 +00001922 if (!CI) {
1923 CI = dyn_cast<CastInst>(RHS);
1924 Other = LHS;
1925 }
Andrew Lenharth44cb67a2006-09-20 15:37:57 +00001926 if (CI && CI->getType()->isSized() &&
1927 (CI->getType()->getPrimitiveSize() ==
1928 TD->getIntPtrType()->getPrimitiveSize())
1929 && isa<PointerType>(CI->getOperand(0)->getType())) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00001930 Value *I2 = InsertCastBefore(Instruction::BitCast, CI->getOperand(0),
Reid Spencerc635f472006-12-31 05:48:39 +00001931 PointerType::get(Type::Int8Ty), I);
Andrew Lenharth44cb67a2006-09-20 15:37:57 +00001932 I2 = InsertNewInstBefore(new GetElementPtrInst(I2, Other, "ctg2"), I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001933 return new PtrToIntInst(I2, CI->getType());
Andrew Lenharth4f339be2006-09-19 18:24:51 +00001934 }
1935 }
1936
Chris Lattner113f4f42002-06-25 16:13:24 +00001937 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +00001938}
1939
Chris Lattnerbdb0ce02003-07-22 21:46:59 +00001940// isSignBit - Return true if the value represented by the constant only has the
1941// highest order bit set.
1942static bool isSignBit(ConstantInt *CI) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001943 unsigned NumBits = CI->getType()->getPrimitiveSizeInBits();
Reid Spencere0fc4df2006-10-20 07:07:24 +00001944 return (CI->getZExtValue() & (~0ULL >> (64-NumBits))) == (1ULL << (NumBits-1));
Chris Lattnerbdb0ce02003-07-22 21:46:59 +00001945}
1946
Chris Lattner022167f2004-03-13 00:11:49 +00001947/// RemoveNoopCast - Strip off nonconverting casts from the value.
1948///
1949static Value *RemoveNoopCast(Value *V) {
1950 if (CastInst *CI = dyn_cast<CastInst>(V)) {
1951 const Type *CTy = CI->getType();
1952 const Type *OpTy = CI->getOperand(0)->getType();
1953 if (CTy->isInteger() && OpTy->isInteger()) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001954 if (CTy->getPrimitiveSizeInBits() == OpTy->getPrimitiveSizeInBits())
Chris Lattner022167f2004-03-13 00:11:49 +00001955 return RemoveNoopCast(CI->getOperand(0));
1956 } else if (isa<PointerType>(CTy) && isa<PointerType>(OpTy))
1957 return RemoveNoopCast(CI->getOperand(0));
1958 }
1959 return V;
1960}
1961
Chris Lattner113f4f42002-06-25 16:13:24 +00001962Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +00001963 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001964
Chris Lattnere6794492002-08-12 21:17:25 +00001965 if (Op0 == Op1) // sub X, X -> 0
1966 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner260ab202002-04-18 17:39:14 +00001967
Chris Lattnere6794492002-08-12 21:17:25 +00001968 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattnerbb74e222003-03-10 23:06:50 +00001969 if (Value *V = dyn_castNegVal(Op1))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001970 return BinaryOperator::createAdd(Op0, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +00001971
Chris Lattner81a7a232004-10-16 18:11:37 +00001972 if (isa<UndefValue>(Op0))
1973 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
1974 if (isa<UndefValue>(Op1))
1975 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
1976
Chris Lattner8f2f5982003-11-05 01:06:05 +00001977 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
1978 // Replace (-1 - A) with (~A)...
Chris Lattner3082c5a2003-02-18 19:28:33 +00001979 if (C->isAllOnesValue())
1980 return BinaryOperator::createNot(Op1);
Chris Lattnerad3c4952002-05-09 01:29:19 +00001981
Chris Lattner8f2f5982003-11-05 01:06:05 +00001982 // C - ~X == X + (1+C)
Reid Spencer4fdd96c2005-06-18 17:37:34 +00001983 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00001984 if (match(Op1, m_Not(m_Value(X))))
1985 return BinaryOperator::createAdd(X,
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001986 ConstantExpr::getAdd(C, ConstantInt::get(I.getType(), 1)));
Chris Lattner92295c52004-03-12 23:53:13 +00001987 // -((uint)X >> 31) -> ((int)X >> 31)
1988 // -((int)X >> 31) -> ((uint)X >> 31)
Chris Lattner022167f2004-03-13 00:11:49 +00001989 if (C->isNullValue()) {
1990 Value *NoopCastedRHS = RemoveNoopCast(Op1);
1991 if (ShiftInst *SI = dyn_cast<ShiftInst>(NoopCastedRHS))
Reid Spencerfdff9382006-11-08 06:47:33 +00001992 if (SI->getOpcode() == Instruction::LShr) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00001993 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
Chris Lattner92295c52004-03-12 23:53:13 +00001994 // Check to see if we are shifting out everything but the sign bit.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001995 if (CU->getZExtValue() ==
1996 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerfdff9382006-11-08 06:47:33 +00001997 // Ok, the transformation is safe. Insert AShr.
Reid Spencer193df252006-12-24 00:40:59 +00001998 // FIXME: Once integer types are signless, this cast should be
1999 // removed.
2000 Value *ShiftOp = SI->getOperand(0);
2001 if (ShiftOp->getType() != I.getType())
2002 ShiftOp = InsertCastBefore(Instruction::BitCast, ShiftOp,
2003 I.getType(), I);
2004 return new ShiftInst(Instruction::AShr, ShiftOp, CU,
2005 SI->getName());
Chris Lattner92295c52004-03-12 23:53:13 +00002006 }
2007 }
Reid Spencerfdff9382006-11-08 06:47:33 +00002008 }
2009 else if (SI->getOpcode() == Instruction::AShr) {
2010 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2011 // Check to see if we are shifting out everything but the sign bit.
2012 if (CU->getZExtValue() ==
2013 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerc635f472006-12-31 05:48:39 +00002014
2015 // Ok, the transformation is safe. Insert LShr.
2016 return new ShiftInst(Instruction::LShr, SI->getOperand(0), CU,
2017 SI->getName());
Reid Spencerfdff9382006-11-08 06:47:33 +00002018 }
2019 }
2020 }
Chris Lattner022167f2004-03-13 00:11:49 +00002021 }
Chris Lattner183b3362004-04-09 19:05:30 +00002022
2023 // Try to fold constant sub into select arguments.
2024 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner86102b82005-01-01 16:22:27 +00002025 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00002026 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002027
2028 if (isa<PHINode>(Op0))
2029 if (Instruction *NV = FoldOpIntoPhi(I))
2030 return NV;
Chris Lattner8f2f5982003-11-05 01:06:05 +00002031 }
2032
Chris Lattnera9be4492005-04-07 16:15:25 +00002033 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2034 if (Op1I->getOpcode() == Instruction::Add &&
Chris Lattner7a002fe2006-12-02 00:13:08 +00002035 !Op0->getType()->isFPOrFPVector()) {
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00002036 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Chris Lattnera9be4492005-04-07 16:15:25 +00002037 return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00002038 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Chris Lattnera9be4492005-04-07 16:15:25 +00002039 return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00002040 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2041 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2042 // C1-(X+C2) --> (C1-C2)-X
2043 return BinaryOperator::createSub(ConstantExpr::getSub(CI1, CI2),
2044 Op1I->getOperand(0));
2045 }
Chris Lattnera9be4492005-04-07 16:15:25 +00002046 }
2047
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002048 if (Op1I->hasOneUse()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00002049 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2050 // is not used by anyone else...
2051 //
Chris Lattnerc2f0aa52004-02-02 20:09:56 +00002052 if (Op1I->getOpcode() == Instruction::Sub &&
Chris Lattner7a002fe2006-12-02 00:13:08 +00002053 !Op1I->getType()->isFPOrFPVector()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00002054 // Swap the two operands of the subexpr...
2055 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2056 Op1I->setOperand(0, IIOp1);
2057 Op1I->setOperand(1, IIOp0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002058
Chris Lattner3082c5a2003-02-18 19:28:33 +00002059 // Create the new top level add instruction...
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002060 return BinaryOperator::createAdd(Op0, Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002061 }
2062
2063 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2064 //
2065 if (Op1I->getOpcode() == Instruction::And &&
2066 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2067 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2068
Chris Lattner396dbfe2004-06-09 05:08:07 +00002069 Value *NewNot =
2070 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002071 return BinaryOperator::createAnd(Op0, NewNot);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002072 }
Chris Lattner57c8d992003-02-18 19:57:07 +00002073
Reid Spencer3c514952006-10-16 23:08:08 +00002074 // 0 - (X sdiv C) -> (X sdiv -C)
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002075 if (Op1I->getOpcode() == Instruction::SDiv)
Reid Spencere0fc4df2006-10-20 07:07:24 +00002076 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002077 if (CSI->isNullValue())
Chris Lattner0aee4b72004-10-06 15:08:25 +00002078 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002079 return BinaryOperator::createSDiv(Op1I->getOperand(0),
Chris Lattner0aee4b72004-10-06 15:08:25 +00002080 ConstantExpr::getNeg(DivRHS));
2081
Chris Lattner57c8d992003-02-18 19:57:07 +00002082 // X - X*C --> X * (1-C)
Reid Spencer4fdd96c2005-06-18 17:37:34 +00002083 ConstantInt *C2 = 0;
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002084 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00002085 Constant *CP1 =
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002086 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1), C2);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002087 return BinaryOperator::createMul(Op0, CP1);
Chris Lattner57c8d992003-02-18 19:57:07 +00002088 }
Chris Lattnerad3c4952002-05-09 01:29:19 +00002089 }
Chris Lattnera9be4492005-04-07 16:15:25 +00002090 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00002091
Chris Lattner7a002fe2006-12-02 00:13:08 +00002092 if (!Op0->getType()->isFPOrFPVector())
Chris Lattner47060462005-04-07 17:14:51 +00002093 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2094 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner411336f2005-01-19 21:50:18 +00002095 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2096 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2097 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2098 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner47060462005-04-07 17:14:51 +00002099 } else if (Op0I->getOpcode() == Instruction::Sub) {
2100 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
2101 return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
Chris Lattner411336f2005-01-19 21:50:18 +00002102 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002103
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002104 ConstantInt *C1;
2105 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2106 if (X == Op1) { // X*C - X --> X * (C-1)
2107 Constant *CP1 = ConstantExpr::getSub(C1, ConstantInt::get(I.getType(),1));
2108 return BinaryOperator::createMul(Op1, CP1);
2109 }
Chris Lattner57c8d992003-02-18 19:57:07 +00002110
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002111 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
2112 if (X == dyn_castFoldableMul(Op1, C2))
2113 return BinaryOperator::createMul(Op1, ConstantExpr::getSub(C1, C2));
2114 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002115 return 0;
Chris Lattner260ab202002-04-18 17:39:14 +00002116}
2117
Reid Spencer266e42b2006-12-23 06:05:41 +00002118/// isSignBitCheck - Given an exploded icmp instruction, return true if it
Chris Lattnere79e8542004-02-23 06:38:22 +00002119/// really just returns true if the most significant (sign) bit is set.
Reid Spencer266e42b2006-12-23 06:05:41 +00002120static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS) {
2121 switch (pred) {
2122 case ICmpInst::ICMP_SLT:
2123 // True if LHS s< RHS and RHS == 0
2124 return RHS->isNullValue();
2125 case ICmpInst::ICMP_SLE:
2126 // True if LHS s<= RHS and RHS == -1
2127 return RHS->isAllOnesValue();
2128 case ICmpInst::ICMP_UGE:
2129 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2130 return RHS->getZExtValue() == (1ULL <<
2131 (RHS->getType()->getPrimitiveSizeInBits()-1));
2132 case ICmpInst::ICMP_UGT:
2133 // True if LHS u> RHS and RHS == high-bit-mask - 1
2134 return RHS->getZExtValue() ==
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002135 (1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1))-1;
Reid Spencer266e42b2006-12-23 06:05:41 +00002136 default:
2137 return false;
Chris Lattnere79e8542004-02-23 06:38:22 +00002138 }
Chris Lattnere79e8542004-02-23 06:38:22 +00002139}
2140
Chris Lattner113f4f42002-06-25 16:13:24 +00002141Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00002142 bool Changed = SimplifyCommutative(I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002143 Value *Op0 = I.getOperand(0);
Chris Lattner260ab202002-04-18 17:39:14 +00002144
Chris Lattner81a7a232004-10-16 18:11:37 +00002145 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
2146 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2147
Chris Lattnere6794492002-08-12 21:17:25 +00002148 // Simplify mul instructions with a constant RHS...
Chris Lattner3082c5a2003-02-18 19:28:33 +00002149 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2150 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerede3fe02003-08-13 04:18:28 +00002151
2152 // ((X << C1)*C2) == (X * (C2 << C1))
2153 if (ShiftInst *SI = dyn_cast<ShiftInst>(Op0))
2154 if (SI->getOpcode() == Instruction::Shl)
2155 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002156 return BinaryOperator::createMul(SI->getOperand(0),
2157 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanb1c93172005-04-21 23:48:37 +00002158
Chris Lattnercce81be2003-09-11 22:24:54 +00002159 if (CI->isNullValue())
2160 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2161 if (CI->equalsInt(1)) // X * 1 == X
2162 return ReplaceInstUsesWith(I, Op0);
2163 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Chris Lattner35236d82003-06-25 17:09:20 +00002164 return BinaryOperator::createNeg(Op0, I.getName());
Chris Lattner31ba1292002-04-29 22:24:47 +00002165
Reid Spencere0fc4df2006-10-20 07:07:24 +00002166 int64_t Val = (int64_t)cast<ConstantInt>(CI)->getZExtValue();
Chris Lattner22d00a82005-08-02 19:16:58 +00002167 if (isPowerOf2_64(Val)) { // Replace X*(2^C) with X << C
2168 uint64_t C = Log2_64(Val);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002169 return new ShiftInst(Instruction::Shl, Op0,
Reid Spencerc635f472006-12-31 05:48:39 +00002170 ConstantInt::get(Type::Int8Ty, C));
Chris Lattner22d00a82005-08-02 19:16:58 +00002171 }
Robert Bocchino7b5b86c2004-07-27 21:02:21 +00002172 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00002173 if (Op1F->isNullValue())
2174 return ReplaceInstUsesWith(I, Op1);
Chris Lattner31ba1292002-04-29 22:24:47 +00002175
Chris Lattner3082c5a2003-02-18 19:28:33 +00002176 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2177 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2178 if (Op1F->getValue() == 1.0)
2179 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
2180 }
Chris Lattner32c01df2006-03-04 06:04:02 +00002181
2182 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2183 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2184 isa<ConstantInt>(Op0I->getOperand(1))) {
2185 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2186 Instruction *Add = BinaryOperator::createMul(Op0I->getOperand(0),
2187 Op1, "tmp");
2188 InsertNewInstBefore(Add, I);
2189 Value *C1C2 = ConstantExpr::getMul(Op1,
2190 cast<Constant>(Op0I->getOperand(1)));
2191 return BinaryOperator::createAdd(Add, C1C2);
2192
2193 }
Chris Lattner183b3362004-04-09 19:05:30 +00002194
2195 // Try to fold constant mul into select arguments.
2196 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00002197 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00002198 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002199
2200 if (isa<PHINode>(Op0))
2201 if (Instruction *NV = FoldOpIntoPhi(I))
2202 return NV;
Chris Lattner260ab202002-04-18 17:39:14 +00002203 }
2204
Chris Lattner934a64cf2003-03-10 23:23:04 +00002205 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
2206 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002207 return BinaryOperator::createMul(Op0v, Op1v);
Chris Lattner934a64cf2003-03-10 23:23:04 +00002208
Chris Lattner2635b522004-02-23 05:39:21 +00002209 // If one of the operands of the multiply is a cast from a boolean value, then
2210 // we know the bool is either zero or one, so this is a 'masking' multiply.
2211 // See if we can simplify things based on how the boolean was originally
2212 // formed.
2213 CastInst *BoolCast = 0;
Reid Spencer74a528b2006-12-13 18:21:21 +00002214 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(0)))
2215 if (CI->getOperand(0)->getType() == Type::BoolTy)
Chris Lattner2635b522004-02-23 05:39:21 +00002216 BoolCast = CI;
2217 if (!BoolCast)
Reid Spencer74a528b2006-12-13 18:21:21 +00002218 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
2219 if (CI->getOperand(0)->getType() == Type::BoolTy)
Chris Lattner2635b522004-02-23 05:39:21 +00002220 BoolCast = CI;
2221 if (BoolCast) {
Reid Spencer266e42b2006-12-23 06:05:41 +00002222 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
Chris Lattner2635b522004-02-23 05:39:21 +00002223 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2224 const Type *SCOpTy = SCIOp0->getType();
2225
Reid Spencer266e42b2006-12-23 06:05:41 +00002226 // If the icmp is true iff the sign bit of X is set, then convert this
Chris Lattnere79e8542004-02-23 06:38:22 +00002227 // multiply into a shift/and combination.
2228 if (isa<ConstantInt>(SCIOp1) &&
Reid Spencer266e42b2006-12-23 06:05:41 +00002229 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1))) {
Chris Lattner2635b522004-02-23 05:39:21 +00002230 // Shift the X value right to turn it into "all signbits".
Reid Spencerc635f472006-12-31 05:48:39 +00002231 Constant *Amt = ConstantInt::get(Type::Int8Ty,
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002232 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattnere79e8542004-02-23 06:38:22 +00002233 Value *V =
Reid Spencerfdff9382006-11-08 06:47:33 +00002234 InsertNewInstBefore(new ShiftInst(Instruction::AShr, SCIOp0, Amt,
Chris Lattnere79e8542004-02-23 06:38:22 +00002235 BoolCast->getOperand(0)->getName()+
2236 ".mask"), I);
Chris Lattner2635b522004-02-23 05:39:21 +00002237
2238 // If the multiply type is not the same as the source type, sign extend
2239 // or truncate to the multiply type.
Reid Spencer13bc5d72006-12-12 09:18:51 +00002240 if (I.getType() != V->getType()) {
2241 unsigned SrcBits = V->getType()->getPrimitiveSizeInBits();
2242 unsigned DstBits = I.getType()->getPrimitiveSizeInBits();
2243 Instruction::CastOps opcode =
2244 (SrcBits == DstBits ? Instruction::BitCast :
2245 (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2246 V = InsertCastBefore(opcode, V, I.getType(), I);
2247 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002248
Chris Lattner2635b522004-02-23 05:39:21 +00002249 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002250 return BinaryOperator::createAnd(V, OtherOp);
Chris Lattner2635b522004-02-23 05:39:21 +00002251 }
2252 }
2253 }
2254
Chris Lattner113f4f42002-06-25 16:13:24 +00002255 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +00002256}
2257
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002258/// This function implements the transforms on div instructions that work
2259/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2260/// used by the visitors to those instructions.
2261/// @brief Transforms common to all three div instructions
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002262Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002263 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner81a7a232004-10-16 18:11:37 +00002264
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002265 // undef / X -> 0
2266 if (isa<UndefValue>(Op0))
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002267 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002268
2269 // X / undef -> undef
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002270 if (isa<UndefValue>(Op1))
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002271 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002272
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002273 // Handle cases involving: div X, (select Cond, Y, Z)
Chris Lattnerd79dc792006-09-09 20:26:32 +00002274 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2275 // div X, (Cond ? 0 : Y) -> div X, Y. If the div and the select are in the
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002276 // same basic block, then we replace the select with Y, and the condition
2277 // of the select with false (if the cond value is in the same BB). If the
Chris Lattnerd79dc792006-09-09 20:26:32 +00002278 // select has uses other than the div, this allows them to be simplified
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002279 // also. Note that div X, Y is just as good as div X, 0 (undef)
Chris Lattnerd79dc792006-09-09 20:26:32 +00002280 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2281 if (ST->isNullValue()) {
2282 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2283 if (CondI && CondI->getParent() == I.getParent())
Chris Lattner6ab03f62006-09-28 23:35:22 +00002284 UpdateValueUsesWith(CondI, ConstantBool::getFalse());
Chris Lattnerd79dc792006-09-09 20:26:32 +00002285 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2286 I.setOperand(1, SI->getOperand(2));
2287 else
2288 UpdateValueUsesWith(SI, SI->getOperand(2));
2289 return &I;
2290 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002291
Chris Lattnerd79dc792006-09-09 20:26:32 +00002292 // Likewise for: div X, (Cond ? Y : 0) -> div X, Y
2293 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2294 if (ST->isNullValue()) {
2295 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2296 if (CondI && CondI->getParent() == I.getParent())
Chris Lattner6ab03f62006-09-28 23:35:22 +00002297 UpdateValueUsesWith(CondI, ConstantBool::getTrue());
Chris Lattnerd79dc792006-09-09 20:26:32 +00002298 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2299 I.setOperand(1, SI->getOperand(1));
2300 else
2301 UpdateValueUsesWith(SI, SI->getOperand(1));
2302 return &I;
2303 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002304 }
Chris Lattnerd79dc792006-09-09 20:26:32 +00002305
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002306 return 0;
2307}
Misha Brukmanb1c93172005-04-21 23:48:37 +00002308
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002309/// This function implements the transforms common to both integer division
2310/// instructions (udiv and sdiv). It is called by the visitors to those integer
2311/// division instructions.
2312/// @brief Common integer divide transforms
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002313Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002314 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2315
2316 if (Instruction *Common = commonDivTransforms(I))
2317 return Common;
2318
2319 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2320 // div X, 1 == X
2321 if (RHS->equalsInt(1))
2322 return ReplaceInstUsesWith(I, Op0);
2323
2324 // (X / C1) / C2 -> X / (C1*C2)
2325 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2326 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2327 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
2328 return BinaryOperator::create(I.getOpcode(), LHS->getOperand(0),
2329 ConstantExpr::getMul(RHS, LHSRHS));
Chris Lattner42362612005-04-08 04:03:26 +00002330 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002331
2332 if (!RHS->isNullValue()) { // avoid X udiv 0
2333 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2334 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2335 return R;
2336 if (isa<PHINode>(Op0))
2337 if (Instruction *NV = FoldOpIntoPhi(I))
2338 return NV;
2339 }
Chris Lattnerd79dc792006-09-09 20:26:32 +00002340 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002341
Chris Lattner3082c5a2003-02-18 19:28:33 +00002342 // 0 / X == 0, we don't need to preserve faults!
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002343 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattner3082c5a2003-02-18 19:28:33 +00002344 if (LHS->equalsInt(0))
2345 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2346
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002347 return 0;
2348}
2349
2350Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2351 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2352
2353 // Handle the integer div common cases
2354 if (Instruction *Common = commonIDivTransforms(I))
2355 return Common;
2356
2357 // X udiv C^2 -> X >> C
2358 // Check to see if this is an unsigned division with an exact power of 2,
2359 // if so, convert to a right shift.
2360 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
2361 if (uint64_t Val = C->getZExtValue()) // Don't break X / 0
2362 if (isPowerOf2_64(Val)) {
2363 uint64_t ShiftAmt = Log2_64(Val);
Reid Spencerfdff9382006-11-08 06:47:33 +00002364 return new ShiftInst(Instruction::LShr, Op0,
Reid Spencerc635f472006-12-31 05:48:39 +00002365 ConstantInt::get(Type::Int8Ty, ShiftAmt));
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002366 }
2367 }
2368
2369 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
2370 if (ShiftInst *RHSI = dyn_cast<ShiftInst>(I.getOperand(1))) {
2371 if (RHSI->getOpcode() == Instruction::Shl &&
2372 isa<ConstantInt>(RHSI->getOperand(0))) {
2373 uint64_t C1 = cast<ConstantInt>(RHSI->getOperand(0))->getZExtValue();
2374 if (isPowerOf2_64(C1)) {
2375 Value *N = RHSI->getOperand(1);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002376 const Type *NTy = N->getType();
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002377 if (uint64_t C2 = Log2_64(C1)) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002378 Constant *C2V = ConstantInt::get(NTy, C2);
2379 N = InsertNewInstBefore(BinaryOperator::createAdd(N, C2V, "tmp"), I);
Chris Lattner2e90b732006-02-05 07:54:04 +00002380 }
Reid Spencerfdff9382006-11-08 06:47:33 +00002381 return new ShiftInst(Instruction::LShr, Op0, N);
Chris Lattner2e90b732006-02-05 07:54:04 +00002382 }
2383 }
Chris Lattnerdd0c1742005-11-05 07:40:31 +00002384 }
2385
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002386 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
2387 // where C1&C2 are powers of two.
2388 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2389 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2390 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2)))
2391 if (!STO->isNullValue() && !STO->isNullValue()) {
2392 uint64_t TVA = STO->getZExtValue(), FVA = SFO->getZExtValue();
2393 if (isPowerOf2_64(TVA) && isPowerOf2_64(FVA)) {
2394 // Compute the shift amounts
2395 unsigned TSA = Log2_64(TVA), FSA = Log2_64(FVA);
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002396 // Construct the "on true" case of the select
Reid Spencerc635f472006-12-31 05:48:39 +00002397 Constant *TC = ConstantInt::get(Type::Int8Ty, TSA);
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002398 Instruction *TSI =
Reid Spencerfdff9382006-11-08 06:47:33 +00002399 new ShiftInst(Instruction::LShr, Op0, TC, SI->getName()+".t");
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002400 TSI = InsertNewInstBefore(TSI, I);
2401
2402 // Construct the "on false" case of the select
Reid Spencerc635f472006-12-31 05:48:39 +00002403 Constant *FC = ConstantInt::get(Type::Int8Ty, FSA);
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002404 Instruction *FSI =
Reid Spencerfdff9382006-11-08 06:47:33 +00002405 new ShiftInst(Instruction::LShr, Op0, FC, SI->getName()+".f");
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002406 FSI = InsertNewInstBefore(FSI, I);
2407
2408 // construct the select instruction and return it.
Reid Spencerfdff9382006-11-08 06:47:33 +00002409 return new SelectInst(SI->getOperand(0), TSI, FSI, SI->getName());
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002410 }
2411 }
2412 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002413 return 0;
2414}
2415
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002416Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
2417 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2418
2419 // Handle the integer div common cases
2420 if (Instruction *Common = commonIDivTransforms(I))
2421 return Common;
2422
2423 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2424 // sdiv X, -1 == -X
2425 if (RHS->isAllOnesValue())
2426 return BinaryOperator::createNeg(Op0);
2427
2428 // -X/C -> X/-C
2429 if (Value *LHSNeg = dyn_castNegVal(Op0))
2430 return BinaryOperator::createSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
2431 }
2432
2433 // If the sign bits of both operands are zero (i.e. we can prove they are
2434 // unsigned inputs), turn this into a udiv.
2435 if (I.getType()->isInteger()) {
2436 uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
2437 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2438 return BinaryOperator::createUDiv(Op0, Op1, I.getName());
2439 }
2440 }
2441
2442 return 0;
2443}
2444
2445Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
2446 return commonDivTransforms(I);
2447}
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002448
Chris Lattner85dda9a2006-03-02 06:50:58 +00002449/// GetFactor - If we can prove that the specified value is at least a multiple
2450/// of some factor, return that factor.
2451static Constant *GetFactor(Value *V) {
2452 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
2453 return CI;
2454
2455 // Unless we can be tricky, we know this is a multiple of 1.
2456 Constant *Result = ConstantInt::get(V->getType(), 1);
2457
2458 Instruction *I = dyn_cast<Instruction>(V);
2459 if (!I) return Result;
2460
2461 if (I->getOpcode() == Instruction::Mul) {
2462 // Handle multiplies by a constant, etc.
2463 return ConstantExpr::getMul(GetFactor(I->getOperand(0)),
2464 GetFactor(I->getOperand(1)));
2465 } else if (I->getOpcode() == Instruction::Shl) {
2466 // (X<<C) -> X * (1 << C)
2467 if (Constant *ShRHS = dyn_cast<Constant>(I->getOperand(1))) {
2468 ShRHS = ConstantExpr::getShl(Result, ShRHS);
2469 return ConstantExpr::getMul(GetFactor(I->getOperand(0)), ShRHS);
2470 }
2471 } else if (I->getOpcode() == Instruction::And) {
2472 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
2473 // X & 0xFFF0 is known to be a multiple of 16.
2474 unsigned Zeros = CountTrailingZeros_64(RHS->getZExtValue());
2475 if (Zeros != V->getType()->getPrimitiveSizeInBits())
2476 return ConstantExpr::getShl(Result,
Reid Spencerc635f472006-12-31 05:48:39 +00002477 ConstantInt::get(Type::Int8Ty, Zeros));
Chris Lattner85dda9a2006-03-02 06:50:58 +00002478 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002479 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
Chris Lattner85dda9a2006-03-02 06:50:58 +00002480 // Only handle int->int casts.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002481 if (!CI->isIntegerCast())
2482 return Result;
2483 Value *Op = CI->getOperand(0);
2484 return ConstantExpr::getCast(CI->getOpcode(), GetFactor(Op), V->getType());
Chris Lattner85dda9a2006-03-02 06:50:58 +00002485 }
2486 return Result;
2487}
2488
Reid Spencer7eb55b32006-11-02 01:53:59 +00002489/// This function implements the transforms on rem instructions that work
2490/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
2491/// is used by the visitors to those instructions.
2492/// @brief Transforms common to all three rem instructions
2493Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002494 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Reid Spencer7eb55b32006-11-02 01:53:59 +00002495
Chris Lattner0de4a8d2006-02-28 05:30:45 +00002496 // 0 % X == 0, we don't need to preserve faults!
2497 if (Constant *LHS = dyn_cast<Constant>(Op0))
2498 if (LHS->isNullValue())
2499 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2500
2501 if (isa<UndefValue>(Op0)) // undef % X -> 0
2502 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2503 if (isa<UndefValue>(Op1))
2504 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Reid Spencer7eb55b32006-11-02 01:53:59 +00002505
2506 // Handle cases involving: rem X, (select Cond, Y, Z)
2507 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2508 // rem X, (Cond ? 0 : Y) -> rem X, Y. If the rem and the select are in
2509 // the same basic block, then we replace the select with Y, and the
2510 // condition of the select with false (if the cond value is in the same
2511 // BB). If the select has uses other than the div, this allows them to be
2512 // simplified also.
2513 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2514 if (ST->isNullValue()) {
2515 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2516 if (CondI && CondI->getParent() == I.getParent())
2517 UpdateValueUsesWith(CondI, ConstantBool::getFalse());
2518 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2519 I.setOperand(1, SI->getOperand(2));
2520 else
2521 UpdateValueUsesWith(SI, SI->getOperand(2));
Chris Lattner7fd5f072004-07-06 07:01:22 +00002522 return &I;
2523 }
Reid Spencer7eb55b32006-11-02 01:53:59 +00002524 // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
2525 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2526 if (ST->isNullValue()) {
2527 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2528 if (CondI && CondI->getParent() == I.getParent())
2529 UpdateValueUsesWith(CondI, ConstantBool::getTrue());
2530 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2531 I.setOperand(1, SI->getOperand(1));
2532 else
2533 UpdateValueUsesWith(SI, SI->getOperand(1));
2534 return &I;
2535 }
Chris Lattnere9ff0ea2005-11-05 07:28:37 +00002536 }
Chris Lattner7fd5f072004-07-06 07:01:22 +00002537
Reid Spencer7eb55b32006-11-02 01:53:59 +00002538 return 0;
2539}
2540
2541/// This function implements the transforms common to both integer remainder
2542/// instructions (urem and srem). It is called by the visitors to those integer
2543/// remainder instructions.
2544/// @brief Common integer remainder transforms
2545Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
2546 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2547
2548 if (Instruction *common = commonRemTransforms(I))
2549 return common;
2550
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002551 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner0de4a8d2006-02-28 05:30:45 +00002552 // X % 0 == undef, we don't need to preserve faults!
2553 if (RHS->equalsInt(0))
2554 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2555
Chris Lattner3082c5a2003-02-18 19:28:33 +00002556 if (RHS->equalsInt(1)) // X % 1 == 0
2557 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2558
Chris Lattnerb70f1412006-02-28 05:49:21 +00002559 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2560 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2561 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2562 return R;
2563 } else if (isa<PHINode>(Op0I)) {
2564 if (Instruction *NV = FoldOpIntoPhi(I))
2565 return NV;
Chris Lattnerb70f1412006-02-28 05:49:21 +00002566 }
Reid Spencer7eb55b32006-11-02 01:53:59 +00002567 // (X * C1) % C2 --> 0 iff C1 % C2 == 0
2568 if (ConstantExpr::getSRem(GetFactor(Op0I), RHS)->isNullValue())
Chris Lattner85dda9a2006-03-02 06:50:58 +00002569 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerb70f1412006-02-28 05:49:21 +00002570 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00002571 }
2572
Reid Spencer7eb55b32006-11-02 01:53:59 +00002573 return 0;
2574}
2575
2576Instruction *InstCombiner::visitURem(BinaryOperator &I) {
2577 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2578
2579 if (Instruction *common = commonIRemTransforms(I))
2580 return common;
2581
2582 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2583 // X urem C^2 -> X and C
2584 // Check to see if this is an unsigned remainder with an exact power of 2,
2585 // if so, convert to a bitwise and.
2586 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
2587 if (isPowerOf2_64(C->getZExtValue()))
2588 return BinaryOperator::createAnd(Op0, SubOne(C));
2589 }
2590
Chris Lattner2e90b732006-02-05 07:54:04 +00002591 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00002592 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
2593 if (RHSI->getOpcode() == Instruction::Shl &&
2594 isa<ConstantInt>(RHSI->getOperand(0))) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002595 unsigned C1 = cast<ConstantInt>(RHSI->getOperand(0))->getZExtValue();
Chris Lattner2e90b732006-02-05 07:54:04 +00002596 if (isPowerOf2_64(C1)) {
2597 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
2598 Value *Add = InsertNewInstBefore(BinaryOperator::createAdd(RHSI, N1,
2599 "tmp"), I);
2600 return BinaryOperator::createAnd(Op0, Add);
2601 }
2602 }
Reid Spencer7eb55b32006-11-02 01:53:59 +00002603 }
Chris Lattnerd79dc792006-09-09 20:26:32 +00002604
Reid Spencer7eb55b32006-11-02 01:53:59 +00002605 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
2606 // where C1&C2 are powers of two.
2607 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2608 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2609 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
2610 // STO == 0 and SFO == 0 handled above.
2611 if (isPowerOf2_64(STO->getZExtValue()) &&
2612 isPowerOf2_64(SFO->getZExtValue())) {
2613 Value *TrueAnd = InsertNewInstBefore(
2614 BinaryOperator::createAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
2615 Value *FalseAnd = InsertNewInstBefore(
2616 BinaryOperator::createAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
2617 return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
2618 }
2619 }
Chris Lattner2e90b732006-02-05 07:54:04 +00002620 }
2621
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002622 return 0;
2623}
2624
Reid Spencer7eb55b32006-11-02 01:53:59 +00002625Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
2626 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2627
2628 if (Instruction *common = commonIRemTransforms(I))
2629 return common;
2630
2631 if (Value *RHSNeg = dyn_castNegVal(Op1))
2632 if (!isa<ConstantInt>(RHSNeg) ||
2633 cast<ConstantInt>(RHSNeg)->getSExtValue() > 0) {
2634 // X % -Y -> X % Y
2635 AddUsesToWorkList(I);
2636 I.setOperand(1, RHSNeg);
2637 return &I;
2638 }
2639
2640 // If the top bits of both operands are zero (i.e. we can prove they are
2641 // unsigned inputs), turn this into a urem.
2642 uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
2643 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2644 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
2645 return BinaryOperator::createURem(Op0, Op1, I.getName());
2646 }
2647
2648 return 0;
2649}
2650
2651Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00002652 return commonRemTransforms(I);
2653}
2654
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002655// isMaxValueMinusOne - return true if this is Max-1
Reid Spencer266e42b2006-12-23 06:05:41 +00002656static bool isMaxValueMinusOne(const ConstantInt *C, bool isSigned) {
2657 if (isSigned) {
2658 // Calculate 0111111111..11111
2659 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
2660 int64_t Val = INT64_MAX; // All ones
2661 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
2662 return C->getSExtValue() == Val-1;
2663 }
2664 return C->getZExtValue() == C->getType()->getIntegralTypeMask()-1;
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002665}
2666
2667// isMinValuePlusOne - return true if this is Min+1
Reid Spencer266e42b2006-12-23 06:05:41 +00002668static bool isMinValuePlusOne(const ConstantInt *C, bool isSigned) {
2669 if (isSigned) {
2670 // Calculate 1111111111000000000000
2671 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
2672 int64_t Val = -1; // All ones
2673 Val <<= TypeBits-1; // Shift over to the right spot
2674 return C->getSExtValue() == Val+1;
2675 }
2676 return C->getZExtValue() == 1; // unsigned
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002677}
2678
Chris Lattner35167c32004-06-09 07:59:58 +00002679// isOneBitSet - Return true if there is exactly one bit set in the specified
2680// constant.
2681static bool isOneBitSet(const ConstantInt *CI) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002682 uint64_t V = CI->getZExtValue();
Chris Lattner35167c32004-06-09 07:59:58 +00002683 return V && (V & (V-1)) == 0;
2684}
2685
Chris Lattner8fc5af42004-09-23 21:46:38 +00002686#if 0 // Currently unused
2687// isLowOnes - Return true if the constant is of the form 0+1+.
2688static bool isLowOnes(const ConstantInt *CI) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002689 uint64_t V = CI->getZExtValue();
Chris Lattner8fc5af42004-09-23 21:46:38 +00002690
2691 // There won't be bits set in parts that the type doesn't contain.
Reid Spencere0fc4df2006-10-20 07:07:24 +00002692 V &= ConstantInt::getAllOnesValue(CI->getType())->getZExtValue();
Chris Lattner8fc5af42004-09-23 21:46:38 +00002693
2694 uint64_t U = V+1; // If it is low ones, this should be a power of two.
2695 return U && V && (U & V) == 0;
2696}
2697#endif
2698
2699// isHighOnes - Return true if the constant is of the form 1+0+.
2700// This is the same as lowones(~X).
2701static bool isHighOnes(const ConstantInt *CI) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002702 uint64_t V = ~CI->getZExtValue();
Chris Lattner2c14cf72005-08-07 07:03:10 +00002703 if (~V == 0) return false; // 0's does not match "1+"
Chris Lattner8fc5af42004-09-23 21:46:38 +00002704
2705 // There won't be bits set in parts that the type doesn't contain.
Reid Spencere0fc4df2006-10-20 07:07:24 +00002706 V &= ConstantInt::getAllOnesValue(CI->getType())->getZExtValue();
Chris Lattner8fc5af42004-09-23 21:46:38 +00002707
2708 uint64_t U = V+1; // If it is low ones, this should be a power of two.
2709 return U && V && (U & V) == 0;
2710}
2711
Reid Spencer266e42b2006-12-23 06:05:41 +00002712/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
Chris Lattner3ac7c262003-08-13 20:16:26 +00002713/// are carefully arranged to allow folding of expressions such as:
2714///
2715/// (A < B) | (A > B) --> (A != B)
2716///
Reid Spencer266e42b2006-12-23 06:05:41 +00002717/// Note that this is only valid if the first and second predicates have the
2718/// same sign. Is illegal to do: (A u< B) | (A s> B)
Chris Lattner3ac7c262003-08-13 20:16:26 +00002719///
Reid Spencer266e42b2006-12-23 06:05:41 +00002720/// Three bits are used to represent the condition, as follows:
2721/// 0 A > B
2722/// 1 A == B
2723/// 2 A < B
2724///
2725/// <=> Value Definition
2726/// 000 0 Always false
2727/// 001 1 A > B
2728/// 010 2 A == B
2729/// 011 3 A >= B
2730/// 100 4 A < B
2731/// 101 5 A != B
2732/// 110 6 A <= B
2733/// 111 7 Always true
2734///
2735static unsigned getICmpCode(const ICmpInst *ICI) {
2736 switch (ICI->getPredicate()) {
Chris Lattner3ac7c262003-08-13 20:16:26 +00002737 // False -> 0
Reid Spencer266e42b2006-12-23 06:05:41 +00002738 case ICmpInst::ICMP_UGT: return 1; // 001
2739 case ICmpInst::ICMP_SGT: return 1; // 001
2740 case ICmpInst::ICMP_EQ: return 2; // 010
2741 case ICmpInst::ICMP_UGE: return 3; // 011
2742 case ICmpInst::ICMP_SGE: return 3; // 011
2743 case ICmpInst::ICMP_ULT: return 4; // 100
2744 case ICmpInst::ICMP_SLT: return 4; // 100
2745 case ICmpInst::ICMP_NE: return 5; // 101
2746 case ICmpInst::ICMP_ULE: return 6; // 110
2747 case ICmpInst::ICMP_SLE: return 6; // 110
Chris Lattner3ac7c262003-08-13 20:16:26 +00002748 // True -> 7
2749 default:
Reid Spencer266e42b2006-12-23 06:05:41 +00002750 assert(0 && "Invalid ICmp predicate!");
Chris Lattner3ac7c262003-08-13 20:16:26 +00002751 return 0;
2752 }
2753}
2754
Reid Spencer266e42b2006-12-23 06:05:41 +00002755/// getICmpValue - This is the complement of getICmpCode, which turns an
2756/// opcode and two operands into either a constant true or false, or a brand
2757/// new /// ICmp instruction. The sign is passed in to determine which kind
2758/// of predicate to use in new icmp instructions.
2759static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
2760 switch (code) {
2761 default: assert(0 && "Illegal ICmp code!");
2762 case 0: return ConstantBool::getFalse();
2763 case 1:
2764 if (sign)
2765 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
2766 else
2767 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
2768 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
2769 case 3:
2770 if (sign)
2771 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
2772 else
2773 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
2774 case 4:
2775 if (sign)
2776 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
2777 else
2778 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
2779 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
2780 case 6:
2781 if (sign)
2782 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
2783 else
2784 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
2785 case 7: return ConstantBool::getTrue();
Chris Lattner3ac7c262003-08-13 20:16:26 +00002786 }
2787}
2788
Reid Spencer266e42b2006-12-23 06:05:41 +00002789static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
2790 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
2791 (ICmpInst::isSignedPredicate(p1) &&
2792 (p2 == ICmpInst::ICMP_EQ || p2 == ICmpInst::ICMP_NE)) ||
2793 (ICmpInst::isSignedPredicate(p2) &&
2794 (p1 == ICmpInst::ICMP_EQ || p1 == ICmpInst::ICMP_NE));
2795}
2796
2797namespace {
2798// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
2799struct FoldICmpLogical {
Chris Lattner3ac7c262003-08-13 20:16:26 +00002800 InstCombiner &IC;
2801 Value *LHS, *RHS;
Reid Spencer266e42b2006-12-23 06:05:41 +00002802 ICmpInst::Predicate pred;
2803 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
2804 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
2805 pred(ICI->getPredicate()) {}
Chris Lattner3ac7c262003-08-13 20:16:26 +00002806 bool shouldApply(Value *V) const {
Reid Spencer266e42b2006-12-23 06:05:41 +00002807 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
2808 if (PredicatesFoldable(pred, ICI->getPredicate()))
2809 return (ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS ||
2810 ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS);
Chris Lattner3ac7c262003-08-13 20:16:26 +00002811 return false;
2812 }
Reid Spencer266e42b2006-12-23 06:05:41 +00002813 Instruction *apply(Instruction &Log) const {
2814 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
2815 if (ICI->getOperand(0) != LHS) {
2816 assert(ICI->getOperand(1) == LHS);
2817 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
Chris Lattner3ac7c262003-08-13 20:16:26 +00002818 }
2819
Reid Spencer266e42b2006-12-23 06:05:41 +00002820 unsigned LHSCode = getICmpCode(ICI);
2821 unsigned RHSCode = getICmpCode(cast<ICmpInst>(Log.getOperand(1)));
Chris Lattner3ac7c262003-08-13 20:16:26 +00002822 unsigned Code;
2823 switch (Log.getOpcode()) {
2824 case Instruction::And: Code = LHSCode & RHSCode; break;
2825 case Instruction::Or: Code = LHSCode | RHSCode; break;
2826 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner2caaaba2003-09-22 20:33:34 +00002827 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattner3ac7c262003-08-13 20:16:26 +00002828 }
2829
Reid Spencer266e42b2006-12-23 06:05:41 +00002830 Value *RV = getICmpValue(ICmpInst::isSignedPredicate(pred), Code, LHS, RHS);
Chris Lattner3ac7c262003-08-13 20:16:26 +00002831 if (Instruction *I = dyn_cast<Instruction>(RV))
2832 return I;
2833 // Otherwise, it's a constant boolean value...
2834 return IC.ReplaceInstUsesWith(Log, RV);
2835 }
2836};
Chris Lattnere3a63d12006-11-15 04:53:24 +00002837} // end anonymous namespace
Chris Lattner3ac7c262003-08-13 20:16:26 +00002838
Chris Lattnerba1cb382003-09-19 17:17:26 +00002839// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
2840// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
2841// guaranteed to be either a shift instruction or a binary operator.
2842Instruction *InstCombiner::OptAndOp(Instruction *Op,
2843 ConstantIntegral *OpRHS,
2844 ConstantIntegral *AndRHS,
2845 BinaryOperator &TheAnd) {
2846 Value *X = Op->getOperand(0);
Chris Lattnerfcf21a72004-01-12 19:47:05 +00002847 Constant *Together = 0;
2848 if (!isa<ShiftInst>(Op))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002849 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002850
Chris Lattnerba1cb382003-09-19 17:17:26 +00002851 switch (Op->getOpcode()) {
2852 case Instruction::Xor:
Chris Lattner86102b82005-01-01 16:22:27 +00002853 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00002854 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
2855 std::string OpName = Op->getName(); Op->setName("");
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002856 Instruction *And = BinaryOperator::createAnd(X, AndRHS, OpName);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002857 InsertNewInstBefore(And, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002858 return BinaryOperator::createXor(And, Together);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002859 }
2860 break;
2861 case Instruction::Or:
Chris Lattner86102b82005-01-01 16:22:27 +00002862 if (Together == AndRHS) // (X | C) & C --> C
2863 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002864
Chris Lattner86102b82005-01-01 16:22:27 +00002865 if (Op->hasOneUse() && Together != OpRHS) {
2866 // (X | C1) & C2 --> (X | (C1&C2)) & C2
2867 std::string Op0Name = Op->getName(); Op->setName("");
2868 Instruction *Or = BinaryOperator::createOr(X, Together, Op0Name);
2869 InsertNewInstBefore(Or, TheAnd);
2870 return BinaryOperator::createAnd(Or, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002871 }
2872 break;
2873 case Instruction::Add:
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002874 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00002875 // Adding a one to a single bit bit-field should be turned into an XOR
2876 // of the bit. First thing to check is to see if this AND is with a
2877 // single bit constant.
Reid Spencere0fc4df2006-10-20 07:07:24 +00002878 uint64_t AndRHSV = cast<ConstantInt>(AndRHS)->getZExtValue();
Chris Lattnerba1cb382003-09-19 17:17:26 +00002879
2880 // Clear bits that are not part of the constant.
Chris Lattner77defba2006-02-07 07:00:41 +00002881 AndRHSV &= AndRHS->getType()->getIntegralTypeMask();
Chris Lattnerba1cb382003-09-19 17:17:26 +00002882
2883 // If there is only one bit set...
Chris Lattner35167c32004-06-09 07:59:58 +00002884 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00002885 // Ok, at this point, we know that we are masking the result of the
2886 // ADD down to exactly one bit. If the constant we are adding has
2887 // no bits set below this bit, then we can eliminate the ADD.
Reid Spencere0fc4df2006-10-20 07:07:24 +00002888 uint64_t AddRHS = cast<ConstantInt>(OpRHS)->getZExtValue();
Misha Brukmanb1c93172005-04-21 23:48:37 +00002889
Chris Lattnerba1cb382003-09-19 17:17:26 +00002890 // Check to see if any bits below the one bit set in AndRHSV are set.
2891 if ((AddRHS & (AndRHSV-1)) == 0) {
2892 // If not, the only thing that can effect the output of the AND is
2893 // the bit specified by AndRHSV. If that bit is set, the effect of
2894 // the XOR is to toggle the bit. If it is clear, then the ADD has
2895 // no effect.
2896 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
2897 TheAnd.setOperand(0, X);
2898 return &TheAnd;
2899 } else {
2900 std::string Name = Op->getName(); Op->setName("");
2901 // Pull the XOR out of the AND.
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002902 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS, Name);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002903 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002904 return BinaryOperator::createXor(NewAnd, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002905 }
2906 }
2907 }
2908 }
2909 break;
Chris Lattner2da29172003-09-19 19:05:02 +00002910
2911 case Instruction::Shl: {
2912 // We know that the AND will not produce any of the bits shifted in, so if
2913 // the anded constant includes them, clear them now!
2914 //
2915 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner7e794272004-09-24 15:21:34 +00002916 Constant *ShlMask = ConstantExpr::getShl(AllOne, OpRHS);
2917 Constant *CI = ConstantExpr::getAnd(AndRHS, ShlMask);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002918
Chris Lattner7e794272004-09-24 15:21:34 +00002919 if (CI == ShlMask) { // Masking out bits that the shift already masks
2920 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
2921 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner2da29172003-09-19 19:05:02 +00002922 TheAnd.setOperand(1, CI);
2923 return &TheAnd;
2924 }
2925 break;
Misha Brukmanb1c93172005-04-21 23:48:37 +00002926 }
Reid Spencerfdff9382006-11-08 06:47:33 +00002927 case Instruction::LShr:
2928 {
Chris Lattner2da29172003-09-19 19:05:02 +00002929 // We know that the AND will not produce any of the bits shifted in, so if
2930 // the anded constant includes them, clear them now! This only applies to
2931 // unsigned shifts, because a signed shr may bring in set bits!
2932 //
Reid Spencerfdff9382006-11-08 06:47:33 +00002933 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
2934 Constant *ShrMask = ConstantExpr::getLShr(AllOne, OpRHS);
2935 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
Chris Lattner7e794272004-09-24 15:21:34 +00002936
Reid Spencerfdff9382006-11-08 06:47:33 +00002937 if (CI == ShrMask) { // Masking out bits that the shift already masks.
2938 return ReplaceInstUsesWith(TheAnd, Op);
2939 } else if (CI != AndRHS) {
2940 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
2941 return &TheAnd;
2942 }
2943 break;
2944 }
2945 case Instruction::AShr:
2946 // Signed shr.
2947 // See if this is shifting in some sign extension, then masking it out
2948 // with an and.
2949 if (Op->hasOneUse()) {
2950 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
2951 Constant *ShrMask = ConstantExpr::getLShr(AllOne, OpRHS);
Reid Spencer2a499b02006-12-13 17:19:09 +00002952 Constant *C = ConstantExpr::getAnd(AndRHS, ShrMask);
2953 if (C == AndRHS) { // Masking out bits shifted in.
Reid Spencer13bc5d72006-12-12 09:18:51 +00002954 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
Reid Spencerfdff9382006-11-08 06:47:33 +00002955 // Make the argument unsigned.
2956 Value *ShVal = Op->getOperand(0);
Reid Spencer2a499b02006-12-13 17:19:09 +00002957 ShVal = InsertNewInstBefore(new ShiftInst(Instruction::LShr, ShVal,
2958 OpRHS, Op->getName()), TheAnd);
2959 return BinaryOperator::createAnd(ShVal, AndRHS, TheAnd.getName());
Chris Lattner7e794272004-09-24 15:21:34 +00002960 }
Chris Lattner2da29172003-09-19 19:05:02 +00002961 }
2962 break;
Chris Lattnerba1cb382003-09-19 17:17:26 +00002963 }
2964 return 0;
2965}
2966
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002967
Chris Lattner6862fbd2004-09-29 17:40:11 +00002968/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
2969/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
Reid Spencer266e42b2006-12-23 06:05:41 +00002970/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
2971/// whether to treat the V, Lo and HI as signed or not. IB is the location to
Chris Lattner6862fbd2004-09-29 17:40:11 +00002972/// insert new instructions.
2973Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencer266e42b2006-12-23 06:05:41 +00002974 bool isSigned, bool Inside,
2975 Instruction &IB) {
2976 assert(cast<ConstantBool>(ConstantExpr::getICmp((isSigned ?
2977 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getValue() &&
Chris Lattner6862fbd2004-09-29 17:40:11 +00002978 "Lo is not <= Hi in range emission code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00002979
Chris Lattner6862fbd2004-09-29 17:40:11 +00002980 if (Inside) {
2981 if (Lo == Hi) // Trivially false.
Reid Spencer266e42b2006-12-23 06:05:41 +00002982 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002983
Reid Spencer266e42b2006-12-23 06:05:41 +00002984 // V >= Min && V < Hi --> V < Hi
2985 if (cast<ConstantIntegral>(Lo)->isMinValue(isSigned)) {
2986 ICmpInst::Predicate pred = (isSigned ?
2987 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
2988 return new ICmpInst(pred, V, Hi);
2989 }
2990
2991 // Emit V-Lo <u Hi-Lo
2992 Constant *NegLo = ConstantExpr::getNeg(Lo);
2993 Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
Chris Lattner6862fbd2004-09-29 17:40:11 +00002994 InsertNewInstBefore(Add, IB);
Reid Spencer266e42b2006-12-23 06:05:41 +00002995 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
2996 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00002997 }
2998
2999 if (Lo == Hi) // Trivially true.
Reid Spencer266e42b2006-12-23 06:05:41 +00003000 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
Chris Lattner6862fbd2004-09-29 17:40:11 +00003001
Reid Spencer266e42b2006-12-23 06:05:41 +00003002 // V < Min || V >= Hi ->'V > Hi-1'
Chris Lattner6862fbd2004-09-29 17:40:11 +00003003 Hi = SubOne(cast<ConstantInt>(Hi));
Reid Spencer266e42b2006-12-23 06:05:41 +00003004 if (cast<ConstantIntegral>(Lo)->isMinValue(isSigned)) {
3005 ICmpInst::Predicate pred = (isSigned ?
3006 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3007 return new ICmpInst(pred, V, Hi);
3008 }
Reid Spencere0fc4df2006-10-20 07:07:24 +00003009
Reid Spencer266e42b2006-12-23 06:05:41 +00003010 // Emit V-Lo > Hi-1-Lo
3011 Constant *NegLo = ConstantExpr::getNeg(Lo);
3012 Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
Chris Lattner6862fbd2004-09-29 17:40:11 +00003013 InsertNewInstBefore(Add, IB);
Reid Spencer266e42b2006-12-23 06:05:41 +00003014 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3015 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00003016}
3017
Chris Lattnerb4b25302005-09-18 07:22:02 +00003018// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3019// any number of 0s on either side. The 1s are allowed to wrap from LSB to
3020// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3021// not, since all 1s are not contiguous.
3022static bool isRunOfOnes(ConstantIntegral *Val, unsigned &MB, unsigned &ME) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00003023 uint64_t V = Val->getZExtValue();
Chris Lattnerb4b25302005-09-18 07:22:02 +00003024 if (!isShiftedMask_64(V)) return false;
3025
3026 // look for the first zero bit after the run of ones
3027 MB = 64-CountLeadingZeros_64((V - 1) ^ V);
3028 // look for the first non-zero bit
3029 ME = 64-CountLeadingZeros_64(V);
3030 return true;
3031}
3032
3033
3034
3035/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3036/// where isSub determines whether the operator is a sub. If we can fold one of
3037/// the following xforms:
Chris Lattneraf517572005-09-18 04:24:45 +00003038///
3039/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3040/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3041/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3042///
3043/// return (A +/- B).
3044///
3045Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
3046 ConstantIntegral *Mask, bool isSub,
3047 Instruction &I) {
3048 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3049 if (!LHSI || LHSI->getNumOperands() != 2 ||
3050 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3051
3052 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3053
3054 switch (LHSI->getOpcode()) {
3055 default: return 0;
3056 case Instruction::And:
Chris Lattnerb4b25302005-09-18 07:22:02 +00003057 if (ConstantExpr::getAnd(N, Mask) == Mask) {
3058 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Reid Spencere0fc4df2006-10-20 07:07:24 +00003059 if ((Mask->getZExtValue() & Mask->getZExtValue()+1) == 0)
Chris Lattnerb4b25302005-09-18 07:22:02 +00003060 break;
3061
3062 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3063 // part, we don't need any explicit masks to take them out of A. If that
3064 // is all N is, ignore it.
3065 unsigned MB, ME;
3066 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003067 uint64_t Mask = RHS->getType()->getIntegralTypeMask();
3068 Mask >>= 64-MB+1;
3069 if (MaskedValueIsZero(RHS, Mask))
Chris Lattnerb4b25302005-09-18 07:22:02 +00003070 break;
3071 }
3072 }
Chris Lattneraf517572005-09-18 04:24:45 +00003073 return 0;
3074 case Instruction::Or:
3075 case Instruction::Xor:
Chris Lattnerb4b25302005-09-18 07:22:02 +00003076 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Reid Spencere0fc4df2006-10-20 07:07:24 +00003077 if ((Mask->getZExtValue() & Mask->getZExtValue()+1) == 0 &&
Chris Lattnerb4b25302005-09-18 07:22:02 +00003078 ConstantExpr::getAnd(N, Mask)->isNullValue())
Chris Lattneraf517572005-09-18 04:24:45 +00003079 break;
3080 return 0;
3081 }
3082
3083 Instruction *New;
3084 if (isSub)
3085 New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
3086 else
3087 New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
3088 return InsertNewInstBefore(New, I);
3089}
3090
Chris Lattner113f4f42002-06-25 16:13:24 +00003091Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003092 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00003093 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003094
Chris Lattner81a7a232004-10-16 18:11:37 +00003095 if (isa<UndefValue>(Op1)) // X & undef -> 0
3096 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3097
Chris Lattner86102b82005-01-01 16:22:27 +00003098 // and X, X = X
3099 if (Op0 == Op1)
Chris Lattnere6794492002-08-12 21:17:25 +00003100 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003101
Chris Lattner5b2edb12006-02-12 08:02:11 +00003102 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner5997cf92006-02-08 03:25:32 +00003103 // purpose is to compute bits we don't care about.
Chris Lattner0157e7f2006-02-11 09:31:47 +00003104 uint64_t KnownZero, KnownOne;
Chris Lattnerd70d9f52006-03-25 21:58:26 +00003105 if (!isa<PackedType>(I.getType()) &&
3106 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
Chris Lattner0157e7f2006-02-11 09:31:47 +00003107 KnownZero, KnownOne))
Chris Lattner5997cf92006-02-08 03:25:32 +00003108 return &I;
3109
Chris Lattner86102b82005-01-01 16:22:27 +00003110 if (ConstantIntegral *AndRHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00003111 uint64_t AndRHSMask = AndRHS->getZExtValue();
3112 uint64_t TypeMask = Op0->getType()->getIntegralTypeMask();
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00003113 uint64_t NotAndRHS = AndRHSMask^TypeMask;
Chris Lattner86102b82005-01-01 16:22:27 +00003114
Chris Lattnerba1cb382003-09-19 17:17:26 +00003115 // Optimize a variety of ((val OP C1) & C2) combinations...
3116 if (isa<BinaryOperator>(Op0) || isa<ShiftInst>(Op0)) {
3117 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner86102b82005-01-01 16:22:27 +00003118 Value *Op0LHS = Op0I->getOperand(0);
3119 Value *Op0RHS = Op0I->getOperand(1);
3120 switch (Op0I->getOpcode()) {
3121 case Instruction::Xor:
3122 case Instruction::Or:
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00003123 // If the mask is only needed on one incoming arm, push it up.
3124 if (Op0I->hasOneUse()) {
3125 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3126 // Not masking anything out for the LHS, move to RHS.
3127 Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
3128 Op0RHS->getName()+".masked");
3129 InsertNewInstBefore(NewRHS, I);
3130 return BinaryOperator::create(
3131 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003132 }
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003133 if (!isa<Constant>(Op0RHS) &&
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00003134 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3135 // Not masking anything out for the RHS, move to LHS.
3136 Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
3137 Op0LHS->getName()+".masked");
3138 InsertNewInstBefore(NewLHS, I);
3139 return BinaryOperator::create(
3140 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3141 }
3142 }
3143
Chris Lattner86102b82005-01-01 16:22:27 +00003144 break;
Chris Lattneraf517572005-09-18 04:24:45 +00003145 case Instruction::Add:
Chris Lattnerb4b25302005-09-18 07:22:02 +00003146 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3147 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3148 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3149 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
3150 return BinaryOperator::createAnd(V, AndRHS);
3151 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
3152 return BinaryOperator::createAnd(V, AndRHS); // Add commutes
Chris Lattneraf517572005-09-18 04:24:45 +00003153 break;
3154
3155 case Instruction::Sub:
Chris Lattnerb4b25302005-09-18 07:22:02 +00003156 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3157 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3158 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3159 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
3160 return BinaryOperator::createAnd(V, AndRHS);
Chris Lattneraf517572005-09-18 04:24:45 +00003161 break;
Chris Lattner86102b82005-01-01 16:22:27 +00003162 }
3163
Chris Lattner16464b32003-07-23 19:25:52 +00003164 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner86102b82005-01-01 16:22:27 +00003165 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerba1cb382003-09-19 17:17:26 +00003166 return Res;
Chris Lattner86102b82005-01-01 16:22:27 +00003167 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
Chris Lattner2c14cf72005-08-07 07:03:10 +00003168 // If this is an integer truncation or change from signed-to-unsigned, and
3169 // if the source is an and/or with immediate, transform it. This
3170 // frequently occurs for bitfield accesses.
3171 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003172 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
Chris Lattner2c14cf72005-08-07 07:03:10 +00003173 CastOp->getNumOperands() == 2)
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00003174 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1)))
Chris Lattner2c14cf72005-08-07 07:03:10 +00003175 if (CastOp->getOpcode() == Instruction::And) {
3176 // Change: and (cast (and X, C1) to T), C2
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003177 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
3178 // This will fold the two constants together, which may allow
3179 // other simplifications.
Reid Spencerbb65ebf2006-12-12 23:36:14 +00003180 Instruction *NewCast = CastInst::createTruncOrBitCast(
3181 CastOp->getOperand(0), I.getType(),
3182 CastOp->getName()+".shrunk");
Chris Lattner2c14cf72005-08-07 07:03:10 +00003183 NewCast = InsertNewInstBefore(NewCast, I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003184 // trunc_or_bitcast(C1)&C2
Reid Spencerbb65ebf2006-12-12 23:36:14 +00003185 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003186 C3 = ConstantExpr::getAnd(C3, AndRHS);
Chris Lattner2c14cf72005-08-07 07:03:10 +00003187 return BinaryOperator::createAnd(NewCast, C3);
3188 } else if (CastOp->getOpcode() == Instruction::Or) {
3189 // Change: and (cast (or X, C1) to T), C2
3190 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Chris Lattner2dc148e2006-12-12 19:11:20 +00003191 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Chris Lattner2c14cf72005-08-07 07:03:10 +00003192 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
3193 return ReplaceInstUsesWith(I, AndRHS);
3194 }
3195 }
Chris Lattner33217db2003-07-23 19:36:21 +00003196 }
Chris Lattner183b3362004-04-09 19:05:30 +00003197
3198 // Try to fold constant and into select arguments.
3199 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00003200 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00003201 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00003202 if (isa<PHINode>(Op0))
3203 if (Instruction *NV = FoldOpIntoPhi(I))
3204 return NV;
Chris Lattner49b47ae2003-07-23 17:57:01 +00003205 }
3206
Chris Lattnerbb74e222003-03-10 23:06:50 +00003207 Value *Op0NotVal = dyn_castNotVal(Op0);
3208 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00003209
Chris Lattner023a4832004-06-18 06:07:51 +00003210 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
3211 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3212
Misha Brukman9c003d82004-07-30 12:50:08 +00003213 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattnerbb74e222003-03-10 23:06:50 +00003214 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003215 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
3216 I.getName()+".demorgan");
Chris Lattner49b47ae2003-07-23 17:57:01 +00003217 InsertNewInstBefore(Or, I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00003218 return BinaryOperator::createNot(Or);
3219 }
Chris Lattner8b10ab32006-02-13 23:07:23 +00003220
3221 {
3222 Value *A = 0, *B = 0;
Chris Lattner8b10ab32006-02-13 23:07:23 +00003223 if (match(Op0, m_Or(m_Value(A), m_Value(B))))
3224 if (A == Op1 || B == Op1) // (A | ?) & A --> A
3225 return ReplaceInstUsesWith(I, Op1);
3226 if (match(Op1, m_Or(m_Value(A), m_Value(B))))
3227 if (A == Op0 || B == Op0) // A & (A | ?) --> A
3228 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerdcd07922006-04-01 08:03:55 +00003229
3230 if (Op0->hasOneUse() &&
3231 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3232 if (A == Op1) { // (A^B)&A -> A&(A^B)
3233 I.swapOperands(); // Simplify below
3234 std::swap(Op0, Op1);
3235 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
3236 cast<BinaryOperator>(Op0)->swapOperands();
3237 I.swapOperands(); // Simplify below
3238 std::swap(Op0, Op1);
3239 }
3240 }
3241 if (Op1->hasOneUse() &&
3242 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3243 if (B == Op0) { // B&(A^B) -> B&(B^A)
3244 cast<BinaryOperator>(Op1)->swapOperands();
3245 std::swap(A, B);
3246 }
3247 if (A == Op0) { // A&(A^B) -> A & ~B
3248 Instruction *NotB = BinaryOperator::createNot(B, "tmp");
3249 InsertNewInstBefore(NotB, I);
3250 return BinaryOperator::createAnd(A, NotB);
3251 }
3252 }
Chris Lattner8b10ab32006-02-13 23:07:23 +00003253 }
3254
Reid Spencer266e42b2006-12-23 06:05:41 +00003255 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
3256 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3257 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattner3ac7c262003-08-13 20:16:26 +00003258 return R;
3259
Chris Lattner623826c2004-09-28 21:48:02 +00003260 Value *LHSVal, *RHSVal;
3261 ConstantInt *LHSCst, *RHSCst;
Reid Spencer266e42b2006-12-23 06:05:41 +00003262 ICmpInst::Predicate LHSCC, RHSCC;
3263 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3264 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3265 if (LHSVal == RHSVal && // Found (X icmp C1) & (X icmp C2)
3266 // ICMP_[GL]E X, CST is folded to ICMP_[GL]T elsewhere.
3267 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3268 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3269 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
3270 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE) {
Chris Lattner623826c2004-09-28 21:48:02 +00003271 // Ensure that the larger constant is on the RHS.
Reid Spencer266e42b2006-12-23 06:05:41 +00003272 ICmpInst::Predicate GT = ICmpInst::isSignedPredicate(LHSCC) ?
3273 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
3274 Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3275 ICmpInst *LHS = cast<ICmpInst>(Op0);
Chris Lattner623826c2004-09-28 21:48:02 +00003276 if (cast<ConstantBool>(Cmp)->getValue()) {
3277 std::swap(LHS, RHS);
3278 std::swap(LHSCst, RHSCst);
3279 std::swap(LHSCC, RHSCC);
3280 }
3281
Reid Spencer266e42b2006-12-23 06:05:41 +00003282 // At this point, we know we have have two icmp instructions
Chris Lattner623826c2004-09-28 21:48:02 +00003283 // comparing a value against two constants and and'ing the result
3284 // together. Because of the above check, we know that we only have
Reid Spencer266e42b2006-12-23 06:05:41 +00003285 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3286 // (from the FoldICmpLogical check above), that the two constants
3287 // are not equal and that the larger constant is on the RHS
Chris Lattner623826c2004-09-28 21:48:02 +00003288 assert(LHSCst != RHSCst && "Compares not folded above?");
3289
3290 switch (LHSCC) {
3291 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003292 case ICmpInst::ICMP_EQ:
Chris Lattner623826c2004-09-28 21:48:02 +00003293 switch (RHSCC) {
3294 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003295 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
3296 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3297 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
Chris Lattner6ab03f62006-09-28 23:35:22 +00003298 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00003299 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3300 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3301 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
Chris Lattner623826c2004-09-28 21:48:02 +00003302 return ReplaceInstUsesWith(I, LHS);
3303 }
Reid Spencer266e42b2006-12-23 06:05:41 +00003304 case ICmpInst::ICMP_NE:
Chris Lattner623826c2004-09-28 21:48:02 +00003305 switch (RHSCC) {
3306 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003307 case ICmpInst::ICMP_ULT:
3308 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3309 return new ICmpInst(ICmpInst::ICMP_ULT, LHSVal, LHSCst);
3310 break; // (X != 13 & X u< 15) -> no change
3311 case ICmpInst::ICMP_SLT:
3312 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3313 return new ICmpInst(ICmpInst::ICMP_SLT, LHSVal, LHSCst);
3314 break; // (X != 13 & X s< 15) -> no change
3315 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
3316 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
3317 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
Chris Lattner623826c2004-09-28 21:48:02 +00003318 return ReplaceInstUsesWith(I, RHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00003319 case ICmpInst::ICMP_NE:
3320 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
Chris Lattner623826c2004-09-28 21:48:02 +00003321 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3322 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3323 LHSVal->getName()+".off");
3324 InsertNewInstBefore(Add, I);
Reid Spencerc635f472006-12-31 05:48:39 +00003325 return new ICmpInst(ICmpInst::ICMP_UGT, Add, AddCST);
Chris Lattner623826c2004-09-28 21:48:02 +00003326 }
3327 break; // (X != 13 & X != 15) -> no change
3328 }
3329 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00003330 case ICmpInst::ICMP_ULT:
Chris Lattner623826c2004-09-28 21:48:02 +00003331 switch (RHSCC) {
3332 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003333 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
3334 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Chris Lattner6ab03f62006-09-28 23:35:22 +00003335 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00003336 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
3337 break;
3338 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
3339 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
Chris Lattner623826c2004-09-28 21:48:02 +00003340 return ReplaceInstUsesWith(I, LHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00003341 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
3342 break;
Chris Lattner623826c2004-09-28 21:48:02 +00003343 }
Reid Spencer266e42b2006-12-23 06:05:41 +00003344 break;
3345 case ICmpInst::ICMP_SLT:
Chris Lattner623826c2004-09-28 21:48:02 +00003346 switch (RHSCC) {
3347 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003348 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
3349 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
3350 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
3351 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
3352 break;
3353 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
3354 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
Chris Lattner623826c2004-09-28 21:48:02 +00003355 return ReplaceInstUsesWith(I, LHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00003356 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
3357 break;
Chris Lattner623826c2004-09-28 21:48:02 +00003358 }
Reid Spencer266e42b2006-12-23 06:05:41 +00003359 break;
3360 case ICmpInst::ICMP_UGT:
3361 switch (RHSCC) {
3362 default: assert(0 && "Unknown integer condition code!");
3363 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X > 13
3364 return ReplaceInstUsesWith(I, LHS);
3365 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
3366 return ReplaceInstUsesWith(I, RHS);
3367 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
3368 break;
3369 case ICmpInst::ICMP_NE:
3370 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3371 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3372 break; // (X u> 13 & X != 15) -> no change
3373 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) ->(X-14) <u 1
3374 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, false,
3375 true, I);
3376 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
3377 break;
3378 }
3379 break;
3380 case ICmpInst::ICMP_SGT:
3381 switch (RHSCC) {
3382 default: assert(0 && "Unknown integer condition code!");
3383 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X s> 13
3384 return ReplaceInstUsesWith(I, LHS);
3385 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
3386 return ReplaceInstUsesWith(I, RHS);
3387 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
3388 break;
3389 case ICmpInst::ICMP_NE:
3390 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3391 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3392 break; // (X s> 13 & X != 15) -> no change
3393 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) ->(X-14) s< 1
3394 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true,
3395 true, I);
3396 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
3397 break;
3398 }
3399 break;
Chris Lattner623826c2004-09-28 21:48:02 +00003400 }
3401 }
3402 }
3403
Chris Lattner3af10532006-05-05 06:39:07 +00003404 // fold (and (cast A), (cast B)) -> (cast (and A, B))
Reid Spencer799b5bf2006-12-13 08:27:15 +00003405 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
3406 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3407 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
3408 const Type *SrcTy = Op0C->getOperand(0)->getType();
3409 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegral() &&
3410 // Only do this if the casts both really cause code to be generated.
Reid Spencer266e42b2006-12-23 06:05:41 +00003411 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
3412 I.getType(), TD) &&
3413 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
3414 I.getType(), TD)) {
Reid Spencer799b5bf2006-12-13 08:27:15 +00003415 Instruction *NewOp = BinaryOperator::createAnd(Op0C->getOperand(0),
3416 Op1C->getOperand(0),
3417 I.getName());
3418 InsertNewInstBefore(NewOp, I);
3419 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
3420 }
Chris Lattner3af10532006-05-05 06:39:07 +00003421 }
Chris Lattnerf05d69a2006-11-14 07:46:50 +00003422
3423 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
3424 if (ShiftInst *SI1 = dyn_cast<ShiftInst>(Op1)) {
3425 if (ShiftInst *SI0 = dyn_cast<ShiftInst>(Op0))
3426 if (SI0->getOpcode() == SI1->getOpcode() &&
3427 SI0->getOperand(1) == SI1->getOperand(1) &&
3428 (SI0->hasOneUse() || SI1->hasOneUse())) {
3429 Instruction *NewOp =
3430 InsertNewInstBefore(BinaryOperator::createAnd(SI0->getOperand(0),
3431 SI1->getOperand(0),
3432 SI0->getName()), I);
3433 return new ShiftInst(SI1->getOpcode(), NewOp, SI1->getOperand(1));
3434 }
Chris Lattner3af10532006-05-05 06:39:07 +00003435 }
3436
Chris Lattner113f4f42002-06-25 16:13:24 +00003437 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003438}
3439
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003440/// CollectBSwapParts - Look to see if the specified value defines a single byte
3441/// in the result. If it does, and if the specified byte hasn't been filled in
3442/// yet, fill it in and return false.
3443static bool CollectBSwapParts(Value *V, std::vector<Value*> &ByteValues) {
3444 Instruction *I = dyn_cast<Instruction>(V);
3445 if (I == 0) return true;
3446
3447 // If this is an or instruction, it is an inner node of the bswap.
3448 if (I->getOpcode() == Instruction::Or)
3449 return CollectBSwapParts(I->getOperand(0), ByteValues) ||
3450 CollectBSwapParts(I->getOperand(1), ByteValues);
3451
3452 // If this is a shift by a constant int, and it is "24", then its operand
3453 // defines a byte. We only handle unsigned types here.
3454 if (isa<ShiftInst>(I) && isa<ConstantInt>(I->getOperand(1))) {
3455 // Not shifting the entire input by N-1 bytes?
Reid Spencere0fc4df2006-10-20 07:07:24 +00003456 if (cast<ConstantInt>(I->getOperand(1))->getZExtValue() !=
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003457 8*(ByteValues.size()-1))
3458 return true;
3459
3460 unsigned DestNo;
3461 if (I->getOpcode() == Instruction::Shl) {
3462 // X << 24 defines the top byte with the lowest of the input bytes.
3463 DestNo = ByteValues.size()-1;
3464 } else {
3465 // X >>u 24 defines the low byte with the highest of the input bytes.
3466 DestNo = 0;
3467 }
3468
3469 // If the destination byte value is already defined, the values are or'd
3470 // together, which isn't a bswap (unless it's an or of the same bits).
3471 if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
3472 return true;
3473 ByteValues[DestNo] = I->getOperand(0);
3474 return false;
3475 }
3476
3477 // Otherwise, we can only handle and(shift X, imm), imm). Bail out of if we
3478 // don't have this.
3479 Value *Shift = 0, *ShiftLHS = 0;
3480 ConstantInt *AndAmt = 0, *ShiftAmt = 0;
3481 if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
3482 !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
3483 return true;
3484 Instruction *SI = cast<Instruction>(Shift);
3485
3486 // Make sure that the shift amount is by a multiple of 8 and isn't too big.
Reid Spencere0fc4df2006-10-20 07:07:24 +00003487 if (ShiftAmt->getZExtValue() & 7 ||
3488 ShiftAmt->getZExtValue() > 8*ByteValues.size())
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003489 return true;
3490
3491 // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
3492 unsigned DestByte;
3493 for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
Reid Spencere0fc4df2006-10-20 07:07:24 +00003494 if (AndAmt->getZExtValue() == uint64_t(0xFF) << 8*DestByte)
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003495 break;
3496 // Unknown mask for bswap.
3497 if (DestByte == ByteValues.size()) return true;
3498
Reid Spencere0fc4df2006-10-20 07:07:24 +00003499 unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003500 unsigned SrcByte;
3501 if (SI->getOpcode() == Instruction::Shl)
3502 SrcByte = DestByte - ShiftBytes;
3503 else
3504 SrcByte = DestByte + ShiftBytes;
3505
3506 // If the SrcByte isn't a bswapped value from the DestByte, reject it.
3507 if (SrcByte != ByteValues.size()-DestByte-1)
3508 return true;
3509
3510 // If the destination byte value is already defined, the values are or'd
3511 // together, which isn't a bswap (unless it's an or of the same bits).
3512 if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
3513 return true;
3514 ByteValues[DestByte] = SI->getOperand(0);
3515 return false;
3516}
3517
3518/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
3519/// If so, insert the new bswap intrinsic and return it.
3520Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
3521 // We can only handle bswap of unsigned integers, and cannot bswap one byte.
Reid Spencerc635f472006-12-31 05:48:39 +00003522 if (I.getType() == Type::Int8Ty)
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003523 return 0;
3524
3525 /// ByteValues - For each byte of the result, we keep track of which value
3526 /// defines each byte.
3527 std::vector<Value*> ByteValues;
3528 ByteValues.resize(I.getType()->getPrimitiveSize());
3529
3530 // Try to find all the pieces corresponding to the bswap.
3531 if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
3532 CollectBSwapParts(I.getOperand(1), ByteValues))
3533 return 0;
3534
3535 // Check to see if all of the bytes come from the same value.
3536 Value *V = ByteValues[0];
3537 if (V == 0) return 0; // Didn't find a byte? Must be zero.
3538
3539 // Check to make sure that all of the bytes come from the same value.
3540 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
3541 if (ByteValues[i] != V)
3542 return 0;
3543
3544 // If they do then *success* we can turn this into a bswap. Figure out what
3545 // bswap to make it into.
3546 Module *M = I.getParent()->getParent()->getParent();
Chris Lattner091b6ea2006-07-11 18:31:26 +00003547 const char *FnName = 0;
Reid Spencerc635f472006-12-31 05:48:39 +00003548 if (I.getType() == Type::Int16Ty)
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003549 FnName = "llvm.bswap.i16";
Reid Spencerc635f472006-12-31 05:48:39 +00003550 else if (I.getType() == Type::Int32Ty)
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003551 FnName = "llvm.bswap.i32";
Reid Spencerc635f472006-12-31 05:48:39 +00003552 else if (I.getType() == Type::Int64Ty)
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003553 FnName = "llvm.bswap.i64";
3554 else
3555 assert(0 && "Unknown integer type!");
3556 Function *F = M->getOrInsertFunction(FnName, I.getType(), I.getType(), NULL);
3557
3558 return new CallInst(F, V);
3559}
3560
3561
Chris Lattner113f4f42002-06-25 16:13:24 +00003562Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003563 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00003564 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003565
Chris Lattner81a7a232004-10-16 18:11:37 +00003566 if (isa<UndefValue>(Op1))
3567 return ReplaceInstUsesWith(I, // X | undef -> -1
3568 ConstantIntegral::getAllOnesValue(I.getType()));
3569
Chris Lattner5b2edb12006-02-12 08:02:11 +00003570 // or X, X = X
3571 if (Op0 == Op1)
Chris Lattnere6794492002-08-12 21:17:25 +00003572 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003573
Chris Lattner5b2edb12006-02-12 08:02:11 +00003574 // See if we can simplify any instructions used by the instruction whose sole
3575 // purpose is to compute bits we don't care about.
3576 uint64_t KnownZero, KnownOne;
Chris Lattnerd70d9f52006-03-25 21:58:26 +00003577 if (!isa<PackedType>(I.getType()) &&
3578 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
Chris Lattner5b2edb12006-02-12 08:02:11 +00003579 KnownZero, KnownOne))
3580 return &I;
3581
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003582 // or X, -1 == -1
Chris Lattner8f0d1562003-07-23 18:29:44 +00003583 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner330628a2006-01-06 17:59:59 +00003584 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00003585 // (X & C1) | C2 --> (X | C2) & (C1|C2)
3586 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Chris Lattnerb62f5082005-05-09 04:58:36 +00003587 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0->getName());
3588 Op0->setName("");
Chris Lattnerd4252a72004-07-30 07:50:03 +00003589 InsertNewInstBefore(Or, I);
3590 return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, C1));
3591 }
Chris Lattner8f0d1562003-07-23 18:29:44 +00003592
Chris Lattnerd4252a72004-07-30 07:50:03 +00003593 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
3594 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
3595 std::string Op0Name = Op0->getName(); Op0->setName("");
3596 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
3597 InsertNewInstBefore(Or, I);
3598 return BinaryOperator::createXor(Or,
3599 ConstantExpr::getAnd(C1, ConstantExpr::getNot(RHS)));
Chris Lattner8f0d1562003-07-23 18:29:44 +00003600 }
Chris Lattner183b3362004-04-09 19:05:30 +00003601
3602 // Try to fold constant and into select arguments.
3603 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00003604 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00003605 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00003606 if (isa<PHINode>(Op0))
3607 if (Instruction *NV = FoldOpIntoPhi(I))
3608 return NV;
Chris Lattner8f0d1562003-07-23 18:29:44 +00003609 }
3610
Chris Lattner330628a2006-01-06 17:59:59 +00003611 Value *A = 0, *B = 0;
3612 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattner4294cec2005-05-07 23:49:08 +00003613
3614 if (match(Op0, m_And(m_Value(A), m_Value(B))))
3615 if (A == Op1 || B == Op1) // (A & ?) | A --> A
3616 return ReplaceInstUsesWith(I, Op1);
3617 if (match(Op1, m_And(m_Value(A), m_Value(B))))
3618 if (A == Op0 || B == Op0) // A | (A & ?) --> A
3619 return ReplaceInstUsesWith(I, Op0);
3620
Chris Lattnerb7845d62006-07-10 20:25:24 +00003621 // (A | B) | C and A | (B | C) -> bswap if possible.
3622 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003623 if (match(Op0, m_Or(m_Value(), m_Value())) ||
Chris Lattnerb7845d62006-07-10 20:25:24 +00003624 match(Op1, m_Or(m_Value(), m_Value())) ||
3625 (match(Op0, m_Shift(m_Value(), m_Value())) &&
3626 match(Op1, m_Shift(m_Value(), m_Value())))) {
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003627 if (Instruction *BSwap = MatchBSwap(I))
3628 return BSwap;
3629 }
3630
Chris Lattnerb62f5082005-05-09 04:58:36 +00003631 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
3632 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003633 MaskedValueIsZero(Op1, C1->getZExtValue())) {
Chris Lattnerb62f5082005-05-09 04:58:36 +00003634 Instruction *NOr = BinaryOperator::createOr(A, Op1, Op0->getName());
3635 Op0->setName("");
3636 return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
3637 }
3638
3639 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
3640 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003641 MaskedValueIsZero(Op0, C1->getZExtValue())) {
Chris Lattnerb62f5082005-05-09 04:58:36 +00003642 Instruction *NOr = BinaryOperator::createOr(A, Op0, Op1->getName());
3643 Op0->setName("");
3644 return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
3645 }
3646
Chris Lattner15212982005-09-18 03:42:07 +00003647 // (A & C1)|(B & C2)
Chris Lattnerd4252a72004-07-30 07:50:03 +00003648 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattner15212982005-09-18 03:42:07 +00003649 match(Op1, m_And(m_Value(B), m_ConstantInt(C2)))) {
3650
3651 if (A == B) // (A & C1)|(A & C2) == A & (C1|C2)
3652 return BinaryOperator::createAnd(A, ConstantExpr::getOr(C1, C2));
3653
3654
Chris Lattner01f56c62005-09-18 06:02:59 +00003655 // If we have: ((V + N) & C1) | (V & C2)
3656 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
3657 // replace with V+N.
3658 if (C1 == ConstantExpr::getNot(C2)) {
Chris Lattner330628a2006-01-06 17:59:59 +00003659 Value *V1 = 0, *V2 = 0;
Reid Spencere0fc4df2006-10-20 07:07:24 +00003660 if ((C2->getZExtValue() & (C2->getZExtValue()+1)) == 0 && // C2 == 0+1+
Chris Lattner01f56c62005-09-18 06:02:59 +00003661 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
3662 // Add commutes, try both ways.
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003663 if (V1 == B && MaskedValueIsZero(V2, C2->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003664 return ReplaceInstUsesWith(I, A);
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003665 if (V2 == B && MaskedValueIsZero(V1, C2->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003666 return ReplaceInstUsesWith(I, A);
3667 }
3668 // Or commutes, try both ways.
Reid Spencere0fc4df2006-10-20 07:07:24 +00003669 if ((C1->getZExtValue() & (C1->getZExtValue()+1)) == 0 &&
Chris Lattner01f56c62005-09-18 06:02:59 +00003670 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
3671 // Add commutes, try both ways.
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003672 if (V1 == A && MaskedValueIsZero(V2, C1->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003673 return ReplaceInstUsesWith(I, B);
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003674 if (V2 == A && MaskedValueIsZero(V1, C1->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003675 return ReplaceInstUsesWith(I, B);
Chris Lattner15212982005-09-18 03:42:07 +00003676 }
3677 }
3678 }
Chris Lattnerf05d69a2006-11-14 07:46:50 +00003679
3680 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
3681 if (ShiftInst *SI1 = dyn_cast<ShiftInst>(Op1)) {
3682 if (ShiftInst *SI0 = dyn_cast<ShiftInst>(Op0))
3683 if (SI0->getOpcode() == SI1->getOpcode() &&
3684 SI0->getOperand(1) == SI1->getOperand(1) &&
3685 (SI0->hasOneUse() || SI1->hasOneUse())) {
3686 Instruction *NewOp =
3687 InsertNewInstBefore(BinaryOperator::createOr(SI0->getOperand(0),
3688 SI1->getOperand(0),
3689 SI0->getName()), I);
3690 return new ShiftInst(SI1->getOpcode(), NewOp, SI1->getOperand(1));
3691 }
3692 }
Chris Lattner812aab72003-08-12 19:11:07 +00003693
Chris Lattnerd4252a72004-07-30 07:50:03 +00003694 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
3695 if (A == Op1) // ~A | A == -1
Misha Brukmanb1c93172005-04-21 23:48:37 +00003696 return ReplaceInstUsesWith(I,
Chris Lattnerd4252a72004-07-30 07:50:03 +00003697 ConstantIntegral::getAllOnesValue(I.getType()));
3698 } else {
3699 A = 0;
3700 }
Chris Lattner4294cec2005-05-07 23:49:08 +00003701 // Note, A is still live here!
Chris Lattnerd4252a72004-07-30 07:50:03 +00003702 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
3703 if (Op0 == B)
Misha Brukmanb1c93172005-04-21 23:48:37 +00003704 return ReplaceInstUsesWith(I,
Chris Lattnerd4252a72004-07-30 07:50:03 +00003705 ConstantIntegral::getAllOnesValue(I.getType()));
Chris Lattner3e327a42003-03-10 23:13:59 +00003706
Misha Brukman9c003d82004-07-30 12:50:08 +00003707 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattnerd4252a72004-07-30 07:50:03 +00003708 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3709 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
3710 I.getName()+".demorgan"), I);
3711 return BinaryOperator::createNot(And);
3712 }
Chris Lattner3e327a42003-03-10 23:13:59 +00003713 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00003714
Reid Spencer266e42b2006-12-23 06:05:41 +00003715 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
3716 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
3717 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattner3ac7c262003-08-13 20:16:26 +00003718 return R;
3719
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003720 Value *LHSVal, *RHSVal;
3721 ConstantInt *LHSCst, *RHSCst;
Reid Spencer266e42b2006-12-23 06:05:41 +00003722 ICmpInst::Predicate LHSCC, RHSCC;
3723 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3724 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3725 if (LHSVal == RHSVal && // Found (X icmp C1) | (X icmp C2)
3726 // icmp [us][gl]e x, cst is folded to icmp [us][gl]t elsewhere.
3727 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3728 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3729 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
3730 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE) {
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003731 // Ensure that the larger constant is on the RHS.
Reid Spencer266e42b2006-12-23 06:05:41 +00003732 ICmpInst::Predicate GT = ICmpInst::isSignedPredicate(LHSCC) ?
3733 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
3734 Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3735 ICmpInst *LHS = cast<ICmpInst>(Op0);
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003736 if (cast<ConstantBool>(Cmp)->getValue()) {
3737 std::swap(LHS, RHS);
3738 std::swap(LHSCst, RHSCst);
3739 std::swap(LHSCC, RHSCC);
3740 }
3741
Reid Spencer266e42b2006-12-23 06:05:41 +00003742 // At this point, we know we have have two icmp instructions
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003743 // comparing a value against two constants and or'ing the result
3744 // together. Because of the above check, we know that we only have
Reid Spencer266e42b2006-12-23 06:05:41 +00003745 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
3746 // FoldICmpLogical check above), that the two constants are not
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003747 // equal.
3748 assert(LHSCst != RHSCst && "Compares not folded above?");
3749
3750 switch (LHSCC) {
3751 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003752 case ICmpInst::ICMP_EQ:
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003753 switch (RHSCC) {
3754 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003755 case ICmpInst::ICMP_EQ:
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003756 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
3757 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3758 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3759 LHSVal->getName()+".off");
3760 InsertNewInstBefore(Add, I);
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003761 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
Reid Spencer266e42b2006-12-23 06:05:41 +00003762 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003763 }
Reid Spencer266e42b2006-12-23 06:05:41 +00003764 break; // (X == 13 | X == 15) -> no change
3765 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
3766 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
Chris Lattner5c219462005-04-19 06:04:18 +00003767 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00003768 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
3769 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
3770 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003771 return ReplaceInstUsesWith(I, RHS);
3772 }
3773 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00003774 case ICmpInst::ICMP_NE:
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003775 switch (RHSCC) {
3776 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003777 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
3778 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
3779 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003780 return ReplaceInstUsesWith(I, LHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00003781 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
3782 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
3783 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Chris Lattner6ab03f62006-09-28 23:35:22 +00003784 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003785 }
3786 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00003787 case ICmpInst::ICMP_ULT:
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003788 switch (RHSCC) {
3789 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003790 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003791 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00003792 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) ->(X-13) u> 2
3793 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false,
3794 false, I);
3795 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
3796 break;
3797 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
3798 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003799 return ReplaceInstUsesWith(I, RHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00003800 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
3801 break;
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003802 }
3803 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00003804 case ICmpInst::ICMP_SLT:
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003805 switch (RHSCC) {
3806 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003807 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
3808 break;
3809 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) ->(X-13) s> 2
3810 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), true,
3811 false, I);
3812 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
3813 break;
3814 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
3815 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
3816 return ReplaceInstUsesWith(I, RHS);
3817 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
3818 break;
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003819 }
Reid Spencer266e42b2006-12-23 06:05:41 +00003820 break;
3821 case ICmpInst::ICMP_UGT:
3822 switch (RHSCC) {
3823 default: assert(0 && "Unknown integer condition code!");
3824 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
3825 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
3826 return ReplaceInstUsesWith(I, LHS);
3827 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
3828 break;
3829 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
3830 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
3831 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
3832 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
3833 break;
3834 }
3835 break;
3836 case ICmpInst::ICMP_SGT:
3837 switch (RHSCC) {
3838 default: assert(0 && "Unknown integer condition code!");
3839 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
3840 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
3841 return ReplaceInstUsesWith(I, LHS);
3842 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
3843 break;
3844 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
3845 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
3846 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
3847 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
3848 break;
3849 }
3850 break;
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003851 }
3852 }
3853 }
Chris Lattner3af10532006-05-05 06:39:07 +00003854
3855 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Reid Spencer799b5bf2006-12-13 08:27:15 +00003856 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
Chris Lattner3af10532006-05-05 06:39:07 +00003857 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer799b5bf2006-12-13 08:27:15 +00003858 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
3859 const Type *SrcTy = Op0C->getOperand(0)->getType();
3860 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegral() &&
3861 // Only do this if the casts both really cause code to be generated.
Reid Spencer266e42b2006-12-23 06:05:41 +00003862 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
3863 I.getType(), TD) &&
3864 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
3865 I.getType(), TD)) {
Reid Spencer799b5bf2006-12-13 08:27:15 +00003866 Instruction *NewOp = BinaryOperator::createOr(Op0C->getOperand(0),
3867 Op1C->getOperand(0),
3868 I.getName());
3869 InsertNewInstBefore(NewOp, I);
3870 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
3871 }
Chris Lattner3af10532006-05-05 06:39:07 +00003872 }
Chris Lattner3af10532006-05-05 06:39:07 +00003873
Chris Lattner15212982005-09-18 03:42:07 +00003874
Chris Lattner113f4f42002-06-25 16:13:24 +00003875 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003876}
3877
Chris Lattnerc2076352004-02-16 01:20:27 +00003878// XorSelf - Implements: X ^ X --> 0
3879struct XorSelf {
3880 Value *RHS;
3881 XorSelf(Value *rhs) : RHS(rhs) {}
3882 bool shouldApply(Value *LHS) const { return LHS == RHS; }
3883 Instruction *apply(BinaryOperator &Xor) const {
3884 return &Xor;
3885 }
3886};
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003887
3888
Chris Lattner113f4f42002-06-25 16:13:24 +00003889Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003890 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00003891 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003892
Chris Lattner81a7a232004-10-16 18:11:37 +00003893 if (isa<UndefValue>(Op1))
3894 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
3895
Chris Lattnerc2076352004-02-16 01:20:27 +00003896 // xor X, X = 0, even if X is nested in a sequence of Xor's.
3897 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
3898 assert(Result == &I && "AssociativeOpt didn't work?");
Chris Lattnere6794492002-08-12 21:17:25 +00003899 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc2076352004-02-16 01:20:27 +00003900 }
Chris Lattner5b2edb12006-02-12 08:02:11 +00003901
3902 // See if we can simplify any instructions used by the instruction whose sole
3903 // purpose is to compute bits we don't care about.
3904 uint64_t KnownZero, KnownOne;
Chris Lattnerd70d9f52006-03-25 21:58:26 +00003905 if (!isa<PackedType>(I.getType()) &&
3906 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
Chris Lattner5b2edb12006-02-12 08:02:11 +00003907 KnownZero, KnownOne))
3908 return &I;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003909
Chris Lattner97638592003-07-23 21:37:07 +00003910 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00003911 // xor (icmp A, B), true = not (icmp A, B) = !icmp A, B
3912 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
3913 if (RHS == ConstantBool::getTrue() && ICI->hasOneUse())
3914 return new ICmpInst(ICI->getInversePredicate(),
3915 ICI->getOperand(0), ICI->getOperand(1));
Chris Lattnere5806662003-11-04 23:50:51 +00003916
Reid Spencer266e42b2006-12-23 06:05:41 +00003917 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattner8f2f5982003-11-05 01:06:05 +00003918 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003919 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
3920 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003921 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
3922 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003923 ConstantInt::get(I.getType(), 1));
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003924 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003925 }
Chris Lattner023a4832004-06-18 06:07:51 +00003926
3927 // ~(~X & Y) --> (X | ~Y)
3928 if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
3929 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
3930 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
3931 Instruction *NotY =
Misha Brukmanb1c93172005-04-21 23:48:37 +00003932 BinaryOperator::createNot(Op0I->getOperand(1),
Chris Lattner023a4832004-06-18 06:07:51 +00003933 Op0I->getOperand(1)->getName()+".not");
3934 InsertNewInstBefore(NotY, I);
3935 return BinaryOperator::createOr(Op0NotVal, NotY);
3936 }
3937 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003938
Chris Lattner97638592003-07-23 21:37:07 +00003939 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner5b2edb12006-02-12 08:02:11 +00003940 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner0f68fa62003-11-04 23:37:10 +00003941 // ~(X-c) --> (-c-1)-X
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003942 if (RHS->isAllOnesValue()) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003943 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
3944 return BinaryOperator::createSub(
3945 ConstantExpr::getSub(NegOp0CI,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003946 ConstantInt::get(I.getType(), 1)),
Chris Lattner0f68fa62003-11-04 23:37:10 +00003947 Op0I->getOperand(0));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003948 }
Chris Lattnerf78df7c2006-02-26 19:57:54 +00003949 } else if (Op0I->getOpcode() == Instruction::Or) {
3950 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
3951 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getZExtValue())) {
3952 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
3953 // Anything in both C1 and C2 is known to be zero, remove it from
3954 // NewRHS.
3955 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
3956 NewRHS = ConstantExpr::getAnd(NewRHS,
3957 ConstantExpr::getNot(CommonBits));
3958 WorkList.push_back(Op0I);
3959 I.setOperand(0, Op0I->getOperand(0));
3960 I.setOperand(1, NewRHS);
3961 return &I;
3962 }
Chris Lattner97638592003-07-23 21:37:07 +00003963 }
Chris Lattnerb8d6e402002-08-20 18:24:26 +00003964 }
Chris Lattner183b3362004-04-09 19:05:30 +00003965
3966 // Try to fold constant and into select arguments.
3967 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00003968 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00003969 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00003970 if (isa<PHINode>(Op0))
3971 if (Instruction *NV = FoldOpIntoPhi(I))
3972 return NV;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003973 }
3974
Chris Lattnerbb74e222003-03-10 23:06:50 +00003975 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00003976 if (X == Op1)
3977 return ReplaceInstUsesWith(I,
3978 ConstantIntegral::getAllOnesValue(I.getType()));
3979
Chris Lattnerbb74e222003-03-10 23:06:50 +00003980 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00003981 if (X == Op0)
3982 return ReplaceInstUsesWith(I,
3983 ConstantIntegral::getAllOnesValue(I.getType()));
3984
Chris Lattnerdcd07922006-04-01 08:03:55 +00003985 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1))
Chris Lattnerb36d9082004-02-16 03:54:20 +00003986 if (Op1I->getOpcode() == Instruction::Or) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003987 if (Op1I->getOperand(0) == Op0) { // B^(B|A) == (A|B)^B
Chris Lattnerdcd07922006-04-01 08:03:55 +00003988 Op1I->swapOperands();
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003989 I.swapOperands();
3990 std::swap(Op0, Op1);
3991 } else if (Op1I->getOperand(1) == Op0) { // B^(A|B) == (A|B)^B
Chris Lattnerdcd07922006-04-01 08:03:55 +00003992 I.swapOperands(); // Simplified below.
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003993 std::swap(Op0, Op1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003994 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00003995 } else if (Op1I->getOpcode() == Instruction::Xor) {
3996 if (Op0 == Op1I->getOperand(0)) // A^(A^B) == B
3997 return ReplaceInstUsesWith(I, Op1I->getOperand(1));
3998 else if (Op0 == Op1I->getOperand(1)) // A^(B^A) == B
3999 return ReplaceInstUsesWith(I, Op1I->getOperand(0));
Chris Lattnerdcd07922006-04-01 08:03:55 +00004000 } else if (Op1I->getOpcode() == Instruction::And && Op1I->hasOneUse()) {
4001 if (Op1I->getOperand(0) == Op0) // A^(A&B) -> A^(B&A)
4002 Op1I->swapOperands();
4003 if (Op0 == Op1I->getOperand(1)) { // A^(B&A) -> (B&A)^A
4004 I.swapOperands(); // Simplified below.
4005 std::swap(Op0, Op1);
4006 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00004007 }
Chris Lattner1bbb7b62003-03-10 18:24:17 +00004008
Chris Lattnerdcd07922006-04-01 08:03:55 +00004009 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00004010 if (Op0I->getOpcode() == Instruction::Or && Op0I->hasOneUse()) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00004011 if (Op0I->getOperand(0) == Op1) // (B|A)^B == (A|B)^B
Chris Lattnerdcd07922006-04-01 08:03:55 +00004012 Op0I->swapOperands();
Chris Lattnerdcf240a2003-03-10 21:43:22 +00004013 if (Op0I->getOperand(1) == Op1) { // (A|B)^B == A & ~B
Chris Lattnerdcd07922006-04-01 08:03:55 +00004014 Instruction *NotB = BinaryOperator::createNot(Op1, "tmp");
4015 InsertNewInstBefore(NotB, I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004016 return BinaryOperator::createAnd(Op0I->getOperand(0), NotB);
Chris Lattner1bbb7b62003-03-10 18:24:17 +00004017 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00004018 } else if (Op0I->getOpcode() == Instruction::Xor) {
4019 if (Op1 == Op0I->getOperand(0)) // (A^B)^A == B
4020 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
4021 else if (Op1 == Op0I->getOperand(1)) // (B^A)^A == B
4022 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattnerdcd07922006-04-01 08:03:55 +00004023 } else if (Op0I->getOpcode() == Instruction::And && Op0I->hasOneUse()) {
4024 if (Op0I->getOperand(0) == Op1) // (A&B)^A -> (B&A)^A
4025 Op0I->swapOperands();
Chris Lattner6cf49142006-04-01 22:05:01 +00004026 if (Op0I->getOperand(1) == Op1 && // (B&A)^A == ~B & A
4027 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattnerdcd07922006-04-01 08:03:55 +00004028 Instruction *N = BinaryOperator::createNot(Op0I->getOperand(0), "tmp");
4029 InsertNewInstBefore(N, I);
4030 return BinaryOperator::createAnd(N, Op1);
4031 }
Chris Lattner1bbb7b62003-03-10 18:24:17 +00004032 }
4033
Reid Spencer266e42b2006-12-23 06:05:41 +00004034 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
4035 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
4036 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattner3ac7c262003-08-13 20:16:26 +00004037 return R;
4038
Chris Lattner3af10532006-05-05 06:39:07 +00004039 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Reid Spencer799b5bf2006-12-13 08:27:15 +00004040 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
Chris Lattner3af10532006-05-05 06:39:07 +00004041 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer799b5bf2006-12-13 08:27:15 +00004042 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
4043 const Type *SrcTy = Op0C->getOperand(0)->getType();
4044 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegral() &&
4045 // Only do this if the casts both really cause code to be generated.
Reid Spencer266e42b2006-12-23 06:05:41 +00004046 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4047 I.getType(), TD) &&
4048 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4049 I.getType(), TD)) {
Reid Spencer799b5bf2006-12-13 08:27:15 +00004050 Instruction *NewOp = BinaryOperator::createXor(Op0C->getOperand(0),
4051 Op1C->getOperand(0),
4052 I.getName());
4053 InsertNewInstBefore(NewOp, I);
4054 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
4055 }
Chris Lattner3af10532006-05-05 06:39:07 +00004056 }
Chris Lattnerf05d69a2006-11-14 07:46:50 +00004057
4058 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
4059 if (ShiftInst *SI1 = dyn_cast<ShiftInst>(Op1)) {
4060 if (ShiftInst *SI0 = dyn_cast<ShiftInst>(Op0))
4061 if (SI0->getOpcode() == SI1->getOpcode() &&
4062 SI0->getOperand(1) == SI1->getOperand(1) &&
4063 (SI0->hasOneUse() || SI1->hasOneUse())) {
4064 Instruction *NewOp =
4065 InsertNewInstBefore(BinaryOperator::createXor(SI0->getOperand(0),
4066 SI1->getOperand(0),
4067 SI0->getName()), I);
4068 return new ShiftInst(SI1->getOpcode(), NewOp, SI1->getOperand(1));
4069 }
4070 }
Chris Lattner3af10532006-05-05 06:39:07 +00004071
Chris Lattner113f4f42002-06-25 16:13:24 +00004072 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004073}
4074
Chris Lattner6862fbd2004-09-29 17:40:11 +00004075static bool isPositive(ConstantInt *C) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00004076 return C->getSExtValue() >= 0;
Chris Lattner6862fbd2004-09-29 17:40:11 +00004077}
4078
4079/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
4080/// overflowed for this type.
4081static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
4082 ConstantInt *In2) {
4083 Result = cast<ConstantInt>(ConstantExpr::getAdd(In1, In2));
4084
Reid Spencerc635f472006-12-31 05:48:39 +00004085 return cast<ConstantInt>(Result)->getZExtValue() <
4086 cast<ConstantInt>(In1)->getZExtValue();
Chris Lattner6862fbd2004-09-29 17:40:11 +00004087}
4088
Chris Lattner0798af32005-01-13 20:14:25 +00004089/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
4090/// code necessary to compute the offset from the base pointer (without adding
4091/// in the base pointer). Return the result as a signed integer of intptr size.
4092static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
4093 TargetData &TD = IC.getTargetData();
4094 gep_type_iterator GTI = gep_type_begin(GEP);
Reid Spencer266e42b2006-12-23 06:05:41 +00004095 const Type *IntPtrTy = TD.getIntPtrType();
4096 Value *Result = Constant::getNullValue(IntPtrTy);
Chris Lattner0798af32005-01-13 20:14:25 +00004097
4098 // Build a mask for high order bits.
Chris Lattner77defba2006-02-07 07:00:41 +00004099 uint64_t PtrSizeMask = ~0ULL >> (64-TD.getPointerSize()*8);
Chris Lattner0798af32005-01-13 20:14:25 +00004100
Chris Lattner0798af32005-01-13 20:14:25 +00004101 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
4102 Value *Op = GEP->getOperand(i);
Chris Lattnerd35d2102005-01-13 23:26:48 +00004103 uint64_t Size = TD.getTypeSize(GTI.getIndexedType()) & PtrSizeMask;
Reid Spencer266e42b2006-12-23 06:05:41 +00004104 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
Chris Lattner0798af32005-01-13 20:14:25 +00004105 if (Constant *OpC = dyn_cast<Constant>(Op)) {
4106 if (!OpC->isNullValue()) {
Reid Spencer266e42b2006-12-23 06:05:41 +00004107 OpC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
Chris Lattner0798af32005-01-13 20:14:25 +00004108 Scale = ConstantExpr::getMul(OpC, Scale);
4109 if (Constant *RC = dyn_cast<Constant>(Result))
4110 Result = ConstantExpr::getAdd(RC, Scale);
4111 else {
4112 // Emit an add instruction.
4113 Result = IC.InsertNewInstBefore(
4114 BinaryOperator::createAdd(Result, Scale,
4115 GEP->getName()+".offs"), I);
4116 }
4117 }
4118 } else {
Chris Lattner7aa41cf2005-01-14 17:17:59 +00004119 // Convert to correct type.
Reid Spencer266e42b2006-12-23 06:05:41 +00004120 Op = IC.InsertNewInstBefore(CastInst::createSExtOrBitCast(Op, IntPtrTy,
Chris Lattner7aa41cf2005-01-14 17:17:59 +00004121 Op->getName()+".c"), I);
4122 if (Size != 1)
Chris Lattner4cb9fa32005-01-13 20:40:58 +00004123 // We'll let instcombine(mul) convert this to a shl if possible.
4124 Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
4125 GEP->getName()+".idx"), I);
Chris Lattner0798af32005-01-13 20:14:25 +00004126
4127 // Emit an add instruction.
Chris Lattner4cb9fa32005-01-13 20:40:58 +00004128 Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
Chris Lattner0798af32005-01-13 20:14:25 +00004129 GEP->getName()+".offs"), I);
4130 }
4131 }
4132 return Result;
4133}
4134
Reid Spencer266e42b2006-12-23 06:05:41 +00004135/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
Chris Lattner0798af32005-01-13 20:14:25 +00004136/// else. At this point we know that the GEP is on the LHS of the comparison.
Reid Spencer266e42b2006-12-23 06:05:41 +00004137Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
4138 ICmpInst::Predicate Cond,
4139 Instruction &I) {
Chris Lattner0798af32005-01-13 20:14:25 +00004140 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattner81e84172005-01-13 22:25:21 +00004141
4142 if (CastInst *CI = dyn_cast<CastInst>(RHS))
4143 if (isa<PointerType>(CI->getOperand(0)->getType()))
4144 RHS = CI->getOperand(0);
4145
Chris Lattner0798af32005-01-13 20:14:25 +00004146 Value *PtrBase = GEPLHS->getOperand(0);
4147 if (PtrBase == RHS) {
4148 // As an optimization, we don't actually have to compute the actual value of
Reid Spencer266e42b2006-12-23 06:05:41 +00004149 // OFFSET if this is a icmp_eq or icmp_ne comparison, just return whether
4150 // each index is zero or not.
4151 if (Cond == ICmpInst::ICMP_EQ || Cond == ICmpInst::ICMP_NE) {
Chris Lattner81e84172005-01-13 22:25:21 +00004152 Instruction *InVal = 0;
Chris Lattnercd517ff2005-01-28 19:32:01 +00004153 gep_type_iterator GTI = gep_type_begin(GEPLHS);
4154 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i, ++GTI) {
Chris Lattner81e84172005-01-13 22:25:21 +00004155 bool EmitIt = true;
4156 if (Constant *C = dyn_cast<Constant>(GEPLHS->getOperand(i))) {
4157 if (isa<UndefValue>(C)) // undef index -> undef.
4158 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
4159 if (C->isNullValue())
4160 EmitIt = false;
Chris Lattnercd517ff2005-01-28 19:32:01 +00004161 else if (TD->getTypeSize(GTI.getIndexedType()) == 0) {
4162 EmitIt = false; // This is indexing into a zero sized array?
Misha Brukmanb1c93172005-04-21 23:48:37 +00004163 } else if (isa<ConstantInt>(C))
Chris Lattner81e84172005-01-13 22:25:21 +00004164 return ReplaceInstUsesWith(I, // No comparison is needed here.
Reid Spencer266e42b2006-12-23 06:05:41 +00004165 ConstantBool::get(Cond == ICmpInst::ICMP_NE));
Chris Lattner81e84172005-01-13 22:25:21 +00004166 }
4167
4168 if (EmitIt) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00004169 Instruction *Comp =
Reid Spencer266e42b2006-12-23 06:05:41 +00004170 new ICmpInst(Cond, GEPLHS->getOperand(i),
Chris Lattner81e84172005-01-13 22:25:21 +00004171 Constant::getNullValue(GEPLHS->getOperand(i)->getType()));
4172 if (InVal == 0)
4173 InVal = Comp;
4174 else {
4175 InVal = InsertNewInstBefore(InVal, I);
4176 InsertNewInstBefore(Comp, I);
Reid Spencer266e42b2006-12-23 06:05:41 +00004177 if (Cond == ICmpInst::ICMP_NE) // True if any are unequal
Chris Lattner81e84172005-01-13 22:25:21 +00004178 InVal = BinaryOperator::createOr(InVal, Comp);
4179 else // True if all are equal
4180 InVal = BinaryOperator::createAnd(InVal, Comp);
4181 }
4182 }
4183 }
4184
4185 if (InVal)
4186 return InVal;
4187 else
Reid Spencer266e42b2006-12-23 06:05:41 +00004188 // No comparison is needed here, all indexes = 0
4189 ReplaceInstUsesWith(I, ConstantBool::get(Cond == ICmpInst::ICMP_EQ));
Chris Lattner81e84172005-01-13 22:25:21 +00004190 }
Chris Lattner0798af32005-01-13 20:14:25 +00004191
Reid Spencer266e42b2006-12-23 06:05:41 +00004192 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner0798af32005-01-13 20:14:25 +00004193 // the result to fold to a constant!
4194 if (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) {
4195 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
4196 Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
Reid Spencer266e42b2006-12-23 06:05:41 +00004197 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
4198 Constant::getNullValue(Offset->getType()));
Chris Lattner0798af32005-01-13 20:14:25 +00004199 }
4200 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
Chris Lattnera21bf8d2005-04-25 20:17:30 +00004201 // If the base pointers are different, but the indices are the same, just
4202 // compare the base pointer.
4203 if (PtrBase != GEPRHS->getOperand(0)) {
4204 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00004205 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattnerbd43b9d2005-04-26 14:40:41 +00004206 GEPRHS->getOperand(0)->getType();
Chris Lattnera21bf8d2005-04-25 20:17:30 +00004207 if (IndicesTheSame)
4208 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4209 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4210 IndicesTheSame = false;
4211 break;
4212 }
4213
4214 // If all indices are the same, just compare the base pointers.
4215 if (IndicesTheSame)
Reid Spencer266e42b2006-12-23 06:05:41 +00004216 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
4217 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattnera21bf8d2005-04-25 20:17:30 +00004218
4219 // Otherwise, the base pointers are different and the indices are
4220 // different, bail out.
Chris Lattner0798af32005-01-13 20:14:25 +00004221 return 0;
Chris Lattnera21bf8d2005-04-25 20:17:30 +00004222 }
Chris Lattner0798af32005-01-13 20:14:25 +00004223
Chris Lattner81e84172005-01-13 22:25:21 +00004224 // If one of the GEPs has all zero indices, recurse.
4225 bool AllZeros = true;
4226 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4227 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
4228 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
4229 AllZeros = false;
4230 break;
4231 }
4232 if (AllZeros)
Reid Spencer266e42b2006-12-23 06:05:41 +00004233 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
4234 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner4fa89822005-01-14 00:20:05 +00004235
4236 // If the other GEP has all zero indices, recurse.
Chris Lattner81e84172005-01-13 22:25:21 +00004237 AllZeros = true;
4238 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4239 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
4240 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
4241 AllZeros = false;
4242 break;
4243 }
4244 if (AllZeros)
Reid Spencer266e42b2006-12-23 06:05:41 +00004245 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
Chris Lattner81e84172005-01-13 22:25:21 +00004246
Chris Lattner4fa89822005-01-14 00:20:05 +00004247 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
4248 // If the GEPs only differ by one index, compare it.
4249 unsigned NumDifferences = 0; // Keep track of # differences.
4250 unsigned DiffOperand = 0; // The operand that differs.
4251 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4252 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004253 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
4254 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattnerfc4429e2005-01-21 23:06:49 +00004255 // Irreconcilable differences.
Chris Lattner4fa89822005-01-14 00:20:05 +00004256 NumDifferences = 2;
4257 break;
4258 } else {
4259 if (NumDifferences++) break;
4260 DiffOperand = i;
4261 }
4262 }
4263
4264 if (NumDifferences == 0) // SAME GEP?
4265 return ReplaceInstUsesWith(I, // No comparison is needed here.
Reid Spencer266e42b2006-12-23 06:05:41 +00004266 ConstantBool::get(Cond == ICmpInst::ICMP_EQ));
Chris Lattner4fa89822005-01-14 00:20:05 +00004267 else if (NumDifferences == 1) {
Chris Lattnerfc4429e2005-01-21 23:06:49 +00004268 Value *LHSV = GEPLHS->getOperand(DiffOperand);
4269 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Reid Spencer266e42b2006-12-23 06:05:41 +00004270 if (LHSV->getType() != RHSV->getType())
4271 // Doesn't matter which one we bitconvert here.
4272 LHSV = InsertCastBefore(Instruction::BitCast, LHSV, RHSV->getType(),
4273 I);
4274 // Make sure we do a signed comparison here.
4275 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
Chris Lattner4fa89822005-01-14 00:20:05 +00004276 }
4277 }
4278
Reid Spencer266e42b2006-12-23 06:05:41 +00004279 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner0798af32005-01-13 20:14:25 +00004280 // the result to fold to a constant!
4281 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
4282 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
4283 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
4284 Value *L = EmitGEPOffset(GEPLHS, I, *this);
4285 Value *R = EmitGEPOffset(GEPRHS, I, *this);
Reid Spencer266e42b2006-12-23 06:05:41 +00004286 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
Chris Lattner0798af32005-01-13 20:14:25 +00004287 }
4288 }
4289 return 0;
4290}
4291
Reid Spencer266e42b2006-12-23 06:05:41 +00004292Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
4293 bool Changed = SimplifyCompare(I);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004294 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004295
Reid Spencer266e42b2006-12-23 06:05:41 +00004296 // fcmp pred X, X
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004297 if (Op0 == Op1)
4298 return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
Chris Lattner1fc23f32002-05-09 20:11:54 +00004299
Reid Spencer266e42b2006-12-23 06:05:41 +00004300 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
Chris Lattner81a7a232004-10-16 18:11:37 +00004301 return ReplaceInstUsesWith(I, UndefValue::get(Type::BoolTy));
4302
Reid Spencer266e42b2006-12-23 06:05:41 +00004303 // Handle fcmp with constant RHS
4304 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
4305 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4306 switch (LHSI->getOpcode()) {
4307 case Instruction::PHI:
4308 if (Instruction *NV = FoldOpIntoPhi(I))
4309 return NV;
4310 break;
4311 case Instruction::Select:
4312 // If either operand of the select is a constant, we can fold the
4313 // comparison into the select arms, which will cause one to be
4314 // constant folded and the select turned into a bitwise or.
4315 Value *Op1 = 0, *Op2 = 0;
4316 if (LHSI->hasOneUse()) {
4317 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
4318 // Fold the known value into the constant operand.
4319 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
4320 // Insert a new FCmp of the other select operand.
4321 Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
4322 LHSI->getOperand(2), RHSC,
4323 I.getName()), I);
4324 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
4325 // Fold the known value into the constant operand.
4326 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
4327 // Insert a new FCmp of the other select operand.
4328 Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
4329 LHSI->getOperand(1), RHSC,
4330 I.getName()), I);
4331 }
4332 }
4333
4334 if (Op1)
4335 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
4336 break;
4337 }
4338 }
4339
4340 return Changed ? &I : 0;
4341}
4342
4343Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
4344 bool Changed = SimplifyCompare(I);
4345 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4346 const Type *Ty = Op0->getType();
4347
4348 // icmp X, X
4349 if (Op0 == Op1)
4350 return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
4351
4352 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
4353 return ReplaceInstUsesWith(I, UndefValue::get(Type::BoolTy));
4354
4355 // icmp of GlobalValues can never equal each other as long as they aren't
4356 // external weak linkage type.
4357 if (GlobalValue *GV0 = dyn_cast<GlobalValue>(Op0))
4358 if (GlobalValue *GV1 = dyn_cast<GlobalValue>(Op1))
4359 if (!GV0->hasExternalWeakLinkage() || !GV1->hasExternalWeakLinkage())
4360 return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
4361
4362 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
Chris Lattner15ff1e12004-11-14 07:33:16 +00004363 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanb1c93172005-04-21 23:48:37 +00004364 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
4365 isa<ConstantPointerNull>(Op0)) &&
4366 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner15ff1e12004-11-14 07:33:16 +00004367 isa<ConstantPointerNull>(Op1)))
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004368 return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
4369
Reid Spencer266e42b2006-12-23 06:05:41 +00004370 // icmp's with boolean values can always be turned into bitwise operations
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004371 if (Ty == Type::BoolTy) {
Reid Spencer266e42b2006-12-23 06:05:41 +00004372 switch (I.getPredicate()) {
4373 default: assert(0 && "Invalid icmp instruction!");
4374 case ICmpInst::ICMP_EQ: { // icmp eq bool %A, %B -> ~(A^B)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004375 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004376 InsertNewInstBefore(Xor, I);
Chris Lattner16930792003-11-03 04:25:02 +00004377 return BinaryOperator::createNot(Xor);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004378 }
Reid Spencer266e42b2006-12-23 06:05:41 +00004379 case ICmpInst::ICMP_NE: // icmp eq bool %A, %B -> A^B
Chris Lattner4456da62004-08-11 00:50:51 +00004380 return BinaryOperator::createXor(Op0, Op1);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004381
Reid Spencer266e42b2006-12-23 06:05:41 +00004382 case ICmpInst::ICMP_UGT:
4383 case ICmpInst::ICMP_SGT:
4384 std::swap(Op0, Op1); // Change icmp gt -> icmp lt
Chris Lattner4456da62004-08-11 00:50:51 +00004385 // FALL THROUGH
Reid Spencer266e42b2006-12-23 06:05:41 +00004386 case ICmpInst::ICMP_ULT:
4387 case ICmpInst::ICMP_SLT: { // icmp lt bool A, B -> ~X & Y
Chris Lattner4456da62004-08-11 00:50:51 +00004388 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4389 InsertNewInstBefore(Not, I);
4390 return BinaryOperator::createAnd(Not, Op1);
4391 }
Reid Spencer266e42b2006-12-23 06:05:41 +00004392 case ICmpInst::ICMP_UGE:
4393 case ICmpInst::ICMP_SGE:
4394 std::swap(Op0, Op1); // Change icmp ge -> icmp le
Chris Lattner4456da62004-08-11 00:50:51 +00004395 // FALL THROUGH
Reid Spencer266e42b2006-12-23 06:05:41 +00004396 case ICmpInst::ICMP_ULE:
4397 case ICmpInst::ICMP_SLE: { // icmp le bool %A, %B -> ~A | B
Chris Lattner4456da62004-08-11 00:50:51 +00004398 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4399 InsertNewInstBefore(Not, I);
4400 return BinaryOperator::createOr(Not, Op1);
4401 }
4402 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004403 }
4404
Chris Lattner2dd01742004-06-09 04:24:29 +00004405 // See if we are doing a comparison between a constant and an instruction that
4406 // can be folded into the comparison.
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004407 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00004408 switch (I.getPredicate()) {
4409 default: break;
4410 case ICmpInst::ICMP_ULT: // A <u MIN -> FALSE
4411 if (CI->isMinValue(false))
Chris Lattner6ab03f62006-09-28 23:35:22 +00004412 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004413 if (CI->isMaxValue(false)) // A <u MAX -> A != MAX
4414 return new ICmpInst(ICmpInst::ICMP_NE, Op0,Op1);
4415 if (isMinValuePlusOne(CI,false)) // A <u MIN+1 -> A == MIN
4416 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
4417 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00004418
Reid Spencer266e42b2006-12-23 06:05:41 +00004419 case ICmpInst::ICMP_SLT:
4420 if (CI->isMinValue(true)) // A <s MIN -> FALSE
Chris Lattner6ab03f62006-09-28 23:35:22 +00004421 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004422 if (CI->isMaxValue(true)) // A <s MAX -> A != MAX
4423 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4424 if (isMinValuePlusOne(CI,true)) // A <s MIN+1 -> A == MIN
4425 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
4426 break;
4427
4428 case ICmpInst::ICMP_UGT:
4429 if (CI->isMaxValue(false)) // A >u MAX -> FALSE
4430 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4431 if (CI->isMinValue(false)) // A >u MIN -> A != MIN
4432 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4433 if (isMaxValueMinusOne(CI, false)) // A >u MAX-1 -> A == MAX
4434 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
4435 break;
4436
4437 case ICmpInst::ICMP_SGT:
4438 if (CI->isMaxValue(true)) // A >s MAX -> FALSE
4439 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4440 if (CI->isMinValue(true)) // A >s MIN -> A != MIN
4441 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4442 if (isMaxValueMinusOne(CI, true)) // A >s MAX-1 -> A == MAX
4443 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
4444 break;
4445
4446 case ICmpInst::ICMP_ULE:
4447 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
Chris Lattner6ab03f62006-09-28 23:35:22 +00004448 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004449 if (CI->isMinValue(false)) // A <=u MIN -> A == MIN
4450 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4451 if (isMaxValueMinusOne(CI,false)) // A <=u MAX-1 -> A != MAX
4452 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
4453 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00004454
Reid Spencer266e42b2006-12-23 06:05:41 +00004455 case ICmpInst::ICMP_SLE:
4456 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
4457 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4458 if (CI->isMinValue(true)) // A <=s MIN -> A == MIN
4459 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4460 if (isMaxValueMinusOne(CI,true)) // A <=s MAX-1 -> A != MAX
4461 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
4462 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00004463
Reid Spencer266e42b2006-12-23 06:05:41 +00004464 case ICmpInst::ICMP_UGE:
4465 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
4466 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4467 if (CI->isMaxValue(false)) // A >=u MAX -> A == MAX
4468 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4469 if (isMinValuePlusOne(CI,false)) // A >=u MIN-1 -> A != MIN
4470 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
4471 break;
4472
4473 case ICmpInst::ICMP_SGE:
4474 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
4475 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4476 if (CI->isMaxValue(true)) // A >=s MAX -> A == MAX
4477 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4478 if (isMinValuePlusOne(CI,true)) // A >=s MIN-1 -> A != MIN
4479 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
4480 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00004481 }
4482
Reid Spencer266e42b2006-12-23 06:05:41 +00004483 // If we still have a icmp le or icmp ge instruction, turn it into the
4484 // appropriate icmp lt or icmp gt instruction. Since the border cases have
Chris Lattner6862fbd2004-09-29 17:40:11 +00004485 // already been handled above, this requires little checking.
4486 //
Reid Spencer266e42b2006-12-23 06:05:41 +00004487 if (I.getPredicate() == ICmpInst::ICMP_ULE)
4488 return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
4489 if (I.getPredicate() == ICmpInst::ICMP_SLE)
4490 return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
4491 if (I.getPredicate() == ICmpInst::ICMP_UGE)
4492 return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
4493 if (I.getPredicate() == ICmpInst::ICMP_SGE)
4494 return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
Chris Lattneree0f2802006-02-12 02:07:56 +00004495
4496 // See if we can fold the comparison based on bits known to be zero or one
4497 // in the input.
4498 uint64_t KnownZero, KnownOne;
4499 if (SimplifyDemandedBits(Op0, Ty->getIntegralTypeMask(),
4500 KnownZero, KnownOne, 0))
4501 return &I;
4502
4503 // Given the known and unknown bits, compute a range that the LHS could be
4504 // in.
4505 if (KnownOne | KnownZero) {
Reid Spencer266e42b2006-12-23 06:05:41 +00004506 // Compute the Min, Max and RHS values based on the known bits. For the
4507 // EQ and NE we use unsigned values.
Reid Spencer910f23f2006-12-23 19:17:57 +00004508 uint64_t UMin = 0, UMax = 0, URHSVal = 0;
4509 int64_t SMin = 0, SMax = 0, SRHSVal = 0;
Reid Spencer266e42b2006-12-23 06:05:41 +00004510 if (ICmpInst::isSignedPredicate(I.getPredicate())) {
4511 SRHSVal = CI->getSExtValue();
4512 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, SMin,
4513 SMax);
4514 } else {
4515 URHSVal = CI->getZExtValue();
4516 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, UMin,
4517 UMax);
4518 }
4519 switch (I.getPredicate()) { // LE/GE have been folded already.
4520 default: assert(0 && "Unknown icmp opcode!");
4521 case ICmpInst::ICMP_EQ:
4522 if (UMax < URHSVal || UMin > URHSVal)
4523 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4524 break;
4525 case ICmpInst::ICMP_NE:
4526 if (UMax < URHSVal || UMin > URHSVal)
4527 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4528 break;
4529 case ICmpInst::ICMP_ULT:
4530 if (UMax < URHSVal)
4531 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4532 if (UMin > URHSVal)
4533 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4534 break;
4535 case ICmpInst::ICMP_UGT:
4536 if (UMin > URHSVal)
4537 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4538 if (UMax < URHSVal)
4539 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4540 break;
4541 case ICmpInst::ICMP_SLT:
4542 if (SMax < SRHSVal)
4543 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4544 if (SMin > SRHSVal)
4545 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4546 break;
4547 case ICmpInst::ICMP_SGT:
4548 if (SMin > SRHSVal)
4549 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4550 if (SMax < SRHSVal)
4551 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4552 break;
Chris Lattneree0f2802006-02-12 02:07:56 +00004553 }
4554 }
4555
Reid Spencer266e42b2006-12-23 06:05:41 +00004556 // Since the RHS is a ConstantInt (CI), if the left hand side is an
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004557 // instruction, see if that instruction also has constants so that the
Reid Spencer266e42b2006-12-23 06:05:41 +00004558 // instruction can be folded into the icmp
Chris Lattnere1e10e12004-05-25 06:32:08 +00004559 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004560 switch (LHSI->getOpcode()) {
4561 case Instruction::And:
4562 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
4563 LHSI->getOperand(0)->hasOneUse()) {
Chris Lattner4922a0e2006-09-18 05:27:43 +00004564 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
4565
Reid Spencer266e42b2006-12-23 06:05:41 +00004566 // If the LHS is an AND of a truncating cast, we can widen the
Chris Lattner4922a0e2006-09-18 05:27:43 +00004567 // and/compare to be the input width without changing the value
4568 // produced, eliminating a cast.
4569 if (CastInst *Cast = dyn_cast<CastInst>(LHSI->getOperand(0))) {
4570 // We can do this transformation if either the AND constant does not
4571 // have its sign bit set or if it is an equality comparison.
4572 // Extending a relational comparison when we're checking the sign
4573 // bit would not work.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00004574 if (Cast->hasOneUse() && isa<TruncInst>(Cast) &&
Chris Lattner4922a0e2006-09-18 05:27:43 +00004575 (I.isEquality() ||
4576 (AndCST->getZExtValue() == (uint64_t)AndCST->getSExtValue()) &&
4577 (CI->getZExtValue() == (uint64_t)CI->getSExtValue()))) {
4578 ConstantInt *NewCST;
4579 ConstantInt *NewCI;
Reid Spencerc635f472006-12-31 05:48:39 +00004580 NewCST = ConstantInt::get(Cast->getOperand(0)->getType(),
4581 AndCST->getZExtValue());
4582 NewCI = ConstantInt::get(Cast->getOperand(0)->getType(),
4583 CI->getZExtValue());
Chris Lattner4922a0e2006-09-18 05:27:43 +00004584 Instruction *NewAnd =
4585 BinaryOperator::createAnd(Cast->getOperand(0), NewCST,
4586 LHSI->getName());
4587 InsertNewInstBefore(NewAnd, I);
Reid Spencer266e42b2006-12-23 06:05:41 +00004588 return new ICmpInst(I.getPredicate(), NewAnd, NewCI);
Chris Lattner4922a0e2006-09-18 05:27:43 +00004589 }
4590 }
4591
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004592 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
4593 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
4594 // happens a LOT in code produced by the C front-end, for bitfield
4595 // access.
4596 ShiftInst *Shift = dyn_cast<ShiftInst>(LHSI->getOperand(0));
Chris Lattneree0f2802006-02-12 02:07:56 +00004597
4598 // Check to see if there is a noop-cast between the shift and the and.
4599 if (!Shift) {
4600 if (CastInst *CI = dyn_cast<CastInst>(LHSI->getOperand(0)))
Reid Spencer74a528b2006-12-13 18:21:21 +00004601 if (CI->getOpcode() == Instruction::BitCast)
Chris Lattneree0f2802006-02-12 02:07:56 +00004602 Shift = dyn_cast<ShiftInst>(CI->getOperand(0));
4603 }
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004604
Reid Spencere0fc4df2006-10-20 07:07:24 +00004605 ConstantInt *ShAmt;
4606 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
Chris Lattneree0f2802006-02-12 02:07:56 +00004607 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
4608 const Type *AndTy = AndCST->getType(); // Type of the and.
Misha Brukmanb1c93172005-04-21 23:48:37 +00004609
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004610 // We can fold this as long as we can't shift unknown bits
4611 // into the mask. This can only happen with signed shift
4612 // rights, as they sign-extend.
4613 if (ShAmt) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004614 bool CanFold = Shift->isLogicalShift();
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004615 if (!CanFold) {
4616 // To test for the bad case of the signed shr, see if any
4617 // of the bits shifted in could be tested after the mask.
Reid Spencere0fc4df2006-10-20 07:07:24 +00004618 int ShAmtVal = Ty->getPrimitiveSizeInBits()-ShAmt->getZExtValue();
Chris Lattnerc53cb9d2005-06-17 01:29:28 +00004619 if (ShAmtVal < 0) ShAmtVal = 0; // Out of range shift.
4620
Reid Spencerc635f472006-12-31 05:48:39 +00004621 Constant *OShAmt = ConstantInt::get(Type::Int8Ty, ShAmtVal);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004622 Constant *ShVal =
Chris Lattneree0f2802006-02-12 02:07:56 +00004623 ConstantExpr::getShl(ConstantInt::getAllOnesValue(AndTy),
4624 OShAmt);
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004625 if (ConstantExpr::getAnd(ShVal, AndCST)->isNullValue())
4626 CanFold = true;
4627 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004628
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004629 if (CanFold) {
Chris Lattner6afc02f2004-09-28 17:54:07 +00004630 Constant *NewCst;
4631 if (Shift->getOpcode() == Instruction::Shl)
Reid Spencerfdff9382006-11-08 06:47:33 +00004632 NewCst = ConstantExpr::getLShr(CI, ShAmt);
Chris Lattner6afc02f2004-09-28 17:54:07 +00004633 else
4634 NewCst = ConstantExpr::getShl(CI, ShAmt);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004635
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004636 // Check to see if we are shifting out any of the bits being
4637 // compared.
4638 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != CI){
4639 // If we shifted bits out, the fold is not going to work out.
4640 // As a special case, check to see if this means that the
4641 // result is always true or false now.
Reid Spencer266e42b2006-12-23 06:05:41 +00004642 if (I.getPredicate() == ICmpInst::ICMP_EQ)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004643 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004644 if (I.getPredicate() == ICmpInst::ICMP_NE)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004645 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004646 } else {
4647 I.setOperand(1, NewCst);
Chris Lattner6afc02f2004-09-28 17:54:07 +00004648 Constant *NewAndCST;
4649 if (Shift->getOpcode() == Instruction::Shl)
Reid Spencerfdff9382006-11-08 06:47:33 +00004650 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
Chris Lattner6afc02f2004-09-28 17:54:07 +00004651 else
4652 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
4653 LHSI->setOperand(1, NewAndCST);
Chris Lattneree0f2802006-02-12 02:07:56 +00004654 if (AndTy == Ty)
4655 LHSI->setOperand(0, Shift->getOperand(0));
4656 else {
Reid Spencer13bc5d72006-12-12 09:18:51 +00004657 Value *NewCast = InsertCastBefore(Instruction::BitCast,
4658 Shift->getOperand(0), AndTy,
Chris Lattneree0f2802006-02-12 02:07:56 +00004659 *Shift);
4660 LHSI->setOperand(0, NewCast);
4661 }
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004662 WorkList.push_back(Shift); // Shift is dead.
4663 AddUsesToWorkList(I);
4664 return &I;
Chris Lattner1638de42004-07-21 19:50:44 +00004665 }
4666 }
Chris Lattner35167c32004-06-09 07:59:58 +00004667 }
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004668
4669 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
4670 // preferable because it allows the C<<Y expression to be hoisted out
4671 // of a loop if Y is invariant and X is not.
4672 if (Shift && Shift->hasOneUse() && CI->isNullValue() &&
Chris Lattnerde077922006-09-18 18:27:05 +00004673 I.isEquality() && !Shift->isArithmeticShift() &&
4674 isa<Instruction>(Shift->getOperand(0))) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004675 // Compute C << Y.
4676 Value *NS;
Reid Spencerfdff9382006-11-08 06:47:33 +00004677 if (Shift->getOpcode() == Instruction::LShr) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004678 NS = new ShiftInst(Instruction::Shl, AndCST, Shift->getOperand(1),
4679 "tmp");
4680 } else {
Reid Spencer2a499b02006-12-13 17:19:09 +00004681 // Insert a logical shift.
4682 NS = new ShiftInst(Instruction::LShr, AndCST,
Chris Lattner4922a0e2006-09-18 05:27:43 +00004683 Shift->getOperand(1), "tmp");
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004684 }
4685 InsertNewInstBefore(cast<Instruction>(NS), I);
4686
4687 // If C's sign doesn't agree with the and, insert a cast now.
4688 if (NS->getType() != LHSI->getType())
Reid Spencer13bc5d72006-12-12 09:18:51 +00004689 NS = InsertCastBefore(Instruction::BitCast, NS, LHSI->getType(),
4690 I);
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004691
4692 Value *ShiftOp = Shift->getOperand(0);
4693 if (ShiftOp->getType() != LHSI->getType())
Reid Spencer13bc5d72006-12-12 09:18:51 +00004694 ShiftOp = InsertCastBefore(Instruction::BitCast, ShiftOp,
4695 LHSI->getType(), I);
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004696
4697 // Compute X & (C << Y).
4698 Instruction *NewAnd =
4699 BinaryOperator::createAnd(ShiftOp, NS, LHSI->getName());
4700 InsertNewInstBefore(NewAnd, I);
4701
4702 I.setOperand(0, NewAnd);
4703 return &I;
4704 }
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004705 }
4706 break;
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004707
Reid Spencer266e42b2006-12-23 06:05:41 +00004708 case Instruction::Shl: // (icmp pred (shl X, ShAmt), CI)
Reid Spencere0fc4df2006-10-20 07:07:24 +00004709 if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004710 if (I.isEquality()) {
Chris Lattner19b57f52005-06-15 20:53:31 +00004711 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
4712
4713 // Check that the shift amount is in range. If not, don't perform
4714 // undefined shifts. When the shift is visited it will be
4715 // simplified.
Reid Spencere0fc4df2006-10-20 07:07:24 +00004716 if (ShAmt->getZExtValue() >= TypeBits)
Chris Lattner19b57f52005-06-15 20:53:31 +00004717 break;
4718
Chris Lattner272d5ca2004-09-28 18:22:15 +00004719 // If we are comparing against bits always shifted out, the
4720 // comparison cannot succeed.
Misha Brukmanb1c93172005-04-21 23:48:37 +00004721 Constant *Comp =
Reid Spencerfdff9382006-11-08 06:47:33 +00004722 ConstantExpr::getShl(ConstantExpr::getLShr(CI, ShAmt), ShAmt);
Chris Lattner272d5ca2004-09-28 18:22:15 +00004723 if (Comp != CI) {// Comparing against a bit that we know is zero.
Reid Spencer266e42b2006-12-23 06:05:41 +00004724 bool IsICMP_NE = I.getPredicate() == ICmpInst::ICMP_NE;
4725 Constant *Cst = ConstantBool::get(IsICMP_NE);
Chris Lattner272d5ca2004-09-28 18:22:15 +00004726 return ReplaceInstUsesWith(I, Cst);
4727 }
4728
4729 if (LHSI->hasOneUse()) {
4730 // Otherwise strength reduce the shift into an and.
Reid Spencere0fc4df2006-10-20 07:07:24 +00004731 unsigned ShAmtVal = (unsigned)ShAmt->getZExtValue();
Chris Lattner272d5ca2004-09-28 18:22:15 +00004732 uint64_t Val = (1ULL << (TypeBits-ShAmtVal))-1;
Reid Spencerc635f472006-12-31 05:48:39 +00004733 Constant *Mask = ConstantInt::get(CI->getType(), Val);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004734
Chris Lattner272d5ca2004-09-28 18:22:15 +00004735 Instruction *AndI =
4736 BinaryOperator::createAnd(LHSI->getOperand(0),
4737 Mask, LHSI->getName()+".mask");
4738 Value *And = InsertNewInstBefore(AndI, I);
Reid Spencer266e42b2006-12-23 06:05:41 +00004739 return new ICmpInst(I.getPredicate(), And,
Reid Spencerfdff9382006-11-08 06:47:33 +00004740 ConstantExpr::getLShr(CI, ShAmt));
Chris Lattner272d5ca2004-09-28 18:22:15 +00004741 }
4742 }
Chris Lattner272d5ca2004-09-28 18:22:15 +00004743 }
4744 break;
4745
Reid Spencer266e42b2006-12-23 06:05:41 +00004746 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
Reid Spencerfdff9382006-11-08 06:47:33 +00004747 case Instruction::AShr:
Reid Spencere0fc4df2006-10-20 07:07:24 +00004748 if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004749 if (I.isEquality()) {
Chris Lattner19b57f52005-06-15 20:53:31 +00004750 // Check that the shift amount is in range. If not, don't perform
4751 // undefined shifts. When the shift is visited it will be
4752 // simplified.
Chris Lattner104002b2005-06-16 01:52:07 +00004753 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
Reid Spencere0fc4df2006-10-20 07:07:24 +00004754 if (ShAmt->getZExtValue() >= TypeBits)
Chris Lattner19b57f52005-06-15 20:53:31 +00004755 break;
4756
Chris Lattner1023b872004-09-27 16:18:50 +00004757 // If we are comparing against bits always shifted out, the
4758 // comparison cannot succeed.
Reid Spencerfdff9382006-11-08 06:47:33 +00004759 Constant *Comp;
Reid Spencerc635f472006-12-31 05:48:39 +00004760 if (LHSI->getOpcode() == Instruction::LShr)
Reid Spencerfdff9382006-11-08 06:47:33 +00004761 Comp = ConstantExpr::getLShr(ConstantExpr::getShl(CI, ShAmt),
4762 ShAmt);
4763 else
4764 Comp = ConstantExpr::getAShr(ConstantExpr::getShl(CI, ShAmt),
4765 ShAmt);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004766
Chris Lattner1023b872004-09-27 16:18:50 +00004767 if (Comp != CI) {// Comparing against a bit that we know is zero.
Reid Spencer266e42b2006-12-23 06:05:41 +00004768 bool IsICMP_NE = I.getPredicate() == ICmpInst::ICMP_NE;
4769 Constant *Cst = ConstantBool::get(IsICMP_NE);
Chris Lattner1023b872004-09-27 16:18:50 +00004770 return ReplaceInstUsesWith(I, Cst);
4771 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004772
Chris Lattner1023b872004-09-27 16:18:50 +00004773 if (LHSI->hasOneUse() || CI->isNullValue()) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00004774 unsigned ShAmtVal = (unsigned)ShAmt->getZExtValue();
Chris Lattner272d5ca2004-09-28 18:22:15 +00004775
Chris Lattner1023b872004-09-27 16:18:50 +00004776 // Otherwise strength reduce the shift into an and.
4777 uint64_t Val = ~0ULL; // All ones.
4778 Val <<= ShAmtVal; // Shift over to the right spot.
Reid Spencerc635f472006-12-31 05:48:39 +00004779 Val &= ~0ULL >> (64-TypeBits);
4780 Constant *Mask = ConstantInt::get(CI->getType(), Val);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004781
Chris Lattner1023b872004-09-27 16:18:50 +00004782 Instruction *AndI =
4783 BinaryOperator::createAnd(LHSI->getOperand(0),
4784 Mask, LHSI->getName()+".mask");
4785 Value *And = InsertNewInstBefore(AndI, I);
Reid Spencer266e42b2006-12-23 06:05:41 +00004786 return new ICmpInst(I.getPredicate(), And,
Chris Lattner1023b872004-09-27 16:18:50 +00004787 ConstantExpr::getShl(CI, ShAmt));
4788 }
Chris Lattner1023b872004-09-27 16:18:50 +00004789 }
4790 }
4791 break;
Chris Lattner7e794272004-09-24 15:21:34 +00004792
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004793 case Instruction::SDiv:
4794 case Instruction::UDiv:
Reid Spencer266e42b2006-12-23 06:05:41 +00004795 // Fold: icmp pred ([us]div X, C1), C2 -> range test
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004796 // Fold this div into the comparison, producing a range check.
4797 // Determine, based on the divide type, what the range is being
4798 // checked. If there is an overflow on the low or high side, remember
4799 // it, otherwise compute the range [low, hi) bounding the new value.
4800 // See: InsertRangeTest above for the kinds of replacements possible.
Chris Lattner6862fbd2004-09-29 17:40:11 +00004801 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004802 // FIXME: If the operand types don't match the type of the divide
4803 // then don't attempt this transform. The code below doesn't have the
4804 // logic to deal with a signed divide and an unsigned compare (and
4805 // vice versa). This is because (x /s C1) <s C2 produces different
4806 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
4807 // (x /u C1) <u C2. Simply casting the operands and result won't
4808 // work. :( The if statement below tests that condition and bails
4809 // if it finds it.
Reid Spencer266e42b2006-12-23 06:05:41 +00004810 bool DivIsSigned = LHSI->getOpcode() == Instruction::SDiv;
4811 if (!I.isEquality() && DivIsSigned != I.isSignedPredicate())
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004812 break;
4813
4814 // Initialize the variables that will indicate the nature of the
4815 // range check.
4816 bool LoOverflow = false, HiOverflow = false;
Chris Lattner6862fbd2004-09-29 17:40:11 +00004817 ConstantInt *LoBound = 0, *HiBound = 0;
4818
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004819 // Compute Prod = CI * DivRHS. We are essentially solving an equation
4820 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
4821 // C2 (CI). By solving for X we can turn this into a range check
4822 // instead of computing a divide.
4823 ConstantInt *Prod =
4824 cast<ConstantInt>(ConstantExpr::getMul(CI, DivRHS));
Chris Lattner6862fbd2004-09-29 17:40:11 +00004825
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004826 // Determine if the product overflows by seeing if the product is
4827 // not equal to the divide. Make sure we do the same kind of divide
4828 // as in the LHS instruction that we're folding.
4829 bool ProdOV = !DivRHS->isNullValue() &&
Reid Spencer266e42b2006-12-23 06:05:41 +00004830 (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004831 ConstantExpr::getUDiv(Prod, DivRHS)) != CI;
4832
Reid Spencer266e42b2006-12-23 06:05:41 +00004833 // Get the ICmp opcode
4834 ICmpInst::Predicate predicate = I.getPredicate();
Chris Lattnera92af962004-10-11 19:40:04 +00004835
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004836 if (DivRHS->isNullValue()) {
4837 // Don't hack on divide by zeros!
Reid Spencer266e42b2006-12-23 06:05:41 +00004838 } else if (!DivIsSigned) { // udiv
Chris Lattner6862fbd2004-09-29 17:40:11 +00004839 LoBound = Prod;
4840 LoOverflow = ProdOV;
4841 HiOverflow = ProdOV || AddWithOverflow(HiBound, LoBound, DivRHS);
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004842 } else if (isPositive(DivRHS)) { // Divisor is > 0.
Chris Lattner6862fbd2004-09-29 17:40:11 +00004843 if (CI->isNullValue()) { // (X / pos) op 0
4844 // Can't overflow.
4845 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
4846 HiBound = DivRHS;
4847 } else if (isPositive(CI)) { // (X / pos) op pos
4848 LoBound = Prod;
4849 LoOverflow = ProdOV;
4850 HiOverflow = ProdOV || AddWithOverflow(HiBound, Prod, DivRHS);
4851 } else { // (X / pos) op neg
4852 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
4853 LoOverflow = AddWithOverflow(LoBound, Prod,
4854 cast<ConstantInt>(DivRHSH));
4855 HiBound = Prod;
4856 HiOverflow = ProdOV;
4857 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004858 } else { // Divisor is < 0.
Chris Lattner6862fbd2004-09-29 17:40:11 +00004859 if (CI->isNullValue()) { // (X / neg) op 0
4860 LoBound = AddOne(DivRHS);
4861 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner73bcba52005-06-17 02:05:55 +00004862 if (HiBound == DivRHS)
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004863 LoBound = 0; // - INTMIN = INTMIN
Chris Lattner6862fbd2004-09-29 17:40:11 +00004864 } else if (isPositive(CI)) { // (X / neg) op pos
4865 HiOverflow = LoOverflow = ProdOV;
4866 if (!LoOverflow)
4867 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS));
4868 HiBound = AddOne(Prod);
4869 } else { // (X / neg) op neg
4870 LoBound = Prod;
4871 LoOverflow = HiOverflow = ProdOV;
4872 HiBound = cast<ConstantInt>(ConstantExpr::getSub(Prod, DivRHS));
4873 }
Chris Lattner0b41e862004-10-08 19:15:44 +00004874
Chris Lattnera92af962004-10-11 19:40:04 +00004875 // Dividing by a negate swaps the condition.
Reid Spencer266e42b2006-12-23 06:05:41 +00004876 predicate = ICmpInst::getSwappedPredicate(predicate);
Chris Lattner6862fbd2004-09-29 17:40:11 +00004877 }
4878
4879 if (LoBound) {
4880 Value *X = LHSI->getOperand(0);
Reid Spencer266e42b2006-12-23 06:05:41 +00004881 switch (predicate) {
4882 default: assert(0 && "Unhandled icmp opcode!");
4883 case ICmpInst::ICMP_EQ:
Chris Lattner6862fbd2004-09-29 17:40:11 +00004884 if (LoOverflow && HiOverflow)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004885 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattner6862fbd2004-09-29 17:40:11 +00004886 else if (HiOverflow)
Reid Spencer266e42b2006-12-23 06:05:41 +00004887 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
4888 ICmpInst::ICMP_UGE, X, LoBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00004889 else if (LoOverflow)
Reid Spencer266e42b2006-12-23 06:05:41 +00004890 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
4891 ICmpInst::ICMP_ULT, X, HiBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00004892 else
Reid Spencer266e42b2006-12-23 06:05:41 +00004893 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned,
4894 true, I);
4895 case ICmpInst::ICMP_NE:
Chris Lattner6862fbd2004-09-29 17:40:11 +00004896 if (LoOverflow && HiOverflow)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004897 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
Chris Lattner6862fbd2004-09-29 17:40:11 +00004898 else if (HiOverflow)
Reid Spencer266e42b2006-12-23 06:05:41 +00004899 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
4900 ICmpInst::ICMP_ULT, X, LoBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00004901 else if (LoOverflow)
Reid Spencer266e42b2006-12-23 06:05:41 +00004902 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
4903 ICmpInst::ICMP_UGE, X, HiBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00004904 else
Reid Spencer266e42b2006-12-23 06:05:41 +00004905 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned,
4906 false, I);
4907 case ICmpInst::ICMP_ULT:
4908 case ICmpInst::ICMP_SLT:
Chris Lattner6862fbd2004-09-29 17:40:11 +00004909 if (LoOverflow)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004910 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004911 return new ICmpInst(predicate, X, LoBound);
4912 case ICmpInst::ICMP_UGT:
4913 case ICmpInst::ICMP_SGT:
Chris Lattner6862fbd2004-09-29 17:40:11 +00004914 if (HiOverflow)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004915 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004916 if (predicate == ICmpInst::ICMP_UGT)
4917 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
4918 else
4919 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00004920 }
4921 }
4922 }
4923 break;
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004924 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004925
Reid Spencer266e42b2006-12-23 06:05:41 +00004926 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004927 if (I.isEquality()) {
Reid Spencer266e42b2006-12-23 06:05:41 +00004928 bool isICMP_NE = I.getPredicate() == ICmpInst::ICMP_NE;
Chris Lattnerd492a0b2003-07-23 17:02:11 +00004929
Reid Spencere0fc4df2006-10-20 07:07:24 +00004930 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
4931 // the second operand is a constant, simplify a bit.
Chris Lattnerc992add2003-08-13 05:33:12 +00004932 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
4933 switch (BO->getOpcode()) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00004934 case Instruction::SRem:
4935 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
4936 if (CI->isNullValue() && isa<ConstantInt>(BO->getOperand(1)) &&
4937 BO->hasOneUse()) {
4938 int64_t V = cast<ConstantInt>(BO->getOperand(1))->getSExtValue();
4939 if (V > 1 && isPowerOf2_64(V)) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00004940 Value *NewRem = InsertNewInstBefore(BinaryOperator::createURem(
4941 BO->getOperand(0), BO->getOperand(1), BO->getName()), I);
Reid Spencer266e42b2006-12-23 06:05:41 +00004942 return new ICmpInst(I.getPredicate(), NewRem,
4943 Constant::getNullValue(BO->getType()));
Chris Lattner23b47b62004-07-06 07:38:18 +00004944 }
Chris Lattner22d00a82005-08-02 19:16:58 +00004945 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004946 break;
Chris Lattnerc992add2003-08-13 05:33:12 +00004947 case Instruction::Add:
Chris Lattner6e079362004-06-27 22:51:36 +00004948 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
4949 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerb121ae12004-09-21 21:35:23 +00004950 if (BO->hasOneUse())
Reid Spencer266e42b2006-12-23 06:05:41 +00004951 return new ICmpInst(I.getPredicate(), BO->getOperand(0),
4952 ConstantExpr::getSub(CI, BOp1C));
Chris Lattner6e079362004-06-27 22:51:36 +00004953 } else if (CI->isNullValue()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00004954 // Replace ((add A, B) != 0) with (A != -B) if A or B is
4955 // efficiently invertible, or if the add has just this one use.
4956 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004957
Chris Lattnerc992add2003-08-13 05:33:12 +00004958 if (Value *NegVal = dyn_castNegVal(BOp1))
Reid Spencer266e42b2006-12-23 06:05:41 +00004959 return new ICmpInst(I.getPredicate(), BOp0, NegVal);
Chris Lattnerc992add2003-08-13 05:33:12 +00004960 else if (Value *NegVal = dyn_castNegVal(BOp0))
Reid Spencer266e42b2006-12-23 06:05:41 +00004961 return new ICmpInst(I.getPredicate(), NegVal, BOp1);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00004962 else if (BO->hasOneUse()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00004963 Instruction *Neg = BinaryOperator::createNeg(BOp1, BO->getName());
4964 BO->setName("");
4965 InsertNewInstBefore(Neg, I);
Reid Spencer266e42b2006-12-23 06:05:41 +00004966 return new ICmpInst(I.getPredicate(), BOp0, Neg);
Chris Lattnerc992add2003-08-13 05:33:12 +00004967 }
4968 }
4969 break;
4970 case Instruction::Xor:
4971 // For the xor case, we can xor two constants together, eliminating
4972 // the explicit xor.
4973 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
Reid Spencer266e42b2006-12-23 06:05:41 +00004974 return new ICmpInst(I.getPredicate(), BO->getOperand(0),
4975 ConstantExpr::getXor(CI, BOC));
Chris Lattnerc992add2003-08-13 05:33:12 +00004976
4977 // FALLTHROUGH
4978 case Instruction::Sub:
4979 // Replace (([sub|xor] A, B) != 0) with (A != B)
4980 if (CI->isNullValue())
Reid Spencer266e42b2006-12-23 06:05:41 +00004981 return new ICmpInst(I.getPredicate(), BO->getOperand(0),
4982 BO->getOperand(1));
Chris Lattnerc992add2003-08-13 05:33:12 +00004983 break;
4984
4985 case Instruction::Or:
4986 // If bits are being or'd in that are not present in the constant we
4987 // are comparing against, then the comparison could never succeed!
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00004988 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Chris Lattnerc8e7e292004-06-10 02:12:35 +00004989 Constant *NotCI = ConstantExpr::getNot(CI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004990 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Reid Spencer266e42b2006-12-23 06:05:41 +00004991 return ReplaceInstUsesWith(I, ConstantBool::get(isICMP_NE));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00004992 }
Chris Lattnerc992add2003-08-13 05:33:12 +00004993 break;
4994
4995 case Instruction::And:
4996 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerd492a0b2003-07-23 17:02:11 +00004997 // If bits are being compared against that are and'd out, then the
4998 // comparison can never succeed!
Chris Lattnerc8e7e292004-06-10 02:12:35 +00004999 if (!ConstantExpr::getAnd(CI,
5000 ConstantExpr::getNot(BOC))->isNullValue())
Reid Spencer266e42b2006-12-23 06:05:41 +00005001 return ReplaceInstUsesWith(I, ConstantBool::get(isICMP_NE));
Chris Lattnerc992add2003-08-13 05:33:12 +00005002
Chris Lattner35167c32004-06-09 07:59:58 +00005003 // If we have ((X & C) == C), turn it into ((X & C) != 0).
Chris Lattneree59d4b2004-06-10 02:33:20 +00005004 if (CI == BOC && isOneBitSet(CI))
Reid Spencer266e42b2006-12-23 06:05:41 +00005005 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
5006 ICmpInst::ICMP_NE, Op0,
5007 Constant::getNullValue(CI->getType()));
Chris Lattner35167c32004-06-09 07:59:58 +00005008
Reid Spencer266e42b2006-12-23 06:05:41 +00005009 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
Chris Lattnerc992add2003-08-13 05:33:12 +00005010 if (isSignBit(BOC)) {
5011 Value *X = BO->getOperand(0);
Reid Spencer266e42b2006-12-23 06:05:41 +00005012 Constant *Zero = Constant::getNullValue(X->getType());
5013 ICmpInst::Predicate pred = isICMP_NE ?
5014 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
5015 return new ICmpInst(pred, X, Zero);
Chris Lattnerc992add2003-08-13 05:33:12 +00005016 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00005017
Chris Lattnerbfff18a2004-09-27 19:29:18 +00005018 // ((X & ~7) == 0) --> X < 8
Chris Lattner8fc5af42004-09-23 21:46:38 +00005019 if (CI->isNullValue() && isHighOnes(BOC)) {
5020 Value *X = BO->getOperand(0);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00005021 Constant *NegX = ConstantExpr::getNeg(BOC);
Reid Spencer266e42b2006-12-23 06:05:41 +00005022 ICmpInst::Predicate pred = isICMP_NE ?
5023 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
5024 return new ICmpInst(pred, X, NegX);
Chris Lattner8fc5af42004-09-23 21:46:38 +00005025 }
5026
Chris Lattnerd492a0b2003-07-23 17:02:11 +00005027 }
Chris Lattnerc992add2003-08-13 05:33:12 +00005028 default: break;
5029 }
Chris Lattnera7942b72006-11-29 05:02:16 +00005030 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Op0)) {
5031 // Handle set{eq|ne} <intrinsic>, intcst.
5032 switch (II->getIntrinsicID()) {
5033 default: break;
Reid Spencer266e42b2006-12-23 06:05:41 +00005034 case Intrinsic::bswap_i16:
5035 // icmp eq (bswap(x)), c -> icmp eq (x,bswap(c))
Chris Lattnera7942b72006-11-29 05:02:16 +00005036 WorkList.push_back(II); // Dead?
5037 I.setOperand(0, II->getOperand(1));
Reid Spencerc635f472006-12-31 05:48:39 +00005038 I.setOperand(1, ConstantInt::get(Type::Int16Ty,
Chris Lattnera7942b72006-11-29 05:02:16 +00005039 ByteSwap_16(CI->getZExtValue())));
5040 return &I;
Reid Spencer266e42b2006-12-23 06:05:41 +00005041 case Intrinsic::bswap_i32:
5042 // icmp eq (bswap(x)), c -> icmp eq (x,bswap(c))
Chris Lattnera7942b72006-11-29 05:02:16 +00005043 WorkList.push_back(II); // Dead?
5044 I.setOperand(0, II->getOperand(1));
Reid Spencerc635f472006-12-31 05:48:39 +00005045 I.setOperand(1, ConstantInt::get(Type::Int32Ty,
Chris Lattnera7942b72006-11-29 05:02:16 +00005046 ByteSwap_32(CI->getZExtValue())));
5047 return &I;
Reid Spencer266e42b2006-12-23 06:05:41 +00005048 case Intrinsic::bswap_i64:
5049 // icmp eq (bswap(x)), c -> icmp eq (x,bswap(c))
Chris Lattnera7942b72006-11-29 05:02:16 +00005050 WorkList.push_back(II); // Dead?
5051 I.setOperand(0, II->getOperand(1));
Reid Spencerc635f472006-12-31 05:48:39 +00005052 I.setOperand(1, ConstantInt::get(Type::Int64Ty,
Chris Lattnera7942b72006-11-29 05:02:16 +00005053 ByteSwap_64(CI->getZExtValue())));
5054 return &I;
5055 }
Chris Lattnerc992add2003-08-13 05:33:12 +00005056 }
Reid Spencer266e42b2006-12-23 06:05:41 +00005057 } else { // Not a ICMP_EQ/ICMP_NE
5058 // If the LHS is a cast from an integral value of the same size, then
5059 // since we know the RHS is a constant, try to simlify.
Chris Lattner2b55ea32004-02-23 07:16:20 +00005060 if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
5061 Value *CastOp = Cast->getOperand(0);
5062 const Type *SrcTy = CastOp->getType();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005063 unsigned SrcTySize = SrcTy->getPrimitiveSizeInBits();
Reid Spencer266e42b2006-12-23 06:05:41 +00005064 if (SrcTy->isInteger() &&
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005065 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
Reid Spencer266e42b2006-12-23 06:05:41 +00005066 // If this is an unsigned comparison, try to make the comparison use
5067 // smaller constant values.
5068 switch (I.getPredicate()) {
5069 default: break;
5070 case ICmpInst::ICMP_ULT: { // X u< 128 => X s> -1
5071 ConstantInt *CUI = cast<ConstantInt>(CI);
5072 if (CUI->getZExtValue() == 1ULL << (SrcTySize-1))
5073 return new ICmpInst(ICmpInst::ICMP_SGT, CastOp,
5074 ConstantInt::get(SrcTy, -1));
5075 break;
5076 }
5077 case ICmpInst::ICMP_UGT: { // X u> 127 => X s< 0
5078 ConstantInt *CUI = cast<ConstantInt>(CI);
5079 if (CUI->getZExtValue() == (1ULL << (SrcTySize-1))-1)
5080 return new ICmpInst(ICmpInst::ICMP_SLT, CastOp,
5081 Constant::getNullValue(SrcTy));
5082 break;
5083 }
Chris Lattner2b55ea32004-02-23 07:16:20 +00005084 }
Reid Spencer266e42b2006-12-23 06:05:41 +00005085
Chris Lattner2b55ea32004-02-23 07:16:20 +00005086 }
5087 }
Chris Lattnere967b342003-06-04 05:10:11 +00005088 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005089 }
5090
Reid Spencer266e42b2006-12-23 06:05:41 +00005091 // Handle icmp with constant RHS
Chris Lattner77c32c32005-04-23 15:31:55 +00005092 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5093 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5094 switch (LHSI->getOpcode()) {
Chris Lattnera816eee2005-05-01 04:42:15 +00005095 case Instruction::GetElementPtr:
5096 if (RHSC->isNullValue()) {
Reid Spencer266e42b2006-12-23 06:05:41 +00005097 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
Chris Lattnera816eee2005-05-01 04:42:15 +00005098 bool isAllZeros = true;
5099 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
5100 if (!isa<Constant>(LHSI->getOperand(i)) ||
5101 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
5102 isAllZeros = false;
5103 break;
5104 }
5105 if (isAllZeros)
Reid Spencer266e42b2006-12-23 06:05:41 +00005106 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
Chris Lattnera816eee2005-05-01 04:42:15 +00005107 Constant::getNullValue(LHSI->getOperand(0)->getType()));
5108 }
5109 break;
5110
Chris Lattner77c32c32005-04-23 15:31:55 +00005111 case Instruction::PHI:
5112 if (Instruction *NV = FoldOpIntoPhi(I))
5113 return NV;
5114 break;
5115 case Instruction::Select:
5116 // If either operand of the select is a constant, we can fold the
5117 // comparison into the select arms, which will cause one to be
5118 // constant folded and the select turned into a bitwise or.
5119 Value *Op1 = 0, *Op2 = 0;
5120 if (LHSI->hasOneUse()) {
5121 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5122 // Fold the known value into the constant operand.
Reid Spencer266e42b2006-12-23 06:05:41 +00005123 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5124 // Insert a new ICmp of the other select operand.
5125 Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5126 LHSI->getOperand(2), RHSC,
5127 I.getName()), I);
Chris Lattner77c32c32005-04-23 15:31:55 +00005128 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5129 // Fold the known value into the constant operand.
Reid Spencer266e42b2006-12-23 06:05:41 +00005130 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5131 // Insert a new ICmp of the other select operand.
5132 Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5133 LHSI->getOperand(1), RHSC,
5134 I.getName()), I);
Chris Lattner77c32c32005-04-23 15:31:55 +00005135 }
5136 }
Jeff Cohen82639852005-04-23 21:38:35 +00005137
Chris Lattner77c32c32005-04-23 15:31:55 +00005138 if (Op1)
5139 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
5140 break;
5141 }
5142 }
5143
Reid Spencer266e42b2006-12-23 06:05:41 +00005144 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
Chris Lattner0798af32005-01-13 20:14:25 +00005145 if (User *GEP = dyn_castGetElementPtr(Op0))
Reid Spencer266e42b2006-12-23 06:05:41 +00005146 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
Chris Lattner0798af32005-01-13 20:14:25 +00005147 return NI;
5148 if (User *GEP = dyn_castGetElementPtr(Op1))
Reid Spencer266e42b2006-12-23 06:05:41 +00005149 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
5150 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
Chris Lattner0798af32005-01-13 20:14:25 +00005151 return NI;
5152
Reid Spencer266e42b2006-12-23 06:05:41 +00005153 // Test to see if the operands of the icmp are casted versions of other
Chris Lattner16930792003-11-03 04:25:02 +00005154 // values. If the cast can be stripped off both arguments, we do so now.
Chris Lattner6444c372003-11-03 05:17:03 +00005155 if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
5156 Value *CastOp0 = CI->getOperand(0);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005157 if (CI->isLosslessCast() && I.isEquality() &&
5158 (isa<Constant>(Op1) || isa<CastInst>(Op1))) {
Chris Lattner16930792003-11-03 04:25:02 +00005159 // We keep moving the cast from the left operand over to the right
5160 // operand, where it can often be eliminated completely.
Chris Lattner6444c372003-11-03 05:17:03 +00005161 Op0 = CastOp0;
Misha Brukmanb1c93172005-04-21 23:48:37 +00005162
Chris Lattner16930792003-11-03 04:25:02 +00005163 // If operand #1 is a cast instruction, see if we can eliminate it as
5164 // well.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005165 if (CastInst *CI2 = dyn_cast<CastInst>(Op1)) {
5166 Value *CI2Op0 = CI2->getOperand(0);
5167 if (CI2Op0->getType()->canLosslesslyBitCastTo(Op0->getType()))
5168 Op1 = CI2Op0;
5169 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00005170
Chris Lattner16930792003-11-03 04:25:02 +00005171 // If Op1 is a constant, we can fold the cast into the constant.
5172 if (Op1->getType() != Op0->getType())
5173 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Reid Spencerbb65ebf2006-12-12 23:36:14 +00005174 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
Chris Lattner16930792003-11-03 04:25:02 +00005175 } else {
Reid Spencer266e42b2006-12-23 06:05:41 +00005176 // Otherwise, cast the RHS right before the icmp
Reid Spencer13bc5d72006-12-12 09:18:51 +00005177 Op1 = InsertCastBefore(Instruction::BitCast, Op1, Op0->getType(), I);
Chris Lattner16930792003-11-03 04:25:02 +00005178 }
Reid Spencer266e42b2006-12-23 06:05:41 +00005179 return new ICmpInst(I.getPredicate(), Op0, Op1);
Chris Lattner16930792003-11-03 04:25:02 +00005180 }
5181
Reid Spencer266e42b2006-12-23 06:05:41 +00005182 // Handle the special case of: icmp (cast bool to X), <cst>
Chris Lattner6444c372003-11-03 05:17:03 +00005183 // This comes up when you have code like
5184 // int X = A < B;
5185 // if (X) ...
5186 // For generality, we handle any zero-extension of any operand comparison
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005187 // with a constant or another cast from the same type.
5188 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
Reid Spencer266e42b2006-12-23 06:05:41 +00005189 if (Instruction *R = visitICmpInstWithCastAndCast(I))
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005190 return R;
Chris Lattner6444c372003-11-03 05:17:03 +00005191 }
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00005192
Chris Lattnerb3f24c92006-09-18 04:22:48 +00005193 if (I.isEquality()) {
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00005194 Value *A, *B;
5195 if (match(Op0, m_Xor(m_Value(A), m_Value(B))) &&
5196 (A == Op1 || B == Op1)) {
5197 // (A^B) == A -> B == 0
5198 Value *OtherVal = A == Op1 ? B : A;
Reid Spencer266e42b2006-12-23 06:05:41 +00005199 return new ICmpInst(I.getPredicate(), OtherVal,
5200 Constant::getNullValue(A->getType()));
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00005201 } else if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
5202 (A == Op0 || B == Op0)) {
5203 // A == (A^B) -> B == 0
5204 Value *OtherVal = A == Op0 ? B : A;
Reid Spencer266e42b2006-12-23 06:05:41 +00005205 return new ICmpInst(I.getPredicate(), OtherVal,
5206 Constant::getNullValue(A->getType()));
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00005207 } else if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
5208 // (A-B) == A -> B == 0
Reid Spencer266e42b2006-12-23 06:05:41 +00005209 return new ICmpInst(I.getPredicate(), B,
5210 Constant::getNullValue(B->getType()));
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00005211 } else if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
5212 // A == (A-B) -> B == 0
Reid Spencer266e42b2006-12-23 06:05:41 +00005213 return new ICmpInst(I.getPredicate(), B,
5214 Constant::getNullValue(B->getType()));
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00005215 }
Chris Lattnerd12a4bf2006-11-14 06:06:06 +00005216
5217 Value *C, *D;
5218 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
5219 if (Op0->hasOneUse() && Op1->hasOneUse() &&
5220 match(Op0, m_And(m_Value(A), m_Value(B))) &&
5221 match(Op1, m_And(m_Value(C), m_Value(D)))) {
5222 Value *X = 0, *Y = 0, *Z = 0;
5223
5224 if (A == C) {
5225 X = B; Y = D; Z = A;
5226 } else if (A == D) {
5227 X = B; Y = C; Z = A;
5228 } else if (B == C) {
5229 X = A; Y = D; Z = B;
5230 } else if (B == D) {
5231 X = A; Y = C; Z = B;
5232 }
5233
5234 if (X) { // Build (X^Y) & Z
5235 Op1 = InsertNewInstBefore(BinaryOperator::createXor(X, Y, "tmp"), I);
5236 Op1 = InsertNewInstBefore(BinaryOperator::createAnd(Op1, Z, "tmp"), I);
5237 I.setOperand(0, Op1);
5238 I.setOperand(1, Constant::getNullValue(Op1->getType()));
5239 return &I;
5240 }
5241 }
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00005242 }
Chris Lattner113f4f42002-06-25 16:13:24 +00005243 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005244}
5245
Reid Spencer266e42b2006-12-23 06:05:41 +00005246// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005247// We only handle extending casts so far.
5248//
Reid Spencer266e42b2006-12-23 06:05:41 +00005249Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
5250 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005251 Value *LHSCIOp = LHSCI->getOperand(0);
5252 const Type *SrcTy = LHSCIOp->getType();
Reid Spencer266e42b2006-12-23 06:05:41 +00005253 const Type *DestTy = LHSCI->getType();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005254 Value *RHSCIOp;
5255
Reid Spencer266e42b2006-12-23 06:05:41 +00005256 // We only handle extension cast instructions, so far. Enforce this.
5257 if (LHSCI->getOpcode() != Instruction::ZExt &&
5258 LHSCI->getOpcode() != Instruction::SExt)
Chris Lattner03f06f12005-01-17 03:20:02 +00005259 return 0;
5260
Reid Spencer266e42b2006-12-23 06:05:41 +00005261 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
5262 bool isSignedCmp = ICI.isSignedPredicate();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005263
Reid Spencer266e42b2006-12-23 06:05:41 +00005264 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005265 // Not an extension from the same type?
5266 RHSCIOp = CI->getOperand(0);
Reid Spencer266e42b2006-12-23 06:05:41 +00005267 if (RHSCIOp->getType() != LHSCIOp->getType())
5268 return 0;
5269 else
5270 // Okay, just insert a compare of the reduced operands now!
5271 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
Reid Spencer279fa252004-11-28 21:31:15 +00005272 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005273
Reid Spencer266e42b2006-12-23 06:05:41 +00005274 // If we aren't dealing with a constant on the RHS, exit early
5275 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
5276 if (!CI)
5277 return 0;
5278
5279 // Compute the constant that would happen if we truncated to SrcTy then
5280 // reextended to DestTy.
5281 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
5282 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
5283
5284 // If the re-extended constant didn't change...
5285 if (Res2 == CI) {
5286 // Make sure that sign of the Cmp and the sign of the Cast are the same.
5287 // For example, we might have:
5288 // %A = sext short %X to uint
5289 // %B = icmp ugt uint %A, 1330
5290 // It is incorrect to transform this into
5291 // %B = icmp ugt short %X, 1330
5292 // because %A may have negative value.
5293 //
5294 // However, it is OK if SrcTy is bool (See cast-set.ll testcase)
5295 // OR operation is EQ/NE.
5296 if (isSignedExt == isSignedCmp || SrcTy == Type::BoolTy || ICI.isEquality())
5297 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
5298 else
5299 return 0;
5300 }
5301
5302 // The re-extended constant changed so the constant cannot be represented
5303 // in the shorter type. Consequently, we cannot emit a simple comparison.
5304
5305 // First, handle some easy cases. We know the result cannot be equal at this
5306 // point so handle the ICI.isEquality() cases
5307 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
5308 return ReplaceInstUsesWith(ICI, ConstantBool::getFalse());
5309 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
5310 return ReplaceInstUsesWith(ICI, ConstantBool::getTrue());
5311
5312 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
5313 // should have been folded away previously and not enter in here.
5314 Value *Result;
5315 if (isSignedCmp) {
5316 // We're performing a signed comparison.
5317 if (cast<ConstantInt>(CI)->getSExtValue() < 0)
5318 Result = ConstantBool::getFalse(); // X < (small) --> false
5319 else
5320 Result = ConstantBool::getTrue(); // X < (large) --> true
5321 } else {
5322 // We're performing an unsigned comparison.
5323 if (isSignedExt) {
5324 // We're performing an unsigned comp with a sign extended value.
5325 // This is true if the input is >= 0. [aka >s -1]
5326 Constant *NegOne = ConstantIntegral::getAllOnesValue(SrcTy);
5327 Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
5328 NegOne, ICI.getName()), ICI);
5329 } else {
5330 // Unsigned extend & unsigned compare -> always true.
5331 Result = ConstantBool::getTrue();
5332 }
5333 }
5334
5335 // Finally, return the value computed.
5336 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
5337 ICI.getPredicate() == ICmpInst::ICMP_SLT) {
5338 return ReplaceInstUsesWith(ICI, Result);
5339 } else {
5340 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
5341 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
5342 "ICmp should be folded!");
5343 if (Constant *CI = dyn_cast<Constant>(Result))
5344 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
5345 else
5346 return BinaryOperator::createNot(Result);
5347 }
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005348}
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005349
Chris Lattnere8d6c602003-03-10 19:16:08 +00005350Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
Reid Spencerc635f472006-12-31 05:48:39 +00005351 assert(I.getOperand(1)->getType() == Type::Int8Ty);
Chris Lattner113f4f42002-06-25 16:13:24 +00005352 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005353
5354 // shl X, 0 == X and shr X, 0 == X
5355 // shl 0, X == 0 and shr 0, X == 0
Reid Spencerc635f472006-12-31 05:48:39 +00005356 if (Op1 == Constant::getNullValue(Type::Int8Ty) ||
Chris Lattnere6794492002-08-12 21:17:25 +00005357 Op0 == Constant::getNullValue(Op0->getType()))
5358 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf5b4ef72006-02-12 08:07:37 +00005359
Reid Spencer266e42b2006-12-23 06:05:41 +00005360 if (isa<UndefValue>(Op0)) {
5361 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
Chris Lattner67f05452004-10-16 23:28:04 +00005362 return ReplaceInstUsesWith(I, Op0);
Reid Spencer266e42b2006-12-23 06:05:41 +00005363 else // undef << X -> 0, undef >>u X -> 0
Chris Lattner81a7a232004-10-16 18:11:37 +00005364 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5365 }
5366 if (isa<UndefValue>(Op1)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00005367 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
5368 return ReplaceInstUsesWith(I, Op0);
5369 else // X << undef, X >>u undef -> 0
Chris Lattner81a7a232004-10-16 18:11:37 +00005370 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner81a7a232004-10-16 18:11:37 +00005371 }
5372
Chris Lattnerd4dee402006-11-10 23:38:52 +00005373 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
5374 if (I.getOpcode() == Instruction::AShr)
Reid Spencere0fc4df2006-10-20 07:07:24 +00005375 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Chris Lattnerd4dee402006-11-10 23:38:52 +00005376 if (CSI->isAllOnesValue())
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00005377 return ReplaceInstUsesWith(I, CSI);
5378
Chris Lattner183b3362004-04-09 19:05:30 +00005379 // Try to fold constant and into select arguments.
5380 if (isa<Constant>(Op0))
5381 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner86102b82005-01-01 16:22:27 +00005382 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00005383 return R;
5384
Chris Lattnerb18dbbf2005-05-08 17:34:56 +00005385 // See if we can turn a signed shr into an unsigned shr.
Chris Lattnerb3f24c92006-09-18 04:22:48 +00005386 if (I.isArithmeticShift()) {
Chris Lattnerc3ebf402006-02-07 07:27:52 +00005387 if (MaskedValueIsZero(Op0,
5388 1ULL << (I.getType()->getPrimitiveSizeInBits()-1))) {
Reid Spencerfdff9382006-11-08 06:47:33 +00005389 return new ShiftInst(Instruction::LShr, Op0, Op1, I.getName());
Chris Lattnerb18dbbf2005-05-08 17:34:56 +00005390 }
5391 }
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00005392
Reid Spencere0fc4df2006-10-20 07:07:24 +00005393 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
Reid Spencerc635f472006-12-31 05:48:39 +00005394 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
5395 return Res;
Chris Lattner14553932006-01-06 07:12:35 +00005396 return 0;
5397}
5398
Reid Spencere0fc4df2006-10-20 07:07:24 +00005399Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Chris Lattner14553932006-01-06 07:12:35 +00005400 ShiftInst &I) {
Reid Spencer266e42b2006-12-23 06:05:41 +00005401 bool isLeftShift = I.getOpcode() == Instruction::Shl;
5402 bool isSignedShift = I.getOpcode() == Instruction::AShr;
Chris Lattnerb3309392006-01-06 07:22:22 +00005403 bool isUnsignedShift = !isSignedShift;
Chris Lattner14553932006-01-06 07:12:35 +00005404
Chris Lattnerf5b4ef72006-02-12 08:07:37 +00005405 // See if we can simplify any instructions used by the instruction whose sole
5406 // purpose is to compute bits we don't care about.
5407 uint64_t KnownZero, KnownOne;
5408 if (SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
5409 KnownZero, KnownOne))
5410 return &I;
5411
Chris Lattner14553932006-01-06 07:12:35 +00005412 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
5413 // of a signed value.
5414 //
5415 unsigned TypeBits = Op0->getType()->getPrimitiveSizeInBits();
Reid Spencere0fc4df2006-10-20 07:07:24 +00005416 if (Op1->getZExtValue() >= TypeBits) {
Chris Lattnerb3309392006-01-06 07:22:22 +00005417 if (isUnsignedShift || isLeftShift)
Chris Lattner14553932006-01-06 07:12:35 +00005418 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
5419 else {
Reid Spencerc635f472006-12-31 05:48:39 +00005420 I.setOperand(1, ConstantInt::get(Type::Int8Ty, TypeBits-1));
Chris Lattner14553932006-01-06 07:12:35 +00005421 return &I;
Chris Lattnerf5ce2542004-02-23 20:30:06 +00005422 }
Chris Lattner14553932006-01-06 07:12:35 +00005423 }
5424
5425 // ((X*C1) << C2) == (X * (C1 << C2))
5426 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
5427 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
5428 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
5429 return BinaryOperator::createMul(BO->getOperand(0),
5430 ConstantExpr::getShl(BOOp, Op1));
5431
5432 // Try to fold constant and into select arguments.
5433 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5434 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5435 return R;
5436 if (isa<PHINode>(Op0))
5437 if (Instruction *NV = FoldOpIntoPhi(I))
5438 return NV;
5439
5440 if (Op0->hasOneUse()) {
Chris Lattner14553932006-01-06 07:12:35 +00005441 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
5442 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
5443 Value *V1, *V2;
5444 ConstantInt *CC;
5445 switch (Op0BO->getOpcode()) {
Chris Lattner27cb9db2005-09-18 05:12:10 +00005446 default: break;
5447 case Instruction::Add:
5448 case Instruction::And:
5449 case Instruction::Or:
5450 case Instruction::Xor:
5451 // These operators commute.
5452 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner797dee72005-09-18 06:30:59 +00005453 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
5454 match(Op0BO->getOperand(1),
Chris Lattner14553932006-01-06 07:12:35 +00005455 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Chris Lattner797dee72005-09-18 06:30:59 +00005456 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00005457 Op0BO->getOperand(0), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00005458 Op0BO->getName());
5459 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005460 Instruction *X =
5461 BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
5462 Op0BO->getOperand(1)->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00005463 InsertNewInstBefore(X, I); // (X + (Y << C))
5464 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
Chris Lattner14553932006-01-06 07:12:35 +00005465 C2 = ConstantExpr::getShl(C2, Op1);
Chris Lattner797dee72005-09-18 06:30:59 +00005466 return BinaryOperator::createAnd(X, C2);
5467 }
Chris Lattner14553932006-01-06 07:12:35 +00005468
Chris Lattner797dee72005-09-18 06:30:59 +00005469 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
5470 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
5471 match(Op0BO->getOperand(1),
5472 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner14553932006-01-06 07:12:35 +00005473 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005474 cast<BinaryOperator>(Op0BO->getOperand(1))->getOperand(0)->hasOneUse()) {
Chris Lattner797dee72005-09-18 06:30:59 +00005475 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00005476 Op0BO->getOperand(0), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00005477 Op0BO->getName());
5478 InsertNewInstBefore(YS, I); // (Y << C)
5479 Instruction *XM =
Chris Lattner14553932006-01-06 07:12:35 +00005480 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner797dee72005-09-18 06:30:59 +00005481 V1->getName()+".mask");
5482 InsertNewInstBefore(XM, I); // X & (CC << C)
5483
5484 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
5485 }
Chris Lattner14553932006-01-06 07:12:35 +00005486
Chris Lattner797dee72005-09-18 06:30:59 +00005487 // FALL THROUGH.
Chris Lattner27cb9db2005-09-18 05:12:10 +00005488 case Instruction::Sub:
5489 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner797dee72005-09-18 06:30:59 +00005490 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
5491 match(Op0BO->getOperand(0),
Chris Lattner14553932006-01-06 07:12:35 +00005492 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Chris Lattner797dee72005-09-18 06:30:59 +00005493 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00005494 Op0BO->getOperand(1), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00005495 Op0BO->getName());
5496 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005497 Instruction *X =
Chris Lattner1df0e982006-05-31 21:14:00 +00005498 BinaryOperator::create(Op0BO->getOpcode(), V1, YS,
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005499 Op0BO->getOperand(0)->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00005500 InsertNewInstBefore(X, I); // (X + (Y << C))
5501 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
Chris Lattner14553932006-01-06 07:12:35 +00005502 C2 = ConstantExpr::getShl(C2, Op1);
Chris Lattner797dee72005-09-18 06:30:59 +00005503 return BinaryOperator::createAnd(X, C2);
5504 }
Chris Lattner14553932006-01-06 07:12:35 +00005505
Chris Lattner1df0e982006-05-31 21:14:00 +00005506 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner797dee72005-09-18 06:30:59 +00005507 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
5508 match(Op0BO->getOperand(0),
5509 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner14553932006-01-06 07:12:35 +00005510 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005511 cast<BinaryOperator>(Op0BO->getOperand(0))
5512 ->getOperand(0)->hasOneUse()) {
Chris Lattner797dee72005-09-18 06:30:59 +00005513 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00005514 Op0BO->getOperand(1), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00005515 Op0BO->getName());
5516 InsertNewInstBefore(YS, I); // (Y << C)
5517 Instruction *XM =
Chris Lattner14553932006-01-06 07:12:35 +00005518 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner797dee72005-09-18 06:30:59 +00005519 V1->getName()+".mask");
5520 InsertNewInstBefore(XM, I); // X & (CC << C)
5521
Chris Lattner1df0e982006-05-31 21:14:00 +00005522 return BinaryOperator::create(Op0BO->getOpcode(), XM, YS);
Chris Lattner797dee72005-09-18 06:30:59 +00005523 }
Chris Lattner14553932006-01-06 07:12:35 +00005524
Chris Lattner27cb9db2005-09-18 05:12:10 +00005525 break;
Chris Lattner14553932006-01-06 07:12:35 +00005526 }
5527
5528
5529 // If the operand is an bitwise operator with a constant RHS, and the
5530 // shift is the only use, we can pull it out of the shift.
5531 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
5532 bool isValid = true; // Valid only for And, Or, Xor
5533 bool highBitSet = false; // Transform if high bit of constant set?
5534
5535 switch (Op0BO->getOpcode()) {
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00005536 default: isValid = false; break; // Do not perform transform!
Chris Lattner44bd3922004-10-08 03:46:20 +00005537 case Instruction::Add:
5538 isValid = isLeftShift;
5539 break;
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00005540 case Instruction::Or:
5541 case Instruction::Xor:
5542 highBitSet = false;
5543 break;
5544 case Instruction::And:
5545 highBitSet = true;
5546 break;
Chris Lattner14553932006-01-06 07:12:35 +00005547 }
5548
5549 // If this is a signed shift right, and the high bit is modified
5550 // by the logical operation, do not perform the transformation.
5551 // The highBitSet boolean indicates the value of the high bit of
5552 // the constant which would cause it to be modified for this
5553 // operation.
5554 //
Chris Lattnerb3309392006-01-06 07:22:22 +00005555 if (isValid && !isLeftShift && isSignedShift) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00005556 uint64_t Val = Op0C->getZExtValue();
Chris Lattner14553932006-01-06 07:12:35 +00005557 isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
5558 }
5559
5560 if (isValid) {
5561 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
5562
5563 Instruction *NewShift =
5564 new ShiftInst(I.getOpcode(), Op0BO->getOperand(0), Op1,
5565 Op0BO->getName());
5566 Op0BO->setName("");
5567 InsertNewInstBefore(NewShift, I);
5568
5569 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
5570 NewRHS);
5571 }
5572 }
5573 }
5574 }
5575
Chris Lattnereb372a02006-01-06 07:52:12 +00005576 // Find out if this is a shift of a shift by a constant.
5577 ShiftInst *ShiftOp = 0;
Chris Lattner14553932006-01-06 07:12:35 +00005578 if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0))
Chris Lattnereb372a02006-01-06 07:52:12 +00005579 ShiftOp = Op0SI;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005580 else if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
5581 // If this is a noop-integer cast of a shift instruction, use the shift.
5582 if (isa<ShiftInst>(CI->getOperand(0))) {
Chris Lattnereb372a02006-01-06 07:52:12 +00005583 ShiftOp = cast<ShiftInst>(CI->getOperand(0));
5584 }
5585 }
5586
Reid Spencere0fc4df2006-10-20 07:07:24 +00005587 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Chris Lattnereb372a02006-01-06 07:52:12 +00005588 // Find the operands and properties of the input shift. Note that the
5589 // signedness of the input shift may differ from the current shift if there
5590 // is a noop cast between the two.
Reid Spencer266e42b2006-12-23 06:05:41 +00005591 bool isShiftOfLeftShift = ShiftOp->getOpcode() == Instruction::Shl;
5592 bool isShiftOfSignedShift = ShiftOp->getOpcode() == Instruction::AShr;
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005593 bool isShiftOfUnsignedShift = !isShiftOfSignedShift;
Chris Lattnereb372a02006-01-06 07:52:12 +00005594
Reid Spencere0fc4df2006-10-20 07:07:24 +00005595 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Chris Lattnereb372a02006-01-06 07:52:12 +00005596
Reid Spencere0fc4df2006-10-20 07:07:24 +00005597 unsigned ShiftAmt1 = (unsigned)ShiftAmt1C->getZExtValue();
5598 unsigned ShiftAmt2 = (unsigned)Op1->getZExtValue();
Chris Lattnereb372a02006-01-06 07:52:12 +00005599
5600 // Check for (A << c1) << c2 and (A >> c1) >> c2.
5601 if (isLeftShift == isShiftOfLeftShift) {
5602 // Do not fold these shifts if the first one is signed and the second one
5603 // is unsigned and this is a right shift. Further, don't do any folding
5604 // on them.
5605 if (isShiftOfSignedShift && isUnsignedShift && !isLeftShift)
5606 return 0;
Chris Lattner14553932006-01-06 07:12:35 +00005607
Chris Lattnereb372a02006-01-06 07:52:12 +00005608 unsigned Amt = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
5609 if (Amt > Op0->getType()->getPrimitiveSizeInBits())
5610 Amt = Op0->getType()->getPrimitiveSizeInBits();
Chris Lattner14553932006-01-06 07:12:35 +00005611
Chris Lattnereb372a02006-01-06 07:52:12 +00005612 Value *Op = ShiftOp->getOperand(0);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005613 ShiftInst *ShiftResult = new ShiftInst(I.getOpcode(), Op,
Reid Spencerc635f472006-12-31 05:48:39 +00005614 ConstantInt::get(Type::Int8Ty, Amt));
Reid Spencerfdff9382006-11-08 06:47:33 +00005615 if (I.getType() == ShiftResult->getType())
5616 return ShiftResult;
5617 InsertNewInstBefore(ShiftResult, I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005618 return CastInst::create(Instruction::BitCast, ShiftResult, I.getType());
Chris Lattnereb372a02006-01-06 07:52:12 +00005619 }
5620
5621 // Check for (A << c1) >> c2 or (A >> c1) << c2. If we are dealing with
5622 // signed types, we can only support the (A >> c1) << c2 configuration,
5623 // because it can not turn an arbitrary bit of A into a sign bit.
5624 if (isUnsignedShift || isLeftShift) {
5625 // Calculate bitmask for what gets shifted off the edge.
5626 Constant *C = ConstantIntegral::getAllOnesValue(I.getType());
5627 if (isLeftShift)
5628 C = ConstantExpr::getShl(C, ShiftAmt1C);
5629 else
Reid Spencerfdff9382006-11-08 06:47:33 +00005630 C = ConstantExpr::getLShr(C, ShiftAmt1C);
Chris Lattnereb372a02006-01-06 07:52:12 +00005631
5632 Value *Op = ShiftOp->getOperand(0);
Reid Spencerfdff9382006-11-08 06:47:33 +00005633 if (Op->getType() != C->getType())
Reid Spencer13bc5d72006-12-12 09:18:51 +00005634 Op = InsertCastBefore(Instruction::BitCast, Op, I.getType(), I);
Chris Lattnereb372a02006-01-06 07:52:12 +00005635
5636 Instruction *Mask =
5637 BinaryOperator::createAnd(Op, C, Op->getName()+".mask");
5638 InsertNewInstBefore(Mask, I);
5639
5640 // Figure out what flavor of shift we should use...
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005641 if (ShiftAmt1 == ShiftAmt2) {
Chris Lattnereb372a02006-01-06 07:52:12 +00005642 return ReplaceInstUsesWith(I, Mask); // (A << c) >> c === A & c2
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005643 } else if (ShiftAmt1 < ShiftAmt2) {
Chris Lattnereb372a02006-01-06 07:52:12 +00005644 return new ShiftInst(I.getOpcode(), Mask,
Reid Spencerc635f472006-12-31 05:48:39 +00005645 ConstantInt::get(Type::Int8Ty, ShiftAmt2-ShiftAmt1));
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005646 } else if (isShiftOfUnsignedShift || isShiftOfLeftShift) {
5647 if (isShiftOfUnsignedShift && !isShiftOfLeftShift && isSignedShift) {
Reid Spencerfdff9382006-11-08 06:47:33 +00005648 return new ShiftInst(Instruction::LShr, Mask,
Reid Spencerc635f472006-12-31 05:48:39 +00005649 ConstantInt::get(Type::Int8Ty, ShiftAmt1-ShiftAmt2));
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005650 } else {
5651 return new ShiftInst(ShiftOp->getOpcode(), Mask,
Reid Spencerc635f472006-12-31 05:48:39 +00005652 ConstantInt::get(Type::Int8Ty, ShiftAmt1-ShiftAmt2));
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005653 }
5654 } else {
5655 // (X >>s C1) << C2 where C1 > C2 === (X >>s (C1-C2)) & mask
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005656 Instruction *Shift =
Reid Spencer2a499b02006-12-13 17:19:09 +00005657 new ShiftInst(ShiftOp->getOpcode(), Mask,
Reid Spencerc635f472006-12-31 05:48:39 +00005658 ConstantInt::get(Type::Int8Ty, ShiftAmt1-ShiftAmt2));
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005659 InsertNewInstBefore(Shift, I);
5660
5661 C = ConstantIntegral::getAllOnesValue(Shift->getType());
5662 C = ConstantExpr::getShl(C, Op1);
Reid Spencer2a499b02006-12-13 17:19:09 +00005663 return BinaryOperator::createAnd(Shift, C, Op->getName()+".mask");
Chris Lattnereb372a02006-01-06 07:52:12 +00005664 }
5665 } else {
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005666 // We can handle signed (X << C1) >>s C2 if it's a sign extend. In
Chris Lattnereb372a02006-01-06 07:52:12 +00005667 // this case, C1 == C2 and C1 is 8, 16, or 32.
5668 if (ShiftAmt1 == ShiftAmt2) {
5669 const Type *SExtType = 0;
Chris Lattner655d08f2006-04-28 22:21:41 +00005670 switch (Op0->getType()->getPrimitiveSizeInBits() - ShiftAmt1) {
Reid Spencerc635f472006-12-31 05:48:39 +00005671 case 8 : SExtType = Type::Int8Ty; break;
5672 case 16: SExtType = Type::Int16Ty; break;
5673 case 32: SExtType = Type::Int32Ty; break;
Chris Lattnereb372a02006-01-06 07:52:12 +00005674 }
5675
5676 if (SExtType) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005677 Instruction *NewTrunc =
5678 new TruncInst(ShiftOp->getOperand(0), SExtType, "sext");
Chris Lattnereb372a02006-01-06 07:52:12 +00005679 InsertNewInstBefore(NewTrunc, I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005680 return new SExtInst(NewTrunc, I.getType());
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00005681 }
Chris Lattner27cb9db2005-09-18 05:12:10 +00005682 }
Chris Lattner86102b82005-01-01 16:22:27 +00005683 }
Chris Lattnereb372a02006-01-06 07:52:12 +00005684 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005685 return 0;
5686}
5687
Chris Lattner48a44f72002-05-02 17:06:02 +00005688
Chris Lattner8f663e82005-10-29 04:36:15 +00005689/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
5690/// expression. If so, decompose it, returning some value X, such that Val is
5691/// X*Scale+Offset.
5692///
5693static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
5694 unsigned &Offset) {
Reid Spencerc635f472006-12-31 05:48:39 +00005695 assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
Reid Spencere0fc4df2006-10-20 07:07:24 +00005696 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
Reid Spencerc635f472006-12-31 05:48:39 +00005697 Offset = CI->getZExtValue();
5698 Scale = 1;
5699 return ConstantInt::get(Type::Int32Ty, 0);
Chris Lattner8f663e82005-10-29 04:36:15 +00005700 } else if (Instruction *I = dyn_cast<Instruction>(Val)) {
5701 if (I->getNumOperands() == 2) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00005702 if (ConstantInt *CUI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Reid Spencerc635f472006-12-31 05:48:39 +00005703 if (I->getOpcode() == Instruction::Shl) {
5704 // This is a value scaled by '1 << the shift amt'.
5705 Scale = 1U << CUI->getZExtValue();
5706 Offset = 0;
5707 return I->getOperand(0);
5708 } else if (I->getOpcode() == Instruction::Mul) {
5709 // This value is scaled by 'CUI'.
5710 Scale = CUI->getZExtValue();
5711 Offset = 0;
5712 return I->getOperand(0);
5713 } else if (I->getOpcode() == Instruction::Add) {
5714 // We have X+C. Check to see if we really have (X*C2)+C1,
5715 // where C1 is divisible by C2.
5716 unsigned SubScale;
5717 Value *SubVal =
5718 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
5719 Offset += CUI->getZExtValue();
5720 if (SubScale > 1 && (Offset % SubScale == 0)) {
5721 Scale = SubScale;
5722 return SubVal;
Chris Lattner8f663e82005-10-29 04:36:15 +00005723 }
5724 }
5725 }
5726 }
5727 }
5728
5729 // Otherwise, we can't look past this.
5730 Scale = 1;
5731 Offset = 0;
5732 return Val;
5733}
5734
5735
Chris Lattner216be912005-10-24 06:03:58 +00005736/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
5737/// try to eliminate the cast by moving the type information into the alloc.
5738Instruction *InstCombiner::PromoteCastOfAllocation(CastInst &CI,
5739 AllocationInst &AI) {
5740 const PointerType *PTy = dyn_cast<PointerType>(CI.getType());
Chris Lattnerbb171802005-10-27 05:53:56 +00005741 if (!PTy) return 0; // Not casting the allocation to a pointer type.
Chris Lattner216be912005-10-24 06:03:58 +00005742
Chris Lattnerac87beb2005-10-24 06:22:12 +00005743 // Remove any uses of AI that are dead.
5744 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
5745 std::vector<Instruction*> DeadUsers;
5746 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
5747 Instruction *User = cast<Instruction>(*UI++);
5748 if (isInstructionTriviallyDead(User)) {
5749 while (UI != E && *UI == User)
5750 ++UI; // If this instruction uses AI more than once, don't break UI.
5751
5752 // Add operands to the worklist.
5753 AddUsesToWorkList(*User);
5754 ++NumDeadInst;
Bill Wendling5dbf43c2006-11-26 09:46:52 +00005755 DOUT << "IC: DCE: " << *User;
Chris Lattnerac87beb2005-10-24 06:22:12 +00005756
5757 User->eraseFromParent();
5758 removeFromWorkList(User);
5759 }
5760 }
5761
Chris Lattner216be912005-10-24 06:03:58 +00005762 // Get the type really allocated and the type casted to.
5763 const Type *AllocElTy = AI.getAllocatedType();
5764 const Type *CastElTy = PTy->getElementType();
5765 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner355ecc02005-10-24 06:26:18 +00005766
Chris Lattner7d190672006-10-01 19:40:58 +00005767 unsigned AllocElTyAlign = TD->getTypeAlignment(AllocElTy);
5768 unsigned CastElTyAlign = TD->getTypeAlignment(CastElTy);
Chris Lattner355ecc02005-10-24 06:26:18 +00005769 if (CastElTyAlign < AllocElTyAlign) return 0;
5770
Chris Lattner46705b22005-10-24 06:35:18 +00005771 // If the allocation has multiple uses, only promote it if we are strictly
5772 // increasing the alignment of the resultant allocation. If we keep it the
5773 // same, we open the door to infinite loops of various kinds.
5774 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
5775
Chris Lattner216be912005-10-24 06:03:58 +00005776 uint64_t AllocElTySize = TD->getTypeSize(AllocElTy);
5777 uint64_t CastElTySize = TD->getTypeSize(CastElTy);
Chris Lattnerbb171802005-10-27 05:53:56 +00005778 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner355ecc02005-10-24 06:26:18 +00005779
Chris Lattner8270c332005-10-29 03:19:53 +00005780 // See if we can satisfy the modulus by pulling a scale out of the array
5781 // size argument.
Chris Lattner8f663e82005-10-29 04:36:15 +00005782 unsigned ArraySizeScale, ArrayOffset;
5783 Value *NumElements = // See if the array size is a decomposable linear expr.
5784 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
5785
Chris Lattner8270c332005-10-29 03:19:53 +00005786 // If we can now satisfy the modulus, by using a non-1 scale, we really can
5787 // do the xform.
Chris Lattner8f663e82005-10-29 04:36:15 +00005788 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
5789 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattnerb3ecf962005-10-27 06:12:00 +00005790
Chris Lattner8270c332005-10-29 03:19:53 +00005791 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
5792 Value *Amt = 0;
5793 if (Scale == 1) {
5794 Amt = NumElements;
5795 } else {
Reid Spencere0fc4df2006-10-20 07:07:24 +00005796 // If the allocation size is constant, form a constant mul expression
Reid Spencerc635f472006-12-31 05:48:39 +00005797 Amt = ConstantInt::get(Type::Int32Ty, Scale);
5798 if (isa<ConstantInt>(NumElements))
Reid Spencere0fc4df2006-10-20 07:07:24 +00005799 Amt = ConstantExpr::getMul(
5800 cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
5801 // otherwise multiply the amount and the number of elements
Chris Lattner8270c332005-10-29 03:19:53 +00005802 else if (Scale != 1) {
5803 Instruction *Tmp = BinaryOperator::createMul(Amt, NumElements, "tmp");
5804 Amt = InsertNewInstBefore(Tmp, AI);
Chris Lattnerb3ecf962005-10-27 06:12:00 +00005805 }
Chris Lattnerbb171802005-10-27 05:53:56 +00005806 }
5807
Chris Lattner8f663e82005-10-29 04:36:15 +00005808 if (unsigned Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
Reid Spencerc635f472006-12-31 05:48:39 +00005809 Value *Off = ConstantInt::get(Type::Int32Ty, Offset);
Chris Lattner8f663e82005-10-29 04:36:15 +00005810 Instruction *Tmp = BinaryOperator::createAdd(Amt, Off, "tmp");
5811 Amt = InsertNewInstBefore(Tmp, AI);
5812 }
5813
Chris Lattner216be912005-10-24 06:03:58 +00005814 std::string Name = AI.getName(); AI.setName("");
5815 AllocationInst *New;
5816 if (isa<MallocInst>(AI))
Nate Begeman848622f2005-11-05 09:21:28 +00005817 New = new MallocInst(CastElTy, Amt, AI.getAlignment(), Name);
Chris Lattner216be912005-10-24 06:03:58 +00005818 else
Nate Begeman848622f2005-11-05 09:21:28 +00005819 New = new AllocaInst(CastElTy, Amt, AI.getAlignment(), Name);
Chris Lattner216be912005-10-24 06:03:58 +00005820 InsertNewInstBefore(New, AI);
Chris Lattner46705b22005-10-24 06:35:18 +00005821
5822 // If the allocation has multiple uses, insert a cast and change all things
5823 // that used it to use the new cast. This will also hack on CI, but it will
5824 // die soon.
5825 if (!AI.hasOneUse()) {
5826 AddUsesToWorkList(AI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005827 // New is the allocation instruction, pointer typed. AI is the original
5828 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
5829 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
Chris Lattner46705b22005-10-24 06:35:18 +00005830 InsertNewInstBefore(NewCast, AI);
5831 AI.replaceAllUsesWith(NewCast);
5832 }
Chris Lattner216be912005-10-24 06:03:58 +00005833 return ReplaceInstUsesWith(CI, New);
5834}
5835
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005836/// CanEvaluateInDifferentType - Return true if we can take the specified value
5837/// and return it without inserting any new casts. This is used by code that
5838/// tries to decide whether promoting or shrinking integer operations to wider
5839/// or smaller types will allow us to eliminate a truncate or extend.
5840static bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
5841 int &NumCastsRemoved) {
5842 if (isa<Constant>(V)) return true;
5843
5844 Instruction *I = dyn_cast<Instruction>(V);
5845 if (!I || !I->hasOneUse()) return false;
5846
5847 switch (I->getOpcode()) {
5848 case Instruction::And:
5849 case Instruction::Or:
5850 case Instruction::Xor:
5851 // These operators can all arbitrarily be extended or truncated.
5852 return CanEvaluateInDifferentType(I->getOperand(0), Ty, NumCastsRemoved) &&
5853 CanEvaluateInDifferentType(I->getOperand(1), Ty, NumCastsRemoved);
Chris Lattner960acb02006-11-29 07:18:39 +00005854 case Instruction::AShr:
5855 case Instruction::LShr:
5856 case Instruction::Shl:
5857 // If this is just a bitcast changing the sign of the operation, we can
5858 // convert if the operand can be converted.
5859 if (V->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
5860 return CanEvaluateInDifferentType(I->getOperand(0), Ty, NumCastsRemoved);
5861 break;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005862 case Instruction::Trunc:
5863 case Instruction::ZExt:
5864 case Instruction::SExt:
5865 case Instruction::BitCast:
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005866 // If this is a cast from the destination type, we can trivially eliminate
5867 // it, and this will remove a cast overall.
5868 if (I->getOperand(0)->getType() == Ty) {
Chris Lattner3fda3862006-06-28 17:34:50 +00005869 // If the first operand is itself a cast, and is eliminable, do not count
5870 // this as an eliminable cast. We would prefer to eliminate those two
5871 // casts first.
Reid Spencerde46e482006-11-02 20:25:50 +00005872 if (isa<CastInst>(I->getOperand(0)))
Chris Lattner3fda3862006-06-28 17:34:50 +00005873 return true;
5874
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005875 ++NumCastsRemoved;
5876 return true;
5877 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005878 break;
5879 default:
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005880 // TODO: Can handle more cases here.
5881 break;
5882 }
5883
5884 return false;
5885}
5886
5887/// EvaluateInDifferentType - Given an expression that
5888/// CanEvaluateInDifferentType returns true for, actually insert the code to
5889/// evaluate the expression.
Reid Spencer74a528b2006-12-13 18:21:21 +00005890Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
5891 bool isSigned ) {
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005892 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencer74a528b2006-12-13 18:21:21 +00005893 return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005894
5895 // Otherwise, it must be an instruction.
5896 Instruction *I = cast<Instruction>(V);
Chris Lattnerd0622b62006-05-20 23:14:03 +00005897 Instruction *Res = 0;
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005898 switch (I->getOpcode()) {
5899 case Instruction::And:
5900 case Instruction::Or:
5901 case Instruction::Xor: {
Reid Spencer74a528b2006-12-13 18:21:21 +00005902 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
5903 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005904 Res = BinaryOperator::create((Instruction::BinaryOps)I->getOpcode(),
5905 LHS, RHS, I->getName());
5906 break;
5907 }
Chris Lattner960acb02006-11-29 07:18:39 +00005908 case Instruction::AShr:
5909 case Instruction::LShr:
5910 case Instruction::Shl: {
Reid Spencer74a528b2006-12-13 18:21:21 +00005911 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
Chris Lattner960acb02006-11-29 07:18:39 +00005912 Res = new ShiftInst((Instruction::OtherOps)I->getOpcode(), LHS,
5913 I->getOperand(1), I->getName());
5914 break;
5915 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005916 case Instruction::Trunc:
5917 case Instruction::ZExt:
5918 case Instruction::SExt:
5919 case Instruction::BitCast:
5920 // If the source type of the cast is the type we're trying for then we can
5921 // just return the source. There's no need to insert it because its not new.
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005922 if (I->getOperand(0)->getType() == Ty)
5923 return I->getOperand(0);
5924
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005925 // Some other kind of cast, which shouldn't happen, so just ..
5926 // FALL THROUGH
5927 default:
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005928 // TODO: Can handle more cases here.
5929 assert(0 && "Unreachable!");
5930 break;
5931 }
5932
5933 return InsertNewInstBefore(Res, *I);
5934}
5935
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005936/// @brief Implement the transforms common to all CastInst visitors.
5937Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
Chris Lattner55d4bda2003-06-23 21:59:52 +00005938 Value *Src = CI.getOperand(0);
5939
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005940 // Casting undef to anything results in undef so might as just replace it and
5941 // get rid of the cast.
Chris Lattner81a7a232004-10-16 18:11:37 +00005942 if (isa<UndefValue>(Src)) // cast undef -> undef
5943 return ReplaceInstUsesWith(CI, UndefValue::get(CI.getType()));
5944
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005945 // Many cases of "cast of a cast" are eliminable. If its eliminable we just
5946 // eliminate it now.
Chris Lattner86102b82005-01-01 16:22:27 +00005947 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005948 if (Instruction::CastOps opc =
5949 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
5950 // The first cast (CSrc) is eliminable so we need to fix up or replace
5951 // the second cast (CI). CSrc will then have a good chance of being dead.
5952 return CastInst::create(opc, CSrc->getOperand(0), CI.getType());
Chris Lattner650b6da2002-08-02 20:00:25 +00005953 }
5954 }
Chris Lattner03841652004-05-25 04:29:21 +00005955
Chris Lattnerd0d51602003-06-21 23:12:02 +00005956 // If casting the result of a getelementptr instruction with no offset, turn
5957 // this into a cast of the original pointer!
5958 //
Chris Lattner55d4bda2003-06-23 21:59:52 +00005959 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattnerd0d51602003-06-21 23:12:02 +00005960 bool AllZeroOperands = true;
5961 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
5962 if (!isa<Constant>(GEP->getOperand(i)) ||
5963 !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
5964 AllZeroOperands = false;
5965 break;
5966 }
5967 if (AllZeroOperands) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005968 // Changing the cast operand is usually not a good idea but it is safe
5969 // here because the pointer operand is being replaced with another
5970 // pointer operand so the opcode doesn't need to change.
Chris Lattnerd0d51602003-06-21 23:12:02 +00005971 CI.setOperand(0, GEP->getOperand(0));
5972 return &CI;
5973 }
5974 }
Chris Lattnerec45a4c2006-11-21 17:05:13 +00005975
Chris Lattnerf4ad1652003-11-02 05:57:39 +00005976 // If we are casting a malloc or alloca to a pointer to a type of the same
5977 // size, rewrite the allocation instruction to allocate the "right" type.
Chris Lattnerf4ad1652003-11-02 05:57:39 +00005978 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
Chris Lattner216be912005-10-24 06:03:58 +00005979 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
5980 return V;
Chris Lattnerf4ad1652003-11-02 05:57:39 +00005981
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005982 // If we are casting a select then fold the cast into the select
Chris Lattner86102b82005-01-01 16:22:27 +00005983 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
5984 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
5985 return NV;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005986
5987 // If we are casting a PHI then fold the cast into the PHI
Chris Lattner6a4adcd2004-09-29 05:07:12 +00005988 if (isa<PHINode>(Src))
5989 if (Instruction *NV = FoldOpIntoPhi(CI))
5990 return NV;
Chris Lattnerb19a5c62006-04-12 18:09:35 +00005991
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005992 return 0;
5993}
5994
5995/// Only the TRUNC, ZEXT, SEXT, and BITCONVERT can have both operands as
5996/// integers. This function implements the common transforms for all those
5997/// cases.
5998/// @brief Implement the transforms common to CastInst with integer operands
5999Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
6000 if (Instruction *Result = commonCastTransforms(CI))
6001 return Result;
6002
6003 Value *Src = CI.getOperand(0);
6004 const Type *SrcTy = Src->getType();
6005 const Type *DestTy = CI.getType();
6006 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
6007 unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
6008
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006009 // See if we can simplify any instructions used by the LHS whose sole
6010 // purpose is to compute bits we don't care about.
6011 uint64_t KnownZero = 0, KnownOne = 0;
6012 if (SimplifyDemandedBits(&CI, DestTy->getIntegralTypeMask(),
6013 KnownZero, KnownOne))
6014 return &CI;
6015
6016 // If the source isn't an instruction or has more than one use then we
6017 // can't do anything more.
Reid Spencer266e42b2006-12-23 06:05:41 +00006018 Instruction *SrcI = dyn_cast<Instruction>(Src);
6019 if (!SrcI || !Src->hasOneUse())
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006020 return 0;
6021
6022 // Attempt to propagate the cast into the instruction.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006023 int NumCastsRemoved = 0;
6024 if (CanEvaluateInDifferentType(SrcI, DestTy, NumCastsRemoved)) {
6025 // If this cast is a truncate, evaluting in a different type always
6026 // eliminates the cast, so it is always a win. If this is a noop-cast
6027 // this just removes a noop cast which isn't pointful, but simplifies
6028 // the code. If this is a zero-extension, we need to do an AND to
6029 // maintain the clear top-part of the computation, so we require that
6030 // the input have eliminated at least one cast. If this is a sign
6031 // extension, we insert two new casts (to do the extension) so we
6032 // require that two casts have been eliminated.
6033 bool DoXForm = CI.isNoopCast(TD->getIntPtrType());
6034 if (!DoXForm) {
6035 switch (CI.getOpcode()) {
6036 case Instruction::Trunc:
6037 DoXForm = true;
6038 break;
6039 case Instruction::ZExt:
6040 DoXForm = NumCastsRemoved >= 1;
6041 break;
6042 case Instruction::SExt:
6043 DoXForm = NumCastsRemoved >= 2;
6044 break;
6045 case Instruction::BitCast:
6046 DoXForm = false;
6047 break;
6048 default:
6049 // All the others use floating point so we shouldn't actually
6050 // get here because of the check above.
6051 assert(!"Unknown cast type .. unreachable");
6052 break;
6053 }
6054 }
6055
6056 if (DoXForm) {
Reid Spencer74a528b2006-12-13 18:21:21 +00006057 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
6058 CI.getOpcode() == Instruction::SExt);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006059 assert(Res->getType() == DestTy);
6060 switch (CI.getOpcode()) {
6061 default: assert(0 && "Unknown cast type!");
6062 case Instruction::Trunc:
6063 case Instruction::BitCast:
6064 // Just replace this cast with the result.
6065 return ReplaceInstUsesWith(CI, Res);
6066 case Instruction::ZExt: {
6067 // We need to emit an AND to clear the high bits.
6068 assert(SrcBitSize < DestBitSize && "Not a zext?");
6069 Constant *C =
Reid Spencerc635f472006-12-31 05:48:39 +00006070 ConstantInt::get(Type::Int64Ty, (1ULL << SrcBitSize)-1);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006071 if (DestBitSize < 64)
6072 C = ConstantExpr::getTrunc(C, DestTy);
6073 else {
6074 assert(DestBitSize == 64);
6075 C = ConstantExpr::getBitCast(C, DestTy);
6076 }
6077 return BinaryOperator::createAnd(Res, C);
6078 }
6079 case Instruction::SExt:
6080 // We need to emit a cast to truncate, then a cast to sext.
6081 return CastInst::create(Instruction::SExt,
Reid Spencer13bc5d72006-12-12 09:18:51 +00006082 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
6083 CI), DestTy);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006084 }
6085 }
6086 }
6087
6088 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
6089 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
6090
6091 switch (SrcI->getOpcode()) {
6092 case Instruction::Add:
6093 case Instruction::Mul:
6094 case Instruction::And:
6095 case Instruction::Or:
6096 case Instruction::Xor:
6097 // If we are discarding information, or just changing the sign,
6098 // rewrite.
6099 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
6100 // Don't insert two casts if they cannot be eliminated. We allow
6101 // two casts to be inserted if the sizes are the same. This could
6102 // only be converting signedness, which is a noop.
6103 if (DestBitSize == SrcBitSize ||
Reid Spencer266e42b2006-12-23 06:05:41 +00006104 !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
6105 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer2a499b02006-12-13 17:19:09 +00006106 Instruction::CastOps opcode = CI.getOpcode();
Reid Spencer13bc5d72006-12-12 09:18:51 +00006107 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
6108 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
6109 return BinaryOperator::create(
6110 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006111 }
6112 }
6113
6114 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
6115 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
6116 SrcI->getOpcode() == Instruction::Xor &&
6117 Op1 == ConstantBool::getTrue() &&
Reid Spencer266e42b2006-12-23 06:05:41 +00006118 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00006119 Value *New = InsertOperandCastBefore(Instruction::ZExt, Op0, DestTy, &CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006120 return BinaryOperator::createXor(New, ConstantInt::get(CI.getType(), 1));
6121 }
6122 break;
6123 case Instruction::SDiv:
6124 case Instruction::UDiv:
6125 case Instruction::SRem:
6126 case Instruction::URem:
6127 // If we are just changing the sign, rewrite.
6128 if (DestBitSize == SrcBitSize) {
6129 // Don't insert two casts if they cannot be eliminated. We allow
6130 // two casts to be inserted if the sizes are the same. This could
6131 // only be converting signedness, which is a noop.
Reid Spencer266e42b2006-12-23 06:05:41 +00006132 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
6133 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00006134 Value *Op0c = InsertOperandCastBefore(Instruction::BitCast,
6135 Op0, DestTy, SrcI);
6136 Value *Op1c = InsertOperandCastBefore(Instruction::BitCast,
6137 Op1, DestTy, SrcI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006138 return BinaryOperator::create(
6139 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
6140 }
6141 }
6142 break;
6143
6144 case Instruction::Shl:
6145 // Allow changing the sign of the source operand. Do not allow
6146 // changing the size of the shift, UNLESS the shift amount is a
6147 // constant. We must not change variable sized shifts to a smaller
6148 // size, because it is undefined to shift more bits out than exist
6149 // in the value.
6150 if (DestBitSize == SrcBitSize ||
6151 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00006152 Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
6153 Instruction::BitCast : Instruction::Trunc);
6154 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006155 return new ShiftInst(Instruction::Shl, Op0c, Op1);
6156 }
6157 break;
6158 case Instruction::AShr:
6159 // If this is a signed shr, and if all bits shifted in are about to be
6160 // truncated off, turn it into an unsigned shr to allow greater
6161 // simplifications.
6162 if (DestBitSize < SrcBitSize &&
6163 isa<ConstantInt>(Op1)) {
6164 unsigned ShiftAmt = cast<ConstantInt>(Op1)->getZExtValue();
6165 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
6166 // Insert the new logical shift right.
6167 return new ShiftInst(Instruction::LShr, Op0, Op1);
6168 }
6169 }
6170 break;
6171
Reid Spencer266e42b2006-12-23 06:05:41 +00006172 case Instruction::ICmp:
6173 // If we are just checking for a icmp eq of a single bit and casting it
6174 // to an integer, then shift the bit to the appropriate place and then
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006175 // cast to integer to avoid the comparison.
6176 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
6177 uint64_t Op1CV = Op1C->getZExtValue();
6178 // cast (X == 0) to int --> X^1 iff X has only the low bit set.
6179 // cast (X == 0) to int --> (X>>1)^1 iff X has only the 2nd bit set.
6180 // cast (X == 1) to int --> X iff X has only the low bit set.
6181 // cast (X == 2) to int --> X>>1 iff X has only the 2nd bit set.
6182 // cast (X != 0) to int --> X iff X has only the low bit set.
6183 // cast (X != 0) to int --> X>>1 iff X has only the 2nd bit set.
6184 // cast (X != 1) to int --> X^1 iff X has only the low bit set.
6185 // cast (X != 2) to int --> (X>>1)^1 iff X has only the 2nd bit set.
6186 if (Op1CV == 0 || isPowerOf2_64(Op1CV)) {
6187 // If Op1C some other power of two, convert:
6188 uint64_t KnownZero, KnownOne;
6189 uint64_t TypeMask = Op1->getType()->getIntegralTypeMask();
6190 ComputeMaskedBits(Op0, TypeMask, KnownZero, KnownOne);
Reid Spencer266e42b2006-12-23 06:05:41 +00006191
6192 // This only works for EQ and NE
6193 ICmpInst::Predicate pred = cast<ICmpInst>(SrcI)->getPredicate();
6194 if (pred != ICmpInst::ICMP_NE && pred != ICmpInst::ICMP_EQ)
6195 break;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006196
6197 if (isPowerOf2_64(KnownZero^TypeMask)) { // Exactly 1 possible 1?
Reid Spencer266e42b2006-12-23 06:05:41 +00006198 bool isNE = pred == ICmpInst::ICMP_NE;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006199 if (Op1CV && (Op1CV != (KnownZero^TypeMask))) {
6200 // (X&4) == 2 --> false
6201 // (X&4) != 2 --> true
Reid Spencer266e42b2006-12-23 06:05:41 +00006202 Constant *Res = ConstantBool::get(isNE);
Reid Spencerbb65ebf2006-12-12 23:36:14 +00006203 Res = ConstantExpr::getZExt(Res, CI.getType());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006204 return ReplaceInstUsesWith(CI, Res);
6205 }
6206
6207 unsigned ShiftAmt = Log2_64(KnownZero^TypeMask);
6208 Value *In = Op0;
6209 if (ShiftAmt) {
6210 // Perform a logical shr by shiftamt.
6211 // Insert the shift to put the result in the low bit.
6212 In = InsertNewInstBefore(
6213 new ShiftInst(Instruction::LShr, In,
Reid Spencerc635f472006-12-31 05:48:39 +00006214 ConstantInt::get(Type::Int8Ty, ShiftAmt),
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006215 In->getName()+".lobit"), CI);
6216 }
6217
Reid Spencer266e42b2006-12-23 06:05:41 +00006218 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006219 Constant *One = ConstantInt::get(In->getType(), 1);
6220 In = BinaryOperator::createXor(In, One, "tmp");
6221 InsertNewInstBefore(cast<Instruction>(In), CI);
6222 }
6223
6224 if (CI.getType() == In->getType())
6225 return ReplaceInstUsesWith(CI, In);
6226 else
Reid Spencerbb65ebf2006-12-12 23:36:14 +00006227 return CastInst::createIntegerCast(In, CI.getType(), false/*ZExt*/);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006228 }
6229 }
6230 }
6231 break;
6232 }
6233 return 0;
6234}
6235
6236Instruction *InstCombiner::visitTrunc(CastInst &CI) {
Chris Lattnerd747f012006-11-29 07:04:07 +00006237 if (Instruction *Result = commonIntCastTransforms(CI))
6238 return Result;
6239
6240 Value *Src = CI.getOperand(0);
6241 const Type *Ty = CI.getType();
6242 unsigned DestBitWidth = Ty->getPrimitiveSizeInBits();
6243
6244 if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
6245 switch (SrcI->getOpcode()) {
6246 default: break;
6247 case Instruction::LShr:
6248 // We can shrink lshr to something smaller if we know the bits shifted in
6249 // are already zeros.
6250 if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
6251 unsigned ShAmt = ShAmtV->getZExtValue();
6252
6253 // Get a mask for the bits shifting in.
6254 uint64_t Mask = (~0ULL >> (64-ShAmt)) << DestBitWidth;
Reid Spencer13bc5d72006-12-12 09:18:51 +00006255 Value* SrcIOp0 = SrcI->getOperand(0);
6256 if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
Chris Lattnerd747f012006-11-29 07:04:07 +00006257 if (ShAmt >= DestBitWidth) // All zeros.
6258 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
6259
6260 // Okay, we can shrink this. Truncate the input, then return a new
6261 // shift.
Reid Spencer2a499b02006-12-13 17:19:09 +00006262 Value *V = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
Chris Lattnerd747f012006-11-29 07:04:07 +00006263 return new ShiftInst(Instruction::LShr, V, SrcI->getOperand(1));
6264 }
Chris Lattnerc209b582006-12-05 01:26:29 +00006265 } else { // This is a variable shr.
6266
6267 // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'. This is
6268 // more LLVM instructions, but allows '1 << Y' to be hoisted if
6269 // loop-invariant and CSE'd.
6270 if (CI.getType() == Type::BoolTy && SrcI->hasOneUse()) {
6271 Value *One = ConstantInt::get(SrcI->getType(), 1);
6272
6273 Value *V = InsertNewInstBefore(new ShiftInst(Instruction::Shl, One,
6274 SrcI->getOperand(1),
6275 "tmp"), CI);
6276 V = InsertNewInstBefore(BinaryOperator::createAnd(V,
6277 SrcI->getOperand(0),
6278 "tmp"), CI);
6279 Value *Zero = Constant::getNullValue(V->getType());
Reid Spencer266e42b2006-12-23 06:05:41 +00006280 return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
Chris Lattnerc209b582006-12-05 01:26:29 +00006281 }
Chris Lattnerd747f012006-11-29 07:04:07 +00006282 }
6283 break;
6284 }
6285 }
6286
6287 return 0;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006288}
6289
6290Instruction *InstCombiner::visitZExt(CastInst &CI) {
6291 // If one of the common conversion will work ..
6292 if (Instruction *Result = commonIntCastTransforms(CI))
6293 return Result;
6294
6295 Value *Src = CI.getOperand(0);
6296
6297 // If this is a cast of a cast
6298 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006299 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
6300 // types and if the sizes are just right we can convert this into a logical
6301 // 'and' which will be much cheaper than the pair of casts.
6302 if (isa<TruncInst>(CSrc)) {
6303 // Get the sizes of the types involved
6304 Value *A = CSrc->getOperand(0);
6305 unsigned SrcSize = A->getType()->getPrimitiveSizeInBits();
6306 unsigned MidSize = CSrc->getType()->getPrimitiveSizeInBits();
6307 unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
6308 // If we're actually extending zero bits and the trunc is a no-op
6309 if (MidSize < DstSize && SrcSize == DstSize) {
6310 // Replace both of the casts with an And of the type mask.
6311 uint64_t AndValue = CSrc->getType()->getIntegralTypeMask();
6312 Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
6313 Instruction *And =
6314 BinaryOperator::createAnd(CSrc->getOperand(0), AndConst);
6315 // Unfortunately, if the type changed, we need to cast it back.
6316 if (And->getType() != CI.getType()) {
6317 And->setName(CSrc->getName()+".mask");
6318 InsertNewInstBefore(And, CI);
Reid Spencerbb65ebf2006-12-12 23:36:14 +00006319 And = CastInst::createIntegerCast(And, CI.getType(), false/*ZExt*/);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006320 }
6321 return And;
6322 }
6323 }
6324 }
6325
6326 return 0;
6327}
6328
6329Instruction *InstCombiner::visitSExt(CastInst &CI) {
6330 return commonIntCastTransforms(CI);
6331}
6332
6333Instruction *InstCombiner::visitFPTrunc(CastInst &CI) {
6334 return commonCastTransforms(CI);
6335}
6336
6337Instruction *InstCombiner::visitFPExt(CastInst &CI) {
6338 return commonCastTransforms(CI);
6339}
6340
6341Instruction *InstCombiner::visitFPToUI(CastInst &CI) {
Reid Spencerad05ee92006-11-30 23:13:36 +00006342 return commonCastTransforms(CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006343}
6344
6345Instruction *InstCombiner::visitFPToSI(CastInst &CI) {
Reid Spencerad05ee92006-11-30 23:13:36 +00006346 return commonCastTransforms(CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006347}
6348
6349Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
6350 return commonCastTransforms(CI);
6351}
6352
6353Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
6354 return commonCastTransforms(CI);
6355}
6356
6357Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
Reid Spencerad05ee92006-11-30 23:13:36 +00006358 return commonCastTransforms(CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006359}
6360
6361Instruction *InstCombiner::visitIntToPtr(CastInst &CI) {
6362 return commonCastTransforms(CI);
6363}
6364
6365Instruction *InstCombiner::visitBitCast(CastInst &CI) {
6366
6367 // If the operands are integer typed then apply the integer transforms,
6368 // otherwise just apply the common ones.
6369 Value *Src = CI.getOperand(0);
6370 const Type *SrcTy = Src->getType();
6371 const Type *DestTy = CI.getType();
6372
6373 if (SrcTy->isInteger() && DestTy->isInteger()) {
6374 if (Instruction *Result = commonIntCastTransforms(CI))
6375 return Result;
6376 } else {
6377 if (Instruction *Result = commonCastTransforms(CI))
6378 return Result;
6379 }
6380
6381
6382 // Get rid of casts from one type to the same type. These are useless and can
6383 // be replaced by the operand.
6384 if (DestTy == Src->getType())
6385 return ReplaceInstUsesWith(CI, Src);
6386
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006387 // If the source and destination are pointers, and this cast is equivalent to
6388 // a getelementptr X, 0, 0, 0... turn it into the appropriate getelementptr.
6389 // This can enhance SROA and other transforms that want type-safe pointers.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006390 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
6391 if (const PointerType *SrcPTy = dyn_cast<PointerType>(SrcTy)) {
6392 const Type *DstElTy = DstPTy->getElementType();
6393 const Type *SrcElTy = SrcPTy->getElementType();
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006394
Reid Spencerc635f472006-12-31 05:48:39 +00006395 Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006396 unsigned NumZeros = 0;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006397 while (SrcElTy != DstElTy &&
6398 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
6399 SrcElTy->getNumContainedTypes() /* not "{}" */) {
6400 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006401 ++NumZeros;
6402 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00006403
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006404 // If we found a path from the src to dest, create the getelementptr now.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006405 if (SrcElTy == DstElTy) {
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006406 std::vector<Value*> Idxs(NumZeros+1, ZeroUInt);
6407 return new GetElementPtrInst(Src, Idxs);
6408 }
6409 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006410 }
Chris Lattnerdfae8be2003-07-24 17:35:25 +00006411
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006412 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
6413 if (SVI->hasOneUse()) {
6414 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
6415 // a bitconvert to a vector with the same # elts.
6416 if (isa<PackedType>(DestTy) &&
6417 cast<PackedType>(DestTy)->getNumElements() ==
6418 SVI->getType()->getNumElements()) {
6419 CastInst *Tmp;
6420 // If either of the operands is a cast from CI.getType(), then
6421 // evaluating the shuffle in the casted destination's type will allow
6422 // us to eliminate at least one cast.
6423 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
6424 Tmp->getOperand(0)->getType() == DestTy) ||
6425 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
6426 Tmp->getOperand(0)->getType() == DestTy)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00006427 Value *LHS = InsertOperandCastBefore(Instruction::BitCast,
6428 SVI->getOperand(0), DestTy, &CI);
6429 Value *RHS = InsertOperandCastBefore(Instruction::BitCast,
6430 SVI->getOperand(1), DestTy, &CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006431 // Return a new shuffle vector. Use the same element ID's, as we
6432 // know the vector types match #elts.
6433 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner99155be2006-05-25 23:24:33 +00006434 }
6435 }
6436 }
6437 }
Chris Lattner260ab202002-04-18 17:39:14 +00006438 return 0;
Chris Lattnerca081252001-12-14 16:52:21 +00006439}
6440
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006441/// GetSelectFoldableOperands - We want to turn code that looks like this:
6442/// %C = or %A, %B
6443/// %D = select %cond, %C, %A
6444/// into:
6445/// %C = select %cond, %B, 0
6446/// %D = or %A, %C
6447///
6448/// Assuming that the specified instruction is an operand to the select, return
6449/// a bitmask indicating which operands of this instruction are foldable if they
6450/// equal the other incoming value of the select.
6451///
6452static unsigned GetSelectFoldableOperands(Instruction *I) {
6453 switch (I->getOpcode()) {
6454 case Instruction::Add:
6455 case Instruction::Mul:
6456 case Instruction::And:
6457 case Instruction::Or:
6458 case Instruction::Xor:
6459 return 3; // Can fold through either operand.
6460 case Instruction::Sub: // Can only fold on the amount subtracted.
6461 case Instruction::Shl: // Can only fold on the shift amount.
Reid Spencerfdff9382006-11-08 06:47:33 +00006462 case Instruction::LShr:
6463 case Instruction::AShr:
Misha Brukmanb1c93172005-04-21 23:48:37 +00006464 return 1;
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006465 default:
6466 return 0; // Cannot fold
6467 }
6468}
6469
6470/// GetSelectFoldableConstant - For the same transformation as the previous
6471/// function, return the identity constant that goes into the select.
6472static Constant *GetSelectFoldableConstant(Instruction *I) {
6473 switch (I->getOpcode()) {
6474 default: assert(0 && "This cannot happen!"); abort();
6475 case Instruction::Add:
6476 case Instruction::Sub:
6477 case Instruction::Or:
6478 case Instruction::Xor:
6479 return Constant::getNullValue(I->getType());
6480 case Instruction::Shl:
Reid Spencerfdff9382006-11-08 06:47:33 +00006481 case Instruction::LShr:
6482 case Instruction::AShr:
Reid Spencerc635f472006-12-31 05:48:39 +00006483 return Constant::getNullValue(Type::Int8Ty);
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006484 case Instruction::And:
6485 return ConstantInt::getAllOnesValue(I->getType());
6486 case Instruction::Mul:
6487 return ConstantInt::get(I->getType(), 1);
6488 }
6489}
6490
Chris Lattner411336f2005-01-19 21:50:18 +00006491/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
6492/// have the same opcode and only one use each. Try to simplify this.
6493Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
6494 Instruction *FI) {
6495 if (TI->getNumOperands() == 1) {
6496 // If this is a non-volatile load or a cast from the same type,
6497 // merge.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006498 if (TI->isCast()) {
Chris Lattner411336f2005-01-19 21:50:18 +00006499 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
6500 return 0;
6501 } else {
6502 return 0; // unknown unary op.
6503 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00006504
Chris Lattner411336f2005-01-19 21:50:18 +00006505 // Fold this by inserting a select from the input values.
6506 SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
6507 FI->getOperand(0), SI.getName()+".v");
6508 InsertNewInstBefore(NewSI, SI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006509 return CastInst::create(Instruction::CastOps(TI->getOpcode()), NewSI,
6510 TI->getType());
Chris Lattner411336f2005-01-19 21:50:18 +00006511 }
6512
Reid Spencer266e42b2006-12-23 06:05:41 +00006513 // Only handle binary, compare and shift operators here.
Reid Spencer43c77d52006-12-23 18:58:04 +00006514 if (!isa<ShiftInst>(TI) && !isa<BinaryOperator>(TI))
Chris Lattner411336f2005-01-19 21:50:18 +00006515 return 0;
6516
6517 // Figure out if the operations have any operands in common.
6518 Value *MatchOp, *OtherOpT, *OtherOpF;
6519 bool MatchIsOpZero;
6520 if (TI->getOperand(0) == FI->getOperand(0)) {
6521 MatchOp = TI->getOperand(0);
6522 OtherOpT = TI->getOperand(1);
6523 OtherOpF = FI->getOperand(1);
6524 MatchIsOpZero = true;
6525 } else if (TI->getOperand(1) == FI->getOperand(1)) {
6526 MatchOp = TI->getOperand(1);
6527 OtherOpT = TI->getOperand(0);
6528 OtherOpF = FI->getOperand(0);
6529 MatchIsOpZero = false;
6530 } else if (!TI->isCommutative()) {
6531 return 0;
6532 } else if (TI->getOperand(0) == FI->getOperand(1)) {
6533 MatchOp = TI->getOperand(0);
6534 OtherOpT = TI->getOperand(1);
6535 OtherOpF = FI->getOperand(0);
6536 MatchIsOpZero = true;
6537 } else if (TI->getOperand(1) == FI->getOperand(0)) {
6538 MatchOp = TI->getOperand(1);
6539 OtherOpT = TI->getOperand(0);
6540 OtherOpF = FI->getOperand(1);
6541 MatchIsOpZero = true;
6542 } else {
6543 return 0;
6544 }
6545
6546 // If we reach here, they do have operations in common.
6547 SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
6548 OtherOpF, SI.getName()+".v");
6549 InsertNewInstBefore(NewSI, SI);
6550
6551 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
6552 if (MatchIsOpZero)
6553 return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
6554 else
6555 return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
Chris Lattner411336f2005-01-19 21:50:18 +00006556 }
Reid Spencer43c77d52006-12-23 18:58:04 +00006557
6558 assert(isa<ShiftInst>(TI) && "Should only have Shift here");
6559 if (MatchIsOpZero)
6560 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), MatchOp, NewSI);
6561 else
6562 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), NewSI, MatchOp);
Chris Lattner411336f2005-01-19 21:50:18 +00006563}
6564
Chris Lattnerb909e8b2004-03-12 05:52:32 +00006565Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattner533bc492004-03-30 19:37:13 +00006566 Value *CondVal = SI.getCondition();
6567 Value *TrueVal = SI.getTrueValue();
6568 Value *FalseVal = SI.getFalseValue();
6569
6570 // select true, X, Y -> X
6571 // select false, X, Y -> Y
6572 if (ConstantBool *C = dyn_cast<ConstantBool>(CondVal))
Chris Lattner6ab03f62006-09-28 23:35:22 +00006573 return ReplaceInstUsesWith(SI, C->getValue() ? TrueVal : FalseVal);
Chris Lattner533bc492004-03-30 19:37:13 +00006574
6575 // select C, X, X -> X
6576 if (TrueVal == FalseVal)
6577 return ReplaceInstUsesWith(SI, TrueVal);
6578
Chris Lattner81a7a232004-10-16 18:11:37 +00006579 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
6580 return ReplaceInstUsesWith(SI, FalseVal);
6581 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
6582 return ReplaceInstUsesWith(SI, TrueVal);
6583 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
6584 if (isa<Constant>(TrueVal))
6585 return ReplaceInstUsesWith(SI, TrueVal);
6586 else
6587 return ReplaceInstUsesWith(SI, FalseVal);
6588 }
6589
Chris Lattner1c631e82004-04-08 04:43:23 +00006590 if (SI.getType() == Type::BoolTy)
6591 if (ConstantBool *C = dyn_cast<ConstantBool>(TrueVal)) {
Chris Lattner6ab03f62006-09-28 23:35:22 +00006592 if (C->getValue()) {
Chris Lattner1c631e82004-04-08 04:43:23 +00006593 // Change: A = select B, true, C --> A = or B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00006594 return BinaryOperator::createOr(CondVal, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00006595 } else {
6596 // Change: A = select B, false, C --> A = and !B, C
6597 Value *NotCond =
6598 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
6599 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00006600 return BinaryOperator::createAnd(NotCond, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00006601 }
6602 } else if (ConstantBool *C = dyn_cast<ConstantBool>(FalseVal)) {
Chris Lattner6ab03f62006-09-28 23:35:22 +00006603 if (C->getValue() == false) {
Chris Lattner1c631e82004-04-08 04:43:23 +00006604 // Change: A = select B, C, false --> A = and B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00006605 return BinaryOperator::createAnd(CondVal, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00006606 } else {
6607 // Change: A = select B, C, true --> A = or !B, C
6608 Value *NotCond =
6609 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
6610 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00006611 return BinaryOperator::createOr(NotCond, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00006612 }
6613 }
6614
Chris Lattner183b3362004-04-09 19:05:30 +00006615 // Selecting between two integer constants?
6616 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
6617 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
6618 // select C, 1, 0 -> cast C to int
Reid Spencere0fc4df2006-10-20 07:07:24 +00006619 if (FalseValC->isNullValue() && TrueValC->getZExtValue() == 1) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006620 return CastInst::create(Instruction::ZExt, CondVal, SI.getType());
Reid Spencere0fc4df2006-10-20 07:07:24 +00006621 } else if (TrueValC->isNullValue() && FalseValC->getZExtValue() == 1) {
Chris Lattner183b3362004-04-09 19:05:30 +00006622 // select C, 0, 1 -> cast !C to int
6623 Value *NotCond =
6624 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
Chris Lattnercf7baf32004-04-09 18:19:44 +00006625 "not."+CondVal->getName()), SI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006626 return CastInst::create(Instruction::ZExt, NotCond, SI.getType());
Chris Lattnercf7baf32004-04-09 18:19:44 +00006627 }
Chris Lattner35167c32004-06-09 07:59:58 +00006628
Reid Spencer266e42b2006-12-23 06:05:41 +00006629 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Chris Lattner380c7e92006-09-20 04:44:59 +00006630
Reid Spencer266e42b2006-12-23 06:05:41 +00006631 // (x <s 0) ? -1 : 0 -> ashr x, 31
6632 // (x >u 2147483647) ? -1 : 0 -> ashr x, 31
Chris Lattner380c7e92006-09-20 04:44:59 +00006633 if (TrueValC->isAllOnesValue() && FalseValC->isNullValue())
6634 if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
6635 bool CanXForm = false;
Reid Spencer266e42b2006-12-23 06:05:41 +00006636 if (IC->isSignedPredicate())
Chris Lattner380c7e92006-09-20 04:44:59 +00006637 CanXForm = CmpCst->isNullValue() &&
Reid Spencer266e42b2006-12-23 06:05:41 +00006638 IC->getPredicate() == ICmpInst::ICMP_SLT;
Chris Lattner380c7e92006-09-20 04:44:59 +00006639 else {
6640 unsigned Bits = CmpCst->getType()->getPrimitiveSizeInBits();
Reid Spencere0fc4df2006-10-20 07:07:24 +00006641 CanXForm = (CmpCst->getZExtValue() == ~0ULL >> (64-Bits+1)) &&
Reid Spencer266e42b2006-12-23 06:05:41 +00006642 IC->getPredicate() == ICmpInst::ICMP_UGT;
Chris Lattner380c7e92006-09-20 04:44:59 +00006643 }
6644
6645 if (CanXForm) {
6646 // The comparison constant and the result are not neccessarily the
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006647 // same width. Make an all-ones value by inserting a AShr.
Chris Lattner380c7e92006-09-20 04:44:59 +00006648 Value *X = IC->getOperand(0);
Chris Lattner380c7e92006-09-20 04:44:59 +00006649 unsigned Bits = X->getType()->getPrimitiveSizeInBits();
Reid Spencerc635f472006-12-31 05:48:39 +00006650 Constant *ShAmt = ConstantInt::get(Type::Int8Ty, Bits-1);
Reid Spencerfdff9382006-11-08 06:47:33 +00006651 Instruction *SRA = new ShiftInst(Instruction::AShr, X,
Chris Lattner380c7e92006-09-20 04:44:59 +00006652 ShAmt, "ones");
6653 InsertNewInstBefore(SRA, SI);
6654
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006655 // Finally, convert to the type of the select RHS. We figure out
6656 // if this requires a SExt, Trunc or BitCast based on the sizes.
6657 Instruction::CastOps opc = Instruction::BitCast;
6658 unsigned SRASize = SRA->getType()->getPrimitiveSizeInBits();
6659 unsigned SISize = SI.getType()->getPrimitiveSizeInBits();
6660 if (SRASize < SISize)
6661 opc = Instruction::SExt;
6662 else if (SRASize > SISize)
6663 opc = Instruction::Trunc;
6664 return CastInst::create(opc, SRA, SI.getType());
Chris Lattner380c7e92006-09-20 04:44:59 +00006665 }
6666 }
6667
6668
6669 // If one of the constants is zero (we know they can't both be) and we
Reid Spencer266e42b2006-12-23 06:05:41 +00006670 // have a fcmp instruction with zero, and we have an 'and' with the
Chris Lattner380c7e92006-09-20 04:44:59 +00006671 // non-constant value, eliminate this whole mess. This corresponds to
6672 // cases like this: ((X & 27) ? 27 : 0)
6673 if (TrueValC->isNullValue() || FalseValC->isNullValue())
Chris Lattnerb3f24c92006-09-18 04:22:48 +00006674 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner35167c32004-06-09 07:59:58 +00006675 cast<Constant>(IC->getOperand(1))->isNullValue())
6676 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
6677 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00006678 isa<ConstantInt>(ICA->getOperand(1)) &&
6679 (ICA->getOperand(1) == TrueValC ||
6680 ICA->getOperand(1) == FalseValC) &&
Chris Lattner35167c32004-06-09 07:59:58 +00006681 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
6682 // Okay, now we know that everything is set up, we just don't
Reid Spencer266e42b2006-12-23 06:05:41 +00006683 // know whether we have a icmp_ne or icmp_eq and whether the
6684 // true or false val is the zero.
Chris Lattner35167c32004-06-09 07:59:58 +00006685 bool ShouldNotVal = !TrueValC->isNullValue();
Reid Spencer266e42b2006-12-23 06:05:41 +00006686 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
Chris Lattner35167c32004-06-09 07:59:58 +00006687 Value *V = ICA;
6688 if (ShouldNotVal)
6689 V = InsertNewInstBefore(BinaryOperator::create(
6690 Instruction::Xor, V, ICA->getOperand(1)), SI);
6691 return ReplaceInstUsesWith(SI, V);
6692 }
Chris Lattner380c7e92006-09-20 04:44:59 +00006693 }
Chris Lattner533bc492004-03-30 19:37:13 +00006694 }
Chris Lattner623fba12004-04-10 22:21:27 +00006695
6696 // See if we are selecting two values based on a comparison of the two values.
Reid Spencer266e42b2006-12-23 06:05:41 +00006697 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
6698 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
Chris Lattner623fba12004-04-10 22:21:27 +00006699 // Transform (X == Y) ? X : Y -> Y
Reid Spencer266e42b2006-12-23 06:05:41 +00006700 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ)
Chris Lattner623fba12004-04-10 22:21:27 +00006701 return ReplaceInstUsesWith(SI, FalseVal);
6702 // Transform (X != Y) ? X : Y -> X
Reid Spencer266e42b2006-12-23 06:05:41 +00006703 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
Chris Lattner623fba12004-04-10 22:21:27 +00006704 return ReplaceInstUsesWith(SI, TrueVal);
6705 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6706
Reid Spencer266e42b2006-12-23 06:05:41 +00006707 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
Chris Lattner623fba12004-04-10 22:21:27 +00006708 // Transform (X == Y) ? Y : X -> X
Reid Spencer266e42b2006-12-23 06:05:41 +00006709 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ)
Chris Lattner24cf0202004-04-11 01:39:19 +00006710 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattner623fba12004-04-10 22:21:27 +00006711 // Transform (X != Y) ? Y : X -> Y
Reid Spencer266e42b2006-12-23 06:05:41 +00006712 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
6713 return ReplaceInstUsesWith(SI, TrueVal);
6714 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6715 }
6716 }
6717
6718 // See if we are selecting two values based on a comparison of the two values.
6719 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal)) {
6720 if (ICI->getOperand(0) == TrueVal && ICI->getOperand(1) == FalseVal) {
6721 // Transform (X == Y) ? X : Y -> Y
6722 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
6723 return ReplaceInstUsesWith(SI, FalseVal);
6724 // Transform (X != Y) ? X : Y -> X
6725 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
6726 return ReplaceInstUsesWith(SI, TrueVal);
6727 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6728
6729 } else if (ICI->getOperand(0) == FalseVal && ICI->getOperand(1) == TrueVal){
6730 // Transform (X == Y) ? Y : X -> X
6731 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
6732 return ReplaceInstUsesWith(SI, FalseVal);
6733 // Transform (X != Y) ? Y : X -> Y
6734 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
Chris Lattner24cf0202004-04-11 01:39:19 +00006735 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattner623fba12004-04-10 22:21:27 +00006736 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6737 }
6738 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00006739
Chris Lattnera04c9042005-01-13 22:52:24 +00006740 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
6741 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
6742 if (TI->hasOneUse() && FI->hasOneUse()) {
Chris Lattnera04c9042005-01-13 22:52:24 +00006743 Instruction *AddOp = 0, *SubOp = 0;
6744
Chris Lattner411336f2005-01-19 21:50:18 +00006745 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
6746 if (TI->getOpcode() == FI->getOpcode())
6747 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
6748 return IV;
6749
6750 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
6751 // even legal for FP.
Chris Lattnera04c9042005-01-13 22:52:24 +00006752 if (TI->getOpcode() == Instruction::Sub &&
6753 FI->getOpcode() == Instruction::Add) {
6754 AddOp = FI; SubOp = TI;
6755 } else if (FI->getOpcode() == Instruction::Sub &&
6756 TI->getOpcode() == Instruction::Add) {
6757 AddOp = TI; SubOp = FI;
6758 }
6759
6760 if (AddOp) {
6761 Value *OtherAddOp = 0;
6762 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
6763 OtherAddOp = AddOp->getOperand(1);
6764 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
6765 OtherAddOp = AddOp->getOperand(0);
6766 }
6767
6768 if (OtherAddOp) {
Chris Lattnerb580d262006-02-24 18:05:58 +00006769 // So at this point we know we have (Y -> OtherAddOp):
6770 // select C, (add X, Y), (sub X, Z)
6771 Value *NegVal; // Compute -Z
6772 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
6773 NegVal = ConstantExpr::getNeg(C);
6774 } else {
6775 NegVal = InsertNewInstBefore(
6776 BinaryOperator::createNeg(SubOp->getOperand(1), "tmp"), SI);
Chris Lattnera04c9042005-01-13 22:52:24 +00006777 }
Chris Lattnerb580d262006-02-24 18:05:58 +00006778
6779 Value *NewTrueOp = OtherAddOp;
6780 Value *NewFalseOp = NegVal;
6781 if (AddOp != TI)
6782 std::swap(NewTrueOp, NewFalseOp);
6783 Instruction *NewSel =
6784 new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
6785
6786 NewSel = InsertNewInstBefore(NewSel, SI);
6787 return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
Chris Lattnera04c9042005-01-13 22:52:24 +00006788 }
6789 }
6790 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00006791
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006792 // See if we can fold the select into one of our operands.
6793 if (SI.getType()->isInteger()) {
6794 // See the comment above GetSelectFoldableOperands for a description of the
6795 // transformation we are doing here.
6796 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
6797 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
6798 !isa<Constant>(FalseVal))
6799 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
6800 unsigned OpToFold = 0;
6801 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
6802 OpToFold = 1;
6803 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
6804 OpToFold = 2;
6805 }
6806
6807 if (OpToFold) {
6808 Constant *C = GetSelectFoldableConstant(TVI);
6809 std::string Name = TVI->getName(); TVI->setName("");
6810 Instruction *NewSel =
6811 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C,
6812 Name);
6813 InsertNewInstBefore(NewSel, SI);
6814 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
6815 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
6816 else if (ShiftInst *SI = dyn_cast<ShiftInst>(TVI))
6817 return new ShiftInst(SI->getOpcode(), FalseVal, NewSel);
6818 else {
6819 assert(0 && "Unknown instruction!!");
6820 }
6821 }
6822 }
Chris Lattner6862fbd2004-09-29 17:40:11 +00006823
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006824 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
6825 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
6826 !isa<Constant>(TrueVal))
6827 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
6828 unsigned OpToFold = 0;
6829 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
6830 OpToFold = 1;
6831 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
6832 OpToFold = 2;
6833 }
6834
6835 if (OpToFold) {
6836 Constant *C = GetSelectFoldableConstant(FVI);
6837 std::string Name = FVI->getName(); FVI->setName("");
6838 Instruction *NewSel =
6839 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold),
6840 Name);
6841 InsertNewInstBefore(NewSel, SI);
6842 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
6843 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
6844 else if (ShiftInst *SI = dyn_cast<ShiftInst>(FVI))
6845 return new ShiftInst(SI->getOpcode(), TrueVal, NewSel);
6846 else {
6847 assert(0 && "Unknown instruction!!");
6848 }
6849 }
6850 }
6851 }
Chris Lattnerd6f636a2005-04-24 07:30:14 +00006852
6853 if (BinaryOperator::isNot(CondVal)) {
6854 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
6855 SI.setOperand(1, FalseVal);
6856 SI.setOperand(2, TrueVal);
6857 return &SI;
6858 }
6859
Chris Lattnerb909e8b2004-03-12 05:52:32 +00006860 return 0;
6861}
6862
Chris Lattner82f2ef22006-03-06 20:18:44 +00006863/// GetKnownAlignment - If the specified pointer has an alignment that we can
6864/// determine, return it, otherwise return 0.
6865static unsigned GetKnownAlignment(Value *V, TargetData *TD) {
6866 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
6867 unsigned Align = GV->getAlignment();
6868 if (Align == 0 && TD)
6869 Align = TD->getTypeAlignment(GV->getType()->getElementType());
6870 return Align;
6871 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
6872 unsigned Align = AI->getAlignment();
6873 if (Align == 0 && TD) {
6874 if (isa<AllocaInst>(AI))
6875 Align = TD->getTypeAlignment(AI->getType()->getElementType());
6876 else if (isa<MallocInst>(AI)) {
6877 // Malloc returns maximally aligned memory.
6878 Align = TD->getTypeAlignment(AI->getType()->getElementType());
6879 Align = std::max(Align, (unsigned)TD->getTypeAlignment(Type::DoubleTy));
Reid Spencerc635f472006-12-31 05:48:39 +00006880 Align = std::max(Align, (unsigned)TD->getTypeAlignment(Type::Int64Ty));
Chris Lattner82f2ef22006-03-06 20:18:44 +00006881 }
6882 }
6883 return Align;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006884 } else if (isa<BitCastInst>(V) ||
Chris Lattner53ef5a02006-03-07 01:28:57 +00006885 (isa<ConstantExpr>(V) &&
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006886 cast<ConstantExpr>(V)->getOpcode() == Instruction::BitCast)) {
Chris Lattner53ef5a02006-03-07 01:28:57 +00006887 User *CI = cast<User>(V);
Chris Lattner82f2ef22006-03-06 20:18:44 +00006888 if (isa<PointerType>(CI->getOperand(0)->getType()))
6889 return GetKnownAlignment(CI->getOperand(0), TD);
6890 return 0;
Chris Lattner53ef5a02006-03-07 01:28:57 +00006891 } else if (isa<GetElementPtrInst>(V) ||
6892 (isa<ConstantExpr>(V) &&
6893 cast<ConstantExpr>(V)->getOpcode()==Instruction::GetElementPtr)) {
6894 User *GEPI = cast<User>(V);
Chris Lattner82f2ef22006-03-06 20:18:44 +00006895 unsigned BaseAlignment = GetKnownAlignment(GEPI->getOperand(0), TD);
6896 if (BaseAlignment == 0) return 0;
6897
6898 // If all indexes are zero, it is just the alignment of the base pointer.
6899 bool AllZeroOperands = true;
6900 for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
6901 if (!isa<Constant>(GEPI->getOperand(i)) ||
6902 !cast<Constant>(GEPI->getOperand(i))->isNullValue()) {
6903 AllZeroOperands = false;
6904 break;
6905 }
6906 if (AllZeroOperands)
6907 return BaseAlignment;
6908
6909 // Otherwise, if the base alignment is >= the alignment we expect for the
6910 // base pointer type, then we know that the resultant pointer is aligned at
6911 // least as much as its type requires.
6912 if (!TD) return 0;
6913
6914 const Type *BasePtrTy = GEPI->getOperand(0)->getType();
6915 if (TD->getTypeAlignment(cast<PointerType>(BasePtrTy)->getElementType())
Chris Lattner53ef5a02006-03-07 01:28:57 +00006916 <= BaseAlignment) {
6917 const Type *GEPTy = GEPI->getType();
6918 return TD->getTypeAlignment(cast<PointerType>(GEPTy)->getElementType());
6919 }
Chris Lattner82f2ef22006-03-06 20:18:44 +00006920 return 0;
6921 }
6922 return 0;
6923}
6924
Chris Lattnerb909e8b2004-03-12 05:52:32 +00006925
Chris Lattnerc66b2232006-01-13 20:11:04 +00006926/// visitCallInst - CallInst simplification. This mostly only handles folding
6927/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
6928/// the heavy lifting.
6929///
Chris Lattner970c33a2003-06-19 17:00:31 +00006930Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattnerc66b2232006-01-13 20:11:04 +00006931 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
6932 if (!II) return visitCallSite(&CI);
6933
Chris Lattner51ea1272004-02-28 05:22:00 +00006934 // Intrinsics cannot occur in an invoke, so handle them here instead of in
6935 // visitCallSite.
Chris Lattnerc66b2232006-01-13 20:11:04 +00006936 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner00648e12004-10-12 04:52:52 +00006937 bool Changed = false;
6938
6939 // memmove/cpy/set of zero bytes is a noop.
6940 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
6941 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
6942
Chris Lattner00648e12004-10-12 04:52:52 +00006943 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencere0fc4df2006-10-20 07:07:24 +00006944 if (CI->getZExtValue() == 1) {
Chris Lattner00648e12004-10-12 04:52:52 +00006945 // Replace the instruction with just byte operations. We would
6946 // transform other cases to loads/stores, but we don't know if
6947 // alignment is sufficient.
6948 }
Chris Lattner51ea1272004-02-28 05:22:00 +00006949 }
6950
Chris Lattner00648e12004-10-12 04:52:52 +00006951 // If we have a memmove and the source operation is a constant global,
6952 // then the source and dest pointers can't alias, so we can change this
6953 // into a call to memcpy.
Chris Lattner82f2ef22006-03-06 20:18:44 +00006954 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(II)) {
Chris Lattner00648e12004-10-12 04:52:52 +00006955 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
6956 if (GVSrc->isConstant()) {
6957 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner681ef2f2006-03-03 01:34:17 +00006958 const char *Name;
Andrew Lenharth0ebb0b02006-11-03 22:45:50 +00006959 if (CI.getCalledFunction()->getFunctionType()->getParamType(2) ==
Reid Spencerc635f472006-12-31 05:48:39 +00006960 Type::Int32Ty)
Chris Lattner681ef2f2006-03-03 01:34:17 +00006961 Name = "llvm.memcpy.i32";
6962 else
6963 Name = "llvm.memcpy.i64";
6964 Function *MemCpy = M->getOrInsertFunction(Name,
Chris Lattner00648e12004-10-12 04:52:52 +00006965 CI.getCalledFunction()->getFunctionType());
6966 CI.setOperand(0, MemCpy);
6967 Changed = true;
6968 }
Chris Lattner82f2ef22006-03-06 20:18:44 +00006969 }
Chris Lattner00648e12004-10-12 04:52:52 +00006970
Chris Lattner82f2ef22006-03-06 20:18:44 +00006971 // If we can determine a pointer alignment that is bigger than currently
6972 // set, update the alignment.
6973 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
6974 unsigned Alignment1 = GetKnownAlignment(MI->getOperand(1), TD);
6975 unsigned Alignment2 = GetKnownAlignment(MI->getOperand(2), TD);
6976 unsigned Align = std::min(Alignment1, Alignment2);
Reid Spencere0fc4df2006-10-20 07:07:24 +00006977 if (MI->getAlignment()->getZExtValue() < Align) {
Reid Spencerc635f472006-12-31 05:48:39 +00006978 MI->setAlignment(ConstantInt::get(Type::Int32Ty, Align));
Chris Lattner82f2ef22006-03-06 20:18:44 +00006979 Changed = true;
6980 }
6981 } else if (isa<MemSetInst>(MI)) {
6982 unsigned Alignment = GetKnownAlignment(MI->getDest(), TD);
Reid Spencere0fc4df2006-10-20 07:07:24 +00006983 if (MI->getAlignment()->getZExtValue() < Alignment) {
Reid Spencerc635f472006-12-31 05:48:39 +00006984 MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
Chris Lattner82f2ef22006-03-06 20:18:44 +00006985 Changed = true;
6986 }
6987 }
6988
Chris Lattnerc66b2232006-01-13 20:11:04 +00006989 if (Changed) return II;
Chris Lattner503221f2006-01-13 21:28:09 +00006990 } else {
6991 switch (II->getIntrinsicID()) {
6992 default: break;
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00006993 case Intrinsic::ppc_altivec_lvx:
6994 case Intrinsic::ppc_altivec_lvxl:
Chris Lattner36dd7c92006-04-17 22:26:56 +00006995 case Intrinsic::x86_sse_loadu_ps:
6996 case Intrinsic::x86_sse2_loadu_pd:
6997 case Intrinsic::x86_sse2_loadu_dq:
6998 // Turn PPC lvx -> load if the pointer is known aligned.
6999 // Turn X86 loadups -> load if the pointer is known aligned.
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00007000 if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00007001 Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(1),
Chris Lattnere79d2492006-04-06 19:19:17 +00007002 PointerType::get(II->getType()), CI);
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00007003 return new LoadInst(Ptr);
7004 }
7005 break;
7006 case Intrinsic::ppc_altivec_stvx:
7007 case Intrinsic::ppc_altivec_stvxl:
7008 // Turn stvx -> store if the pointer is known aligned.
7009 if (GetKnownAlignment(II->getOperand(2), TD) >= 16) {
Chris Lattnere79d2492006-04-06 19:19:17 +00007010 const Type *OpPtrTy = PointerType::get(II->getOperand(1)->getType());
Reid Spencer13bc5d72006-12-12 09:18:51 +00007011 Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(2),
7012 OpPtrTy, CI);
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00007013 return new StoreInst(II->getOperand(1), Ptr);
7014 }
7015 break;
Chris Lattner36dd7c92006-04-17 22:26:56 +00007016 case Intrinsic::x86_sse_storeu_ps:
7017 case Intrinsic::x86_sse2_storeu_pd:
7018 case Intrinsic::x86_sse2_storeu_dq:
7019 case Intrinsic::x86_sse2_storel_dq:
7020 // Turn X86 storeu -> store if the pointer is known aligned.
7021 if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
7022 const Type *OpPtrTy = PointerType::get(II->getOperand(2)->getType());
Reid Spencer13bc5d72006-12-12 09:18:51 +00007023 Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(1),
7024 OpPtrTy, CI);
Chris Lattner36dd7c92006-04-17 22:26:56 +00007025 return new StoreInst(II->getOperand(2), Ptr);
7026 }
7027 break;
Chris Lattner2deeaea2006-10-05 06:55:50 +00007028
7029 case Intrinsic::x86_sse_cvttss2si: {
7030 // These intrinsics only demands the 0th element of its input vector. If
7031 // we can simplify the input based on that, do so now.
7032 uint64_t UndefElts;
7033 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1,
7034 UndefElts)) {
7035 II->setOperand(1, V);
7036 return II;
7037 }
7038 break;
7039 }
7040
Chris Lattnere79d2492006-04-06 19:19:17 +00007041 case Intrinsic::ppc_altivec_vperm:
7042 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
7043 if (ConstantPacked *Mask = dyn_cast<ConstantPacked>(II->getOperand(3))) {
7044 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
7045
7046 // Check that all of the elements are integer constants or undefs.
7047 bool AllEltsOk = true;
7048 for (unsigned i = 0; i != 16; ++i) {
7049 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
7050 !isa<UndefValue>(Mask->getOperand(i))) {
7051 AllEltsOk = false;
7052 break;
7053 }
7054 }
7055
7056 if (AllEltsOk) {
7057 // Cast the input vectors to byte vectors.
Reid Spencer13bc5d72006-12-12 09:18:51 +00007058 Value *Op0 = InsertCastBefore(Instruction::BitCast,
7059 II->getOperand(1), Mask->getType(), CI);
7060 Value *Op1 = InsertCastBefore(Instruction::BitCast,
7061 II->getOperand(2), Mask->getType(), CI);
Chris Lattnere79d2492006-04-06 19:19:17 +00007062 Value *Result = UndefValue::get(Op0->getType());
7063
7064 // Only extract each element once.
7065 Value *ExtractedElts[32];
7066 memset(ExtractedElts, 0, sizeof(ExtractedElts));
7067
7068 for (unsigned i = 0; i != 16; ++i) {
7069 if (isa<UndefValue>(Mask->getOperand(i)))
7070 continue;
Reid Spencere0fc4df2006-10-20 07:07:24 +00007071 unsigned Idx =cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
Chris Lattnere79d2492006-04-06 19:19:17 +00007072 Idx &= 31; // Match the hardware behavior.
7073
7074 if (ExtractedElts[Idx] == 0) {
7075 Instruction *Elt =
Chris Lattner2deeaea2006-10-05 06:55:50 +00007076 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
Chris Lattnere79d2492006-04-06 19:19:17 +00007077 InsertNewInstBefore(Elt, CI);
7078 ExtractedElts[Idx] = Elt;
7079 }
7080
7081 // Insert this value into the result vector.
Chris Lattner2deeaea2006-10-05 06:55:50 +00007082 Result = new InsertElementInst(Result, ExtractedElts[Idx], i,"tmp");
Chris Lattnere79d2492006-04-06 19:19:17 +00007083 InsertNewInstBefore(cast<Instruction>(Result), CI);
7084 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007085 return CastInst::create(Instruction::BitCast, Result, CI.getType());
Chris Lattnere79d2492006-04-06 19:19:17 +00007086 }
7087 }
7088 break;
7089
Chris Lattner503221f2006-01-13 21:28:09 +00007090 case Intrinsic::stackrestore: {
7091 // If the save is right next to the restore, remove the restore. This can
7092 // happen when variable allocas are DCE'd.
7093 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
7094 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
7095 BasicBlock::iterator BI = SS;
7096 if (&*++BI == II)
7097 return EraseInstFromFunction(CI);
7098 }
7099 }
7100
7101 // If the stack restore is in a return/unwind block and if there are no
7102 // allocas or calls between the restore and the return, nuke the restore.
7103 TerminatorInst *TI = II->getParent()->getTerminator();
7104 if (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)) {
7105 BasicBlock::iterator BI = II;
7106 bool CannotRemove = false;
7107 for (++BI; &*BI != TI; ++BI) {
7108 if (isa<AllocaInst>(BI) ||
7109 (isa<CallInst>(BI) && !isa<IntrinsicInst>(BI))) {
7110 CannotRemove = true;
7111 break;
7112 }
7113 }
7114 if (!CannotRemove)
7115 return EraseInstFromFunction(CI);
7116 }
7117 break;
7118 }
7119 }
Chris Lattner00648e12004-10-12 04:52:52 +00007120 }
7121
Chris Lattnerc66b2232006-01-13 20:11:04 +00007122 return visitCallSite(II);
Chris Lattner970c33a2003-06-19 17:00:31 +00007123}
7124
7125// InvokeInst simplification
7126//
7127Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattneraec3d942003-10-07 22:32:43 +00007128 return visitCallSite(&II);
Chris Lattner970c33a2003-06-19 17:00:31 +00007129}
7130
Chris Lattneraec3d942003-10-07 22:32:43 +00007131// visitCallSite - Improvements for call and invoke instructions.
7132//
7133Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner75b4d1d2003-10-07 22:54:13 +00007134 bool Changed = false;
7135
7136 // If the callee is a constexpr cast of a function, attempt to move the cast
7137 // to the arguments of the call/invoke.
Chris Lattneraec3d942003-10-07 22:32:43 +00007138 if (transformConstExprCastCall(CS)) return 0;
7139
Chris Lattner75b4d1d2003-10-07 22:54:13 +00007140 Value *Callee = CS.getCalledValue();
Chris Lattner81a7a232004-10-16 18:11:37 +00007141
Chris Lattner61d9d812005-05-13 07:09:09 +00007142 if (Function *CalleeF = dyn_cast<Function>(Callee))
7143 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
7144 Instruction *OldCall = CS.getInstruction();
7145 // If the call and callee calling conventions don't match, this call must
7146 // be unreachable, as the call is undefined.
Chris Lattner6ab03f62006-09-28 23:35:22 +00007147 new StoreInst(ConstantBool::getTrue(),
Chris Lattner61d9d812005-05-13 07:09:09 +00007148 UndefValue::get(PointerType::get(Type::BoolTy)), OldCall);
7149 if (!OldCall->use_empty())
7150 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
7151 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
7152 return EraseInstFromFunction(*OldCall);
7153 return 0;
7154 }
7155
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007156 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
7157 // This instruction is not reachable, just remove it. We insert a store to
7158 // undef so that we know that this code is not reachable, despite the fact
7159 // that we can't modify the CFG here.
Chris Lattner6ab03f62006-09-28 23:35:22 +00007160 new StoreInst(ConstantBool::getTrue(),
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007161 UndefValue::get(PointerType::get(Type::BoolTy)),
7162 CS.getInstruction());
7163
7164 if (!CS.getInstruction()->use_empty())
7165 CS.getInstruction()->
7166 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
7167
7168 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
7169 // Don't break the CFG, insert a dummy cond branch.
7170 new BranchInst(II->getNormalDest(), II->getUnwindDest(),
Chris Lattner6ab03f62006-09-28 23:35:22 +00007171 ConstantBool::getTrue(), II);
Chris Lattner81a7a232004-10-16 18:11:37 +00007172 }
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007173 return EraseInstFromFunction(*CS.getInstruction());
7174 }
Chris Lattner81a7a232004-10-16 18:11:37 +00007175
Chris Lattner75b4d1d2003-10-07 22:54:13 +00007176 const PointerType *PTy = cast<PointerType>(Callee->getType());
7177 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
7178 if (FTy->isVarArg()) {
7179 // See if we can optimize any arguments passed through the varargs area of
7180 // the call.
7181 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
7182 E = CS.arg_end(); I != E; ++I)
7183 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
7184 // If this cast does not effect the value passed through the varargs
7185 // area, we can eliminate the use of the cast.
7186 Value *Op = CI->getOperand(0);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007187 if (CI->isLosslessCast()) {
Chris Lattner75b4d1d2003-10-07 22:54:13 +00007188 *I = Op;
7189 Changed = true;
7190 }
7191 }
7192 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00007193
Chris Lattner75b4d1d2003-10-07 22:54:13 +00007194 return Changed ? CS.getInstruction() : 0;
Chris Lattneraec3d942003-10-07 22:32:43 +00007195}
7196
Chris Lattner970c33a2003-06-19 17:00:31 +00007197// transformConstExprCastCall - If the callee is a constexpr cast of a function,
7198// attempt to move the cast to the arguments of the call/invoke.
7199//
7200bool InstCombiner::transformConstExprCastCall(CallSite CS) {
7201 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
7202 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007203 if (CE->getOpcode() != Instruction::BitCast ||
7204 !isa<Function>(CE->getOperand(0)))
Chris Lattner970c33a2003-06-19 17:00:31 +00007205 return false;
Reid Spencer87436872004-07-18 00:38:32 +00007206 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner970c33a2003-06-19 17:00:31 +00007207 Instruction *Caller = CS.getInstruction();
7208
7209 // Okay, this is a cast from a function to a different type. Unless doing so
7210 // would cause a type conversion of one of our arguments, change this call to
7211 // be a direct call with arguments casted to the appropriate types.
7212 //
7213 const FunctionType *FT = Callee->getFunctionType();
7214 const Type *OldRetTy = Caller->getType();
7215
Chris Lattner1f7942f2004-01-14 06:06:08 +00007216 // Check to see if we are changing the return type...
7217 if (OldRetTy != FT->getReturnType()) {
7218 if (Callee->isExternal() &&
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007219 !Caller->use_empty() &&
7220 !(OldRetTy->canLosslesslyBitCastTo(FT->getReturnType()) ||
Andrew Lenharth61eae292006-04-20 14:56:47 +00007221 (isa<PointerType>(FT->getReturnType()) &&
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007222 TD->getIntPtrType()->canLosslesslyBitCastTo(OldRetTy)))
7223 )
Chris Lattner1f7942f2004-01-14 06:06:08 +00007224 return false; // Cannot transform this return value...
7225
7226 // If the callsite is an invoke instruction, and the return value is used by
7227 // a PHI node in a successor, we cannot change the return type of the call
7228 // because there is no place to put the cast instruction (without breaking
7229 // the critical edge). Bail out in this case.
7230 if (!Caller->use_empty())
7231 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
7232 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
7233 UI != E; ++UI)
7234 if (PHINode *PN = dyn_cast<PHINode>(*UI))
7235 if (PN->getParent() == II->getNormalDest() ||
Chris Lattnerfae8ab32004-02-08 21:44:31 +00007236 PN->getParent() == II->getUnwindDest())
Chris Lattner1f7942f2004-01-14 06:06:08 +00007237 return false;
7238 }
Chris Lattner970c33a2003-06-19 17:00:31 +00007239
7240 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
7241 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanb1c93172005-04-21 23:48:37 +00007242
Chris Lattner970c33a2003-06-19 17:00:31 +00007243 CallSite::arg_iterator AI = CS.arg_begin();
7244 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
7245 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthebfa24e2006-06-28 01:01:52 +00007246 const Type *ActTy = (*AI)->getType();
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007247 ConstantInt *c = dyn_cast<ConstantInt>(*AI);
Andrew Lenharthebfa24e2006-06-28 01:01:52 +00007248 //Either we can cast directly, or we can upconvert the argument
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007249 bool isConvertible = ActTy->canLosslesslyBitCastTo(ParamTy) ||
Andrew Lenharthebfa24e2006-06-28 01:01:52 +00007250 (ParamTy->isIntegral() && ActTy->isIntegral() &&
Andrew Lenharthebfa24e2006-06-28 01:01:52 +00007251 ParamTy->getPrimitiveSize() >= ActTy->getPrimitiveSize()) ||
7252 (c && ParamTy->getPrimitiveSize() >= ActTy->getPrimitiveSize() &&
Reid Spencere0fc4df2006-10-20 07:07:24 +00007253 c->getSExtValue() > 0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00007254 if (Callee->isExternal() && !isConvertible) return false;
Chris Lattner970c33a2003-06-19 17:00:31 +00007255 }
7256
7257 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
7258 Callee->isExternal())
7259 return false; // Do not delete arguments unless we have a function body...
7260
7261 // Okay, we decided that this is a safe thing to do: go ahead and start
7262 // inserting cast instructions as necessary...
7263 std::vector<Value*> Args;
7264 Args.reserve(NumActualArgs);
7265
7266 AI = CS.arg_begin();
7267 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
7268 const Type *ParamTy = FT->getParamType(i);
7269 if ((*AI)->getType() == ParamTy) {
7270 Args.push_back(*AI);
7271 } else {
Reid Spencer668d90f2006-12-18 08:47:13 +00007272 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
Reid Spencerc635f472006-12-31 05:48:39 +00007273 false, ParamTy, false);
Reid Spencer668d90f2006-12-18 08:47:13 +00007274 CastInst *NewCast = CastInst::create(opcode, *AI, ParamTy, "tmp");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007275 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
Chris Lattner970c33a2003-06-19 17:00:31 +00007276 }
7277 }
7278
7279 // If the function takes more arguments than the call was taking, add them
7280 // now...
7281 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
7282 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
7283
7284 // If we are removing arguments to the function, emit an obnoxious warning...
7285 if (FT->getNumParams() < NumActualArgs)
7286 if (!FT->isVarArg()) {
Bill Wendlingf3baad32006-12-07 01:30:32 +00007287 cerr << "WARNING: While resolving call to function '"
7288 << Callee->getName() << "' arguments were dropped!\n";
Chris Lattner970c33a2003-06-19 17:00:31 +00007289 } else {
7290 // Add all of the arguments in their promoted form to the arg list...
7291 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
7292 const Type *PTy = getPromotedType((*AI)->getType());
7293 if (PTy != (*AI)->getType()) {
7294 // Must promote to pass through va_arg area!
Reid Spencerc635f472006-12-31 05:48:39 +00007295 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false,
7296 PTy, false);
Reid Spencer668d90f2006-12-18 08:47:13 +00007297 Instruction *Cast = CastInst::create(opcode, *AI, PTy, "tmp");
Chris Lattner970c33a2003-06-19 17:00:31 +00007298 InsertNewInstBefore(Cast, *Caller);
7299 Args.push_back(Cast);
7300 } else {
7301 Args.push_back(*AI);
7302 }
7303 }
7304 }
7305
7306 if (FT->getReturnType() == Type::VoidTy)
7307 Caller->setName(""); // Void type should not have a name...
7308
7309 Instruction *NC;
7310 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Chris Lattnerfae8ab32004-02-08 21:44:31 +00007311 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
Chris Lattner970c33a2003-06-19 17:00:31 +00007312 Args, Caller->getName(), Caller);
Chris Lattner05c703e2005-05-14 12:25:32 +00007313 cast<InvokeInst>(II)->setCallingConv(II->getCallingConv());
Chris Lattner970c33a2003-06-19 17:00:31 +00007314 } else {
7315 NC = new CallInst(Callee, Args, Caller->getName(), Caller);
Chris Lattner6aacb0f2005-05-06 06:48:21 +00007316 if (cast<CallInst>(Caller)->isTailCall())
7317 cast<CallInst>(NC)->setTailCall();
Chris Lattner05c703e2005-05-14 12:25:32 +00007318 cast<CallInst>(NC)->setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Chris Lattner970c33a2003-06-19 17:00:31 +00007319 }
7320
7321 // Insert a cast of the return type as necessary...
7322 Value *NV = NC;
7323 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
7324 if (NV->getType() != Type::VoidTy) {
Reid Spencer668d90f2006-12-18 08:47:13 +00007325 const Type *CallerTy = Caller->getType();
Reid Spencerc635f472006-12-31 05:48:39 +00007326 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
7327 CallerTy, false);
Reid Spencer668d90f2006-12-18 08:47:13 +00007328 NV = NC = CastInst::create(opcode, NC, CallerTy, "tmp");
Chris Lattner686767f2003-10-30 00:46:41 +00007329
7330 // If this is an invoke instruction, we should insert it after the first
7331 // non-phi, instruction in the normal successor block.
7332 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
7333 BasicBlock::iterator I = II->getNormalDest()->begin();
7334 while (isa<PHINode>(I)) ++I;
7335 InsertNewInstBefore(NC, *I);
7336 } else {
7337 // Otherwise, it's a call, just insert cast right after the call instr
7338 InsertNewInstBefore(NC, *Caller);
7339 }
Chris Lattner51ea1272004-02-28 05:22:00 +00007340 AddUsersToWorkList(*Caller);
Chris Lattner970c33a2003-06-19 17:00:31 +00007341 } else {
Chris Lattnere29d6342004-10-17 21:22:38 +00007342 NV = UndefValue::get(Caller->getType());
Chris Lattner970c33a2003-06-19 17:00:31 +00007343 }
7344 }
7345
7346 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
7347 Caller->replaceAllUsesWith(NV);
7348 Caller->getParent()->getInstList().erase(Caller);
7349 removeFromWorkList(Caller);
7350 return true;
7351}
7352
Chris Lattnercadac0c2006-11-01 04:51:18 +00007353/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
7354/// and if a/b/c/d and the add's all have a single use, turn this into two phi's
7355/// and a single binop.
7356Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
7357 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Chris Lattnereebea432006-11-01 07:43:41 +00007358 assert(isa<BinaryOperator>(FirstInst) || isa<ShiftInst>(FirstInst) ||
Reid Spencer266e42b2006-12-23 06:05:41 +00007359 isa<GetElementPtrInst>(FirstInst) || isa<CmpInst>(FirstInst));
Chris Lattnercadac0c2006-11-01 04:51:18 +00007360 unsigned Opc = FirstInst->getOpcode();
Chris Lattnercd62f112006-11-08 19:29:23 +00007361 Value *LHSVal = FirstInst->getOperand(0);
7362 Value *RHSVal = FirstInst->getOperand(1);
7363
7364 const Type *LHSType = LHSVal->getType();
7365 const Type *RHSType = RHSVal->getType();
Chris Lattnercadac0c2006-11-01 04:51:18 +00007366
7367 // Scan to see if all operands are the same opcode, all have one use, and all
7368 // kill their operands (i.e. the operands have one use).
Chris Lattnerdc826fc2006-11-01 04:55:47 +00007369 for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
Chris Lattnercadac0c2006-11-01 04:51:18 +00007370 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Chris Lattnerdc826fc2006-11-01 04:55:47 +00007371 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
Reid Spencer266e42b2006-12-23 06:05:41 +00007372 // Verify type of the LHS matches so we don't fold cmp's of different
Chris Lattnereebea432006-11-01 07:43:41 +00007373 // types or GEP's with different index types.
7374 I->getOperand(0)->getType() != LHSType ||
7375 I->getOperand(1)->getType() != RHSType)
Chris Lattnercadac0c2006-11-01 04:51:18 +00007376 return 0;
Reid Spencer266e42b2006-12-23 06:05:41 +00007377
7378 // If they are CmpInst instructions, check their predicates
7379 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
7380 if (cast<CmpInst>(I)->getPredicate() !=
7381 cast<CmpInst>(FirstInst)->getPredicate())
7382 return 0;
Chris Lattnercd62f112006-11-08 19:29:23 +00007383
7384 // Keep track of which operand needs a phi node.
7385 if (I->getOperand(0) != LHSVal) LHSVal = 0;
7386 if (I->getOperand(1) != RHSVal) RHSVal = 0;
Chris Lattnercadac0c2006-11-01 04:51:18 +00007387 }
7388
Chris Lattner4f218d52006-11-08 19:42:28 +00007389 // Otherwise, this is safe to transform, determine if it is profitable.
7390
7391 // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
7392 // Indexes are often folded into load/store instructions, so we don't want to
7393 // hide them behind a phi.
7394 if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
7395 return 0;
7396
Chris Lattnercadac0c2006-11-01 04:51:18 +00007397 Value *InLHS = FirstInst->getOperand(0);
Chris Lattnercadac0c2006-11-01 04:51:18 +00007398 Value *InRHS = FirstInst->getOperand(1);
Chris Lattner4f218d52006-11-08 19:42:28 +00007399 PHINode *NewLHS = 0, *NewRHS = 0;
Chris Lattnercd62f112006-11-08 19:29:23 +00007400 if (LHSVal == 0) {
7401 NewLHS = new PHINode(LHSType, FirstInst->getOperand(0)->getName()+".pn");
7402 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
7403 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
Chris Lattnereebea432006-11-01 07:43:41 +00007404 InsertNewInstBefore(NewLHS, PN);
7405 LHSVal = NewLHS;
7406 }
Chris Lattnercd62f112006-11-08 19:29:23 +00007407
7408 if (RHSVal == 0) {
7409 NewRHS = new PHINode(RHSType, FirstInst->getOperand(1)->getName()+".pn");
7410 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
7411 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
Chris Lattnereebea432006-11-01 07:43:41 +00007412 InsertNewInstBefore(NewRHS, PN);
7413 RHSVal = NewRHS;
7414 }
7415
Chris Lattnercd62f112006-11-08 19:29:23 +00007416 // Add all operands to the new PHIs.
7417 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7418 if (NewLHS) {
7419 Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
7420 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
7421 }
7422 if (NewRHS) {
7423 Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
7424 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
7425 }
7426 }
7427
Chris Lattnercadac0c2006-11-01 04:51:18 +00007428 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattnereebea432006-11-01 07:43:41 +00007429 return BinaryOperator::create(BinOp->getOpcode(), LHSVal, RHSVal);
Reid Spencer266e42b2006-12-23 06:05:41 +00007430 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
7431 return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal,
7432 RHSVal);
Chris Lattnereebea432006-11-01 07:43:41 +00007433 else if (ShiftInst *SI = dyn_cast<ShiftInst>(FirstInst))
7434 return new ShiftInst(SI->getOpcode(), LHSVal, RHSVal);
7435 else {
7436 assert(isa<GetElementPtrInst>(FirstInst));
7437 return new GetElementPtrInst(LHSVal, RHSVal);
7438 }
Chris Lattnercadac0c2006-11-01 04:51:18 +00007439}
7440
Chris Lattner14f82c72006-11-01 07:13:54 +00007441/// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
7442/// of the block that defines it. This means that it must be obvious the value
7443/// of the load is not changed from the point of the load to the end of the
7444/// block it is in.
7445static bool isSafeToSinkLoad(LoadInst *L) {
7446 BasicBlock::iterator BBI = L, E = L->getParent()->end();
7447
7448 for (++BBI; BBI != E; ++BBI)
7449 if (BBI->mayWriteToMemory())
7450 return false;
7451 return true;
7452}
7453
Chris Lattner970c33a2003-06-19 17:00:31 +00007454
Chris Lattner7515cab2004-11-14 19:13:23 +00007455// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
7456// operator and they all are only used by the PHI, PHI together their
7457// inputs, and do the operation once, to the result of the PHI.
7458Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
7459 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
7460
7461 // Scan the instruction, looking for input operations that can be folded away.
7462 // If all input operands to the phi are the same instruction (e.g. a cast from
7463 // the same type or "+42") we can pull the operation through the PHI, reducing
7464 // code size and simplifying code.
7465 Constant *ConstantOp = 0;
7466 const Type *CastSrcTy = 0;
Chris Lattner14f82c72006-11-01 07:13:54 +00007467 bool isVolatile = false;
Chris Lattner7515cab2004-11-14 19:13:23 +00007468 if (isa<CastInst>(FirstInst)) {
7469 CastSrcTy = FirstInst->getOperand(0)->getType();
Reid Spencer266e42b2006-12-23 06:05:41 +00007470 } else if (isa<BinaryOperator>(FirstInst) || isa<ShiftInst>(FirstInst) ||
7471 isa<CmpInst>(FirstInst)) {
7472 // Can fold binop, compare or shift here if the RHS is a constant,
7473 // otherwise call FoldPHIArgBinOpIntoPHI.
Chris Lattner7515cab2004-11-14 19:13:23 +00007474 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Chris Lattnercadac0c2006-11-01 04:51:18 +00007475 if (ConstantOp == 0)
7476 return FoldPHIArgBinOpIntoPHI(PN);
Chris Lattner14f82c72006-11-01 07:13:54 +00007477 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
7478 isVolatile = LI->isVolatile();
7479 // We can't sink the load if the loaded value could be modified between the
7480 // load and the PHI.
7481 if (LI->getParent() != PN.getIncomingBlock(0) ||
7482 !isSafeToSinkLoad(LI))
7483 return 0;
Chris Lattnereebea432006-11-01 07:43:41 +00007484 } else if (isa<GetElementPtrInst>(FirstInst)) {
Chris Lattner4f218d52006-11-08 19:42:28 +00007485 if (FirstInst->getNumOperands() == 2)
Chris Lattnereebea432006-11-01 07:43:41 +00007486 return FoldPHIArgBinOpIntoPHI(PN);
7487 // Can't handle general GEPs yet.
7488 return 0;
Chris Lattner7515cab2004-11-14 19:13:23 +00007489 } else {
7490 return 0; // Cannot fold this operation.
7491 }
7492
7493 // Check to see if all arguments are the same operation.
7494 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7495 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
7496 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
Reid Spencer266e42b2006-12-23 06:05:41 +00007497 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
Chris Lattner7515cab2004-11-14 19:13:23 +00007498 return 0;
7499 if (CastSrcTy) {
7500 if (I->getOperand(0)->getType() != CastSrcTy)
7501 return 0; // Cast operation must match.
Chris Lattner14f82c72006-11-01 07:13:54 +00007502 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00007503 // We can't sink the load if the loaded value could be modified between
7504 // the load and the PHI.
Chris Lattner14f82c72006-11-01 07:13:54 +00007505 if (LI->isVolatile() != isVolatile ||
7506 LI->getParent() != PN.getIncomingBlock(i) ||
7507 !isSafeToSinkLoad(LI))
7508 return 0;
Chris Lattner7515cab2004-11-14 19:13:23 +00007509 } else if (I->getOperand(1) != ConstantOp) {
7510 return 0;
7511 }
7512 }
7513
7514 // Okay, they are all the same operation. Create a new PHI node of the
7515 // correct type, and PHI together all of the LHS's of the instructions.
7516 PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
7517 PN.getName()+".in");
Chris Lattnerd8e20182005-01-29 00:39:08 +00007518 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattner46dd5a62004-11-14 19:29:34 +00007519
7520 Value *InVal = FirstInst->getOperand(0);
7521 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattner7515cab2004-11-14 19:13:23 +00007522
7523 // Add all operands to the new PHI.
Chris Lattner46dd5a62004-11-14 19:29:34 +00007524 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7525 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
7526 if (NewInVal != InVal)
7527 InVal = 0;
7528 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
7529 }
7530
7531 Value *PhiVal;
7532 if (InVal) {
7533 // The new PHI unions all of the same values together. This is really
7534 // common, so we handle it intelligently here for compile-time speed.
7535 PhiVal = InVal;
7536 delete NewPN;
7537 } else {
7538 InsertNewInstBefore(NewPN, PN);
7539 PhiVal = NewPN;
7540 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00007541
Chris Lattner7515cab2004-11-14 19:13:23 +00007542 // Insert and return the new operation.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007543 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
7544 return CastInst::create(FirstCI->getOpcode(), PhiVal, PN.getType());
Reid Spencerde46e482006-11-02 20:25:50 +00007545 else if (isa<LoadInst>(FirstInst))
Chris Lattner14f82c72006-11-01 07:13:54 +00007546 return new LoadInst(PhiVal, "", isVolatile);
Chris Lattner7515cab2004-11-14 19:13:23 +00007547 else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattner46dd5a62004-11-14 19:29:34 +00007548 return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
Reid Spencer266e42b2006-12-23 06:05:41 +00007549 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
7550 return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(),
7551 PhiVal, ConstantOp);
Chris Lattner7515cab2004-11-14 19:13:23 +00007552 else
7553 return new ShiftInst(cast<ShiftInst>(FirstInst)->getOpcode(),
Chris Lattner46dd5a62004-11-14 19:29:34 +00007554 PhiVal, ConstantOp);
Chris Lattner7515cab2004-11-14 19:13:23 +00007555}
Chris Lattner48a44f72002-05-02 17:06:02 +00007556
Chris Lattner71536432005-01-17 05:10:15 +00007557/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
7558/// that is dead.
7559static bool DeadPHICycle(PHINode *PN, std::set<PHINode*> &PotentiallyDeadPHIs) {
7560 if (PN->use_empty()) return true;
7561 if (!PN->hasOneUse()) return false;
7562
7563 // Remember this node, and if we find the cycle, return.
7564 if (!PotentiallyDeadPHIs.insert(PN).second)
7565 return true;
7566
7567 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
7568 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanb1c93172005-04-21 23:48:37 +00007569
Chris Lattner71536432005-01-17 05:10:15 +00007570 return false;
7571}
7572
Chris Lattnerbbbdd852002-05-06 18:06:38 +00007573// PHINode simplification
7574//
Chris Lattner113f4f42002-06-25 16:13:24 +00007575Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonbbf89902006-07-10 22:15:25 +00007576 // If LCSSA is around, don't mess with Phi nodes
7577 if (mustPreserveAnalysisID(LCSSAID)) return 0;
Owen Andersona6968f82006-07-10 19:03:49 +00007578
Owen Andersonae8aa642006-07-10 22:03:18 +00007579 if (Value *V = PN.hasConstantValue())
7580 return ReplaceInstUsesWith(PN, V);
7581
Owen Andersonae8aa642006-07-10 22:03:18 +00007582 // If all PHI operands are the same operation, pull them through the PHI,
7583 // reducing code size.
7584 if (isa<Instruction>(PN.getIncomingValue(0)) &&
7585 PN.getIncomingValue(0)->hasOneUse())
7586 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
7587 return Result;
7588
7589 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
7590 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
7591 // PHI)... break the cycle.
7592 if (PN.hasOneUse())
7593 if (PHINode *PU = dyn_cast<PHINode>(PN.use_back())) {
7594 std::set<PHINode*> PotentiallyDeadPHIs;
7595 PotentiallyDeadPHIs.insert(&PN);
7596 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
7597 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
7598 }
7599
Chris Lattner91daeb52003-12-19 05:58:40 +00007600 return 0;
Chris Lattnerbbbdd852002-05-06 18:06:38 +00007601}
7602
Reid Spencer13bc5d72006-12-12 09:18:51 +00007603static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
7604 Instruction *InsertPoint,
7605 InstCombiner *IC) {
Reid Spencer2a499b02006-12-13 17:19:09 +00007606 unsigned PtrSize = DTy->getPrimitiveSize();
Reid Spencer13bc5d72006-12-12 09:18:51 +00007607 unsigned VTySize = V->getType()->getPrimitiveSize();
7608 // We must cast correctly to the pointer type. Ensure that we
7609 // sign extend the integer value if it is smaller as this is
7610 // used for address computation.
7611 Instruction::CastOps opcode =
7612 (VTySize < PtrSize ? Instruction::SExt :
7613 (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
7614 return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
Chris Lattner69193f92004-04-05 01:30:19 +00007615}
7616
Chris Lattner48a44f72002-05-02 17:06:02 +00007617
Chris Lattner113f4f42002-06-25 16:13:24 +00007618Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner5f667a62004-05-07 22:09:22 +00007619 Value *PtrOp = GEP.getOperand(0);
Chris Lattner471bd762003-05-22 19:07:21 +00007620 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
Chris Lattner113f4f42002-06-25 16:13:24 +00007621 // If so, eliminate the noop.
Chris Lattner8d0bacb2004-02-22 05:25:17 +00007622 if (GEP.getNumOperands() == 1)
Chris Lattner5f667a62004-05-07 22:09:22 +00007623 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner8d0bacb2004-02-22 05:25:17 +00007624
Chris Lattner81a7a232004-10-16 18:11:37 +00007625 if (isa<UndefValue>(GEP.getOperand(0)))
7626 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
7627
Chris Lattner8d0bacb2004-02-22 05:25:17 +00007628 bool HasZeroPointerIndex = false;
7629 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
7630 HasZeroPointerIndex = C->isNullValue();
7631
7632 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner5f667a62004-05-07 22:09:22 +00007633 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner48a44f72002-05-02 17:06:02 +00007634
Chris Lattner69193f92004-04-05 01:30:19 +00007635 // Eliminate unneeded casts for indices.
7636 bool MadeChange = false;
Chris Lattner2b2412d2004-04-07 18:38:20 +00007637 gep_type_iterator GTI = gep_type_begin(GEP);
7638 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI)
7639 if (isa<SequentialType>(*GTI)) {
7640 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
7641 Value *Src = CI->getOperand(0);
7642 const Type *SrcTy = Src->getType();
7643 const Type *DestTy = CI->getType();
7644 if (Src->getType()->isInteger()) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00007645 if (SrcTy->getPrimitiveSizeInBits() ==
7646 DestTy->getPrimitiveSizeInBits()) {
Chris Lattner2b2412d2004-04-07 18:38:20 +00007647 // We can always eliminate a cast from ulong or long to the other.
7648 // We can always eliminate a cast from uint to int or the other on
7649 // 32-bit pointer platforms.
Chris Lattnerd1f46d32005-04-24 06:59:08 +00007650 if (DestTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()){
Chris Lattner2b2412d2004-04-07 18:38:20 +00007651 MadeChange = true;
7652 GEP.setOperand(i, Src);
7653 }
7654 } else if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
7655 SrcTy->getPrimitiveSize() == 4) {
Reid Spencer266e42b2006-12-23 06:05:41 +00007656 // We can eliminate a cast from [u]int to [u]long iff the target
7657 // is a 32-bit pointer target.
7658 if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
Chris Lattner2b2412d2004-04-07 18:38:20 +00007659 MadeChange = true;
7660 GEP.setOperand(i, Src);
7661 }
Chris Lattner69193f92004-04-05 01:30:19 +00007662 }
7663 }
7664 }
Chris Lattner2b2412d2004-04-07 18:38:20 +00007665 // If we are using a wider index than needed for this platform, shrink it
7666 // to what we need. If the incoming value needs a cast instruction,
7667 // insert it. This explicit cast can make subsequent optimizations more
7668 // obvious.
7669 Value *Op = GEP.getOperand(i);
7670 if (Op->getType()->getPrimitiveSize() > TD->getPointerSize())
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00007671 if (Constant *C = dyn_cast<Constant>(Op)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00007672 GEP.setOperand(i, ConstantExpr::getTrunc(C, TD->getIntPtrType()));
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00007673 MadeChange = true;
7674 } else {
Reid Spencer13bc5d72006-12-12 09:18:51 +00007675 Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
7676 GEP);
Chris Lattner2b2412d2004-04-07 18:38:20 +00007677 GEP.setOperand(i, Op);
7678 MadeChange = true;
7679 }
Chris Lattner69193f92004-04-05 01:30:19 +00007680 }
7681 if (MadeChange) return &GEP;
7682
Chris Lattnerae7a0d32002-08-02 19:29:35 +00007683 // Combine Indices - If the source pointer to this getelementptr instruction
7684 // is a getelementptr instruction, combine the indices of the two
7685 // getelementptr instructions into a single instruction.
7686 //
Chris Lattner57c67b02004-03-25 22:59:29 +00007687 std::vector<Value*> SrcGEPOperands;
Chris Lattner0798af32005-01-13 20:14:25 +00007688 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattner57c67b02004-03-25 22:59:29 +00007689 SrcGEPOperands.assign(Src->op_begin(), Src->op_end());
Chris Lattner57c67b02004-03-25 22:59:29 +00007690
7691 if (!SrcGEPOperands.empty()) {
Chris Lattner5f667a62004-05-07 22:09:22 +00007692 // Note that if our source is a gep chain itself that we wait for that
7693 // chain to be resolved before we perform this transformation. This
7694 // avoids us creating a TON of code in some cases.
7695 //
7696 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
7697 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
7698 return 0; // Wait until our source is folded to completion.
7699
Chris Lattnerae7a0d32002-08-02 19:29:35 +00007700 std::vector<Value *> Indices;
Chris Lattner5f667a62004-05-07 22:09:22 +00007701
7702 // Find out whether the last index in the source GEP is a sequential idx.
7703 bool EndsWithSequential = false;
7704 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
7705 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattner8ec5f882004-05-08 22:41:42 +00007706 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00007707
Chris Lattnerae7a0d32002-08-02 19:29:35 +00007708 // Can we combine the two pointer arithmetics offsets?
Chris Lattner5f667a62004-05-07 22:09:22 +00007709 if (EndsWithSequential) {
Chris Lattner235af562003-03-05 22:33:14 +00007710 // Replace: gep (gep %P, long B), long A, ...
7711 // With: T = long A+B; gep %P, T, ...
7712 //
Chris Lattner5f667a62004-05-07 22:09:22 +00007713 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner69193f92004-04-05 01:30:19 +00007714 if (SO1 == Constant::getNullValue(SO1->getType())) {
7715 Sum = GO1;
7716 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
7717 Sum = SO1;
7718 } else {
7719 // If they aren't the same type, convert both to an integer of the
7720 // target's pointer size.
7721 if (SO1->getType() != GO1->getType()) {
7722 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00007723 SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
Chris Lattner69193f92004-04-05 01:30:19 +00007724 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00007725 GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
Chris Lattner69193f92004-04-05 01:30:19 +00007726 } else {
7727 unsigned PS = TD->getPointerSize();
Chris Lattner69193f92004-04-05 01:30:19 +00007728 if (SO1->getType()->getPrimitiveSize() == PS) {
7729 // Convert GO1 to SO1's type.
Reid Spencer13bc5d72006-12-12 09:18:51 +00007730 GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
Chris Lattner69193f92004-04-05 01:30:19 +00007731
7732 } else if (GO1->getType()->getPrimitiveSize() == PS) {
7733 // Convert SO1 to GO1's type.
Reid Spencer13bc5d72006-12-12 09:18:51 +00007734 SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
Chris Lattner69193f92004-04-05 01:30:19 +00007735 } else {
7736 const Type *PT = TD->getIntPtrType();
Reid Spencer13bc5d72006-12-12 09:18:51 +00007737 SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
7738 GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
Chris Lattner69193f92004-04-05 01:30:19 +00007739 }
7740 }
7741 }
Chris Lattner5f667a62004-05-07 22:09:22 +00007742 if (isa<Constant>(SO1) && isa<Constant>(GO1))
7743 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
7744 else {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00007745 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
7746 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner5f667a62004-05-07 22:09:22 +00007747 }
Chris Lattner69193f92004-04-05 01:30:19 +00007748 }
Chris Lattner5f667a62004-05-07 22:09:22 +00007749
7750 // Recycle the GEP we already have if possible.
7751 if (SrcGEPOperands.size() == 2) {
7752 GEP.setOperand(0, SrcGEPOperands[0]);
7753 GEP.setOperand(1, Sum);
7754 return &GEP;
7755 } else {
7756 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
7757 SrcGEPOperands.end()-1);
7758 Indices.push_back(Sum);
7759 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
7760 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00007761 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner69193f92004-04-05 01:30:19 +00007762 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00007763 SrcGEPOperands.size() != 1) {
Chris Lattnerae7a0d32002-08-02 19:29:35 +00007764 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattner57c67b02004-03-25 22:59:29 +00007765 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
7766 SrcGEPOperands.end());
Chris Lattnerae7a0d32002-08-02 19:29:35 +00007767 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
7768 }
7769
7770 if (!Indices.empty())
Chris Lattner57c67b02004-03-25 22:59:29 +00007771 return new GetElementPtrInst(SrcGEPOperands[0], Indices, GEP.getName());
Chris Lattnerc59af1d2002-08-17 22:21:59 +00007772
Chris Lattner5f667a62004-05-07 22:09:22 +00007773 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattnerc59af1d2002-08-17 22:21:59 +00007774 // GEP of global variable. If all of the indices for this GEP are
7775 // constants, we can promote this to a constexpr instead of an instruction.
7776
7777 // Scan for nonconstants...
7778 std::vector<Constant*> Indices;
7779 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
7780 for (; I != E && isa<Constant>(*I); ++I)
7781 Indices.push_back(cast<Constant>(*I));
7782
7783 if (I == E) { // If they are all constants...
Chris Lattnerf3edc492004-07-18 18:59:44 +00007784 Constant *CE = ConstantExpr::getGetElementPtr(GV, Indices);
Chris Lattnerc59af1d2002-08-17 22:21:59 +00007785
7786 // Replace all uses of the GEP with the new constexpr...
7787 return ReplaceInstUsesWith(GEP, CE);
7788 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007789 } else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast?
Chris Lattner567b81f2005-09-13 00:40:14 +00007790 if (!isa<PointerType>(X->getType())) {
7791 // Not interesting. Source pointer must be a cast from pointer.
7792 } else if (HasZeroPointerIndex) {
7793 // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
7794 // into : GEP [10 x ubyte]* X, long 0, ...
7795 //
7796 // This occurs when the program declares an array extern like "int X[];"
7797 //
7798 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
7799 const PointerType *XTy = cast<PointerType>(X->getType());
7800 if (const ArrayType *XATy =
7801 dyn_cast<ArrayType>(XTy->getElementType()))
7802 if (const ArrayType *CATy =
7803 dyn_cast<ArrayType>(CPTy->getElementType()))
7804 if (CATy->getElementType() == XATy->getElementType()) {
7805 // At this point, we know that the cast source type is a pointer
7806 // to an array of the same type as the destination pointer
7807 // array. Because the array type is never stepped over (there
7808 // is a leading zero) we can fold the cast into this GEP.
7809 GEP.setOperand(0, X);
7810 return &GEP;
7811 }
7812 } else if (GEP.getNumOperands() == 2) {
7813 // Transform things like:
Chris Lattner2a893292005-09-13 18:36:04 +00007814 // %t = getelementptr ubyte* cast ([2 x int]* %str to uint*), uint %V
7815 // into: %t1 = getelementptr [2 x int*]* %str, int 0, uint %V; cast
Chris Lattner567b81f2005-09-13 00:40:14 +00007816 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
7817 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
7818 if (isa<ArrayType>(SrcElTy) &&
7819 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
7820 TD->getTypeSize(ResElTy)) {
7821 Value *V = InsertNewInstBefore(
Reid Spencerc635f472006-12-31 05:48:39 +00007822 new GetElementPtrInst(X, Constant::getNullValue(Type::Int32Ty),
Chris Lattner567b81f2005-09-13 00:40:14 +00007823 GEP.getOperand(1), GEP.getName()), GEP);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007824 // V and GEP are both pointer types --> BitCast
7825 return new BitCastInst(V, GEP.getType());
Chris Lattner8d0bacb2004-02-22 05:25:17 +00007826 }
Chris Lattner2a893292005-09-13 18:36:04 +00007827
7828 // Transform things like:
7829 // getelementptr sbyte* cast ([100 x double]* X to sbyte*), int %tmp
7830 // (where tmp = 8*tmp2) into:
7831 // getelementptr [100 x double]* %arr, int 0, int %tmp.2
7832
7833 if (isa<ArrayType>(SrcElTy) &&
Reid Spencerc635f472006-12-31 05:48:39 +00007834 (ResElTy == Type::Int8Ty || ResElTy == Type::Int8Ty)) {
Chris Lattner2a893292005-09-13 18:36:04 +00007835 uint64_t ArrayEltSize =
7836 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType());
7837
7838 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
7839 // allow either a mul, shift, or constant here.
7840 Value *NewIdx = 0;
7841 ConstantInt *Scale = 0;
7842 if (ArrayEltSize == 1) {
7843 NewIdx = GEP.getOperand(1);
7844 Scale = ConstantInt::get(NewIdx->getType(), 1);
7845 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Chris Lattnera393e4d2005-09-14 17:32:56 +00007846 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner2a893292005-09-13 18:36:04 +00007847 Scale = CI;
7848 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
7849 if (Inst->getOpcode() == Instruction::Shl &&
7850 isa<ConstantInt>(Inst->getOperand(1))) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00007851 unsigned ShAmt =
7852 cast<ConstantInt>(Inst->getOperand(1))->getZExtValue();
Reid Spencer266e42b2006-12-23 06:05:41 +00007853 Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmt);
Chris Lattner2a893292005-09-13 18:36:04 +00007854 NewIdx = Inst->getOperand(0);
7855 } else if (Inst->getOpcode() == Instruction::Mul &&
7856 isa<ConstantInt>(Inst->getOperand(1))) {
7857 Scale = cast<ConstantInt>(Inst->getOperand(1));
7858 NewIdx = Inst->getOperand(0);
7859 }
7860 }
7861
7862 // If the index will be to exactly the right offset with the scale taken
7863 // out, perform the transformation.
Reid Spencere0fc4df2006-10-20 07:07:24 +00007864 if (Scale && Scale->getZExtValue() % ArrayEltSize == 0) {
Reid Spencerde46e482006-11-02 20:25:50 +00007865 if (isa<ConstantInt>(Scale))
Reid Spencere0fc4df2006-10-20 07:07:24 +00007866 Scale = ConstantInt::get(Scale->getType(),
7867 Scale->getZExtValue() / ArrayEltSize);
7868 if (Scale->getZExtValue() != 1) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00007869 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
7870 true /*SExt*/);
Chris Lattner2a893292005-09-13 18:36:04 +00007871 Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
7872 NewIdx = InsertNewInstBefore(Sc, GEP);
7873 }
7874
7875 // Insert the new GEP instruction.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007876 Instruction *NewGEP =
Reid Spencerc635f472006-12-31 05:48:39 +00007877 new GetElementPtrInst(X, Constant::getNullValue(Type::Int32Ty),
Chris Lattner2a893292005-09-13 18:36:04 +00007878 NewIdx, GEP.getName());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007879 NewGEP = InsertNewInstBefore(NewGEP, GEP);
7880 // The NewGEP must be pointer typed, so must the old one -> BitCast
7881 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner2a893292005-09-13 18:36:04 +00007882 }
7883 }
Chris Lattner8d0bacb2004-02-22 05:25:17 +00007884 }
Chris Lattnerca081252001-12-14 16:52:21 +00007885 }
7886
Chris Lattnerca081252001-12-14 16:52:21 +00007887 return 0;
7888}
7889
Chris Lattner1085bdf2002-11-04 16:18:53 +00007890Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
7891 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
7892 if (AI.isArrayAllocation()) // Check C != 1
Reid Spencere0fc4df2006-10-20 07:07:24 +00007893 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
7894 const Type *NewTy =
7895 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Chris Lattnera2620ac2002-11-09 00:49:43 +00007896 AllocationInst *New = 0;
Chris Lattner1085bdf2002-11-04 16:18:53 +00007897
7898 // Create and insert the replacement instruction...
7899 if (isa<MallocInst>(AI))
Nate Begeman848622f2005-11-05 09:21:28 +00007900 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00007901 else {
7902 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Nate Begeman848622f2005-11-05 09:21:28 +00007903 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00007904 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00007905
7906 InsertNewInstBefore(New, AI);
Misha Brukmanb1c93172005-04-21 23:48:37 +00007907
Chris Lattner1085bdf2002-11-04 16:18:53 +00007908 // Scan to the end of the allocation instructions, to skip over a block of
7909 // allocas if possible...
7910 //
7911 BasicBlock::iterator It = New;
7912 while (isa<AllocationInst>(*It)) ++It;
7913
7914 // Now that I is pointing to the first non-allocation-inst in the block,
7915 // insert our getelementptr instruction...
7916 //
Reid Spencerc635f472006-12-31 05:48:39 +00007917 Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
Chris Lattner809dfac2005-05-04 19:10:26 +00007918 Value *V = new GetElementPtrInst(New, NullIdx, NullIdx,
7919 New->getName()+".sub", It);
Chris Lattner1085bdf2002-11-04 16:18:53 +00007920
7921 // Now make everything use the getelementptr instead of the original
7922 // allocation.
Chris Lattnerabb77c92004-03-19 06:08:10 +00007923 return ReplaceInstUsesWith(AI, V);
Chris Lattner81a7a232004-10-16 18:11:37 +00007924 } else if (isa<UndefValue>(AI.getArraySize())) {
7925 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner1085bdf2002-11-04 16:18:53 +00007926 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00007927
7928 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
7929 // Note that we only do this for alloca's, because malloc should allocate and
7930 // return a unique pointer, even for a zero byte allocation.
Misha Brukmanb1c93172005-04-21 23:48:37 +00007931 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
Chris Lattner49df6ce2004-07-02 22:55:47 +00007932 TD->getTypeSize(AI.getAllocatedType()) == 0)
Chris Lattnerabb77c92004-03-19 06:08:10 +00007933 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
7934
Chris Lattner1085bdf2002-11-04 16:18:53 +00007935 return 0;
7936}
7937
Chris Lattner8427bff2003-12-07 01:24:23 +00007938Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
7939 Value *Op = FI.getOperand(0);
7940
7941 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
7942 if (CastInst *CI = dyn_cast<CastInst>(Op))
7943 if (isa<PointerType>(CI->getOperand(0)->getType())) {
7944 FI.setOperand(0, CI->getOperand(0));
7945 return &FI;
7946 }
7947
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007948 // free undef -> unreachable.
7949 if (isa<UndefValue>(Op)) {
7950 // Insert a new store to null because we cannot modify the CFG here.
Chris Lattner6ab03f62006-09-28 23:35:22 +00007951 new StoreInst(ConstantBool::getTrue(),
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007952 UndefValue::get(PointerType::get(Type::BoolTy)), &FI);
7953 return EraseInstFromFunction(FI);
7954 }
7955
Chris Lattnerf3a36602004-02-28 04:57:37 +00007956 // If we have 'free null' delete the instruction. This can happen in stl code
7957 // when lots of inlining happens.
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007958 if (isa<ConstantPointerNull>(Op))
Chris Lattner51ea1272004-02-28 05:22:00 +00007959 return EraseInstFromFunction(FI);
Chris Lattnerf3a36602004-02-28 04:57:37 +00007960
Chris Lattner8427bff2003-12-07 01:24:23 +00007961 return 0;
7962}
7963
7964
Chris Lattner72684fe2005-01-31 05:51:45 +00007965/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Chris Lattner35e24772004-07-13 01:49:43 +00007966static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
7967 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00007968 Value *CastOp = CI->getOperand(0);
Chris Lattner35e24772004-07-13 01:49:43 +00007969
7970 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00007971 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Chris Lattner35e24772004-07-13 01:49:43 +00007972 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00007973
Chris Lattnerebca4762006-04-02 05:37:12 +00007974 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
7975 isa<PackedType>(DestPTy)) {
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00007976 // If the source is an array, the code below will not succeed. Check to
7977 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
7978 // constants.
7979 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
7980 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
7981 if (ASrcTy->getNumElements() != 0) {
Reid Spencerc635f472006-12-31 05:48:39 +00007982 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::Int32Ty));
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00007983 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
7984 SrcTy = cast<PointerType>(CastOp->getType());
7985 SrcPTy = SrcTy->getElementType();
7986 }
7987
Chris Lattnerebca4762006-04-02 05:37:12 +00007988 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
7989 isa<PackedType>(SrcPTy)) &&
Chris Lattnerecfa9b52005-03-29 06:37:47 +00007990 // Do not allow turning this into a load of an integer, which is then
7991 // casted to a pointer, this pessimizes pointer analysis a lot.
7992 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00007993 IC.getTargetData().getTypeSize(SrcPTy) ==
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00007994 IC.getTargetData().getTypeSize(DestPTy)) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00007995
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00007996 // Okay, we are casting from one integer or pointer type to another of
7997 // the same size. Instead of casting the pointer before the load, cast
7998 // the result of the loaded value.
7999 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
8000 CI->getName(),
8001 LI.isVolatile()),LI);
8002 // Now cast the result of the load.
Reid Spencerbb65ebf2006-12-12 23:36:14 +00008003 return new BitCastInst(NewLoad, LI.getType());
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00008004 }
Chris Lattner35e24772004-07-13 01:49:43 +00008005 }
8006 }
8007 return 0;
8008}
8009
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008010/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattnere6f13092004-09-19 19:18:10 +00008011/// from this value cannot trap. If it is not obviously safe to load from the
8012/// specified pointer, we do a quick local scan of the basic block containing
8013/// ScanFrom, to determine if the address is already accessed.
8014static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
8015 // If it is an alloca or global variable, it is always safe to load from.
8016 if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
8017
8018 // Otherwise, be a little bit agressive by scanning the local block where we
8019 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00008020 // from/to. If so, the previous load or store would have already trapped,
8021 // so there is no harm doing an extra load (also, CSE will later eliminate
8022 // the load entirely).
Chris Lattnere6f13092004-09-19 19:18:10 +00008023 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
8024
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00008025 while (BBI != E) {
Chris Lattnere6f13092004-09-19 19:18:10 +00008026 --BBI;
8027
8028 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
8029 if (LI->getOperand(0) == V) return true;
8030 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
8031 if (SI->getOperand(1) == V) return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +00008032
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00008033 }
Chris Lattnere6f13092004-09-19 19:18:10 +00008034 return false;
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008035}
8036
Chris Lattner0f1d8a32003-06-26 05:06:25 +00008037Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
8038 Value *Op = LI.getOperand(0);
Chris Lattner7e8af382004-01-12 04:13:56 +00008039
Chris Lattnera9d84e32005-05-01 04:24:53 +00008040 // load (cast X) --> cast (load X) iff safe
Reid Spencerde46e482006-11-02 20:25:50 +00008041 if (isa<CastInst>(Op))
Chris Lattnera9d84e32005-05-01 04:24:53 +00008042 if (Instruction *Res = InstCombineLoadCast(*this, LI))
8043 return Res;
8044
8045 // None of the following transforms are legal for volatile loads.
8046 if (LI.isVolatile()) return 0;
Chris Lattnerb990f7d2005-09-12 22:00:15 +00008047
Chris Lattnerb990f7d2005-09-12 22:00:15 +00008048 if (&LI.getParent()->front() != &LI) {
8049 BasicBlock::iterator BBI = &LI; --BBI;
Chris Lattnere0bfdf12005-09-12 22:21:03 +00008050 // If the instruction immediately before this is a store to the same
8051 // address, do a simple form of store->load forwarding.
Chris Lattnerb990f7d2005-09-12 22:00:15 +00008052 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
8053 if (SI->getOperand(1) == LI.getOperand(0))
8054 return ReplaceInstUsesWith(LI, SI->getOperand(0));
Chris Lattnere0bfdf12005-09-12 22:21:03 +00008055 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
8056 if (LIB->getOperand(0) == LI.getOperand(0))
8057 return ReplaceInstUsesWith(LI, LIB);
Chris Lattnerb990f7d2005-09-12 22:00:15 +00008058 }
Chris Lattnera9d84e32005-05-01 04:24:53 +00008059
8060 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op))
8061 if (isa<ConstantPointerNull>(GEPI->getOperand(0)) ||
8062 isa<UndefValue>(GEPI->getOperand(0))) {
8063 // Insert a new store to null instruction before the load to indicate
8064 // that this code is not reachable. We do this instead of inserting
8065 // an unreachable instruction directly because we cannot modify the
8066 // CFG.
8067 new StoreInst(UndefValue::get(LI.getType()),
8068 Constant::getNullValue(Op->getType()), &LI);
8069 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
8070 }
8071
Chris Lattner81a7a232004-10-16 18:11:37 +00008072 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattnera9d84e32005-05-01 04:24:53 +00008073 // load null/undef -> undef
8074 if ((C->isNullValue() || isa<UndefValue>(C))) {
Chris Lattner8ba9ec92004-10-18 02:59:09 +00008075 // Insert a new store to null instruction before the load to indicate that
8076 // this code is not reachable. We do this instead of inserting an
8077 // unreachable instruction directly because we cannot modify the CFG.
Chris Lattnera9d84e32005-05-01 04:24:53 +00008078 new StoreInst(UndefValue::get(LI.getType()),
8079 Constant::getNullValue(Op->getType()), &LI);
Chris Lattner81a7a232004-10-16 18:11:37 +00008080 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner8ba9ec92004-10-18 02:59:09 +00008081 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00008082
Chris Lattner81a7a232004-10-16 18:11:37 +00008083 // Instcombine load (constant global) into the value loaded.
8084 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
8085 if (GV->isConstant() && !GV->isExternal())
8086 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanb1c93172005-04-21 23:48:37 +00008087
Chris Lattner81a7a232004-10-16 18:11:37 +00008088 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
8089 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
8090 if (CE->getOpcode() == Instruction::GetElementPtr) {
8091 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
8092 if (GV->isConstant() && !GV->isExternal())
Chris Lattner0b011ec2005-09-26 05:28:06 +00008093 if (Constant *V =
8094 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
Chris Lattner81a7a232004-10-16 18:11:37 +00008095 return ReplaceInstUsesWith(LI, V);
Chris Lattnera9d84e32005-05-01 04:24:53 +00008096 if (CE->getOperand(0)->isNullValue()) {
8097 // Insert a new store to null instruction before the load to indicate
8098 // that this code is not reachable. We do this instead of inserting
8099 // an unreachable instruction directly because we cannot modify the
8100 // CFG.
8101 new StoreInst(UndefValue::get(LI.getType()),
8102 Constant::getNullValue(Op->getType()), &LI);
8103 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
8104 }
8105
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008106 } else if (CE->isCast()) {
Chris Lattner81a7a232004-10-16 18:11:37 +00008107 if (Instruction *Res = InstCombineLoadCast(*this, LI))
8108 return Res;
8109 }
8110 }
Chris Lattnere228ee52004-04-08 20:39:49 +00008111
Chris Lattnera9d84e32005-05-01 04:24:53 +00008112 if (Op->hasOneUse()) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008113 // Change select and PHI nodes to select values instead of addresses: this
8114 // helps alias analysis out a lot, allows many others simplifications, and
8115 // exposes redundancy in the code.
8116 //
8117 // Note that we cannot do the transformation unless we know that the
8118 // introduced loads cannot trap! Something like this is valid as long as
8119 // the condition is always false: load (select bool %C, int* null, int* %G),
8120 // but it would not be valid if we transformed it to load from null
8121 // unconditionally.
8122 //
8123 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
8124 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattnere6f13092004-09-19 19:18:10 +00008125 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
8126 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008127 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner42618552004-09-20 10:15:10 +00008128 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008129 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner42618552004-09-20 10:15:10 +00008130 SI->getOperand(2)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008131 return new SelectInst(SI->getCondition(), V1, V2);
8132 }
8133
Chris Lattnerbdcf41a2004-09-23 15:46:00 +00008134 // load (select (cond, null, P)) -> load P
8135 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
8136 if (C->isNullValue()) {
8137 LI.setOperand(0, SI->getOperand(2));
8138 return &LI;
8139 }
8140
8141 // load (select (cond, P, null)) -> load P
8142 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
8143 if (C->isNullValue()) {
8144 LI.setOperand(0, SI->getOperand(1));
8145 return &LI;
8146 }
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008147 }
8148 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00008149 return 0;
8150}
8151
Chris Lattner72684fe2005-01-31 05:51:45 +00008152/// InstCombineStoreToCast - Fold 'store V, (cast P)' -> store (cast V), P'
8153/// when possible.
8154static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
8155 User *CI = cast<User>(SI.getOperand(1));
8156 Value *CastOp = CI->getOperand(0);
8157
8158 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
8159 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
8160 const Type *SrcPTy = SrcTy->getElementType();
8161
8162 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
8163 // If the source is an array, the code below will not succeed. Check to
8164 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
8165 // constants.
8166 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
8167 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
8168 if (ASrcTy->getNumElements() != 0) {
Reid Spencerc635f472006-12-31 05:48:39 +00008169 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::Int32Ty));
Chris Lattner72684fe2005-01-31 05:51:45 +00008170 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
8171 SrcTy = cast<PointerType>(CastOp->getType());
8172 SrcPTy = SrcTy->getElementType();
8173 }
8174
8175 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00008176 IC.getTargetData().getTypeSize(SrcPTy) ==
Chris Lattner72684fe2005-01-31 05:51:45 +00008177 IC.getTargetData().getTypeSize(DestPTy)) {
8178
8179 // Okay, we are casting from one integer or pointer type to another of
8180 // the same size. Instead of casting the pointer before the store, cast
8181 // the value to be stored.
8182 Value *NewCast;
Reid Spencerbb65ebf2006-12-12 23:36:14 +00008183 Instruction::CastOps opcode = Instruction::BitCast;
8184 Value *SIOp0 = SI.getOperand(0);
Reid Spencer74a528b2006-12-13 18:21:21 +00008185 if (isa<PointerType>(SrcPTy)) {
Reid Spencerbb65ebf2006-12-12 23:36:14 +00008186 if (SIOp0->getType()->isIntegral())
8187 opcode = Instruction::IntToPtr;
8188 } else if (SrcPTy->isIntegral()) {
Reid Spencer74a528b2006-12-13 18:21:21 +00008189 if (isa<PointerType>(SIOp0->getType()))
Reid Spencerbb65ebf2006-12-12 23:36:14 +00008190 opcode = Instruction::PtrToInt;
8191 }
8192 if (Constant *C = dyn_cast<Constant>(SIOp0))
8193 NewCast = ConstantExpr::getCast(opcode, C, SrcPTy);
Chris Lattner72684fe2005-01-31 05:51:45 +00008194 else
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008195 NewCast = IC.InsertNewInstBefore(
Reid Spencerbb65ebf2006-12-12 23:36:14 +00008196 CastInst::create(opcode, SIOp0, SrcPTy, SIOp0->getName()+".c"), SI);
Chris Lattner72684fe2005-01-31 05:51:45 +00008197 return new StoreInst(NewCast, CastOp);
8198 }
8199 }
8200 }
8201 return 0;
8202}
8203
Chris Lattner31f486c2005-01-31 05:36:43 +00008204Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
8205 Value *Val = SI.getOperand(0);
8206 Value *Ptr = SI.getOperand(1);
8207
8208 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner5997cf92006-02-08 03:25:32 +00008209 EraseInstFromFunction(SI);
Chris Lattner31f486c2005-01-31 05:36:43 +00008210 ++NumCombined;
8211 return 0;
8212 }
8213
Chris Lattner5997cf92006-02-08 03:25:32 +00008214 // Do really simple DSE, to catch cases where there are several consequtive
8215 // stores to the same location, separated by a few arithmetic operations. This
8216 // situation often occurs with bitfield accesses.
8217 BasicBlock::iterator BBI = &SI;
8218 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
8219 --ScanInsts) {
8220 --BBI;
8221
8222 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
8223 // Prev store isn't volatile, and stores to the same location?
8224 if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
8225 ++NumDeadStore;
8226 ++BBI;
8227 EraseInstFromFunction(*PrevSI);
8228 continue;
8229 }
8230 break;
8231 }
8232
Chris Lattnerdab43b22006-05-26 19:19:20 +00008233 // If this is a load, we have to stop. However, if the loaded value is from
8234 // the pointer we're loading and is producing the pointer we're storing,
8235 // then *this* store is dead (X = load P; store X -> P).
8236 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
8237 if (LI == Val && LI->getOperand(0) == Ptr) {
8238 EraseInstFromFunction(SI);
8239 ++NumCombined;
8240 return 0;
8241 }
8242 // Otherwise, this is a load from some other location. Stores before it
8243 // may not be dead.
8244 break;
8245 }
8246
Chris Lattner5997cf92006-02-08 03:25:32 +00008247 // Don't skip over loads or things that can modify memory.
Chris Lattnerdab43b22006-05-26 19:19:20 +00008248 if (BBI->mayWriteToMemory())
Chris Lattner5997cf92006-02-08 03:25:32 +00008249 break;
8250 }
8251
8252
8253 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner31f486c2005-01-31 05:36:43 +00008254
8255 // store X, null -> turns into 'unreachable' in SimplifyCFG
8256 if (isa<ConstantPointerNull>(Ptr)) {
8257 if (!isa<UndefValue>(Val)) {
8258 SI.setOperand(0, UndefValue::get(Val->getType()));
8259 if (Instruction *U = dyn_cast<Instruction>(Val))
8260 WorkList.push_back(U); // Dropped a use.
8261 ++NumCombined;
8262 }
8263 return 0; // Do not modify these!
8264 }
8265
8266 // store undef, Ptr -> noop
8267 if (isa<UndefValue>(Val)) {
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 Lattner72684fe2005-01-31 05:51:45 +00008273 // If the pointer destination is a cast, see if we can fold the cast into the
8274 // source instead.
Reid Spencerde46e482006-11-02 20:25:50 +00008275 if (isa<CastInst>(Ptr))
Chris Lattner72684fe2005-01-31 05:51:45 +00008276 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
8277 return Res;
8278 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008279 if (CE->isCast())
Chris Lattner72684fe2005-01-31 05:51:45 +00008280 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
8281 return Res;
8282
Chris Lattner219175c2005-09-12 23:23:25 +00008283
8284 // If this store is the last instruction in the basic block, and if the block
8285 // ends with an unconditional branch, try to move it to the successor block.
Chris Lattner5997cf92006-02-08 03:25:32 +00008286 BBI = &SI; ++BBI;
Chris Lattner219175c2005-09-12 23:23:25 +00008287 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
8288 if (BI->isUnconditional()) {
8289 // Check to see if the successor block has exactly two incoming edges. If
8290 // so, see if the other predecessor contains a store to the same location.
8291 // if so, insert a PHI node (if needed) and move the stores down.
8292 BasicBlock *Dest = BI->getSuccessor(0);
8293
8294 pred_iterator PI = pred_begin(Dest);
8295 BasicBlock *Other = 0;
8296 if (*PI != BI->getParent())
8297 Other = *PI;
8298 ++PI;
8299 if (PI != pred_end(Dest)) {
8300 if (*PI != BI->getParent())
8301 if (Other)
8302 Other = 0;
8303 else
8304 Other = *PI;
8305 if (++PI != pred_end(Dest))
8306 Other = 0;
8307 }
8308 if (Other) { // If only one other pred...
8309 BBI = Other->getTerminator();
8310 // Make sure this other block ends in an unconditional branch and that
8311 // there is an instruction before the branch.
8312 if (isa<BranchInst>(BBI) && cast<BranchInst>(BBI)->isUnconditional() &&
8313 BBI != Other->begin()) {
8314 --BBI;
8315 StoreInst *OtherStore = dyn_cast<StoreInst>(BBI);
8316
8317 // If this instruction is a store to the same location.
8318 if (OtherStore && OtherStore->getOperand(1) == SI.getOperand(1)) {
8319 // Okay, we know we can perform this transformation. Insert a PHI
8320 // node now if we need it.
8321 Value *MergedVal = OtherStore->getOperand(0);
8322 if (MergedVal != SI.getOperand(0)) {
8323 PHINode *PN = new PHINode(MergedVal->getType(), "storemerge");
8324 PN->reserveOperandSpace(2);
8325 PN->addIncoming(SI.getOperand(0), SI.getParent());
8326 PN->addIncoming(OtherStore->getOperand(0), Other);
8327 MergedVal = InsertNewInstBefore(PN, Dest->front());
8328 }
8329
8330 // Advance to a place where it is safe to insert the new store and
8331 // insert it.
8332 BBI = Dest->begin();
8333 while (isa<PHINode>(BBI)) ++BBI;
8334 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
8335 OtherStore->isVolatile()), *BBI);
8336
8337 // Nuke the old stores.
Chris Lattner5997cf92006-02-08 03:25:32 +00008338 EraseInstFromFunction(SI);
8339 EraseInstFromFunction(*OtherStore);
Chris Lattner219175c2005-09-12 23:23:25 +00008340 ++NumCombined;
8341 return 0;
8342 }
8343 }
8344 }
8345 }
8346
Chris Lattner31f486c2005-01-31 05:36:43 +00008347 return 0;
8348}
8349
8350
Chris Lattner9eef8a72003-06-04 04:46:00 +00008351Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
8352 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4fdd96c2005-06-18 17:37:34 +00008353 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00008354 BasicBlock *TrueDest;
8355 BasicBlock *FalseDest;
8356 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
8357 !isa<Constant>(X)) {
8358 // Swap Destinations and condition...
8359 BI.setCondition(X);
8360 BI.setSuccessor(0, FalseDest);
8361 BI.setSuccessor(1, TrueDest);
8362 return &BI;
8363 }
8364
Reid Spencer266e42b2006-12-23 06:05:41 +00008365 // Cannonicalize fcmp_one -> fcmp_oeq
8366 FCmpInst::Predicate FPred; Value *Y;
8367 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
8368 TrueDest, FalseDest)))
8369 if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
8370 FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
8371 FCmpInst *I = cast<FCmpInst>(BI.getCondition());
Chris Lattnerd4252a72004-07-30 07:50:03 +00008372 std::string Name = I->getName(); I->setName("");
Reid Spencer266e42b2006-12-23 06:05:41 +00008373 FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
8374 Value *NewSCC = new FCmpInst(NewPred, X, Y, Name, I);
8375 // Swap Destinations and condition...
8376 BI.setCondition(NewSCC);
8377 BI.setSuccessor(0, FalseDest);
8378 BI.setSuccessor(1, TrueDest);
8379 removeFromWorkList(I);
8380 I->getParent()->getInstList().erase(I);
8381 WorkList.push_back(cast<Instruction>(NewSCC));
8382 return &BI;
8383 }
8384
8385 // Cannonicalize icmp_ne -> icmp_eq
8386 ICmpInst::Predicate IPred;
8387 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
8388 TrueDest, FalseDest)))
8389 if ((IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
8390 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
8391 IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
8392 ICmpInst *I = cast<ICmpInst>(BI.getCondition());
8393 std::string Name = I->getName(); I->setName("");
8394 ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
8395 Value *NewSCC = new ICmpInst(NewPred, X, Y, Name, I);
Chris Lattnere967b342003-06-04 05:10:11 +00008396 // Swap Destinations and condition...
Chris Lattnerd4252a72004-07-30 07:50:03 +00008397 BI.setCondition(NewSCC);
Chris Lattnere967b342003-06-04 05:10:11 +00008398 BI.setSuccessor(0, FalseDest);
8399 BI.setSuccessor(1, TrueDest);
Chris Lattnerd4252a72004-07-30 07:50:03 +00008400 removeFromWorkList(I);
8401 I->getParent()->getInstList().erase(I);
8402 WorkList.push_back(cast<Instruction>(NewSCC));
Chris Lattnere967b342003-06-04 05:10:11 +00008403 return &BI;
8404 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00008405
Chris Lattner9eef8a72003-06-04 04:46:00 +00008406 return 0;
8407}
Chris Lattner1085bdf2002-11-04 16:18:53 +00008408
Chris Lattner4c9c20a2004-07-03 00:26:11 +00008409Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
8410 Value *Cond = SI.getCondition();
8411 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
8412 if (I->getOpcode() == Instruction::Add)
8413 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
8414 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
8415 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattner81a7a232004-10-16 18:11:37 +00008416 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner4c9c20a2004-07-03 00:26:11 +00008417 AddRHS));
8418 SI.setOperand(0, I->getOperand(0));
8419 WorkList.push_back(I);
8420 return &SI;
8421 }
8422 }
8423 return 0;
8424}
8425
Chris Lattner6bc98652006-03-05 00:22:33 +00008426/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
8427/// is to leave as a vector operation.
8428static bool CheapToScalarize(Value *V, bool isConstant) {
8429 if (isa<ConstantAggregateZero>(V))
8430 return true;
8431 if (ConstantPacked *C = dyn_cast<ConstantPacked>(V)) {
8432 if (isConstant) return true;
8433 // If all elts are the same, we can extract.
8434 Constant *Op0 = C->getOperand(0);
8435 for (unsigned i = 1; i < C->getNumOperands(); ++i)
8436 if (C->getOperand(i) != Op0)
8437 return false;
8438 return true;
8439 }
8440 Instruction *I = dyn_cast<Instruction>(V);
8441 if (!I) return false;
8442
8443 // Insert element gets simplified to the inserted element or is deleted if
8444 // this is constant idx extract element and its a constant idx insertelt.
8445 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
8446 isa<ConstantInt>(I->getOperand(2)))
8447 return true;
8448 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
8449 return true;
8450 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
8451 if (BO->hasOneUse() &&
8452 (CheapToScalarize(BO->getOperand(0), isConstant) ||
8453 CheapToScalarize(BO->getOperand(1), isConstant)))
8454 return true;
Reid Spencer266e42b2006-12-23 06:05:41 +00008455 if (CmpInst *CI = dyn_cast<CmpInst>(I))
8456 if (CI->hasOneUse() &&
8457 (CheapToScalarize(CI->getOperand(0), isConstant) ||
8458 CheapToScalarize(CI->getOperand(1), isConstant)))
8459 return true;
Chris Lattner6bc98652006-03-05 00:22:33 +00008460
8461 return false;
8462}
8463
Chris Lattner12249be2006-05-25 23:48:38 +00008464/// getShuffleMask - Read and decode a shufflevector mask. It turns undef
8465/// elements into values that are larger than the #elts in the input.
8466static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
8467 unsigned NElts = SVI->getType()->getNumElements();
8468 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
8469 return std::vector<unsigned>(NElts, 0);
8470 if (isa<UndefValue>(SVI->getOperand(2)))
8471 return std::vector<unsigned>(NElts, 2*NElts);
8472
8473 std::vector<unsigned> Result;
8474 const ConstantPacked *CP = cast<ConstantPacked>(SVI->getOperand(2));
8475 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
8476 if (isa<UndefValue>(CP->getOperand(i)))
8477 Result.push_back(NElts*2); // undef -> 8
8478 else
Reid Spencere0fc4df2006-10-20 07:07:24 +00008479 Result.push_back(cast<ConstantInt>(CP->getOperand(i))->getZExtValue());
Chris Lattner12249be2006-05-25 23:48:38 +00008480 return Result;
8481}
8482
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008483/// FindScalarElement - Given a vector and an element number, see if the scalar
8484/// value is already around as a register, for example if it were inserted then
8485/// extracted from the vector.
8486static Value *FindScalarElement(Value *V, unsigned EltNo) {
8487 assert(isa<PackedType>(V->getType()) && "Not looking at a vector?");
8488 const PackedType *PTy = cast<PackedType>(V->getType());
Chris Lattner2d37f922006-04-10 23:06:36 +00008489 unsigned Width = PTy->getNumElements();
8490 if (EltNo >= Width) // Out of range access.
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008491 return UndefValue::get(PTy->getElementType());
8492
8493 if (isa<UndefValue>(V))
8494 return UndefValue::get(PTy->getElementType());
8495 else if (isa<ConstantAggregateZero>(V))
8496 return Constant::getNullValue(PTy->getElementType());
8497 else if (ConstantPacked *CP = dyn_cast<ConstantPacked>(V))
8498 return CP->getOperand(EltNo);
8499 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
8500 // If this is an insert to a variable element, we don't know what it is.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008501 if (!isa<ConstantInt>(III->getOperand(2)))
8502 return 0;
8503 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008504
8505 // If this is an insert to the element we are looking for, return the
8506 // inserted value.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008507 if (EltNo == IIElt)
8508 return III->getOperand(1);
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008509
8510 // Otherwise, the insertelement doesn't modify the value, recurse on its
8511 // vector input.
8512 return FindScalarElement(III->getOperand(0), EltNo);
Chris Lattner2d37f922006-04-10 23:06:36 +00008513 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Chris Lattner12249be2006-05-25 23:48:38 +00008514 unsigned InEl = getShuffleMask(SVI)[EltNo];
8515 if (InEl < Width)
8516 return FindScalarElement(SVI->getOperand(0), InEl);
8517 else if (InEl < Width*2)
8518 return FindScalarElement(SVI->getOperand(1), InEl - Width);
8519 else
8520 return UndefValue::get(PTy->getElementType());
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008521 }
8522
8523 // Otherwise, we don't know.
8524 return 0;
8525}
8526
Robert Bocchinoa8352962006-01-13 22:48:06 +00008527Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008528
Chris Lattner92346c32006-03-31 18:25:14 +00008529 // If packed val is undef, replace extract with scalar undef.
8530 if (isa<UndefValue>(EI.getOperand(0)))
8531 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
8532
8533 // If packed val is constant 0, replace extract with scalar 0.
8534 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
8535 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
8536
Robert Bocchinoa8352962006-01-13 22:48:06 +00008537 if (ConstantPacked *C = dyn_cast<ConstantPacked>(EI.getOperand(0))) {
8538 // If packed val is constant with uniform operands, replace EI
8539 // with that operand
Chris Lattner6bc98652006-03-05 00:22:33 +00008540 Constant *op0 = C->getOperand(0);
Robert Bocchinoa8352962006-01-13 22:48:06 +00008541 for (unsigned i = 1; i < C->getNumOperands(); ++i)
Chris Lattner6bc98652006-03-05 00:22:33 +00008542 if (C->getOperand(i) != op0) {
8543 op0 = 0;
8544 break;
8545 }
8546 if (op0)
8547 return ReplaceInstUsesWith(EI, op0);
Robert Bocchinoa8352962006-01-13 22:48:06 +00008548 }
Chris Lattner6bc98652006-03-05 00:22:33 +00008549
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008550 // If extracting a specified index from the vector, see if we can recursively
8551 // find a previously computed scalar that was inserted into the vector.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008552 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Chris Lattner2deeaea2006-10-05 06:55:50 +00008553 // This instruction only demands the single element from the input vector.
8554 // If the input vector has a single use, simplify it based on this use
8555 // property.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008556 uint64_t IndexVal = IdxC->getZExtValue();
Chris Lattner2deeaea2006-10-05 06:55:50 +00008557 if (EI.getOperand(0)->hasOneUse()) {
8558 uint64_t UndefElts;
8559 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Reid Spencere0fc4df2006-10-20 07:07:24 +00008560 1 << IndexVal,
Chris Lattner2deeaea2006-10-05 06:55:50 +00008561 UndefElts)) {
8562 EI.setOperand(0, V);
8563 return &EI;
8564 }
8565 }
8566
Reid Spencere0fc4df2006-10-20 07:07:24 +00008567 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008568 return ReplaceInstUsesWith(EI, Elt);
Chris Lattner2d37f922006-04-10 23:06:36 +00008569 }
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008570
Chris Lattner83f65782006-05-25 22:53:38 +00008571 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Robert Bocchinoa8352962006-01-13 22:48:06 +00008572 if (I->hasOneUse()) {
8573 // Push extractelement into predecessor operation if legal and
8574 // profitable to do so
8575 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Chris Lattner6bc98652006-03-05 00:22:33 +00008576 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
8577 if (CheapToScalarize(BO, isConstantElt)) {
8578 ExtractElementInst *newEI0 =
8579 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
8580 EI.getName()+".lhs");
8581 ExtractElementInst *newEI1 =
8582 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
8583 EI.getName()+".rhs");
8584 InsertNewInstBefore(newEI0, EI);
8585 InsertNewInstBefore(newEI1, EI);
8586 return BinaryOperator::create(BO->getOpcode(), newEI0, newEI1);
8587 }
Reid Spencerde46e482006-11-02 20:25:50 +00008588 } else if (isa<LoadInst>(I)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00008589 Value *Ptr = InsertCastBefore(Instruction::BitCast, I->getOperand(0),
Robert Bocchinoa8352962006-01-13 22:48:06 +00008590 PointerType::get(EI.getType()), EI);
8591 GetElementPtrInst *GEP =
Reid Spencera736fdf2006-11-29 01:11:01 +00008592 new GetElementPtrInst(Ptr, EI.getOperand(1), I->getName() + ".gep");
Robert Bocchinoa8352962006-01-13 22:48:06 +00008593 InsertNewInstBefore(GEP, EI);
8594 return new LoadInst(GEP);
Chris Lattner83f65782006-05-25 22:53:38 +00008595 }
8596 }
8597 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
8598 // Extracting the inserted element?
8599 if (IE->getOperand(2) == EI.getOperand(1))
8600 return ReplaceInstUsesWith(EI, IE->getOperand(1));
8601 // If the inserted and extracted elements are constants, they must not
8602 // be the same value, extract from the pre-inserted value instead.
8603 if (isa<Constant>(IE->getOperand(2)) &&
8604 isa<Constant>(EI.getOperand(1))) {
8605 AddUsesToWorkList(EI);
8606 EI.setOperand(0, IE->getOperand(0));
8607 return &EI;
8608 }
8609 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
8610 // If this is extracting an element from a shufflevector, figure out where
8611 // it came from and extract from the appropriate input element instead.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008612 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
8613 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
Chris Lattner12249be2006-05-25 23:48:38 +00008614 Value *Src;
8615 if (SrcIdx < SVI->getType()->getNumElements())
8616 Src = SVI->getOperand(0);
8617 else if (SrcIdx < SVI->getType()->getNumElements()*2) {
8618 SrcIdx -= SVI->getType()->getNumElements();
8619 Src = SVI->getOperand(1);
8620 } else {
8621 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattner612fa8e2006-03-30 22:02:40 +00008622 }
Chris Lattner2deeaea2006-10-05 06:55:50 +00008623 return new ExtractElementInst(Src, SrcIdx);
Robert Bocchinoa8352962006-01-13 22:48:06 +00008624 }
8625 }
Chris Lattner83f65782006-05-25 22:53:38 +00008626 }
Robert Bocchinoa8352962006-01-13 22:48:06 +00008627 return 0;
8628}
8629
Chris Lattner90951862006-04-16 00:51:47 +00008630/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
8631/// elements from either LHS or RHS, return the shuffle mask and true.
8632/// Otherwise, return false.
8633static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
8634 std::vector<Constant*> &Mask) {
8635 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
8636 "Invalid CollectSingleShuffleElements");
8637 unsigned NumElts = cast<PackedType>(V->getType())->getNumElements();
8638
8639 if (isa<UndefValue>(V)) {
Reid Spencerc635f472006-12-31 05:48:39 +00008640 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattner90951862006-04-16 00:51:47 +00008641 return true;
8642 } else if (V == LHS) {
8643 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc635f472006-12-31 05:48:39 +00008644 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattner90951862006-04-16 00:51:47 +00008645 return true;
8646 } else if (V == RHS) {
8647 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc635f472006-12-31 05:48:39 +00008648 Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
Chris Lattner90951862006-04-16 00:51:47 +00008649 return true;
8650 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
8651 // If this is an insert of an extract from some other vector, include it.
8652 Value *VecOp = IEI->getOperand(0);
8653 Value *ScalarOp = IEI->getOperand(1);
8654 Value *IdxOp = IEI->getOperand(2);
8655
Chris Lattnerb6cb64b2006-04-27 21:14:21 +00008656 if (!isa<ConstantInt>(IdxOp))
8657 return false;
Reid Spencere0fc4df2006-10-20 07:07:24 +00008658 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerb6cb64b2006-04-27 21:14:21 +00008659
8660 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
8661 // Okay, we can handle this if the vector we are insertinting into is
8662 // transitively ok.
8663 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
8664 // If so, update the mask to reflect the inserted undef.
Reid Spencerc635f472006-12-31 05:48:39 +00008665 Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
Chris Lattnerb6cb64b2006-04-27 21:14:21 +00008666 return true;
8667 }
8668 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
8669 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner90951862006-04-16 00:51:47 +00008670 EI->getOperand(0)->getType() == V->getType()) {
8671 unsigned ExtractedIdx =
Reid Spencere0fc4df2006-10-20 07:07:24 +00008672 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattner90951862006-04-16 00:51:47 +00008673
8674 // This must be extracting from either LHS or RHS.
8675 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
8676 // Okay, we can handle this if the vector we are insertinting into is
8677 // transitively ok.
8678 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
8679 // If so, update the mask to reflect the inserted value.
8680 if (EI->getOperand(0) == LHS) {
8681 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc635f472006-12-31 05:48:39 +00008682 ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattner90951862006-04-16 00:51:47 +00008683 } else {
8684 assert(EI->getOperand(0) == RHS);
8685 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc635f472006-12-31 05:48:39 +00008686 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
Chris Lattner90951862006-04-16 00:51:47 +00008687
8688 }
8689 return true;
8690 }
8691 }
8692 }
8693 }
8694 }
8695 // TODO: Handle shufflevector here!
8696
8697 return false;
8698}
8699
8700/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
8701/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
8702/// that computes V and the LHS value of the shuffle.
Chris Lattner39fac442006-04-15 01:39:45 +00008703static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Chris Lattner90951862006-04-16 00:51:47 +00008704 Value *&RHS) {
8705 assert(isa<PackedType>(V->getType()) &&
8706 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattner39fac442006-04-15 01:39:45 +00008707 "Invalid shuffle!");
8708 unsigned NumElts = cast<PackedType>(V->getType())->getNumElements();
8709
8710 if (isa<UndefValue>(V)) {
Reid Spencerc635f472006-12-31 05:48:39 +00008711 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattner39fac442006-04-15 01:39:45 +00008712 return V;
8713 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencerc635f472006-12-31 05:48:39 +00008714 Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
Chris Lattner39fac442006-04-15 01:39:45 +00008715 return V;
8716 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
8717 // If this is an insert of an extract from some other vector, include it.
8718 Value *VecOp = IEI->getOperand(0);
8719 Value *ScalarOp = IEI->getOperand(1);
8720 Value *IdxOp = IEI->getOperand(2);
8721
8722 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
8723 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
8724 EI->getOperand(0)->getType() == V->getType()) {
8725 unsigned ExtractedIdx =
Reid Spencere0fc4df2006-10-20 07:07:24 +00008726 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
8727 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattner39fac442006-04-15 01:39:45 +00008728
8729 // Either the extracted from or inserted into vector must be RHSVec,
8730 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner90951862006-04-16 00:51:47 +00008731 if (EI->getOperand(0) == RHS || RHS == 0) {
8732 RHS = EI->getOperand(0);
8733 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
Chris Lattner39fac442006-04-15 01:39:45 +00008734 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc635f472006-12-31 05:48:39 +00008735 ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
Chris Lattner39fac442006-04-15 01:39:45 +00008736 return V;
8737 }
8738
Chris Lattner90951862006-04-16 00:51:47 +00008739 if (VecOp == RHS) {
8740 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
Chris Lattner39fac442006-04-15 01:39:45 +00008741 // Everything but the extracted element is replaced with the RHS.
8742 for (unsigned i = 0; i != NumElts; ++i) {
8743 if (i != InsertedIdx)
Reid Spencerc635f472006-12-31 05:48:39 +00008744 Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
Chris Lattner39fac442006-04-15 01:39:45 +00008745 }
8746 return V;
8747 }
Chris Lattner90951862006-04-16 00:51:47 +00008748
8749 // If this insertelement is a chain that comes from exactly these two
8750 // vectors, return the vector and the effective shuffle.
8751 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
8752 return EI->getOperand(0);
8753
Chris Lattner39fac442006-04-15 01:39:45 +00008754 }
8755 }
8756 }
Chris Lattner90951862006-04-16 00:51:47 +00008757 // TODO: Handle shufflevector here!
Chris Lattner39fac442006-04-15 01:39:45 +00008758
8759 // Otherwise, can't do anything fancy. Return an identity vector.
8760 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc635f472006-12-31 05:48:39 +00008761 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattner39fac442006-04-15 01:39:45 +00008762 return V;
8763}
8764
8765Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
8766 Value *VecOp = IE.getOperand(0);
8767 Value *ScalarOp = IE.getOperand(1);
8768 Value *IdxOp = IE.getOperand(2);
8769
8770 // If the inserted element was extracted from some other vector, and if the
8771 // indexes are constant, try to turn this into a shufflevector operation.
8772 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
8773 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
8774 EI->getOperand(0)->getType() == IE.getType()) {
8775 unsigned NumVectorElts = IE.getType()->getNumElements();
Reid Spencere0fc4df2006-10-20 07:07:24 +00008776 unsigned ExtractedIdx=cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
8777 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattner39fac442006-04-15 01:39:45 +00008778
8779 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
8780 return ReplaceInstUsesWith(IE, VecOp);
8781
8782 if (InsertedIdx >= NumVectorElts) // Out of range insert.
8783 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
8784
8785 // If we are extracting a value from a vector, then inserting it right
8786 // back into the same place, just use the input vector.
8787 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
8788 return ReplaceInstUsesWith(IE, VecOp);
8789
8790 // We could theoretically do this for ANY input. However, doing so could
8791 // turn chains of insertelement instructions into a chain of shufflevector
8792 // instructions, and right now we do not merge shufflevectors. As such,
8793 // only do this in a situation where it is clear that there is benefit.
8794 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
8795 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
8796 // the values of VecOp, except then one read from EIOp0.
8797 // Build a new shuffle mask.
8798 std::vector<Constant*> Mask;
8799 if (isa<UndefValue>(VecOp))
Reid Spencerc635f472006-12-31 05:48:39 +00008800 Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
Chris Lattner39fac442006-04-15 01:39:45 +00008801 else {
8802 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
Reid Spencerc635f472006-12-31 05:48:39 +00008803 Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
Chris Lattner39fac442006-04-15 01:39:45 +00008804 NumVectorElts));
8805 }
Reid Spencerc635f472006-12-31 05:48:39 +00008806 Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattner39fac442006-04-15 01:39:45 +00008807 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
8808 ConstantPacked::get(Mask));
8809 }
8810
8811 // If this insertelement isn't used by some other insertelement, turn it
8812 // (and any insertelements it points to), into one big shuffle.
8813 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
8814 std::vector<Constant*> Mask;
Chris Lattner90951862006-04-16 00:51:47 +00008815 Value *RHS = 0;
8816 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
8817 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
8818 // We now have a shuffle of LHS, RHS, Mask.
8819 return new ShuffleVectorInst(LHS, RHS, ConstantPacked::get(Mask));
Chris Lattner39fac442006-04-15 01:39:45 +00008820 }
8821 }
8822 }
8823
8824 return 0;
8825}
8826
8827
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008828Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
8829 Value *LHS = SVI.getOperand(0);
8830 Value *RHS = SVI.getOperand(1);
Chris Lattner12249be2006-05-25 23:48:38 +00008831 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008832
8833 bool MadeChange = false;
8834
Chris Lattner2deeaea2006-10-05 06:55:50 +00008835 // Undefined shuffle mask -> undefined value.
Chris Lattner12249be2006-05-25 23:48:38 +00008836 if (isa<UndefValue>(SVI.getOperand(2)))
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008837 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
8838
Chris Lattner39fac442006-04-15 01:39:45 +00008839 // TODO: If we have shuffle(x, undef, mask) and any elements of mask refer to
8840 // the undef, change them to undefs.
8841
Chris Lattner12249be2006-05-25 23:48:38 +00008842 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
8843 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
8844 if (LHS == RHS || isa<UndefValue>(LHS)) {
8845 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008846 // shuffle(undef,undef,mask) -> undef.
8847 return ReplaceInstUsesWith(SVI, LHS);
8848 }
8849
Chris Lattner12249be2006-05-25 23:48:38 +00008850 // Remap any references to RHS to use LHS.
8851 std::vector<Constant*> Elts;
8852 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner0e477162006-05-26 00:29:06 +00008853 if (Mask[i] >= 2*e)
Reid Spencerc635f472006-12-31 05:48:39 +00008854 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner0e477162006-05-26 00:29:06 +00008855 else {
8856 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
8857 (Mask[i] < e && isa<UndefValue>(LHS)))
8858 Mask[i] = 2*e; // Turn into undef.
8859 else
8860 Mask[i] &= (e-1); // Force to LHS.
Reid Spencerc635f472006-12-31 05:48:39 +00008861 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
Chris Lattner0e477162006-05-26 00:29:06 +00008862 }
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008863 }
Chris Lattner12249be2006-05-25 23:48:38 +00008864 SVI.setOperand(0, SVI.getOperand(1));
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008865 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Chris Lattner12249be2006-05-25 23:48:38 +00008866 SVI.setOperand(2, ConstantPacked::get(Elts));
Chris Lattner0e477162006-05-26 00:29:06 +00008867 LHS = SVI.getOperand(0);
8868 RHS = SVI.getOperand(1);
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008869 MadeChange = true;
8870 }
8871
Chris Lattner0e477162006-05-26 00:29:06 +00008872 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner12249be2006-05-25 23:48:38 +00008873 bool isLHSID = true, isRHSID = true;
Chris Lattner34cebe72006-04-16 00:03:56 +00008874
Chris Lattner12249be2006-05-25 23:48:38 +00008875 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
8876 if (Mask[i] >= e*2) continue; // Ignore undef values.
8877 // Is this an identity shuffle of the LHS value?
8878 isLHSID &= (Mask[i] == i);
8879
8880 // Is this an identity shuffle of the RHS value?
8881 isRHSID &= (Mask[i]-e == i);
Chris Lattner34cebe72006-04-16 00:03:56 +00008882 }
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008883
Chris Lattner12249be2006-05-25 23:48:38 +00008884 // Eliminate identity shuffles.
8885 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
8886 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008887
Chris Lattner0e477162006-05-26 00:29:06 +00008888 // If the LHS is a shufflevector itself, see if we can combine it with this
8889 // one without producing an unusual shuffle. Here we are really conservative:
8890 // we are absolutely afraid of producing a shuffle mask not in the input
8891 // program, because the code gen may not be smart enough to turn a merged
8892 // shuffle into two specific shuffles: it may produce worse code. As such,
8893 // we only merge two shuffles if the result is one of the two input shuffle
8894 // masks. In this case, merging the shuffles just removes one instruction,
8895 // which we know is safe. This is good for things like turning:
8896 // (splat(splat)) -> splat.
8897 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
8898 if (isa<UndefValue>(RHS)) {
8899 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
8900
8901 std::vector<unsigned> NewMask;
8902 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
8903 if (Mask[i] >= 2*e)
8904 NewMask.push_back(2*e);
8905 else
8906 NewMask.push_back(LHSMask[Mask[i]]);
8907
8908 // If the result mask is equal to the src shuffle or this shuffle mask, do
8909 // the replacement.
8910 if (NewMask == LHSMask || NewMask == Mask) {
8911 std::vector<Constant*> Elts;
8912 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
8913 if (NewMask[i] >= e*2) {
Reid Spencerc635f472006-12-31 05:48:39 +00008914 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner0e477162006-05-26 00:29:06 +00008915 } else {
Reid Spencerc635f472006-12-31 05:48:39 +00008916 Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
Chris Lattner0e477162006-05-26 00:29:06 +00008917 }
8918 }
8919 return new ShuffleVectorInst(LHSSVI->getOperand(0),
8920 LHSSVI->getOperand(1),
8921 ConstantPacked::get(Elts));
8922 }
8923 }
8924 }
8925
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008926 return MadeChange ? &SVI : 0;
8927}
8928
8929
Robert Bocchinoa8352962006-01-13 22:48:06 +00008930
Chris Lattner99f48c62002-09-02 04:59:56 +00008931void InstCombiner::removeFromWorkList(Instruction *I) {
8932 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
8933 WorkList.end());
8934}
8935
Chris Lattner39c98bb2004-12-08 23:43:58 +00008936
8937/// TryToSinkInstruction - Try to move the specified instruction from its
8938/// current block into the beginning of DestBlock, which can only happen if it's
8939/// safe to move the instruction past all of the instructions between it and the
8940/// end of its block.
8941static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
8942 assert(I->hasOneUse() && "Invariants didn't hold!");
8943
Chris Lattnerc4f67e62005-10-27 17:13:11 +00008944 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
8945 if (isa<PHINode>(I) || I->mayWriteToMemory()) return false;
Misha Brukmanb1c93172005-04-21 23:48:37 +00008946
Chris Lattner39c98bb2004-12-08 23:43:58 +00008947 // Do not sink alloca instructions out of the entry block.
8948 if (isa<AllocaInst>(I) && I->getParent() == &DestBlock->getParent()->front())
8949 return false;
8950
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00008951 // We can only sink load instructions if there is nothing between the load and
8952 // the end of block that could change the value.
8953 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00008954 for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
8955 Scan != E; ++Scan)
8956 if (Scan->mayWriteToMemory())
8957 return false;
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00008958 }
Chris Lattner39c98bb2004-12-08 23:43:58 +00008959
8960 BasicBlock::iterator InsertPos = DestBlock->begin();
8961 while (isa<PHINode>(InsertPos)) ++InsertPos;
8962
Chris Lattner9f269e42005-08-08 19:11:57 +00008963 I->moveBefore(InsertPos);
Chris Lattner39c98bb2004-12-08 23:43:58 +00008964 ++NumSunkInst;
8965 return true;
8966}
8967
Chris Lattner1443bc52006-05-11 17:11:52 +00008968/// OptimizeConstantExpr - Given a constant expression and target data layout
Reid Spencer13bc5d72006-12-12 09:18:51 +00008969/// information, symbolically evaluate the constant expr to something simpler
Chris Lattner1443bc52006-05-11 17:11:52 +00008970/// if possible.
8971static Constant *OptimizeConstantExpr(ConstantExpr *CE, const TargetData *TD) {
8972 if (!TD) return CE;
8973
8974 Constant *Ptr = CE->getOperand(0);
8975 if (CE->getOpcode() == Instruction::GetElementPtr && Ptr->isNullValue() &&
8976 cast<PointerType>(Ptr->getType())->getElementType()->isSized()) {
8977 // If this is a constant expr gep that is effectively computing an
8978 // "offsetof", fold it into 'cast int Size to T*' instead of 'gep 0, 0, 12'
8979 bool isFoldableGEP = true;
8980 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
8981 if (!isa<ConstantInt>(CE->getOperand(i)))
8982 isFoldableGEP = false;
8983 if (isFoldableGEP) {
8984 std::vector<Value*> Ops(CE->op_begin()+1, CE->op_end());
8985 uint64_t Offset = TD->getIndexedOffset(Ptr->getType(), Ops);
Reid Spencer2a499b02006-12-13 17:19:09 +00008986 Constant *C = ConstantInt::get(TD->getIntPtrType(), Offset);
Reid Spencer13bc5d72006-12-12 09:18:51 +00008987 return ConstantExpr::getIntToPtr(C, CE->getType());
Chris Lattner1443bc52006-05-11 17:11:52 +00008988 }
8989 }
8990
8991 return CE;
8992}
8993
Chris Lattnera36ee4e2006-05-10 19:00:36 +00008994
8995/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
8996/// all reachable code to the worklist.
8997///
8998/// This has a couple of tricks to make the code faster and more powerful. In
8999/// particular, we constant fold and DCE instructions as we go, to avoid adding
9000/// them to the worklist (this significantly speeds up instcombine on code where
9001/// many instructions are dead or constant). Additionally, if we find a branch
9002/// whose condition is a known constant, we only visit the reachable successors.
9003///
9004static void AddReachableCodeToWorklist(BasicBlock *BB,
9005 std::set<BasicBlock*> &Visited,
Chris Lattner1443bc52006-05-11 17:11:52 +00009006 std::vector<Instruction*> &WorkList,
9007 const TargetData *TD) {
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009008 // We have now visited this block! If we've already been here, bail out.
9009 if (!Visited.insert(BB).second) return;
9010
9011 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
9012 Instruction *Inst = BBI++;
9013
9014 // DCE instruction if trivially dead.
9015 if (isInstructionTriviallyDead(Inst)) {
9016 ++NumDeadInst;
Bill Wendling5dbf43c2006-11-26 09:46:52 +00009017 DOUT << "IC: DCE: " << *Inst;
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009018 Inst->eraseFromParent();
9019 continue;
9020 }
9021
9022 // ConstantProp instruction if trivially constant.
9023 if (Constant *C = ConstantFoldInstruction(Inst)) {
Chris Lattner1443bc52006-05-11 17:11:52 +00009024 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
9025 C = OptimizeConstantExpr(CE, TD);
Bill Wendling5dbf43c2006-11-26 09:46:52 +00009026 DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009027 Inst->replaceAllUsesWith(C);
9028 ++NumConstProp;
9029 Inst->eraseFromParent();
9030 continue;
9031 }
9032
9033 WorkList.push_back(Inst);
9034 }
9035
9036 // Recursively visit successors. If this is a branch or switch on a constant,
9037 // only visit the reachable successor.
9038 TerminatorInst *TI = BB->getTerminator();
9039 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
9040 if (BI->isConditional() && isa<ConstantBool>(BI->getCondition())) {
9041 bool CondVal = cast<ConstantBool>(BI->getCondition())->getValue();
Chris Lattner1443bc52006-05-11 17:11:52 +00009042 AddReachableCodeToWorklist(BI->getSuccessor(!CondVal), Visited, WorkList,
9043 TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009044 return;
9045 }
9046 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
9047 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
9048 // See if this is an explicit destination.
9049 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
9050 if (SI->getCaseValue(i) == Cond) {
Chris Lattner1443bc52006-05-11 17:11:52 +00009051 AddReachableCodeToWorklist(SI->getSuccessor(i), Visited, WorkList,TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009052 return;
9053 }
9054
9055 // Otherwise it is the default destination.
Chris Lattner1443bc52006-05-11 17:11:52 +00009056 AddReachableCodeToWorklist(SI->getSuccessor(0), Visited, WorkList, TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009057 return;
9058 }
9059 }
9060
9061 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
Chris Lattner1443bc52006-05-11 17:11:52 +00009062 AddReachableCodeToWorklist(TI->getSuccessor(i), Visited, WorkList, TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009063}
9064
Chris Lattner113f4f42002-06-25 16:13:24 +00009065bool InstCombiner::runOnFunction(Function &F) {
Chris Lattner260ab202002-04-18 17:39:14 +00009066 bool Changed = false;
Chris Lattnerf4ad1652003-11-02 05:57:39 +00009067 TD = &getAnalysis<TargetData>();
Chris Lattnerca081252001-12-14 16:52:21 +00009068
Chris Lattner4ed40f72005-07-07 20:40:38 +00009069 {
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009070 // Do a depth-first traversal of the function, populate the worklist with
9071 // the reachable instructions. Ignore blocks that are not reachable. Keep
9072 // track of which blocks we visit.
Chris Lattner4ed40f72005-07-07 20:40:38 +00009073 std::set<BasicBlock*> Visited;
Chris Lattner1443bc52006-05-11 17:11:52 +00009074 AddReachableCodeToWorklist(F.begin(), Visited, WorkList, TD);
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00009075
Chris Lattner4ed40f72005-07-07 20:40:38 +00009076 // Do a quick scan over the function. If we find any blocks that are
9077 // unreachable, remove any instructions inside of them. This prevents
9078 // the instcombine code from having to deal with some bad special cases.
9079 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
9080 if (!Visited.count(BB)) {
9081 Instruction *Term = BB->getTerminator();
9082 while (Term != BB->begin()) { // Remove instrs bottom-up
9083 BasicBlock::iterator I = Term; --I;
Chris Lattner2d3a7a62004-04-27 15:13:33 +00009084
Bill Wendling5dbf43c2006-11-26 09:46:52 +00009085 DOUT << "IC: DCE: " << *I;
Chris Lattner4ed40f72005-07-07 20:40:38 +00009086 ++NumDeadInst;
9087
9088 if (!I->use_empty())
9089 I->replaceAllUsesWith(UndefValue::get(I->getType()));
9090 I->eraseFromParent();
9091 }
9092 }
9093 }
Chris Lattnerca081252001-12-14 16:52:21 +00009094
9095 while (!WorkList.empty()) {
9096 Instruction *I = WorkList.back(); // Get an instruction from the worklist
9097 WorkList.pop_back();
9098
Chris Lattner1443bc52006-05-11 17:11:52 +00009099 // Check to see if we can DCE the instruction.
Chris Lattner99f48c62002-09-02 04:59:56 +00009100 if (isInstructionTriviallyDead(I)) {
Chris Lattner1443bc52006-05-11 17:11:52 +00009101 // Add operands to the worklist.
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009102 if (I->getNumOperands() < 4)
Chris Lattner51ea1272004-02-28 05:22:00 +00009103 AddUsesToWorkList(*I);
Chris Lattner99f48c62002-09-02 04:59:56 +00009104 ++NumDeadInst;
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009105
Bill Wendling5dbf43c2006-11-26 09:46:52 +00009106 DOUT << "IC: DCE: " << *I;
Chris Lattnercd517ff2005-01-28 19:32:01 +00009107
9108 I->eraseFromParent();
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009109 removeFromWorkList(I);
9110 continue;
9111 }
Chris Lattner99f48c62002-09-02 04:59:56 +00009112
Chris Lattner1443bc52006-05-11 17:11:52 +00009113 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattner99f48c62002-09-02 04:59:56 +00009114 if (Constant *C = ConstantFoldInstruction(I)) {
Chris Lattner1443bc52006-05-11 17:11:52 +00009115 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
9116 C = OptimizeConstantExpr(CE, TD);
Bill Wendling5dbf43c2006-11-26 09:46:52 +00009117 DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
Chris Lattnercd517ff2005-01-28 19:32:01 +00009118
Chris Lattner1443bc52006-05-11 17:11:52 +00009119 // Add operands to the worklist.
Chris Lattner51ea1272004-02-28 05:22:00 +00009120 AddUsesToWorkList(*I);
Chris Lattnerc6509f42002-12-05 22:41:53 +00009121 ReplaceInstUsesWith(*I, C);
9122
Chris Lattner99f48c62002-09-02 04:59:56 +00009123 ++NumConstProp;
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009124 I->eraseFromParent();
Chris Lattner800aaaf2003-10-07 15:17:02 +00009125 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009126 continue;
Chris Lattner99f48c62002-09-02 04:59:56 +00009127 }
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009128
Chris Lattner39c98bb2004-12-08 23:43:58 +00009129 // See if we can trivially sink this instruction to a successor basic block.
9130 if (I->hasOneUse()) {
9131 BasicBlock *BB = I->getParent();
9132 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
9133 if (UserParent != BB) {
9134 bool UserIsSuccessor = false;
9135 // See if the user is one of our successors.
9136 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
9137 if (*SI == UserParent) {
9138 UserIsSuccessor = true;
9139 break;
9140 }
9141
9142 // If the user is one of our immediate successors, and if that successor
9143 // only has us as a predecessors (we'd have to split the critical edge
9144 // otherwise), we can keep going.
9145 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
9146 next(pred_begin(UserParent)) == pred_end(UserParent))
9147 // Okay, the CFG is simple enough, try to sink this instruction.
9148 Changed |= TryToSinkInstruction(I, UserParent);
9149 }
9150 }
9151
Chris Lattnerca081252001-12-14 16:52:21 +00009152 // Now that we have an instruction, try combining it to simplify it...
Chris Lattnerae7a0d32002-08-02 19:29:35 +00009153 if (Instruction *Result = visit(*I)) {
Chris Lattner0b18c1d2002-05-10 15:38:35 +00009154 ++NumCombined;
Chris Lattner260ab202002-04-18 17:39:14 +00009155 // Should we replace the old instruction with a new one?
Chris Lattner053c0932002-05-14 15:24:07 +00009156 if (Result != I) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +00009157 DOUT << "IC: Old = " << *I
9158 << " New = " << *Result;
Chris Lattner7d2a5392004-03-13 23:54:27 +00009159
Chris Lattner396dbfe2004-06-09 05:08:07 +00009160 // Everything uses the new instruction now.
9161 I->replaceAllUsesWith(Result);
9162
9163 // Push the new instruction and any users onto the worklist.
9164 WorkList.push_back(Result);
9165 AddUsersToWorkList(*Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009166
9167 // Move the name to the new instruction first...
9168 std::string OldName = I->getName(); I->setName("");
Chris Lattner950fc782003-10-07 22:58:41 +00009169 Result->setName(OldName);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009170
9171 // Insert the new instruction into the basic block...
9172 BasicBlock *InstParent = I->getParent();
Chris Lattner7515cab2004-11-14 19:13:23 +00009173 BasicBlock::iterator InsertPos = I;
9174
9175 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
9176 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
9177 ++InsertPos;
9178
9179 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009180
Chris Lattner63d75af2004-05-01 23:27:23 +00009181 // Make sure that we reprocess all operands now that we reduced their
9182 // use counts.
Chris Lattnerb643a9e2004-05-01 23:19:52 +00009183 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
9184 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
9185 WorkList.push_back(OpI);
9186
Chris Lattner396dbfe2004-06-09 05:08:07 +00009187 // Instructions can end up on the worklist more than once. Make sure
9188 // we do not process an instruction that has been deleted.
9189 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009190
9191 // Erase the old instruction.
9192 InstParent->getInstList().erase(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00009193 } else {
Bill Wendling5dbf43c2006-11-26 09:46:52 +00009194 DOUT << "IC: MOD = " << *I;
Chris Lattner7d2a5392004-03-13 23:54:27 +00009195
Chris Lattnerae7a0d32002-08-02 19:29:35 +00009196 // If the instruction was modified, it's possible that it is now dead.
9197 // if so, remove it.
Chris Lattner63d75af2004-05-01 23:27:23 +00009198 if (isInstructionTriviallyDead(I)) {
9199 // Make sure we process all operands now that we are reducing their
9200 // use counts.
9201 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
9202 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
9203 WorkList.push_back(OpI);
Misha Brukmanb1c93172005-04-21 23:48:37 +00009204
Chris Lattner63d75af2004-05-01 23:27:23 +00009205 // Instructions may end up in the worklist more than once. Erase all
Robert Bocchinoa8352962006-01-13 22:48:06 +00009206 // occurrences of this instruction.
Chris Lattner99f48c62002-09-02 04:59:56 +00009207 removeFromWorkList(I);
Chris Lattner31f486c2005-01-31 05:36:43 +00009208 I->eraseFromParent();
Chris Lattner396dbfe2004-06-09 05:08:07 +00009209 } else {
9210 WorkList.push_back(Result);
9211 AddUsersToWorkList(*Result);
Chris Lattnerae7a0d32002-08-02 19:29:35 +00009212 }
Chris Lattner053c0932002-05-14 15:24:07 +00009213 }
Chris Lattner260ab202002-04-18 17:39:14 +00009214 Changed = true;
Chris Lattnerca081252001-12-14 16:52:21 +00009215 }
9216 }
9217
Chris Lattner260ab202002-04-18 17:39:14 +00009218 return Changed;
Chris Lattner04805fa2002-02-26 21:46:54 +00009219}
9220
Brian Gaeke38b79e82004-07-27 17:43:21 +00009221FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattner260ab202002-04-18 17:39:14 +00009222 return new InstCombiner();
Chris Lattner04805fa2002-02-26 21:46:54 +00009223}
Brian Gaeke960707c2003-11-11 22:41:34 +00009224