blob: ccc4a9cc8649bf8a8b4deb5e3978fe5bb38f5f3f [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
Chris Lattner99155be2006-05-25 23:24:33 +0000391 // If this is another cast that can be eliminated, it isn't codegen either.
Chris Lattner1d441ad2006-05-06 09:00:16 +0000392 if (const CastInst *CI = dyn_cast<CastInst>(V))
Reid Spencer266e42b2006-12-23 06:05:41 +0000393 if (isEliminableCastPair(CI, opcode, Ty, TD))
Chris Lattner1d441ad2006-05-06 09:00:16 +0000394 return false;
395 return true;
396}
397
398/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
399/// InsertBefore instruction. This is specialized a bit to avoid inserting
400/// casts that are known to not do anything...
401///
Reid Spencer13bc5d72006-12-12 09:18:51 +0000402Value *InstCombiner::InsertOperandCastBefore(Instruction::CastOps opcode,
403 Value *V, const Type *DestTy,
Chris Lattner1d441ad2006-05-06 09:00:16 +0000404 Instruction *InsertBefore) {
405 if (V->getType() == DestTy) return V;
406 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencer13bc5d72006-12-12 09:18:51 +0000407 return ConstantExpr::getCast(opcode, C, DestTy);
Chris Lattner1d441ad2006-05-06 09:00:16 +0000408
Reid Spencer13bc5d72006-12-12 09:18:51 +0000409 return InsertCastBefore(opcode, V, DestTy, *InsertBefore);
Chris Lattner1d441ad2006-05-06 09:00:16 +0000410}
411
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000412// SimplifyCommutative - This performs a few simplifications for commutative
413// operators:
Chris Lattner260ab202002-04-18 17:39:14 +0000414//
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000415// 1. Order operands such that they are listed from right (least complex) to
416// left (most complex). This puts constants before unary operators before
417// binary operators.
418//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000419// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
420// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000421//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000422bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000423 bool Changed = false;
424 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
425 Changed = !I.swapOperands();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000426
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000427 if (!I.isAssociative()) return Changed;
428 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattner7fb29e12003-03-11 00:12:48 +0000429 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
430 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
431 if (isa<Constant>(I.getOperand(1))) {
Chris Lattner34428442003-05-27 16:40:51 +0000432 Constant *Folded = ConstantExpr::get(I.getOpcode(),
433 cast<Constant>(I.getOperand(1)),
434 cast<Constant>(Op->getOperand(1)));
Chris Lattner7fb29e12003-03-11 00:12:48 +0000435 I.setOperand(0, Op->getOperand(0));
436 I.setOperand(1, Folded);
437 return true;
438 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
439 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
440 isOnlyUse(Op) && isOnlyUse(Op1)) {
441 Constant *C1 = cast<Constant>(Op->getOperand(1));
442 Constant *C2 = cast<Constant>(Op1->getOperand(1));
443
444 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner34428442003-05-27 16:40:51 +0000445 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000446 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
447 Op1->getOperand(0),
448 Op1->getName(), &I);
449 WorkList.push_back(New);
450 I.setOperand(0, New);
451 I.setOperand(1, Folded);
452 return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000453 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000454 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000455 return Changed;
Chris Lattner260ab202002-04-18 17:39:14 +0000456}
Chris Lattnerca081252001-12-14 16:52:21 +0000457
Reid Spencer266e42b2006-12-23 06:05:41 +0000458/// SimplifyCompare - For a CmpInst this function just orders the operands
459/// so that theyare listed from right (least complex) to left (most complex).
460/// This puts constants before unary operators before binary operators.
461bool InstCombiner::SimplifyCompare(CmpInst &I) {
462 if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
463 return false;
464 I.swapOperands();
465 // Compare instructions are not associative so there's nothing else we can do.
466 return true;
467}
468
Chris Lattnerbb74e222003-03-10 23:06:50 +0000469// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
470// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattner9fa53de2002-05-06 16:49:18 +0000471//
Chris Lattnerbb74e222003-03-10 23:06:50 +0000472static inline Value *dyn_castNegVal(Value *V) {
473 if (BinaryOperator::isNeg(V))
Chris Lattnerd6f636a2005-04-24 07:30:14 +0000474 return BinaryOperator::getNegArgument(V);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000475
Chris Lattner9ad0d552004-12-14 20:08:06 +0000476 // Constants can be considered to be negated values if they can be folded.
477 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
478 return ConstantExpr::getNeg(C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000479 return 0;
Chris Lattner9fa53de2002-05-06 16:49:18 +0000480}
481
Chris Lattnerbb74e222003-03-10 23:06:50 +0000482static inline Value *dyn_castNotVal(Value *V) {
483 if (BinaryOperator::isNot(V))
Chris Lattnerd6f636a2005-04-24 07:30:14 +0000484 return BinaryOperator::getNotArgument(V);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000485
486 // Constants can be considered to be not'ed values...
Chris Lattnerdd65d862003-04-30 22:34:06 +0000487 if (ConstantIntegral *C = dyn_cast<ConstantIntegral>(V))
Chris Lattnerc8e7e292004-06-10 02:12:35 +0000488 return ConstantExpr::getNot(C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000489 return 0;
490}
491
Chris Lattner7fb29e12003-03-11 00:12:48 +0000492// dyn_castFoldableMul - If this value is a multiply that can be folded into
493// other computations (because it has a constant operand), return the
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000494// non-constant operand of the multiply, and set CST to point to the multiplier.
495// Otherwise, return null.
Chris Lattner7fb29e12003-03-11 00:12:48 +0000496//
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000497static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000498 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000499 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattner7fb29e12003-03-11 00:12:48 +0000500 if (I->getOpcode() == Instruction::Mul)
Chris Lattner970136362004-11-15 05:54:07 +0000501 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattner7fb29e12003-03-11 00:12:48 +0000502 return I->getOperand(0);
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000503 if (I->getOpcode() == Instruction::Shl)
Chris Lattner970136362004-11-15 05:54:07 +0000504 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000505 // The multiplier is really 1 << CST.
506 Constant *One = ConstantInt::get(V->getType(), 1);
507 CST = cast<ConstantInt>(ConstantExpr::getShl(One, CST));
508 return I->getOperand(0);
509 }
510 }
Chris Lattner7fb29e12003-03-11 00:12:48 +0000511 return 0;
Chris Lattner3082c5a2003-02-18 19:28:33 +0000512}
Chris Lattner31ae8632002-08-14 17:51:49 +0000513
Chris Lattner0798af32005-01-13 20:14:25 +0000514/// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
515/// expression, return it.
516static User *dyn_castGetElementPtr(Value *V) {
517 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
518 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
519 if (CE->getOpcode() == Instruction::GetElementPtr)
520 return cast<User>(V);
521 return false;
522}
523
Chris Lattner623826c2004-09-28 21:48:02 +0000524// AddOne, SubOne - Add or subtract a constant one from an integer constant...
Chris Lattner6862fbd2004-09-29 17:40:11 +0000525static ConstantInt *AddOne(ConstantInt *C) {
526 return cast<ConstantInt>(ConstantExpr::getAdd(C,
527 ConstantInt::get(C->getType(), 1)));
Chris Lattner623826c2004-09-28 21:48:02 +0000528}
Chris Lattner6862fbd2004-09-29 17:40:11 +0000529static ConstantInt *SubOne(ConstantInt *C) {
530 return cast<ConstantInt>(ConstantExpr::getSub(C,
531 ConstantInt::get(C->getType(), 1)));
Chris Lattner623826c2004-09-28 21:48:02 +0000532}
533
Chris Lattner0157e7f2006-02-11 09:31:47 +0000534/// GetConstantInType - Return a ConstantInt with the specified type and value.
535///
Chris Lattneree0f2802006-02-12 02:07:56 +0000536static ConstantIntegral *GetConstantInType(const Type *Ty, uint64_t Val) {
Reid Spencerc635f472006-12-31 05:48:39 +0000537 if (Ty->getTypeID() == Type::BoolTyID)
Chris Lattneree0f2802006-02-12 02:07:56 +0000538 return ConstantBool::get(Val);
Reid Spencerc635f472006-12-31 05:48:39 +0000539 return ConstantInt::get(Ty, Val);
Chris Lattner0157e7f2006-02-11 09:31:47 +0000540}
541
542
Chris Lattner4534dd592006-02-09 07:38:58 +0000543/// ComputeMaskedBits - Determine which of the bits specified in Mask are
544/// known to be either zero or one and return them in the KnownZero/KnownOne
545/// bitsets. This code only analyzes bits in Mask, in order to short-circuit
546/// processing.
547static void ComputeMaskedBits(Value *V, uint64_t Mask, uint64_t &KnownZero,
548 uint64_t &KnownOne, unsigned Depth = 0) {
Chris Lattner0b3557f2005-09-24 23:43:33 +0000549 // Note, we cannot consider 'undef' to be "IsZero" here. The problem is that
550 // we cannot optimize based on the assumption that it is zero without changing
Chris Lattnerc3ebf402006-02-07 07:27:52 +0000551 // it to be an explicit zero. If we don't change it to zero, other code could
Chris Lattner0b3557f2005-09-24 23:43:33 +0000552 // optimized based on the contradictory assumption that it is non-zero.
553 // Because instcombine aggressively folds operations with undef args anyway,
554 // this won't lose us code quality.
Chris Lattner4534dd592006-02-09 07:38:58 +0000555 if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(V)) {
556 // We know all of the bits for a constant!
Chris Lattner0157e7f2006-02-11 09:31:47 +0000557 KnownOne = CI->getZExtValue() & Mask;
Chris Lattner4534dd592006-02-09 07:38:58 +0000558 KnownZero = ~KnownOne & Mask;
559 return;
560 }
561
562 KnownZero = KnownOne = 0; // Don't know anything.
Chris Lattner92a68652006-02-07 08:05:22 +0000563 if (Depth == 6 || Mask == 0)
Chris Lattner4534dd592006-02-09 07:38:58 +0000564 return; // Limit search depth.
565
566 uint64_t KnownZero2, KnownOne2;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000567 Instruction *I = dyn_cast<Instruction>(V);
568 if (!I) return;
569
Chris Lattnerfb296922006-05-04 17:33:35 +0000570 Mask &= V->getType()->getIntegralTypeMask();
571
Chris Lattner0157e7f2006-02-11 09:31:47 +0000572 switch (I->getOpcode()) {
573 case Instruction::And:
574 // If either the LHS or the RHS are Zero, the result is zero.
575 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
576 Mask &= ~KnownZero;
577 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
578 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
579 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
580
581 // Output known-1 bits are only known if set in both the LHS & RHS.
582 KnownOne &= KnownOne2;
583 // Output known-0 are known to be clear if zero in either the LHS | RHS.
584 KnownZero |= KnownZero2;
585 return;
586 case Instruction::Or:
587 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
588 Mask &= ~KnownOne;
589 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
590 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
591 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
592
593 // Output known-0 bits are only known if clear in both the LHS & RHS.
594 KnownZero &= KnownZero2;
595 // Output known-1 are known to be set if set in either the LHS | RHS.
596 KnownOne |= KnownOne2;
597 return;
598 case Instruction::Xor: {
599 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
600 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
601 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
602 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
603
604 // Output known-0 bits are known if clear or set in both the LHS & RHS.
605 uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
606 // Output known-1 are known to be set if set in only one of the LHS, RHS.
607 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
608 KnownZero = KnownZeroOut;
609 return;
610 }
611 case Instruction::Select:
612 ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
613 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
614 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
615 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
616
617 // Only known if known in both the LHS and RHS.
618 KnownOne &= KnownOne2;
619 KnownZero &= KnownZero2;
620 return;
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000621 case Instruction::FPTrunc:
622 case Instruction::FPExt:
623 case Instruction::FPToUI:
624 case Instruction::FPToSI:
625 case Instruction::SIToFP:
626 case Instruction::PtrToInt:
627 case Instruction::UIToFP:
628 case Instruction::IntToPtr:
629 return; // Can't work with floating point or pointers
630 case Instruction::Trunc:
631 // All these have integer operands
632 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
633 return;
634 case Instruction::BitCast: {
Chris Lattner0157e7f2006-02-11 09:31:47 +0000635 const Type *SrcTy = I->getOperand(0)->getType();
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000636 if (SrcTy->isIntegral()) {
Chris Lattner0157e7f2006-02-11 09:31:47 +0000637 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
Chris Lattner4534dd592006-02-09 07:38:58 +0000638 return;
639 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000640 break;
641 }
642 case Instruction::ZExt: {
643 // Compute the bits in the result that are not present in the input.
644 const Type *SrcTy = I->getOperand(0)->getType();
Chris Lattner0157e7f2006-02-11 09:31:47 +0000645 uint64_t NotIn = ~SrcTy->getIntegralTypeMask();
646 uint64_t NewBits = I->getType()->getIntegralTypeMask() & NotIn;
Chris Lattner62010c42005-10-09 06:36:35 +0000647
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000648 Mask &= SrcTy->getIntegralTypeMask();
649 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
650 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
651 // The top bits are known to be zero.
652 KnownZero |= NewBits;
653 return;
654 }
655 case Instruction::SExt: {
656 // Compute the bits in the result that are not present in the input.
657 const Type *SrcTy = I->getOperand(0)->getType();
658 uint64_t NotIn = ~SrcTy->getIntegralTypeMask();
659 uint64_t NewBits = I->getType()->getIntegralTypeMask() & NotIn;
660
661 Mask &= SrcTy->getIntegralTypeMask();
662 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
663 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattner92a68652006-02-07 08:05:22 +0000664
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000665 // If the sign bit of the input is known set or clear, then we know the
666 // top bits of the result.
667 uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
668 if (KnownZero & InSignBit) { // Input sign bit known zero
669 KnownZero |= NewBits;
670 KnownOne &= ~NewBits;
671 } else if (KnownOne & InSignBit) { // Input sign bit known set
672 KnownOne |= NewBits;
673 KnownZero &= ~NewBits;
674 } else { // Input sign bit unknown
675 KnownZero &= ~NewBits;
676 KnownOne &= ~NewBits;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000677 }
678 return;
679 }
680 case Instruction::Shl:
681 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
Reid Spencere0fc4df2006-10-20 07:07:24 +0000682 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
683 uint64_t ShiftAmt = SA->getZExtValue();
684 Mask >>= ShiftAmt;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000685 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
686 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Reid Spencere0fc4df2006-10-20 07:07:24 +0000687 KnownZero <<= ShiftAmt;
688 KnownOne <<= ShiftAmt;
689 KnownZero |= (1ULL << ShiftAmt)-1; // low bits known zero.
Chris Lattner0157e7f2006-02-11 09:31:47 +0000690 return;
691 }
692 break;
Reid Spencerfdff9382006-11-08 06:47:33 +0000693 case Instruction::LShr:
Chris Lattner0157e7f2006-02-11 09:31:47 +0000694 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
Reid Spencere0fc4df2006-10-20 07:07:24 +0000695 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Chris Lattner0157e7f2006-02-11 09:31:47 +0000696 // Compute the new bits that are at the top now.
Reid Spencere0fc4df2006-10-20 07:07:24 +0000697 uint64_t ShiftAmt = SA->getZExtValue();
698 uint64_t HighBits = (1ULL << ShiftAmt)-1;
699 HighBits <<= I->getType()->getPrimitiveSizeInBits()-ShiftAmt;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000700
Reid Spencerfdff9382006-11-08 06:47:33 +0000701 // Unsigned shift right.
702 Mask <<= ShiftAmt;
703 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
704 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
705 KnownZero >>= ShiftAmt;
706 KnownOne >>= ShiftAmt;
707 KnownZero |= HighBits; // high bits known zero.
708 return;
709 }
710 break;
711 case Instruction::AShr:
712 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
713 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
714 // Compute the new bits that are at the top now.
715 uint64_t ShiftAmt = SA->getZExtValue();
716 uint64_t HighBits = (1ULL << ShiftAmt)-1;
717 HighBits <<= I->getType()->getPrimitiveSizeInBits()-ShiftAmt;
718
719 // Signed shift right.
720 Mask <<= ShiftAmt;
721 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
722 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
723 KnownZero >>= ShiftAmt;
724 KnownOne >>= ShiftAmt;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000725
Reid Spencerfdff9382006-11-08 06:47:33 +0000726 // Handle the sign bits.
727 uint64_t SignBit = 1ULL << (I->getType()->getPrimitiveSizeInBits()-1);
728 SignBit >>= ShiftAmt; // Adjust to where it is now in the mask.
Chris Lattner0157e7f2006-02-11 09:31:47 +0000729
Reid Spencerfdff9382006-11-08 06:47:33 +0000730 if (KnownZero & SignBit) { // New bits are known zero.
731 KnownZero |= HighBits;
732 } else if (KnownOne & SignBit) { // New bits are known one.
733 KnownOne |= HighBits;
Chris Lattner4534dd592006-02-09 07:38:58 +0000734 }
735 return;
Chris Lattner62010c42005-10-09 06:36:35 +0000736 }
Chris Lattner0157e7f2006-02-11 09:31:47 +0000737 break;
Chris Lattner0b3557f2005-09-24 23:43:33 +0000738 }
Chris Lattner92a68652006-02-07 08:05:22 +0000739}
740
741/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
742/// this predicate to simplify operations downstream. Mask is known to be zero
743/// for bits that V cannot have.
744static bool MaskedValueIsZero(Value *V, uint64_t Mask, unsigned Depth = 0) {
Chris Lattner4534dd592006-02-09 07:38:58 +0000745 uint64_t KnownZero, KnownOne;
746 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
747 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
748 return (KnownZero & Mask) == Mask;
Chris Lattner0b3557f2005-09-24 23:43:33 +0000749}
750
Chris Lattner0157e7f2006-02-11 09:31:47 +0000751/// ShrinkDemandedConstant - Check to see if the specified operand of the
752/// specified instruction is a constant integer. If so, check to see if there
753/// are any bits set in the constant that are not demanded. If so, shrink the
754/// constant and return true.
755static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
756 uint64_t Demanded) {
757 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
758 if (!OpC) return false;
759
760 // If there are no bits set that aren't demanded, nothing to do.
761 if ((~Demanded & OpC->getZExtValue()) == 0)
762 return false;
763
764 // This is producing any bits that are not needed, shrink the RHS.
765 uint64_t Val = Demanded & OpC->getZExtValue();
766 I->setOperand(OpNo, GetConstantInType(OpC->getType(), Val));
767 return true;
768}
769
Chris Lattneree0f2802006-02-12 02:07:56 +0000770// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
771// set of known zero and one bits, compute the maximum and minimum values that
772// could have the specified known zero and known one bits, returning them in
773// min/max.
774static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
775 uint64_t KnownZero,
776 uint64_t KnownOne,
777 int64_t &Min, int64_t &Max) {
778 uint64_t TypeBits = Ty->getIntegralTypeMask();
779 uint64_t UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
780
781 uint64_t SignBit = 1ULL << (Ty->getPrimitiveSizeInBits()-1);
782
783 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
784 // bit if it is unknown.
785 Min = KnownOne;
786 Max = KnownOne|UnknownBits;
787
788 if (SignBit & UnknownBits) { // Sign bit is unknown
789 Min |= SignBit;
790 Max &= ~SignBit;
791 }
792
793 // Sign extend the min/max values.
794 int ShAmt = 64-Ty->getPrimitiveSizeInBits();
795 Min = (Min << ShAmt) >> ShAmt;
796 Max = (Max << ShAmt) >> ShAmt;
797}
798
799// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
800// a set of known zero and one bits, compute the maximum and minimum values that
801// could have the specified known zero and known one bits, returning them in
802// min/max.
803static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
804 uint64_t KnownZero,
805 uint64_t KnownOne,
806 uint64_t &Min,
807 uint64_t &Max) {
808 uint64_t TypeBits = Ty->getIntegralTypeMask();
809 uint64_t UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
810
811 // The minimum value is when the unknown bits are all zeros.
812 Min = KnownOne;
813 // The maximum value is when the unknown bits are all ones.
814 Max = KnownOne|UnknownBits;
815}
Chris Lattner0157e7f2006-02-11 09:31:47 +0000816
817
818/// SimplifyDemandedBits - Look at V. At this point, we know that only the
819/// DemandedMask bits of the result of V are ever used downstream. If we can
820/// use this information to simplify V, do so and return true. Otherwise,
821/// analyze the expression and return a mask of KnownOne and KnownZero bits for
822/// the expression (used to simplify the caller). The KnownZero/One bits may
823/// only be accurate for those bits in the DemandedMask.
824bool InstCombiner::SimplifyDemandedBits(Value *V, uint64_t DemandedMask,
825 uint64_t &KnownZero, uint64_t &KnownOne,
Chris Lattner2590e512006-02-07 06:56:34 +0000826 unsigned Depth) {
Chris Lattner0157e7f2006-02-11 09:31:47 +0000827 if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(V)) {
828 // We know all of the bits for a constant!
829 KnownOne = CI->getZExtValue() & DemandedMask;
830 KnownZero = ~KnownOne & DemandedMask;
831 return false;
832 }
833
834 KnownZero = KnownOne = 0;
Chris Lattner2590e512006-02-07 06:56:34 +0000835 if (!V->hasOneUse()) { // Other users may use these bits.
Chris Lattner0157e7f2006-02-11 09:31:47 +0000836 if (Depth != 0) { // Not at the root.
837 // Just compute the KnownZero/KnownOne bits to simplify things downstream.
838 ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
Chris Lattner2590e512006-02-07 06:56:34 +0000839 return false;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000840 }
Chris Lattner2590e512006-02-07 06:56:34 +0000841 // If this is the root being simplified, allow it to have multiple uses,
Chris Lattner0157e7f2006-02-11 09:31:47 +0000842 // just set the DemandedMask to all bits.
843 DemandedMask = V->getType()->getIntegralTypeMask();
844 } else if (DemandedMask == 0) { // Not demanding any bits from V.
Chris Lattner92a68652006-02-07 08:05:22 +0000845 if (V != UndefValue::get(V->getType()))
846 return UpdateValueUsesWith(V, UndefValue::get(V->getType()));
847 return false;
Chris Lattner2590e512006-02-07 06:56:34 +0000848 } else if (Depth == 6) { // Limit search depth.
849 return false;
850 }
851
852 Instruction *I = dyn_cast<Instruction>(V);
853 if (!I) return false; // Only analyze instructions.
854
Chris Lattnerfb296922006-05-04 17:33:35 +0000855 DemandedMask &= V->getType()->getIntegralTypeMask();
856
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000857 uint64_t KnownZero2 = 0, KnownOne2 = 0;
Chris Lattner2590e512006-02-07 06:56:34 +0000858 switch (I->getOpcode()) {
859 default: break;
860 case Instruction::And:
Chris Lattner0157e7f2006-02-11 09:31:47 +0000861 // If either the LHS or the RHS are Zero, the result is zero.
862 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
863 KnownZero, KnownOne, Depth+1))
864 return true;
865 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
866
867 // If something is known zero on the RHS, the bits aren't demanded on the
868 // LHS.
869 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownZero,
870 KnownZero2, KnownOne2, Depth+1))
871 return true;
872 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
873
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000874 // If all of the demanded bits are known 1 on one side, return the other.
Chris Lattner0157e7f2006-02-11 09:31:47 +0000875 // These bits cannot contribute to the result of the 'and'.
876 if ((DemandedMask & ~KnownZero2 & KnownOne) == (DemandedMask & ~KnownZero2))
877 return UpdateValueUsesWith(I, I->getOperand(0));
878 if ((DemandedMask & ~KnownZero & KnownOne2) == (DemandedMask & ~KnownZero))
879 return UpdateValueUsesWith(I, I->getOperand(1));
Chris Lattner5b2edb12006-02-12 08:02:11 +0000880
881 // If all of the demanded bits in the inputs are known zeros, return zero.
882 if ((DemandedMask & (KnownZero|KnownZero2)) == DemandedMask)
883 return UpdateValueUsesWith(I, Constant::getNullValue(I->getType()));
884
Chris Lattner0157e7f2006-02-11 09:31:47 +0000885 // If the RHS is a constant, see if we can simplify it.
Chris Lattner5b2edb12006-02-12 08:02:11 +0000886 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~KnownZero2))
Chris Lattner0157e7f2006-02-11 09:31:47 +0000887 return UpdateValueUsesWith(I, I);
888
889 // Output known-1 bits are only known if set in both the LHS & RHS.
890 KnownOne &= KnownOne2;
891 // Output known-0 are known to be clear if zero in either the LHS | RHS.
892 KnownZero |= KnownZero2;
893 break;
894 case Instruction::Or:
895 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
896 KnownZero, KnownOne, Depth+1))
897 return true;
898 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
899 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownOne,
900 KnownZero2, KnownOne2, Depth+1))
901 return true;
902 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
903
904 // If all of the demanded bits are known zero on one side, return the other.
905 // These bits cannot contribute to the result of the 'or'.
Jeff Cohen0add83e2006-02-18 03:20:33 +0000906 if ((DemandedMask & ~KnownOne2 & KnownZero) == (DemandedMask & ~KnownOne2))
Chris Lattner0157e7f2006-02-11 09:31:47 +0000907 return UpdateValueUsesWith(I, I->getOperand(0));
Jeff Cohen0add83e2006-02-18 03:20:33 +0000908 if ((DemandedMask & ~KnownOne & KnownZero2) == (DemandedMask & ~KnownOne))
Chris Lattner0157e7f2006-02-11 09:31:47 +0000909 return UpdateValueUsesWith(I, I->getOperand(1));
Chris Lattner5b2edb12006-02-12 08:02:11 +0000910
911 // If all of the potentially set bits on one side are known to be set on
912 // the other side, just use the 'other' side.
913 if ((DemandedMask & (~KnownZero) & KnownOne2) ==
914 (DemandedMask & (~KnownZero)))
915 return UpdateValueUsesWith(I, I->getOperand(0));
Nate Begeman8a77efe2006-02-16 21:11:51 +0000916 if ((DemandedMask & (~KnownZero2) & KnownOne) ==
917 (DemandedMask & (~KnownZero2)))
918 return UpdateValueUsesWith(I, I->getOperand(1));
Chris Lattner0157e7f2006-02-11 09:31:47 +0000919
920 // If the RHS is a constant, see if we can simplify it.
921 if (ShrinkDemandedConstant(I, 1, DemandedMask))
922 return UpdateValueUsesWith(I, I);
923
924 // Output known-0 bits are only known if clear in both the LHS & RHS.
925 KnownZero &= KnownZero2;
926 // Output known-1 are known to be set if set in either the LHS | RHS.
927 KnownOne |= KnownOne2;
928 break;
929 case Instruction::Xor: {
930 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
931 KnownZero, KnownOne, Depth+1))
932 return true;
933 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
934 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
935 KnownZero2, KnownOne2, Depth+1))
936 return true;
937 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
938
939 // If all of the demanded bits are known zero on one side, return the other.
940 // These bits cannot contribute to the result of the 'xor'.
941 if ((DemandedMask & KnownZero) == DemandedMask)
942 return UpdateValueUsesWith(I, I->getOperand(0));
943 if ((DemandedMask & KnownZero2) == DemandedMask)
944 return UpdateValueUsesWith(I, I->getOperand(1));
945
946 // Output known-0 bits are known if clear or set in both the LHS & RHS.
947 uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
948 // Output known-1 are known to be set if set in only one of the LHS, RHS.
949 uint64_t KnownOneOut = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
950
Chris Lattner8e9a7b72006-11-27 19:55:07 +0000951 // If all of the demanded bits are known to be zero on one side or the
952 // other, turn this into an *inclusive* or.
Chris Lattner5b2edb12006-02-12 08:02:11 +0000953 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattner8e9a7b72006-11-27 19:55:07 +0000954 if ((DemandedMask & ~KnownZero & ~KnownZero2) == 0) {
955 Instruction *Or =
956 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
957 I->getName());
958 InsertNewInstBefore(Or, *I);
959 return UpdateValueUsesWith(I, Or);
Chris Lattner2590e512006-02-07 06:56:34 +0000960 }
Chris Lattner0157e7f2006-02-11 09:31:47 +0000961
Chris Lattner5b2edb12006-02-12 08:02:11 +0000962 // If all of the demanded bits on one side are known, and all of the set
963 // bits on that side are also known to be set on the other side, turn this
964 // into an AND, as we know the bits will be cleared.
965 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
966 if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask) { // all known
967 if ((KnownOne & KnownOne2) == KnownOne) {
968 Constant *AndC = GetConstantInType(I->getType(),
969 ~KnownOne & DemandedMask);
970 Instruction *And =
971 BinaryOperator::createAnd(I->getOperand(0), AndC, "tmp");
972 InsertNewInstBefore(And, *I);
973 return UpdateValueUsesWith(I, And);
974 }
975 }
976
Chris Lattner0157e7f2006-02-11 09:31:47 +0000977 // If the RHS is a constant, see if we can simplify it.
978 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
979 if (ShrinkDemandedConstant(I, 1, DemandedMask))
980 return UpdateValueUsesWith(I, I);
981
982 KnownZero = KnownZeroOut;
983 KnownOne = KnownOneOut;
984 break;
985 }
986 case Instruction::Select:
987 if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
988 KnownZero, KnownOne, Depth+1))
989 return true;
990 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
991 KnownZero2, KnownOne2, Depth+1))
992 return true;
993 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
994 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
995
996 // If the operands are constants, see if we can simplify them.
997 if (ShrinkDemandedConstant(I, 1, DemandedMask))
998 return UpdateValueUsesWith(I, I);
999 if (ShrinkDemandedConstant(I, 2, DemandedMask))
1000 return UpdateValueUsesWith(I, I);
1001
1002 // Only known if known in both the LHS and RHS.
1003 KnownOne &= KnownOne2;
1004 KnownZero &= KnownZero2;
1005 break;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001006 case Instruction::Trunc:
1007 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1008 KnownZero, KnownOne, Depth+1))
1009 return true;
1010 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1011 break;
1012 case Instruction::BitCast:
1013 if (!I->getOperand(0)->getType()->isIntegral())
1014 return false;
Chris Lattner850465d2006-09-16 03:14:10 +00001015
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001016 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1017 KnownZero, KnownOne, Depth+1))
1018 return true;
1019 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1020 break;
1021 case Instruction::ZExt: {
1022 // Compute the bits in the result that are not present in the input.
1023 const Type *SrcTy = I->getOperand(0)->getType();
Chris Lattner0157e7f2006-02-11 09:31:47 +00001024 uint64_t NotIn = ~SrcTy->getIntegralTypeMask();
1025 uint64_t NewBits = I->getType()->getIntegralTypeMask() & NotIn;
1026
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001027 DemandedMask &= SrcTy->getIntegralTypeMask();
1028 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1029 KnownZero, KnownOne, Depth+1))
1030 return true;
1031 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1032 // The top bits are known to be zero.
1033 KnownZero |= NewBits;
1034 break;
1035 }
1036 case Instruction::SExt: {
1037 // Compute the bits in the result that are not present in the input.
1038 const Type *SrcTy = I->getOperand(0)->getType();
1039 uint64_t NotIn = ~SrcTy->getIntegralTypeMask();
1040 uint64_t NewBits = I->getType()->getIntegralTypeMask() & NotIn;
1041
1042 // Get the sign bit for the source type
1043 uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
1044 int64_t InputDemandedBits = DemandedMask & SrcTy->getIntegralTypeMask();
Chris Lattner7d852282006-02-13 22:41:07 +00001045
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001046 // If any of the sign extended bits are demanded, we know that the sign
1047 // bit is demanded.
1048 if (NewBits & DemandedMask)
1049 InputDemandedBits |= InSignBit;
Chris Lattner7d852282006-02-13 22:41:07 +00001050
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001051 if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
1052 KnownZero, KnownOne, Depth+1))
1053 return true;
1054 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattner0157e7f2006-02-11 09:31:47 +00001055
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001056 // If the sign bit of the input is known set or clear, then we know the
1057 // top bits of the result.
Chris Lattner2590e512006-02-07 06:56:34 +00001058
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001059 // If the input sign bit is known zero, or if the NewBits are not demanded
1060 // convert this into a zero extension.
1061 if ((KnownZero & InSignBit) || (NewBits & ~DemandedMask) == NewBits) {
1062 // Convert to ZExt cast
1063 CastInst *NewCast = CastInst::create(
1064 Instruction::ZExt, I->getOperand(0), I->getType(), I->getName(), I);
1065 return UpdateValueUsesWith(I, NewCast);
1066 } else if (KnownOne & InSignBit) { // Input sign bit known set
1067 KnownOne |= NewBits;
1068 KnownZero &= ~NewBits;
1069 } else { // Input sign bit unknown
1070 KnownZero &= ~NewBits;
1071 KnownOne &= ~NewBits;
Chris Lattner2590e512006-02-07 06:56:34 +00001072 }
Chris Lattner0157e7f2006-02-11 09:31:47 +00001073 break;
Chris Lattner2590e512006-02-07 06:56:34 +00001074 }
Chris Lattner6e2c15c2006-11-09 05:12:27 +00001075 case Instruction::Add:
1076 // If there is a constant on the RHS, there are a variety of xformations
1077 // we can do.
1078 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1079 // If null, this should be simplified elsewhere. Some of the xforms here
1080 // won't work if the RHS is zero.
1081 if (RHS->isNullValue())
1082 break;
1083
1084 // Figure out what the input bits are. If the top bits of the and result
1085 // are not demanded, then the add doesn't demand them from its input
1086 // either.
1087
1088 // Shift the demanded mask up so that it's at the top of the uint64_t.
1089 unsigned BitWidth = I->getType()->getPrimitiveSizeInBits();
1090 unsigned NLZ = CountLeadingZeros_64(DemandedMask << (64-BitWidth));
1091
1092 // If the top bit of the output is demanded, demand everything from the
1093 // input. Otherwise, we demand all the input bits except NLZ top bits.
1094 uint64_t InDemandedBits = ~0ULL >> 64-BitWidth+NLZ;
1095
1096 // Find information about known zero/one bits in the input.
1097 if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits,
1098 KnownZero2, KnownOne2, Depth+1))
1099 return true;
1100
1101 // If the RHS of the add has bits set that can't affect the input, reduce
1102 // the constant.
1103 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1104 return UpdateValueUsesWith(I, I);
1105
1106 // Avoid excess work.
1107 if (KnownZero2 == 0 && KnownOne2 == 0)
1108 break;
1109
1110 // Turn it into OR if input bits are zero.
1111 if ((KnownZero2 & RHS->getZExtValue()) == RHS->getZExtValue()) {
1112 Instruction *Or =
1113 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1114 I->getName());
1115 InsertNewInstBefore(Or, *I);
1116 return UpdateValueUsesWith(I, Or);
1117 }
1118
1119 // We can say something about the output known-zero and known-one bits,
1120 // depending on potential carries from the input constant and the
1121 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1122 // bits set and the RHS constant is 0x01001, then we know we have a known
1123 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1124
1125 // To compute this, we first compute the potential carry bits. These are
1126 // the bits which may be modified. I'm not aware of a better way to do
1127 // this scan.
1128 uint64_t RHSVal = RHS->getZExtValue();
1129
1130 bool CarryIn = false;
1131 uint64_t CarryBits = 0;
1132 uint64_t CurBit = 1;
1133 for (unsigned i = 0; i != BitWidth; ++i, CurBit <<= 1) {
1134 // Record the current carry in.
1135 if (CarryIn) CarryBits |= CurBit;
1136
1137 bool CarryOut;
1138
1139 // This bit has a carry out unless it is "zero + zero" or
1140 // "zero + anything" with no carry in.
1141 if ((KnownZero2 & CurBit) && ((RHSVal & CurBit) == 0)) {
1142 CarryOut = false; // 0 + 0 has no carry out, even with carry in.
1143 } else if (!CarryIn &&
1144 ((KnownZero2 & CurBit) || ((RHSVal & CurBit) == 0))) {
1145 CarryOut = false; // 0 + anything has no carry out if no carry in.
1146 } else {
1147 // Otherwise, we have to assume we have a carry out.
1148 CarryOut = true;
1149 }
1150
1151 // This stage's carry out becomes the next stage's carry-in.
1152 CarryIn = CarryOut;
1153 }
1154
1155 // Now that we know which bits have carries, compute the known-1/0 sets.
1156
1157 // Bits are known one if they are known zero in one operand and one in the
1158 // other, and there is no input carry.
1159 KnownOne = ((KnownZero2 & RHSVal) | (KnownOne2 & ~RHSVal)) & ~CarryBits;
1160
1161 // Bits are known zero if they are known zero in both operands and there
1162 // is no input carry.
1163 KnownZero = KnownZero2 & ~RHSVal & ~CarryBits;
1164 }
1165 break;
Chris Lattner2590e512006-02-07 06:56:34 +00001166 case Instruction::Shl:
Reid Spencere0fc4df2006-10-20 07:07:24 +00001167 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1168 uint64_t ShiftAmt = SA->getZExtValue();
1169 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask >> ShiftAmt,
Chris Lattner0157e7f2006-02-11 09:31:47 +00001170 KnownZero, KnownOne, Depth+1))
1171 return true;
1172 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Reid Spencere0fc4df2006-10-20 07:07:24 +00001173 KnownZero <<= ShiftAmt;
1174 KnownOne <<= ShiftAmt;
1175 KnownZero |= (1ULL << ShiftAmt) - 1; // low bits known zero.
Chris Lattner0157e7f2006-02-11 09:31:47 +00001176 }
Chris Lattner2590e512006-02-07 06:56:34 +00001177 break;
Reid Spencerfdff9382006-11-08 06:47:33 +00001178 case Instruction::LShr:
1179 // For a logical shift right
1180 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1181 unsigned ShiftAmt = SA->getZExtValue();
1182
1183 // Compute the new bits that are at the top now.
1184 uint64_t HighBits = (1ULL << ShiftAmt)-1;
1185 HighBits <<= I->getType()->getPrimitiveSizeInBits() - ShiftAmt;
1186 uint64_t TypeMask = I->getType()->getIntegralTypeMask();
1187 // Unsigned shift right.
1188 if (SimplifyDemandedBits(I->getOperand(0),
1189 (DemandedMask << ShiftAmt) & TypeMask,
1190 KnownZero, KnownOne, Depth+1))
1191 return true;
1192 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1193 KnownZero &= TypeMask;
1194 KnownOne &= TypeMask;
1195 KnownZero >>= ShiftAmt;
1196 KnownOne >>= ShiftAmt;
1197 KnownZero |= HighBits; // high bits known zero.
1198 }
1199 break;
1200 case Instruction::AShr:
Chris Lattner420c4bc2006-09-18 04:31:40 +00001201 // If this is an arithmetic shift right and only the low-bit is set, we can
1202 // always convert this into a logical shr, even if the shift amount is
1203 // variable. The low bit of the shift cannot be an input sign bit unless
1204 // the shift amount is >= the size of the datatype, which is undefined.
Reid Spencerfdff9382006-11-08 06:47:33 +00001205 if (DemandedMask == 1) {
1206 // Perform the logical shift right.
1207 Value *NewVal = new ShiftInst(Instruction::LShr, I->getOperand(0),
1208 I->getOperand(1), I->getName());
Reid Spencer00c482b2006-10-26 19:19:06 +00001209 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
Chris Lattner420c4bc2006-09-18 04:31:40 +00001210 return UpdateValueUsesWith(I, NewVal);
1211 }
1212
Reid Spencere0fc4df2006-10-20 07:07:24 +00001213 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1214 unsigned ShiftAmt = SA->getZExtValue();
Chris Lattner0157e7f2006-02-11 09:31:47 +00001215
1216 // Compute the new bits that are at the top now.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001217 uint64_t HighBits = (1ULL << ShiftAmt)-1;
1218 HighBits <<= I->getType()->getPrimitiveSizeInBits() - ShiftAmt;
Chris Lattner68e74752006-02-13 06:09:08 +00001219 uint64_t TypeMask = I->getType()->getIntegralTypeMask();
Reid Spencerfdff9382006-11-08 06:47:33 +00001220 // Signed shift right.
1221 if (SimplifyDemandedBits(I->getOperand(0),
1222 (DemandedMask << ShiftAmt) & TypeMask,
1223 KnownZero, KnownOne, Depth+1))
1224 return true;
1225 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1226 KnownZero &= TypeMask;
1227 KnownOne &= TypeMask;
1228 KnownZero >>= ShiftAmt;
1229 KnownOne >>= ShiftAmt;
Chris Lattner0157e7f2006-02-11 09:31:47 +00001230
Reid Spencerfdff9382006-11-08 06:47:33 +00001231 // Handle the sign bits.
1232 uint64_t SignBit = 1ULL << (I->getType()->getPrimitiveSizeInBits()-1);
1233 SignBit >>= ShiftAmt; // Adjust to where it is now in the mask.
Chris Lattner0157e7f2006-02-11 09:31:47 +00001234
Reid Spencerfdff9382006-11-08 06:47:33 +00001235 // If the input sign bit is known to be zero, or if none of the top bits
1236 // are demanded, turn this into an unsigned shift right.
1237 if ((KnownZero & SignBit) || (HighBits & ~DemandedMask) == HighBits) {
1238 // Perform the logical shift right.
1239 Value *NewVal = new ShiftInst(Instruction::LShr, I->getOperand(0),
1240 SA, I->getName());
1241 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1242 return UpdateValueUsesWith(I, NewVal);
1243 } else if (KnownOne & SignBit) { // New bits are known one.
1244 KnownOne |= HighBits;
Chris Lattner2590e512006-02-07 06:56:34 +00001245 }
Chris Lattner0157e7f2006-02-11 09:31:47 +00001246 }
Chris Lattner2590e512006-02-07 06:56:34 +00001247 break;
1248 }
Chris Lattner0157e7f2006-02-11 09:31:47 +00001249
1250 // If the client is only demanding bits that we know, return the known
1251 // constant.
1252 if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask)
1253 return UpdateValueUsesWith(I, GetConstantInType(I->getType(), KnownOne));
Chris Lattner2590e512006-02-07 06:56:34 +00001254 return false;
1255}
1256
Chris Lattner2deeaea2006-10-05 06:55:50 +00001257
1258/// SimplifyDemandedVectorElts - The specified value producecs a vector with
1259/// 64 or fewer elements. DemandedElts contains the set of elements that are
1260/// actually used by the caller. This method analyzes which elements of the
1261/// operand are undef and returns that information in UndefElts.
1262///
1263/// If the information about demanded elements can be used to simplify the
1264/// operation, the operation is simplified, then the resultant value is
1265/// returned. This returns null if no change was made.
1266Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1267 uint64_t &UndefElts,
1268 unsigned Depth) {
1269 unsigned VWidth = cast<PackedType>(V->getType())->getNumElements();
1270 assert(VWidth <= 64 && "Vector too wide to analyze!");
1271 uint64_t EltMask = ~0ULL >> (64-VWidth);
1272 assert(DemandedElts != EltMask && (DemandedElts & ~EltMask) == 0 &&
1273 "Invalid DemandedElts!");
1274
1275 if (isa<UndefValue>(V)) {
1276 // If the entire vector is undefined, just return this info.
1277 UndefElts = EltMask;
1278 return 0;
1279 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1280 UndefElts = EltMask;
1281 return UndefValue::get(V->getType());
1282 }
1283
1284 UndefElts = 0;
1285 if (ConstantPacked *CP = dyn_cast<ConstantPacked>(V)) {
1286 const Type *EltTy = cast<PackedType>(V->getType())->getElementType();
1287 Constant *Undef = UndefValue::get(EltTy);
1288
1289 std::vector<Constant*> Elts;
1290 for (unsigned i = 0; i != VWidth; ++i)
1291 if (!(DemandedElts & (1ULL << i))) { // If not demanded, set to undef.
1292 Elts.push_back(Undef);
1293 UndefElts |= (1ULL << i);
1294 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1295 Elts.push_back(Undef);
1296 UndefElts |= (1ULL << i);
1297 } else { // Otherwise, defined.
1298 Elts.push_back(CP->getOperand(i));
1299 }
1300
1301 // If we changed the constant, return it.
1302 Constant *NewCP = ConstantPacked::get(Elts);
1303 return NewCP != CP ? NewCP : 0;
1304 } else if (isa<ConstantAggregateZero>(V)) {
1305 // Simplify the CAZ to a ConstantPacked where the non-demanded elements are
1306 // set to undef.
1307 const Type *EltTy = cast<PackedType>(V->getType())->getElementType();
1308 Constant *Zero = Constant::getNullValue(EltTy);
1309 Constant *Undef = UndefValue::get(EltTy);
1310 std::vector<Constant*> Elts;
1311 for (unsigned i = 0; i != VWidth; ++i)
1312 Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1313 UndefElts = DemandedElts ^ EltMask;
1314 return ConstantPacked::get(Elts);
1315 }
1316
1317 if (!V->hasOneUse()) { // Other users may use these bits.
1318 if (Depth != 0) { // Not at the root.
1319 // TODO: Just compute the UndefElts information recursively.
1320 return false;
1321 }
1322 return false;
1323 } else if (Depth == 10) { // Limit search depth.
1324 return false;
1325 }
1326
1327 Instruction *I = dyn_cast<Instruction>(V);
1328 if (!I) return false; // Only analyze instructions.
1329
1330 bool MadeChange = false;
1331 uint64_t UndefElts2;
1332 Value *TmpV;
1333 switch (I->getOpcode()) {
1334 default: break;
1335
1336 case Instruction::InsertElement: {
1337 // If this is a variable index, we don't know which element it overwrites.
1338 // demand exactly the same input as we produce.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001339 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
Chris Lattner2deeaea2006-10-05 06:55:50 +00001340 if (Idx == 0) {
1341 // Note that we can't propagate undef elt info, because we don't know
1342 // which elt is getting updated.
1343 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1344 UndefElts2, Depth+1);
1345 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1346 break;
1347 }
1348
1349 // If this is inserting an element that isn't demanded, remove this
1350 // insertelement.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001351 unsigned IdxNo = Idx->getZExtValue();
Chris Lattner2deeaea2006-10-05 06:55:50 +00001352 if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1353 return AddSoonDeadInstToWorklist(*I, 0);
1354
1355 // Otherwise, the element inserted overwrites whatever was there, so the
1356 // input demanded set is simpler than the output set.
1357 TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1358 DemandedElts & ~(1ULL << IdxNo),
1359 UndefElts, Depth+1);
1360 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1361
1362 // The inserted element is defined.
1363 UndefElts |= 1ULL << IdxNo;
1364 break;
1365 }
1366
1367 case Instruction::And:
1368 case Instruction::Or:
1369 case Instruction::Xor:
1370 case Instruction::Add:
1371 case Instruction::Sub:
1372 case Instruction::Mul:
1373 // div/rem demand all inputs, because they don't want divide by zero.
1374 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1375 UndefElts, Depth+1);
1376 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1377 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1378 UndefElts2, Depth+1);
1379 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1380
1381 // Output elements are undefined if both are undefined. Consider things
1382 // like undef&0. The result is known zero, not undef.
1383 UndefElts &= UndefElts2;
1384 break;
1385
1386 case Instruction::Call: {
1387 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1388 if (!II) break;
1389 switch (II->getIntrinsicID()) {
1390 default: break;
1391
1392 // Binary vector operations that work column-wise. A dest element is a
1393 // function of the corresponding input elements from the two inputs.
1394 case Intrinsic::x86_sse_sub_ss:
1395 case Intrinsic::x86_sse_mul_ss:
1396 case Intrinsic::x86_sse_min_ss:
1397 case Intrinsic::x86_sse_max_ss:
1398 case Intrinsic::x86_sse2_sub_sd:
1399 case Intrinsic::x86_sse2_mul_sd:
1400 case Intrinsic::x86_sse2_min_sd:
1401 case Intrinsic::x86_sse2_max_sd:
1402 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1403 UndefElts, Depth+1);
1404 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1405 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1406 UndefElts2, Depth+1);
1407 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1408
1409 // If only the low elt is demanded and this is a scalarizable intrinsic,
1410 // scalarize it now.
1411 if (DemandedElts == 1) {
1412 switch (II->getIntrinsicID()) {
1413 default: break;
1414 case Intrinsic::x86_sse_sub_ss:
1415 case Intrinsic::x86_sse_mul_ss:
1416 case Intrinsic::x86_sse2_sub_sd:
1417 case Intrinsic::x86_sse2_mul_sd:
1418 // TODO: Lower MIN/MAX/ABS/etc
1419 Value *LHS = II->getOperand(1);
1420 Value *RHS = II->getOperand(2);
1421 // Extract the element as scalars.
1422 LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1423 RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1424
1425 switch (II->getIntrinsicID()) {
1426 default: assert(0 && "Case stmts out of sync!");
1427 case Intrinsic::x86_sse_sub_ss:
1428 case Intrinsic::x86_sse2_sub_sd:
1429 TmpV = InsertNewInstBefore(BinaryOperator::createSub(LHS, RHS,
1430 II->getName()), *II);
1431 break;
1432 case Intrinsic::x86_sse_mul_ss:
1433 case Intrinsic::x86_sse2_mul_sd:
1434 TmpV = InsertNewInstBefore(BinaryOperator::createMul(LHS, RHS,
1435 II->getName()), *II);
1436 break;
1437 }
1438
1439 Instruction *New =
1440 new InsertElementInst(UndefValue::get(II->getType()), TmpV, 0U,
1441 II->getName());
1442 InsertNewInstBefore(New, *II);
1443 AddSoonDeadInstToWorklist(*II, 0);
1444 return New;
1445 }
1446 }
1447
1448 // Output elements are undefined if both are undefined. Consider things
1449 // like undef&0. The result is known zero, not undef.
1450 UndefElts &= UndefElts2;
1451 break;
1452 }
1453 break;
1454 }
1455 }
1456 return MadeChange ? I : 0;
1457}
1458
Reid Spencer266e42b2006-12-23 06:05:41 +00001459/// @returns true if the specified compare instruction is
1460/// true when both operands are equal...
1461/// @brief Determine if the ICmpInst returns true if both operands are equal
1462static bool isTrueWhenEqual(ICmpInst &ICI) {
1463 ICmpInst::Predicate pred = ICI.getPredicate();
1464 return pred == ICmpInst::ICMP_EQ || pred == ICmpInst::ICMP_UGE ||
1465 pred == ICmpInst::ICMP_SGE || pred == ICmpInst::ICMP_ULE ||
1466 pred == ICmpInst::ICMP_SLE;
1467}
1468
1469/// @returns true if the specified compare instruction is
1470/// true when both operands are equal...
1471/// @brief Determine if the FCmpInst returns true if both operands are equal
1472static bool isTrueWhenEqual(FCmpInst &FCI) {
1473 FCmpInst::Predicate pred = FCI.getPredicate();
1474 return pred == FCmpInst::FCMP_OEQ || pred == FCmpInst::FCMP_UEQ ||
1475 pred == FCmpInst::FCMP_OGE || pred == FCmpInst::FCMP_UGE ||
1476 pred == FCmpInst::FCMP_OLE || pred == FCmpInst::FCMP_ULE;
Chris Lattner623826c2004-09-28 21:48:02 +00001477}
Chris Lattnerb8b97502003-08-13 19:01:45 +00001478
1479/// AssociativeOpt - Perform an optimization on an associative operator. This
1480/// function is designed to check a chain of associative operators for a
1481/// potential to apply a certain optimization. Since the optimization may be
1482/// applicable if the expression was reassociated, this checks the chain, then
1483/// reassociates the expression as necessary to expose the optimization
1484/// opportunity. This makes use of a special Functor, which must define
1485/// 'shouldApply' and 'apply' methods.
1486///
1487template<typename Functor>
1488Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1489 unsigned Opcode = Root.getOpcode();
1490 Value *LHS = Root.getOperand(0);
1491
1492 // Quick check, see if the immediate LHS matches...
1493 if (F.shouldApply(LHS))
1494 return F.apply(Root);
1495
1496 // Otherwise, if the LHS is not of the same opcode as the root, return.
1497 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001498 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattnerb8b97502003-08-13 19:01:45 +00001499 // Should we apply this transform to the RHS?
1500 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1501
1502 // If not to the RHS, check to see if we should apply to the LHS...
1503 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1504 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1505 ShouldApply = true;
1506 }
1507
1508 // If the functor wants to apply the optimization to the RHS of LHSI,
1509 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1510 if (ShouldApply) {
1511 BasicBlock *BB = Root.getParent();
Misha Brukmanb1c93172005-04-21 23:48:37 +00001512
Chris Lattnerb8b97502003-08-13 19:01:45 +00001513 // Now all of the instructions are in the current basic block, go ahead
1514 // and perform the reassociation.
1515 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1516
1517 // First move the selected RHS to the LHS of the root...
1518 Root.setOperand(0, LHSI->getOperand(1));
1519
1520 // Make what used to be the LHS of the root be the user of the root...
1521 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner284d3b02004-04-16 18:08:07 +00001522 if (&Root == TmpLHSI) {
Chris Lattner8953b902004-04-05 02:10:19 +00001523 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1524 return 0;
1525 }
Chris Lattner284d3b02004-04-16 18:08:07 +00001526 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattnerb8b97502003-08-13 19:01:45 +00001527 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner284d3b02004-04-16 18:08:07 +00001528 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
1529 BasicBlock::iterator ARI = &Root; ++ARI;
1530 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
1531 ARI = Root;
Chris Lattnerb8b97502003-08-13 19:01:45 +00001532
1533 // Now propagate the ExtraOperand down the chain of instructions until we
1534 // get to LHSI.
1535 while (TmpLHSI != LHSI) {
1536 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner284d3b02004-04-16 18:08:07 +00001537 // Move the instruction to immediately before the chain we are
1538 // constructing to avoid breaking dominance properties.
1539 NextLHSI->getParent()->getInstList().remove(NextLHSI);
1540 BB->getInstList().insert(ARI, NextLHSI);
1541 ARI = NextLHSI;
1542
Chris Lattnerb8b97502003-08-13 19:01:45 +00001543 Value *NextOp = NextLHSI->getOperand(1);
1544 NextLHSI->setOperand(1, ExtraOperand);
1545 TmpLHSI = NextLHSI;
1546 ExtraOperand = NextOp;
1547 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001548
Chris Lattnerb8b97502003-08-13 19:01:45 +00001549 // Now that the instructions are reassociated, have the functor perform
1550 // the transformation...
1551 return F.apply(Root);
1552 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001553
Chris Lattnerb8b97502003-08-13 19:01:45 +00001554 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1555 }
1556 return 0;
1557}
1558
1559
1560// AddRHS - Implements: X + X --> X << 1
1561struct AddRHS {
1562 Value *RHS;
1563 AddRHS(Value *rhs) : RHS(rhs) {}
1564 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1565 Instruction *apply(BinaryOperator &Add) const {
1566 return new ShiftInst(Instruction::Shl, Add.getOperand(0),
Reid Spencerc635f472006-12-31 05:48:39 +00001567 ConstantInt::get(Type::Int8Ty, 1));
Chris Lattnerb8b97502003-08-13 19:01:45 +00001568 }
1569};
1570
1571// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1572// iff C1&C2 == 0
1573struct AddMaskingAnd {
1574 Constant *C2;
1575 AddMaskingAnd(Constant *c) : C2(c) {}
1576 bool shouldApply(Value *LHS) const {
Chris Lattnerd4252a72004-07-30 07:50:03 +00001577 ConstantInt *C1;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001578 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Chris Lattnerd4252a72004-07-30 07:50:03 +00001579 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattnerb8b97502003-08-13 19:01:45 +00001580 }
1581 Instruction *apply(BinaryOperator &Add) const {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001582 return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattnerb8b97502003-08-13 19:01:45 +00001583 }
1584};
1585
Chris Lattner86102b82005-01-01 16:22:27 +00001586static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner183b3362004-04-09 19:05:30 +00001587 InstCombiner *IC) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001588 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
Chris Lattner86102b82005-01-01 16:22:27 +00001589 if (Constant *SOC = dyn_cast<Constant>(SO))
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001590 return ConstantExpr::getCast(CI->getOpcode(), SOC, I.getType());
Misha Brukmanb1c93172005-04-21 23:48:37 +00001591
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001592 return IC->InsertNewInstBefore(CastInst::create(
1593 CI->getOpcode(), SO, I.getType(), SO->getName() + ".cast"), I);
Chris Lattner86102b82005-01-01 16:22:27 +00001594 }
1595
Chris Lattner183b3362004-04-09 19:05:30 +00001596 // Figure out if the constant is the left or the right argument.
Chris Lattner86102b82005-01-01 16:22:27 +00001597 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1598 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattnerb8b97502003-08-13 19:01:45 +00001599
Chris Lattner183b3362004-04-09 19:05:30 +00001600 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1601 if (ConstIsRHS)
Chris Lattner86102b82005-01-01 16:22:27 +00001602 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1603 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner183b3362004-04-09 19:05:30 +00001604 }
1605
1606 Value *Op0 = SO, *Op1 = ConstOperand;
1607 if (!ConstIsRHS)
1608 std::swap(Op0, Op1);
1609 Instruction *New;
Chris Lattner86102b82005-01-01 16:22:27 +00001610 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1611 New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
Reid Spencer266e42b2006-12-23 06:05:41 +00001612 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1613 New = CmpInst::create(CI->getOpcode(), CI->getPredicate(), Op0, Op1,
1614 SO->getName()+".cmp");
Chris Lattner86102b82005-01-01 16:22:27 +00001615 else if (ShiftInst *SI = dyn_cast<ShiftInst>(&I))
1616 New = new ShiftInst(SI->getOpcode(), Op0, Op1, SO->getName()+".sh");
Chris Lattnerf9d96652004-04-10 19:15:56 +00001617 else {
Chris Lattner183b3362004-04-09 19:05:30 +00001618 assert(0 && "Unknown binary instruction type!");
Chris Lattnerf9d96652004-04-10 19:15:56 +00001619 abort();
1620 }
Chris Lattner86102b82005-01-01 16:22:27 +00001621 return IC->InsertNewInstBefore(New, I);
1622}
1623
1624// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1625// constant as the other operand, try to fold the binary operator into the
1626// select arguments. This also works for Cast instructions, which obviously do
1627// not have a second operand.
1628static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1629 InstCombiner *IC) {
1630 // Don't modify shared select instructions
1631 if (!SI->hasOneUse()) return 0;
1632 Value *TV = SI->getOperand(1);
1633 Value *FV = SI->getOperand(2);
1634
1635 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner374e6592005-04-21 05:43:13 +00001636 // Bool selects with constant operands can be folded to logical ops.
1637 if (SI->getType() == Type::BoolTy) return 0;
1638
Chris Lattner86102b82005-01-01 16:22:27 +00001639 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1640 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1641
1642 return new SelectInst(SI->getCondition(), SelectTrueVal,
1643 SelectFalseVal);
1644 }
1645 return 0;
Chris Lattner183b3362004-04-09 19:05:30 +00001646}
1647
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001648
1649/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1650/// node as operand #0, see if we can fold the instruction into the PHI (which
1651/// is only possible if all operands to the PHI are constants).
1652Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1653 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattner7515cab2004-11-14 19:13:23 +00001654 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner04689872006-09-09 22:02:56 +00001655 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001656
Chris Lattner04689872006-09-09 22:02:56 +00001657 // Check to see if all of the operands of the PHI are constants. If there is
1658 // one non-constant value, remember the BB it is. If there is more than one
1659 // bail out.
1660 BasicBlock *NonConstBB = 0;
1661 for (unsigned i = 0; i != NumPHIValues; ++i)
1662 if (!isa<Constant>(PN->getIncomingValue(i))) {
1663 if (NonConstBB) return 0; // More than one non-const value.
1664 NonConstBB = PN->getIncomingBlock(i);
1665
1666 // If the incoming non-constant value is in I's block, we have an infinite
1667 // loop.
1668 if (NonConstBB == I.getParent())
1669 return 0;
1670 }
1671
1672 // If there is exactly one non-constant value, we can insert a copy of the
1673 // operation in that block. However, if this is a critical edge, we would be
1674 // inserting the computation one some other paths (e.g. inside a loop). Only
1675 // do this if the pred block is unconditionally branching into the phi block.
1676 if (NonConstBB) {
1677 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1678 if (!BI || !BI->isUnconditional()) return 0;
1679 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001680
1681 // Okay, we can do the transformation: create the new PHI node.
1682 PHINode *NewPN = new PHINode(I.getType(), I.getName());
1683 I.setName("");
Chris Lattnerd8e20182005-01-29 00:39:08 +00001684 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001685 InsertNewInstBefore(NewPN, *PN);
1686
1687 // Next, add all of the operands to the PHI.
1688 if (I.getNumOperands() == 2) {
1689 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattner7515cab2004-11-14 19:13:23 +00001690 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner04689872006-09-09 22:02:56 +00001691 Value *InV;
1692 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencer266e42b2006-12-23 06:05:41 +00001693 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1694 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
1695 else
1696 InV = ConstantExpr::get(I.getOpcode(), InC, C);
Chris Lattner04689872006-09-09 22:02:56 +00001697 } else {
1698 assert(PN->getIncomingBlock(i) == NonConstBB);
1699 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1700 InV = BinaryOperator::create(BO->getOpcode(),
1701 PN->getIncomingValue(i), C, "phitmp",
1702 NonConstBB->getTerminator());
Reid Spencer266e42b2006-12-23 06:05:41 +00001703 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1704 InV = CmpInst::create(CI->getOpcode(),
1705 CI->getPredicate(),
1706 PN->getIncomingValue(i), C, "phitmp",
1707 NonConstBB->getTerminator());
Chris Lattner04689872006-09-09 22:02:56 +00001708 else if (ShiftInst *SI = dyn_cast<ShiftInst>(&I))
1709 InV = new ShiftInst(SI->getOpcode(),
1710 PN->getIncomingValue(i), C, "phitmp",
1711 NonConstBB->getTerminator());
1712 else
1713 assert(0 && "Unknown binop!");
1714
1715 WorkList.push_back(cast<Instruction>(InV));
1716 }
1717 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001718 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001719 } else {
1720 CastInst *CI = cast<CastInst>(&I);
1721 const Type *RetTy = CI->getType();
Chris Lattner7515cab2004-11-14 19:13:23 +00001722 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner04689872006-09-09 22:02:56 +00001723 Value *InV;
1724 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001725 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Chris Lattner04689872006-09-09 22:02:56 +00001726 } else {
1727 assert(PN->getIncomingBlock(i) == NonConstBB);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001728 InV = CastInst::create(CI->getOpcode(), PN->getIncomingValue(i),
1729 I.getType(), "phitmp",
1730 NonConstBB->getTerminator());
Chris Lattner04689872006-09-09 22:02:56 +00001731 WorkList.push_back(cast<Instruction>(InV));
1732 }
1733 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001734 }
1735 }
1736 return ReplaceInstUsesWith(I, NewPN);
1737}
1738
Chris Lattner113f4f42002-06-25 16:13:24 +00001739Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001740 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00001741 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattner9fa53de2002-05-06 16:49:18 +00001742
Chris Lattnercf4a9962004-04-10 22:01:55 +00001743 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattner81a7a232004-10-16 18:11:37 +00001744 // X + undef -> undef
1745 if (isa<UndefValue>(RHS))
1746 return ReplaceInstUsesWith(I, RHS);
1747
Chris Lattnercf4a9962004-04-10 22:01:55 +00001748 // X + 0 --> X
Chris Lattner7a002fe2006-12-02 00:13:08 +00001749 if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
Chris Lattner7fde91e2005-10-17 17:56:38 +00001750 if (RHSC->isNullValue())
1751 return ReplaceInstUsesWith(I, LHS);
Chris Lattnerda1b1522005-10-17 20:18:38 +00001752 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
1753 if (CFP->isExactlyValue(-0.0))
1754 return ReplaceInstUsesWith(I, LHS);
Chris Lattner7fde91e2005-10-17 17:56:38 +00001755 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001756
Chris Lattnercf4a9962004-04-10 22:01:55 +00001757 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattner6e2c15c2006-11-09 05:12:27 +00001758 // X + (signbit) --> X ^ signbit
Chris Lattner92a68652006-02-07 08:05:22 +00001759 uint64_t Val = CI->getZExtValue();
Chris Lattner77defba2006-02-07 07:00:41 +00001760 if (Val == (1ULL << (CI->getType()->getPrimitiveSizeInBits()-1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001761 return BinaryOperator::createXor(LHS, RHS);
Chris Lattner6e2c15c2006-11-09 05:12:27 +00001762
1763 // See if SimplifyDemandedBits can simplify this. This handles stuff like
1764 // (X & 254)+1 -> (X&254)|1
1765 uint64_t KnownZero, KnownOne;
1766 if (!isa<PackedType>(I.getType()) &&
1767 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
1768 KnownZero, KnownOne))
1769 return &I;
Chris Lattnercf4a9962004-04-10 22:01:55 +00001770 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001771
1772 if (isa<PHINode>(LHS))
1773 if (Instruction *NV = FoldOpIntoPhi(I))
1774 return NV;
Chris Lattner0b3557f2005-09-24 23:43:33 +00001775
Chris Lattner330628a2006-01-06 17:59:59 +00001776 ConstantInt *XorRHS = 0;
1777 Value *XorLHS = 0;
Chris Lattner0b3557f2005-09-24 23:43:33 +00001778 if (match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
1779 unsigned TySizeBits = I.getType()->getPrimitiveSizeInBits();
1780 int64_t RHSSExt = cast<ConstantInt>(RHSC)->getSExtValue();
1781 uint64_t RHSZExt = cast<ConstantInt>(RHSC)->getZExtValue();
1782
1783 uint64_t C0080Val = 1ULL << 31;
1784 int64_t CFF80Val = -C0080Val;
1785 unsigned Size = 32;
1786 do {
1787 if (TySizeBits > Size) {
1788 bool Found = false;
1789 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
1790 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
1791 if (RHSSExt == CFF80Val) {
1792 if (XorRHS->getZExtValue() == C0080Val)
1793 Found = true;
1794 } else if (RHSZExt == C0080Val) {
1795 if (XorRHS->getSExtValue() == CFF80Val)
1796 Found = true;
1797 }
1798 if (Found) {
1799 // This is a sign extend if the top bits are known zero.
Chris Lattner4534dd592006-02-09 07:38:58 +00001800 uint64_t Mask = ~0ULL;
Chris Lattnerc3ebf402006-02-07 07:27:52 +00001801 Mask <<= 64-(TySizeBits-Size);
Chris Lattner4534dd592006-02-09 07:38:58 +00001802 Mask &= XorLHS->getType()->getIntegralTypeMask();
Chris Lattnerc3ebf402006-02-07 07:27:52 +00001803 if (!MaskedValueIsZero(XorLHS, Mask))
Chris Lattner0b3557f2005-09-24 23:43:33 +00001804 Size = 0; // Not a sign ext, but can't be any others either.
1805 goto FoundSExt;
1806 }
1807 }
1808 Size >>= 1;
1809 C0080Val >>= Size;
1810 CFF80Val >>= Size;
1811 } while (Size >= 8);
1812
1813FoundSExt:
1814 const Type *MiddleType = 0;
1815 switch (Size) {
1816 default: break;
Reid Spencerc635f472006-12-31 05:48:39 +00001817 case 32: MiddleType = Type::Int32Ty; break;
1818 case 16: MiddleType = Type::Int16Ty; break;
1819 case 8: MiddleType = Type::Int8Ty; break;
Chris Lattner0b3557f2005-09-24 23:43:33 +00001820 }
1821 if (MiddleType) {
Reid Spencerbb65ebf2006-12-12 23:36:14 +00001822 Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
Chris Lattner0b3557f2005-09-24 23:43:33 +00001823 InsertNewInstBefore(NewTrunc, I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001824 return new SExtInst(NewTrunc, I.getType());
Chris Lattner0b3557f2005-09-24 23:43:33 +00001825 }
1826 }
Chris Lattnercf4a9962004-04-10 22:01:55 +00001827 }
Chris Lattner9fa53de2002-05-06 16:49:18 +00001828
Chris Lattnerb8b97502003-08-13 19:01:45 +00001829 // X + X --> X << 1
Robert Bocchino7b5b86c2004-07-27 21:02:21 +00001830 if (I.getType()->isInteger()) {
Chris Lattnerb8b97502003-08-13 19:01:45 +00001831 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Chris Lattner47060462005-04-07 17:14:51 +00001832
1833 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
1834 if (RHSI->getOpcode() == Instruction::Sub)
1835 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
1836 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
1837 }
1838 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
1839 if (LHSI->getOpcode() == Instruction::Sub)
1840 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
1841 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
1842 }
Robert Bocchino7b5b86c2004-07-27 21:02:21 +00001843 }
Chris Lattnerede3fe02003-08-13 04:18:28 +00001844
Chris Lattner147e9752002-05-08 22:46:53 +00001845 // -A + B --> B - A
Chris Lattnerbb74e222003-03-10 23:06:50 +00001846 if (Value *V = dyn_castNegVal(LHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001847 return BinaryOperator::createSub(RHS, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +00001848
1849 // A + -B --> A - B
Chris Lattnerbb74e222003-03-10 23:06:50 +00001850 if (!isa<Constant>(RHS))
1851 if (Value *V = dyn_castNegVal(RHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001852 return BinaryOperator::createSub(LHS, V);
Chris Lattner260ab202002-04-18 17:39:14 +00001853
Misha Brukmanb1c93172005-04-21 23:48:37 +00001854
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001855 ConstantInt *C2;
1856 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
1857 if (X == RHS) // X*C + X --> X * (C+1)
1858 return BinaryOperator::createMul(RHS, AddOne(C2));
1859
1860 // X*C1 + X*C2 --> X * (C1+C2)
1861 ConstantInt *C1;
1862 if (X == dyn_castFoldableMul(RHS, C1))
1863 return BinaryOperator::createMul(X, ConstantExpr::getAdd(C1, C2));
Chris Lattner57c8d992003-02-18 19:57:07 +00001864 }
1865
1866 // X + X*C --> X * (C+1)
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001867 if (dyn_castFoldableMul(RHS, C2) == LHS)
1868 return BinaryOperator::createMul(LHS, AddOne(C2));
1869
Chris Lattner23eb8ec2007-01-05 02:17:46 +00001870 // X + ~X --> -1 since ~X = -X-1
1871 if (dyn_castNotVal(LHS) == RHS ||
1872 dyn_castNotVal(RHS) == LHS)
1873 return ReplaceInstUsesWith(I, ConstantInt::getAllOnesValue(I.getType()));
1874
Chris Lattner57c8d992003-02-18 19:57:07 +00001875
Chris Lattnerb8b97502003-08-13 19:01:45 +00001876 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattnerd4252a72004-07-30 07:50:03 +00001877 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattner23eb8ec2007-01-05 02:17:46 +00001878 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
1879 return R;
Chris Lattner7fb29e12003-03-11 00:12:48 +00001880
Chris Lattnerb9cde762003-10-02 15:11:26 +00001881 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner330628a2006-01-06 17:59:59 +00001882 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00001883 if (match(LHS, m_Not(m_Value(X)))) { // ~X + C --> (C-1) - X
1884 Constant *C= ConstantExpr::getSub(CRHS, ConstantInt::get(I.getType(), 1));
1885 return BinaryOperator::createSub(C, X);
Chris Lattnerb9cde762003-10-02 15:11:26 +00001886 }
Chris Lattnerd4252a72004-07-30 07:50:03 +00001887
Chris Lattnerbff91d92004-10-08 05:07:56 +00001888 // (X & FF00) + xx00 -> (X+xx00) & FF00
1889 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
1890 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
1891 if (Anded == CRHS) {
1892 // See if all bits from the first bit set in the Add RHS up are included
1893 // in the mask. First, get the rightmost bit.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001894 uint64_t AddRHSV = CRHS->getZExtValue();
Chris Lattnerbff91d92004-10-08 05:07:56 +00001895
1896 // Form a mask of all bits from the lowest bit added through the top.
1897 uint64_t AddRHSHighBits = ~((AddRHSV & -AddRHSV)-1);
Chris Lattner77defba2006-02-07 07:00:41 +00001898 AddRHSHighBits &= C2->getType()->getIntegralTypeMask();
Chris Lattnerbff91d92004-10-08 05:07:56 +00001899
1900 // See if the and mask includes all of these bits.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001901 uint64_t AddRHSHighBitsAnd = AddRHSHighBits & C2->getZExtValue();
Misha Brukmanb1c93172005-04-21 23:48:37 +00001902
Chris Lattnerbff91d92004-10-08 05:07:56 +00001903 if (AddRHSHighBits == AddRHSHighBitsAnd) {
1904 // Okay, the xform is safe. Insert the new add pronto.
1905 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
1906 LHS->getName()), I);
1907 return BinaryOperator::createAnd(NewAdd, C2);
1908 }
1909 }
1910 }
1911
Chris Lattnerd4252a72004-07-30 07:50:03 +00001912 // Try to fold constant add into select arguments.
1913 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner86102b82005-01-01 16:22:27 +00001914 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattnerd4252a72004-07-30 07:50:03 +00001915 return R;
Chris Lattnerb9cde762003-10-02 15:11:26 +00001916 }
1917
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001918 // add (cast *A to intptrtype) B ->
1919 // cast (GEP (cast *A to sbyte*) B) ->
1920 // intptrtype
Andrew Lenharth4f339be2006-09-19 18:24:51 +00001921 {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001922 CastInst *CI = dyn_cast<CastInst>(LHS);
1923 Value *Other = RHS;
Andrew Lenharth4f339be2006-09-19 18:24:51 +00001924 if (!CI) {
1925 CI = dyn_cast<CastInst>(RHS);
1926 Other = LHS;
1927 }
Andrew Lenharth44cb67a2006-09-20 15:37:57 +00001928 if (CI && CI->getType()->isSized() &&
1929 (CI->getType()->getPrimitiveSize() ==
1930 TD->getIntPtrType()->getPrimitiveSize())
1931 && isa<PointerType>(CI->getOperand(0)->getType())) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00001932 Value *I2 = InsertCastBefore(Instruction::BitCast, CI->getOperand(0),
Reid Spencerc635f472006-12-31 05:48:39 +00001933 PointerType::get(Type::Int8Ty), I);
Andrew Lenharth44cb67a2006-09-20 15:37:57 +00001934 I2 = InsertNewInstBefore(new GetElementPtrInst(I2, Other, "ctg2"), I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001935 return new PtrToIntInst(I2, CI->getType());
Andrew Lenharth4f339be2006-09-19 18:24:51 +00001936 }
1937 }
1938
Chris Lattner113f4f42002-06-25 16:13:24 +00001939 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +00001940}
1941
Chris Lattnerbdb0ce02003-07-22 21:46:59 +00001942// isSignBit - Return true if the value represented by the constant only has the
1943// highest order bit set.
1944static bool isSignBit(ConstantInt *CI) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001945 unsigned NumBits = CI->getType()->getPrimitiveSizeInBits();
Reid Spencere0fc4df2006-10-20 07:07:24 +00001946 return (CI->getZExtValue() & (~0ULL >> (64-NumBits))) == (1ULL << (NumBits-1));
Chris Lattnerbdb0ce02003-07-22 21:46:59 +00001947}
1948
Chris Lattner022167f2004-03-13 00:11:49 +00001949/// RemoveNoopCast - Strip off nonconverting casts from the value.
1950///
1951static Value *RemoveNoopCast(Value *V) {
1952 if (CastInst *CI = dyn_cast<CastInst>(V)) {
1953 const Type *CTy = CI->getType();
1954 const Type *OpTy = CI->getOperand(0)->getType();
1955 if (CTy->isInteger() && OpTy->isInteger()) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001956 if (CTy->getPrimitiveSizeInBits() == OpTy->getPrimitiveSizeInBits())
Chris Lattner022167f2004-03-13 00:11:49 +00001957 return RemoveNoopCast(CI->getOperand(0));
1958 } else if (isa<PointerType>(CTy) && isa<PointerType>(OpTy))
1959 return RemoveNoopCast(CI->getOperand(0));
1960 }
1961 return V;
1962}
1963
Chris Lattner113f4f42002-06-25 16:13:24 +00001964Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +00001965 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001966
Chris Lattnere6794492002-08-12 21:17:25 +00001967 if (Op0 == Op1) // sub X, X -> 0
1968 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner260ab202002-04-18 17:39:14 +00001969
Chris Lattnere6794492002-08-12 21:17:25 +00001970 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattnerbb74e222003-03-10 23:06:50 +00001971 if (Value *V = dyn_castNegVal(Op1))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001972 return BinaryOperator::createAdd(Op0, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +00001973
Chris Lattner81a7a232004-10-16 18:11:37 +00001974 if (isa<UndefValue>(Op0))
1975 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
1976 if (isa<UndefValue>(Op1))
1977 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
1978
Chris Lattner8f2f5982003-11-05 01:06:05 +00001979 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
1980 // Replace (-1 - A) with (~A)...
Chris Lattner3082c5a2003-02-18 19:28:33 +00001981 if (C->isAllOnesValue())
1982 return BinaryOperator::createNot(Op1);
Chris Lattnerad3c4952002-05-09 01:29:19 +00001983
Chris Lattner8f2f5982003-11-05 01:06:05 +00001984 // C - ~X == X + (1+C)
Reid Spencer4fdd96c2005-06-18 17:37:34 +00001985 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00001986 if (match(Op1, m_Not(m_Value(X))))
1987 return BinaryOperator::createAdd(X,
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001988 ConstantExpr::getAdd(C, ConstantInt::get(I.getType(), 1)));
Chris Lattner92295c52004-03-12 23:53:13 +00001989 // -((uint)X >> 31) -> ((int)X >> 31)
1990 // -((int)X >> 31) -> ((uint)X >> 31)
Chris Lattner022167f2004-03-13 00:11:49 +00001991 if (C->isNullValue()) {
1992 Value *NoopCastedRHS = RemoveNoopCast(Op1);
1993 if (ShiftInst *SI = dyn_cast<ShiftInst>(NoopCastedRHS))
Reid Spencerfdff9382006-11-08 06:47:33 +00001994 if (SI->getOpcode() == Instruction::LShr) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00001995 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
Chris Lattner92295c52004-03-12 23:53:13 +00001996 // Check to see if we are shifting out everything but the sign bit.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001997 if (CU->getZExtValue() ==
1998 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerfdff9382006-11-08 06:47:33 +00001999 // Ok, the transformation is safe. Insert AShr.
Reid Spencer193df252006-12-24 00:40:59 +00002000 // FIXME: Once integer types are signless, this cast should be
2001 // removed.
2002 Value *ShiftOp = SI->getOperand(0);
Reid Spencer193df252006-12-24 00:40:59 +00002003 return new ShiftInst(Instruction::AShr, ShiftOp, CU,
2004 SI->getName());
Chris Lattner92295c52004-03-12 23:53:13 +00002005 }
2006 }
Reid Spencerfdff9382006-11-08 06:47:33 +00002007 }
2008 else if (SI->getOpcode() == Instruction::AShr) {
2009 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2010 // Check to see if we are shifting out everything but the sign bit.
2011 if (CU->getZExtValue() ==
2012 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerc635f472006-12-31 05:48:39 +00002013
2014 // Ok, the transformation is safe. Insert LShr.
2015 return new ShiftInst(Instruction::LShr, SI->getOperand(0), CU,
2016 SI->getName());
Reid Spencerfdff9382006-11-08 06:47:33 +00002017 }
2018 }
2019 }
Chris Lattner022167f2004-03-13 00:11:49 +00002020 }
Chris Lattner183b3362004-04-09 19:05:30 +00002021
2022 // Try to fold constant sub into select arguments.
2023 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner86102b82005-01-01 16:22:27 +00002024 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00002025 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002026
2027 if (isa<PHINode>(Op0))
2028 if (Instruction *NV = FoldOpIntoPhi(I))
2029 return NV;
Chris Lattner8f2f5982003-11-05 01:06:05 +00002030 }
2031
Chris Lattnera9be4492005-04-07 16:15:25 +00002032 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2033 if (Op1I->getOpcode() == Instruction::Add &&
Chris Lattner7a002fe2006-12-02 00:13:08 +00002034 !Op0->getType()->isFPOrFPVector()) {
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00002035 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Chris Lattnera9be4492005-04-07 16:15:25 +00002036 return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00002037 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Chris Lattnera9be4492005-04-07 16:15:25 +00002038 return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00002039 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2040 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2041 // C1-(X+C2) --> (C1-C2)-X
2042 return BinaryOperator::createSub(ConstantExpr::getSub(CI1, CI2),
2043 Op1I->getOperand(0));
2044 }
Chris Lattnera9be4492005-04-07 16:15:25 +00002045 }
2046
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002047 if (Op1I->hasOneUse()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00002048 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2049 // is not used by anyone else...
2050 //
Chris Lattnerc2f0aa52004-02-02 20:09:56 +00002051 if (Op1I->getOpcode() == Instruction::Sub &&
Chris Lattner7a002fe2006-12-02 00:13:08 +00002052 !Op1I->getType()->isFPOrFPVector()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00002053 // Swap the two operands of the subexpr...
2054 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2055 Op1I->setOperand(0, IIOp1);
2056 Op1I->setOperand(1, IIOp0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002057
Chris Lattner3082c5a2003-02-18 19:28:33 +00002058 // Create the new top level add instruction...
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002059 return BinaryOperator::createAdd(Op0, Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002060 }
2061
2062 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2063 //
2064 if (Op1I->getOpcode() == Instruction::And &&
2065 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2066 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2067
Chris Lattner396dbfe2004-06-09 05:08:07 +00002068 Value *NewNot =
2069 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002070 return BinaryOperator::createAnd(Op0, NewNot);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002071 }
Chris Lattner57c8d992003-02-18 19:57:07 +00002072
Reid Spencer3c514952006-10-16 23:08:08 +00002073 // 0 - (X sdiv C) -> (X sdiv -C)
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002074 if (Op1I->getOpcode() == Instruction::SDiv)
Reid Spencere0fc4df2006-10-20 07:07:24 +00002075 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002076 if (CSI->isNullValue())
Chris Lattner0aee4b72004-10-06 15:08:25 +00002077 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002078 return BinaryOperator::createSDiv(Op1I->getOperand(0),
Chris Lattner0aee4b72004-10-06 15:08:25 +00002079 ConstantExpr::getNeg(DivRHS));
2080
Chris Lattner57c8d992003-02-18 19:57:07 +00002081 // X - X*C --> X * (1-C)
Reid Spencer4fdd96c2005-06-18 17:37:34 +00002082 ConstantInt *C2 = 0;
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002083 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00002084 Constant *CP1 =
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002085 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1), C2);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002086 return BinaryOperator::createMul(Op0, CP1);
Chris Lattner57c8d992003-02-18 19:57:07 +00002087 }
Chris Lattnerad3c4952002-05-09 01:29:19 +00002088 }
Chris Lattnera9be4492005-04-07 16:15:25 +00002089 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00002090
Chris Lattner7a002fe2006-12-02 00:13:08 +00002091 if (!Op0->getType()->isFPOrFPVector())
Chris Lattner47060462005-04-07 17:14:51 +00002092 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2093 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner411336f2005-01-19 21:50:18 +00002094 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2095 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2096 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2097 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner47060462005-04-07 17:14:51 +00002098 } else if (Op0I->getOpcode() == Instruction::Sub) {
2099 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
2100 return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
Chris Lattner411336f2005-01-19 21:50:18 +00002101 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002102
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002103 ConstantInt *C1;
2104 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2105 if (X == Op1) { // X*C - X --> X * (C-1)
2106 Constant *CP1 = ConstantExpr::getSub(C1, ConstantInt::get(I.getType(),1));
2107 return BinaryOperator::createMul(Op1, CP1);
2108 }
Chris Lattner57c8d992003-02-18 19:57:07 +00002109
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002110 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
2111 if (X == dyn_castFoldableMul(Op1, C2))
2112 return BinaryOperator::createMul(Op1, ConstantExpr::getSub(C1, C2));
2113 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002114 return 0;
Chris Lattner260ab202002-04-18 17:39:14 +00002115}
2116
Reid Spencer266e42b2006-12-23 06:05:41 +00002117/// isSignBitCheck - Given an exploded icmp instruction, return true if it
Chris Lattnere79e8542004-02-23 06:38:22 +00002118/// really just returns true if the most significant (sign) bit is set.
Reid Spencer266e42b2006-12-23 06:05:41 +00002119static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS) {
2120 switch (pred) {
2121 case ICmpInst::ICMP_SLT:
2122 // True if LHS s< RHS and RHS == 0
2123 return RHS->isNullValue();
2124 case ICmpInst::ICMP_SLE:
2125 // True if LHS s<= RHS and RHS == -1
2126 return RHS->isAllOnesValue();
2127 case ICmpInst::ICMP_UGE:
2128 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2129 return RHS->getZExtValue() == (1ULL <<
2130 (RHS->getType()->getPrimitiveSizeInBits()-1));
2131 case ICmpInst::ICMP_UGT:
2132 // True if LHS u> RHS and RHS == high-bit-mask - 1
2133 return RHS->getZExtValue() ==
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002134 (1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1))-1;
Reid Spencer266e42b2006-12-23 06:05:41 +00002135 default:
2136 return false;
Chris Lattnere79e8542004-02-23 06:38:22 +00002137 }
Chris Lattnere79e8542004-02-23 06:38:22 +00002138}
2139
Chris Lattner113f4f42002-06-25 16:13:24 +00002140Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00002141 bool Changed = SimplifyCommutative(I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002142 Value *Op0 = I.getOperand(0);
Chris Lattner260ab202002-04-18 17:39:14 +00002143
Chris Lattner81a7a232004-10-16 18:11:37 +00002144 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
2145 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2146
Chris Lattnere6794492002-08-12 21:17:25 +00002147 // Simplify mul instructions with a constant RHS...
Chris Lattner3082c5a2003-02-18 19:28:33 +00002148 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2149 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerede3fe02003-08-13 04:18:28 +00002150
2151 // ((X << C1)*C2) == (X * (C2 << C1))
2152 if (ShiftInst *SI = dyn_cast<ShiftInst>(Op0))
2153 if (SI->getOpcode() == Instruction::Shl)
2154 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002155 return BinaryOperator::createMul(SI->getOperand(0),
2156 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanb1c93172005-04-21 23:48:37 +00002157
Chris Lattnercce81be2003-09-11 22:24:54 +00002158 if (CI->isNullValue())
2159 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2160 if (CI->equalsInt(1)) // X * 1 == X
2161 return ReplaceInstUsesWith(I, Op0);
2162 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Chris Lattner35236d82003-06-25 17:09:20 +00002163 return BinaryOperator::createNeg(Op0, I.getName());
Chris Lattner31ba1292002-04-29 22:24:47 +00002164
Reid Spencere0fc4df2006-10-20 07:07:24 +00002165 int64_t Val = (int64_t)cast<ConstantInt>(CI)->getZExtValue();
Chris Lattner22d00a82005-08-02 19:16:58 +00002166 if (isPowerOf2_64(Val)) { // Replace X*(2^C) with X << C
2167 uint64_t C = Log2_64(Val);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002168 return new ShiftInst(Instruction::Shl, Op0,
Reid Spencerc635f472006-12-31 05:48:39 +00002169 ConstantInt::get(Type::Int8Ty, C));
Chris Lattner22d00a82005-08-02 19:16:58 +00002170 }
Robert Bocchino7b5b86c2004-07-27 21:02:21 +00002171 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00002172 if (Op1F->isNullValue())
2173 return ReplaceInstUsesWith(I, Op1);
Chris Lattner31ba1292002-04-29 22:24:47 +00002174
Chris Lattner3082c5a2003-02-18 19:28:33 +00002175 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2176 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2177 if (Op1F->getValue() == 1.0)
2178 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
2179 }
Chris Lattner32c01df2006-03-04 06:04:02 +00002180
2181 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2182 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2183 isa<ConstantInt>(Op0I->getOperand(1))) {
2184 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2185 Instruction *Add = BinaryOperator::createMul(Op0I->getOperand(0),
2186 Op1, "tmp");
2187 InsertNewInstBefore(Add, I);
2188 Value *C1C2 = ConstantExpr::getMul(Op1,
2189 cast<Constant>(Op0I->getOperand(1)));
2190 return BinaryOperator::createAdd(Add, C1C2);
2191
2192 }
Chris Lattner183b3362004-04-09 19:05:30 +00002193
2194 // Try to fold constant mul into select arguments.
2195 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00002196 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00002197 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002198
2199 if (isa<PHINode>(Op0))
2200 if (Instruction *NV = FoldOpIntoPhi(I))
2201 return NV;
Chris Lattner260ab202002-04-18 17:39:14 +00002202 }
2203
Chris Lattner934a64cf2003-03-10 23:23:04 +00002204 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
2205 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002206 return BinaryOperator::createMul(Op0v, Op1v);
Chris Lattner934a64cf2003-03-10 23:23:04 +00002207
Chris Lattner2635b522004-02-23 05:39:21 +00002208 // If one of the operands of the multiply is a cast from a boolean value, then
2209 // we know the bool is either zero or one, so this is a 'masking' multiply.
2210 // See if we can simplify things based on how the boolean was originally
2211 // formed.
2212 CastInst *BoolCast = 0;
Reid Spencer74a528b2006-12-13 18:21:21 +00002213 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(0)))
2214 if (CI->getOperand(0)->getType() == Type::BoolTy)
Chris Lattner2635b522004-02-23 05:39:21 +00002215 BoolCast = CI;
2216 if (!BoolCast)
Reid Spencer74a528b2006-12-13 18:21:21 +00002217 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
2218 if (CI->getOperand(0)->getType() == Type::BoolTy)
Chris Lattner2635b522004-02-23 05:39:21 +00002219 BoolCast = CI;
2220 if (BoolCast) {
Reid Spencer266e42b2006-12-23 06:05:41 +00002221 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
Chris Lattner2635b522004-02-23 05:39:21 +00002222 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2223 const Type *SCOpTy = SCIOp0->getType();
2224
Reid Spencer266e42b2006-12-23 06:05:41 +00002225 // If the icmp is true iff the sign bit of X is set, then convert this
Chris Lattnere79e8542004-02-23 06:38:22 +00002226 // multiply into a shift/and combination.
2227 if (isa<ConstantInt>(SCIOp1) &&
Reid Spencer266e42b2006-12-23 06:05:41 +00002228 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1))) {
Chris Lattner2635b522004-02-23 05:39:21 +00002229 // Shift the X value right to turn it into "all signbits".
Reid Spencerc635f472006-12-31 05:48:39 +00002230 Constant *Amt = ConstantInt::get(Type::Int8Ty,
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002231 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattnere79e8542004-02-23 06:38:22 +00002232 Value *V =
Reid Spencerfdff9382006-11-08 06:47:33 +00002233 InsertNewInstBefore(new ShiftInst(Instruction::AShr, SCIOp0, Amt,
Chris Lattnere79e8542004-02-23 06:38:22 +00002234 BoolCast->getOperand(0)->getName()+
2235 ".mask"), I);
Chris Lattner2635b522004-02-23 05:39:21 +00002236
2237 // If the multiply type is not the same as the source type, sign extend
2238 // or truncate to the multiply type.
Reid Spencer13bc5d72006-12-12 09:18:51 +00002239 if (I.getType() != V->getType()) {
2240 unsigned SrcBits = V->getType()->getPrimitiveSizeInBits();
2241 unsigned DstBits = I.getType()->getPrimitiveSizeInBits();
2242 Instruction::CastOps opcode =
2243 (SrcBits == DstBits ? Instruction::BitCast :
2244 (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2245 V = InsertCastBefore(opcode, V, I.getType(), I);
2246 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002247
Chris Lattner2635b522004-02-23 05:39:21 +00002248 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002249 return BinaryOperator::createAnd(V, OtherOp);
Chris Lattner2635b522004-02-23 05:39:21 +00002250 }
2251 }
2252 }
2253
Chris Lattner113f4f42002-06-25 16:13:24 +00002254 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +00002255}
2256
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002257/// This function implements the transforms on div instructions that work
2258/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2259/// used by the visitors to those instructions.
2260/// @brief Transforms common to all three div instructions
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002261Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002262 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner81a7a232004-10-16 18:11:37 +00002263
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002264 // undef / X -> 0
2265 if (isa<UndefValue>(Op0))
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002266 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002267
2268 // X / undef -> undef
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002269 if (isa<UndefValue>(Op1))
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002270 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002271
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002272 // Handle cases involving: div X, (select Cond, Y, Z)
Chris Lattnerd79dc792006-09-09 20:26:32 +00002273 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2274 // div X, (Cond ? 0 : Y) -> div X, Y. If the div and the select are in the
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002275 // same basic block, then we replace the select with Y, and the condition
2276 // of the select with false (if the cond value is in the same BB). If the
Chris Lattnerd79dc792006-09-09 20:26:32 +00002277 // select has uses other than the div, this allows them to be simplified
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002278 // also. Note that div X, Y is just as good as div X, 0 (undef)
Chris Lattnerd79dc792006-09-09 20:26:32 +00002279 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2280 if (ST->isNullValue()) {
2281 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2282 if (CondI && CondI->getParent() == I.getParent())
Chris Lattner6ab03f62006-09-28 23:35:22 +00002283 UpdateValueUsesWith(CondI, ConstantBool::getFalse());
Chris Lattnerd79dc792006-09-09 20:26:32 +00002284 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2285 I.setOperand(1, SI->getOperand(2));
2286 else
2287 UpdateValueUsesWith(SI, SI->getOperand(2));
2288 return &I;
2289 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002290
Chris Lattnerd79dc792006-09-09 20:26:32 +00002291 // Likewise for: div X, (Cond ? Y : 0) -> div X, Y
2292 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2293 if (ST->isNullValue()) {
2294 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2295 if (CondI && CondI->getParent() == I.getParent())
Chris Lattner6ab03f62006-09-28 23:35:22 +00002296 UpdateValueUsesWith(CondI, ConstantBool::getTrue());
Chris Lattnerd79dc792006-09-09 20:26:32 +00002297 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2298 I.setOperand(1, SI->getOperand(1));
2299 else
2300 UpdateValueUsesWith(SI, SI->getOperand(1));
2301 return &I;
2302 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002303 }
Chris Lattnerd79dc792006-09-09 20:26:32 +00002304
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002305 return 0;
2306}
Misha Brukmanb1c93172005-04-21 23:48:37 +00002307
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002308/// This function implements the transforms common to both integer division
2309/// instructions (udiv and sdiv). It is called by the visitors to those integer
2310/// division instructions.
2311/// @brief Common integer divide transforms
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002312Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002313 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2314
2315 if (Instruction *Common = commonDivTransforms(I))
2316 return Common;
2317
2318 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2319 // div X, 1 == X
2320 if (RHS->equalsInt(1))
2321 return ReplaceInstUsesWith(I, Op0);
2322
2323 // (X / C1) / C2 -> X / (C1*C2)
2324 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2325 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2326 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
2327 return BinaryOperator::create(I.getOpcode(), LHS->getOperand(0),
2328 ConstantExpr::getMul(RHS, LHSRHS));
Chris Lattner42362612005-04-08 04:03:26 +00002329 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002330
2331 if (!RHS->isNullValue()) { // avoid X udiv 0
2332 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2333 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2334 return R;
2335 if (isa<PHINode>(Op0))
2336 if (Instruction *NV = FoldOpIntoPhi(I))
2337 return NV;
2338 }
Chris Lattnerd79dc792006-09-09 20:26:32 +00002339 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002340
Chris Lattner3082c5a2003-02-18 19:28:33 +00002341 // 0 / X == 0, we don't need to preserve faults!
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002342 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattner3082c5a2003-02-18 19:28:33 +00002343 if (LHS->equalsInt(0))
2344 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2345
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002346 return 0;
2347}
2348
2349Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2350 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2351
2352 // Handle the integer div common cases
2353 if (Instruction *Common = commonIDivTransforms(I))
2354 return Common;
2355
2356 // X udiv C^2 -> X >> C
2357 // Check to see if this is an unsigned division with an exact power of 2,
2358 // if so, convert to a right shift.
2359 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
2360 if (uint64_t Val = C->getZExtValue()) // Don't break X / 0
2361 if (isPowerOf2_64(Val)) {
2362 uint64_t ShiftAmt = Log2_64(Val);
Reid Spencerfdff9382006-11-08 06:47:33 +00002363 return new ShiftInst(Instruction::LShr, Op0,
Reid Spencerc635f472006-12-31 05:48:39 +00002364 ConstantInt::get(Type::Int8Ty, ShiftAmt));
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002365 }
2366 }
2367
2368 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
2369 if (ShiftInst *RHSI = dyn_cast<ShiftInst>(I.getOperand(1))) {
2370 if (RHSI->getOpcode() == Instruction::Shl &&
2371 isa<ConstantInt>(RHSI->getOperand(0))) {
2372 uint64_t C1 = cast<ConstantInt>(RHSI->getOperand(0))->getZExtValue();
2373 if (isPowerOf2_64(C1)) {
2374 Value *N = RHSI->getOperand(1);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002375 const Type *NTy = N->getType();
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002376 if (uint64_t C2 = Log2_64(C1)) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002377 Constant *C2V = ConstantInt::get(NTy, C2);
2378 N = InsertNewInstBefore(BinaryOperator::createAdd(N, C2V, "tmp"), I);
Chris Lattner2e90b732006-02-05 07:54:04 +00002379 }
Reid Spencerfdff9382006-11-08 06:47:33 +00002380 return new ShiftInst(Instruction::LShr, Op0, N);
Chris Lattner2e90b732006-02-05 07:54:04 +00002381 }
2382 }
Chris Lattnerdd0c1742005-11-05 07:40:31 +00002383 }
2384
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002385 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
2386 // where C1&C2 are powers of two.
2387 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2388 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2389 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2)))
2390 if (!STO->isNullValue() && !STO->isNullValue()) {
2391 uint64_t TVA = STO->getZExtValue(), FVA = SFO->getZExtValue();
2392 if (isPowerOf2_64(TVA) && isPowerOf2_64(FVA)) {
2393 // Compute the shift amounts
2394 unsigned TSA = Log2_64(TVA), FSA = Log2_64(FVA);
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002395 // Construct the "on true" case of the select
Reid Spencerc635f472006-12-31 05:48:39 +00002396 Constant *TC = ConstantInt::get(Type::Int8Ty, TSA);
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002397 Instruction *TSI =
Reid Spencerfdff9382006-11-08 06:47:33 +00002398 new ShiftInst(Instruction::LShr, Op0, TC, SI->getName()+".t");
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002399 TSI = InsertNewInstBefore(TSI, I);
2400
2401 // Construct the "on false" case of the select
Reid Spencerc635f472006-12-31 05:48:39 +00002402 Constant *FC = ConstantInt::get(Type::Int8Ty, FSA);
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002403 Instruction *FSI =
Reid Spencerfdff9382006-11-08 06:47:33 +00002404 new ShiftInst(Instruction::LShr, Op0, FC, SI->getName()+".f");
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002405 FSI = InsertNewInstBefore(FSI, I);
2406
2407 // construct the select instruction and return it.
Reid Spencerfdff9382006-11-08 06:47:33 +00002408 return new SelectInst(SI->getOperand(0), TSI, FSI, SI->getName());
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002409 }
2410 }
2411 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002412 return 0;
2413}
2414
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002415Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
2416 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2417
2418 // Handle the integer div common cases
2419 if (Instruction *Common = commonIDivTransforms(I))
2420 return Common;
2421
2422 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2423 // sdiv X, -1 == -X
2424 if (RHS->isAllOnesValue())
2425 return BinaryOperator::createNeg(Op0);
2426
2427 // -X/C -> X/-C
2428 if (Value *LHSNeg = dyn_castNegVal(Op0))
2429 return BinaryOperator::createSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
2430 }
2431
2432 // If the sign bits of both operands are zero (i.e. we can prove they are
2433 // unsigned inputs), turn this into a udiv.
2434 if (I.getType()->isInteger()) {
2435 uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
2436 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2437 return BinaryOperator::createUDiv(Op0, Op1, I.getName());
2438 }
2439 }
2440
2441 return 0;
2442}
2443
2444Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
2445 return commonDivTransforms(I);
2446}
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002447
Chris Lattner85dda9a2006-03-02 06:50:58 +00002448/// GetFactor - If we can prove that the specified value is at least a multiple
2449/// of some factor, return that factor.
2450static Constant *GetFactor(Value *V) {
2451 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
2452 return CI;
2453
2454 // Unless we can be tricky, we know this is a multiple of 1.
2455 Constant *Result = ConstantInt::get(V->getType(), 1);
2456
2457 Instruction *I = dyn_cast<Instruction>(V);
2458 if (!I) return Result;
2459
2460 if (I->getOpcode() == Instruction::Mul) {
2461 // Handle multiplies by a constant, etc.
2462 return ConstantExpr::getMul(GetFactor(I->getOperand(0)),
2463 GetFactor(I->getOperand(1)));
2464 } else if (I->getOpcode() == Instruction::Shl) {
2465 // (X<<C) -> X * (1 << C)
2466 if (Constant *ShRHS = dyn_cast<Constant>(I->getOperand(1))) {
2467 ShRHS = ConstantExpr::getShl(Result, ShRHS);
2468 return ConstantExpr::getMul(GetFactor(I->getOperand(0)), ShRHS);
2469 }
2470 } else if (I->getOpcode() == Instruction::And) {
2471 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
2472 // X & 0xFFF0 is known to be a multiple of 16.
2473 unsigned Zeros = CountTrailingZeros_64(RHS->getZExtValue());
2474 if (Zeros != V->getType()->getPrimitiveSizeInBits())
2475 return ConstantExpr::getShl(Result,
Reid Spencerc635f472006-12-31 05:48:39 +00002476 ConstantInt::get(Type::Int8Ty, Zeros));
Chris Lattner85dda9a2006-03-02 06:50:58 +00002477 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002478 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
Chris Lattner85dda9a2006-03-02 06:50:58 +00002479 // Only handle int->int casts.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002480 if (!CI->isIntegerCast())
2481 return Result;
2482 Value *Op = CI->getOperand(0);
2483 return ConstantExpr::getCast(CI->getOpcode(), GetFactor(Op), V->getType());
Chris Lattner85dda9a2006-03-02 06:50:58 +00002484 }
2485 return Result;
2486}
2487
Reid Spencer7eb55b32006-11-02 01:53:59 +00002488/// This function implements the transforms on rem instructions that work
2489/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
2490/// is used by the visitors to those instructions.
2491/// @brief Transforms common to all three rem instructions
2492Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002493 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Reid Spencer7eb55b32006-11-02 01:53:59 +00002494
Chris Lattner0de4a8d2006-02-28 05:30:45 +00002495 // 0 % X == 0, we don't need to preserve faults!
2496 if (Constant *LHS = dyn_cast<Constant>(Op0))
2497 if (LHS->isNullValue())
2498 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2499
2500 if (isa<UndefValue>(Op0)) // undef % X -> 0
2501 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2502 if (isa<UndefValue>(Op1))
2503 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Reid Spencer7eb55b32006-11-02 01:53:59 +00002504
2505 // Handle cases involving: rem X, (select Cond, Y, Z)
2506 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2507 // rem X, (Cond ? 0 : Y) -> rem X, Y. If the rem and the select are in
2508 // the same basic block, then we replace the select with Y, and the
2509 // condition of the select with false (if the cond value is in the same
2510 // BB). If the select has uses other than the div, this allows them to be
2511 // simplified also.
2512 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2513 if (ST->isNullValue()) {
2514 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2515 if (CondI && CondI->getParent() == I.getParent())
2516 UpdateValueUsesWith(CondI, ConstantBool::getFalse());
2517 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2518 I.setOperand(1, SI->getOperand(2));
2519 else
2520 UpdateValueUsesWith(SI, SI->getOperand(2));
Chris Lattner7fd5f072004-07-06 07:01:22 +00002521 return &I;
2522 }
Reid Spencer7eb55b32006-11-02 01:53:59 +00002523 // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
2524 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2525 if (ST->isNullValue()) {
2526 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2527 if (CondI && CondI->getParent() == I.getParent())
2528 UpdateValueUsesWith(CondI, ConstantBool::getTrue());
2529 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2530 I.setOperand(1, SI->getOperand(1));
2531 else
2532 UpdateValueUsesWith(SI, SI->getOperand(1));
2533 return &I;
2534 }
Chris Lattnere9ff0ea2005-11-05 07:28:37 +00002535 }
Chris Lattner7fd5f072004-07-06 07:01:22 +00002536
Reid Spencer7eb55b32006-11-02 01:53:59 +00002537 return 0;
2538}
2539
2540/// This function implements the transforms common to both integer remainder
2541/// instructions (urem and srem). It is called by the visitors to those integer
2542/// remainder instructions.
2543/// @brief Common integer remainder transforms
2544Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
2545 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2546
2547 if (Instruction *common = commonRemTransforms(I))
2548 return common;
2549
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002550 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner0de4a8d2006-02-28 05:30:45 +00002551 // X % 0 == undef, we don't need to preserve faults!
2552 if (RHS->equalsInt(0))
2553 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2554
Chris Lattner3082c5a2003-02-18 19:28:33 +00002555 if (RHS->equalsInt(1)) // X % 1 == 0
2556 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2557
Chris Lattnerb70f1412006-02-28 05:49:21 +00002558 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2559 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2560 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2561 return R;
2562 } else if (isa<PHINode>(Op0I)) {
2563 if (Instruction *NV = FoldOpIntoPhi(I))
2564 return NV;
Chris Lattnerb70f1412006-02-28 05:49:21 +00002565 }
Reid Spencer7eb55b32006-11-02 01:53:59 +00002566 // (X * C1) % C2 --> 0 iff C1 % C2 == 0
2567 if (ConstantExpr::getSRem(GetFactor(Op0I), RHS)->isNullValue())
Chris Lattner85dda9a2006-03-02 06:50:58 +00002568 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerb70f1412006-02-28 05:49:21 +00002569 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00002570 }
2571
Reid Spencer7eb55b32006-11-02 01:53:59 +00002572 return 0;
2573}
2574
2575Instruction *InstCombiner::visitURem(BinaryOperator &I) {
2576 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2577
2578 if (Instruction *common = commonIRemTransforms(I))
2579 return common;
2580
2581 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2582 // X urem C^2 -> X and C
2583 // Check to see if this is an unsigned remainder with an exact power of 2,
2584 // if so, convert to a bitwise and.
2585 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
2586 if (isPowerOf2_64(C->getZExtValue()))
2587 return BinaryOperator::createAnd(Op0, SubOne(C));
2588 }
2589
Chris Lattner2e90b732006-02-05 07:54:04 +00002590 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00002591 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
2592 if (RHSI->getOpcode() == Instruction::Shl &&
2593 isa<ConstantInt>(RHSI->getOperand(0))) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002594 unsigned C1 = cast<ConstantInt>(RHSI->getOperand(0))->getZExtValue();
Chris Lattner2e90b732006-02-05 07:54:04 +00002595 if (isPowerOf2_64(C1)) {
2596 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
2597 Value *Add = InsertNewInstBefore(BinaryOperator::createAdd(RHSI, N1,
2598 "tmp"), I);
2599 return BinaryOperator::createAnd(Op0, Add);
2600 }
2601 }
Reid Spencer7eb55b32006-11-02 01:53:59 +00002602 }
Chris Lattnerd79dc792006-09-09 20:26:32 +00002603
Reid Spencer7eb55b32006-11-02 01:53:59 +00002604 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
2605 // where C1&C2 are powers of two.
2606 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2607 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2608 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
2609 // STO == 0 and SFO == 0 handled above.
2610 if (isPowerOf2_64(STO->getZExtValue()) &&
2611 isPowerOf2_64(SFO->getZExtValue())) {
2612 Value *TrueAnd = InsertNewInstBefore(
2613 BinaryOperator::createAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
2614 Value *FalseAnd = InsertNewInstBefore(
2615 BinaryOperator::createAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
2616 return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
2617 }
2618 }
Chris Lattner2e90b732006-02-05 07:54:04 +00002619 }
2620
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002621 return 0;
2622}
2623
Reid Spencer7eb55b32006-11-02 01:53:59 +00002624Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
2625 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2626
2627 if (Instruction *common = commonIRemTransforms(I))
2628 return common;
2629
2630 if (Value *RHSNeg = dyn_castNegVal(Op1))
2631 if (!isa<ConstantInt>(RHSNeg) ||
2632 cast<ConstantInt>(RHSNeg)->getSExtValue() > 0) {
2633 // X % -Y -> X % Y
2634 AddUsesToWorkList(I);
2635 I.setOperand(1, RHSNeg);
2636 return &I;
2637 }
2638
2639 // If the top bits of both operands are zero (i.e. we can prove they are
2640 // unsigned inputs), turn this into a urem.
2641 uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
2642 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2643 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
2644 return BinaryOperator::createURem(Op0, Op1, I.getName());
2645 }
2646
2647 return 0;
2648}
2649
2650Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00002651 return commonRemTransforms(I);
2652}
2653
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002654// isMaxValueMinusOne - return true if this is Max-1
Reid Spencer266e42b2006-12-23 06:05:41 +00002655static bool isMaxValueMinusOne(const ConstantInt *C, bool isSigned) {
2656 if (isSigned) {
2657 // Calculate 0111111111..11111
2658 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
2659 int64_t Val = INT64_MAX; // All ones
2660 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
2661 return C->getSExtValue() == Val-1;
2662 }
2663 return C->getZExtValue() == C->getType()->getIntegralTypeMask()-1;
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002664}
2665
2666// isMinValuePlusOne - return true if this is Min+1
Reid Spencer266e42b2006-12-23 06:05:41 +00002667static bool isMinValuePlusOne(const ConstantInt *C, bool isSigned) {
2668 if (isSigned) {
2669 // Calculate 1111111111000000000000
2670 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
2671 int64_t Val = -1; // All ones
2672 Val <<= TypeBits-1; // Shift over to the right spot
2673 return C->getSExtValue() == Val+1;
2674 }
2675 return C->getZExtValue() == 1; // unsigned
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002676}
2677
Chris Lattner35167c32004-06-09 07:59:58 +00002678// isOneBitSet - Return true if there is exactly one bit set in the specified
2679// constant.
2680static bool isOneBitSet(const ConstantInt *CI) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002681 uint64_t V = CI->getZExtValue();
Chris Lattner35167c32004-06-09 07:59:58 +00002682 return V && (V & (V-1)) == 0;
2683}
2684
Chris Lattner8fc5af42004-09-23 21:46:38 +00002685#if 0 // Currently unused
2686// isLowOnes - Return true if the constant is of the form 0+1+.
2687static bool isLowOnes(const ConstantInt *CI) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002688 uint64_t V = CI->getZExtValue();
Chris Lattner8fc5af42004-09-23 21:46:38 +00002689
2690 // There won't be bits set in parts that the type doesn't contain.
Reid Spencere0fc4df2006-10-20 07:07:24 +00002691 V &= ConstantInt::getAllOnesValue(CI->getType())->getZExtValue();
Chris Lattner8fc5af42004-09-23 21:46:38 +00002692
2693 uint64_t U = V+1; // If it is low ones, this should be a power of two.
2694 return U && V && (U & V) == 0;
2695}
2696#endif
2697
2698// isHighOnes - Return true if the constant is of the form 1+0+.
2699// This is the same as lowones(~X).
2700static bool isHighOnes(const ConstantInt *CI) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002701 uint64_t V = ~CI->getZExtValue();
Chris Lattner2c14cf72005-08-07 07:03:10 +00002702 if (~V == 0) return false; // 0's does not match "1+"
Chris Lattner8fc5af42004-09-23 21:46:38 +00002703
2704 // There won't be bits set in parts that the type doesn't contain.
Reid Spencere0fc4df2006-10-20 07:07:24 +00002705 V &= ConstantInt::getAllOnesValue(CI->getType())->getZExtValue();
Chris Lattner8fc5af42004-09-23 21:46:38 +00002706
2707 uint64_t U = V+1; // If it is low ones, this should be a power of two.
2708 return U && V && (U & V) == 0;
2709}
2710
Reid Spencer266e42b2006-12-23 06:05:41 +00002711/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
Chris Lattner3ac7c262003-08-13 20:16:26 +00002712/// are carefully arranged to allow folding of expressions such as:
2713///
2714/// (A < B) | (A > B) --> (A != B)
2715///
Reid Spencer266e42b2006-12-23 06:05:41 +00002716/// Note that this is only valid if the first and second predicates have the
2717/// same sign. Is illegal to do: (A u< B) | (A s> B)
Chris Lattner3ac7c262003-08-13 20:16:26 +00002718///
Reid Spencer266e42b2006-12-23 06:05:41 +00002719/// Three bits are used to represent the condition, as follows:
2720/// 0 A > B
2721/// 1 A == B
2722/// 2 A < B
2723///
2724/// <=> Value Definition
2725/// 000 0 Always false
2726/// 001 1 A > B
2727/// 010 2 A == B
2728/// 011 3 A >= B
2729/// 100 4 A < B
2730/// 101 5 A != B
2731/// 110 6 A <= B
2732/// 111 7 Always true
2733///
2734static unsigned getICmpCode(const ICmpInst *ICI) {
2735 switch (ICI->getPredicate()) {
Chris Lattner3ac7c262003-08-13 20:16:26 +00002736 // False -> 0
Reid Spencer266e42b2006-12-23 06:05:41 +00002737 case ICmpInst::ICMP_UGT: return 1; // 001
2738 case ICmpInst::ICMP_SGT: return 1; // 001
2739 case ICmpInst::ICMP_EQ: return 2; // 010
2740 case ICmpInst::ICMP_UGE: return 3; // 011
2741 case ICmpInst::ICMP_SGE: return 3; // 011
2742 case ICmpInst::ICMP_ULT: return 4; // 100
2743 case ICmpInst::ICMP_SLT: return 4; // 100
2744 case ICmpInst::ICMP_NE: return 5; // 101
2745 case ICmpInst::ICMP_ULE: return 6; // 110
2746 case ICmpInst::ICMP_SLE: return 6; // 110
Chris Lattner3ac7c262003-08-13 20:16:26 +00002747 // True -> 7
2748 default:
Reid Spencer266e42b2006-12-23 06:05:41 +00002749 assert(0 && "Invalid ICmp predicate!");
Chris Lattner3ac7c262003-08-13 20:16:26 +00002750 return 0;
2751 }
2752}
2753
Reid Spencer266e42b2006-12-23 06:05:41 +00002754/// getICmpValue - This is the complement of getICmpCode, which turns an
2755/// opcode and two operands into either a constant true or false, or a brand
2756/// new /// ICmp instruction. The sign is passed in to determine which kind
2757/// of predicate to use in new icmp instructions.
2758static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
2759 switch (code) {
2760 default: assert(0 && "Illegal ICmp code!");
2761 case 0: return ConstantBool::getFalse();
2762 case 1:
2763 if (sign)
2764 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
2765 else
2766 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
2767 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
2768 case 3:
2769 if (sign)
2770 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
2771 else
2772 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
2773 case 4:
2774 if (sign)
2775 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
2776 else
2777 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
2778 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
2779 case 6:
2780 if (sign)
2781 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
2782 else
2783 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
2784 case 7: return ConstantBool::getTrue();
Chris Lattner3ac7c262003-08-13 20:16:26 +00002785 }
2786}
2787
Reid Spencer266e42b2006-12-23 06:05:41 +00002788static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
2789 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
2790 (ICmpInst::isSignedPredicate(p1) &&
2791 (p2 == ICmpInst::ICMP_EQ || p2 == ICmpInst::ICMP_NE)) ||
2792 (ICmpInst::isSignedPredicate(p2) &&
2793 (p1 == ICmpInst::ICMP_EQ || p1 == ICmpInst::ICMP_NE));
2794}
2795
2796namespace {
2797// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
2798struct FoldICmpLogical {
Chris Lattner3ac7c262003-08-13 20:16:26 +00002799 InstCombiner &IC;
2800 Value *LHS, *RHS;
Reid Spencer266e42b2006-12-23 06:05:41 +00002801 ICmpInst::Predicate pred;
2802 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
2803 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
2804 pred(ICI->getPredicate()) {}
Chris Lattner3ac7c262003-08-13 20:16:26 +00002805 bool shouldApply(Value *V) const {
Reid Spencer266e42b2006-12-23 06:05:41 +00002806 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
2807 if (PredicatesFoldable(pred, ICI->getPredicate()))
2808 return (ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS ||
2809 ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS);
Chris Lattner3ac7c262003-08-13 20:16:26 +00002810 return false;
2811 }
Reid Spencer266e42b2006-12-23 06:05:41 +00002812 Instruction *apply(Instruction &Log) const {
2813 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
2814 if (ICI->getOperand(0) != LHS) {
2815 assert(ICI->getOperand(1) == LHS);
2816 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
Chris Lattner3ac7c262003-08-13 20:16:26 +00002817 }
2818
Reid Spencer266e42b2006-12-23 06:05:41 +00002819 unsigned LHSCode = getICmpCode(ICI);
2820 unsigned RHSCode = getICmpCode(cast<ICmpInst>(Log.getOperand(1)));
Chris Lattner3ac7c262003-08-13 20:16:26 +00002821 unsigned Code;
2822 switch (Log.getOpcode()) {
2823 case Instruction::And: Code = LHSCode & RHSCode; break;
2824 case Instruction::Or: Code = LHSCode | RHSCode; break;
2825 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner2caaaba2003-09-22 20:33:34 +00002826 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattner3ac7c262003-08-13 20:16:26 +00002827 }
2828
Reid Spencer266e42b2006-12-23 06:05:41 +00002829 Value *RV = getICmpValue(ICmpInst::isSignedPredicate(pred), Code, LHS, RHS);
Chris Lattner3ac7c262003-08-13 20:16:26 +00002830 if (Instruction *I = dyn_cast<Instruction>(RV))
2831 return I;
2832 // Otherwise, it's a constant boolean value...
2833 return IC.ReplaceInstUsesWith(Log, RV);
2834 }
2835};
Chris Lattnere3a63d12006-11-15 04:53:24 +00002836} // end anonymous namespace
Chris Lattner3ac7c262003-08-13 20:16:26 +00002837
Chris Lattnerba1cb382003-09-19 17:17:26 +00002838// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
2839// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
2840// guaranteed to be either a shift instruction or a binary operator.
2841Instruction *InstCombiner::OptAndOp(Instruction *Op,
2842 ConstantIntegral *OpRHS,
2843 ConstantIntegral *AndRHS,
2844 BinaryOperator &TheAnd) {
2845 Value *X = Op->getOperand(0);
Chris Lattnerfcf21a72004-01-12 19:47:05 +00002846 Constant *Together = 0;
2847 if (!isa<ShiftInst>(Op))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002848 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002849
Chris Lattnerba1cb382003-09-19 17:17:26 +00002850 switch (Op->getOpcode()) {
2851 case Instruction::Xor:
Chris Lattner86102b82005-01-01 16:22:27 +00002852 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00002853 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
2854 std::string OpName = Op->getName(); Op->setName("");
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002855 Instruction *And = BinaryOperator::createAnd(X, AndRHS, OpName);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002856 InsertNewInstBefore(And, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002857 return BinaryOperator::createXor(And, Together);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002858 }
2859 break;
2860 case Instruction::Or:
Chris Lattner86102b82005-01-01 16:22:27 +00002861 if (Together == AndRHS) // (X | C) & C --> C
2862 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002863
Chris Lattner86102b82005-01-01 16:22:27 +00002864 if (Op->hasOneUse() && Together != OpRHS) {
2865 // (X | C1) & C2 --> (X | (C1&C2)) & C2
2866 std::string Op0Name = Op->getName(); Op->setName("");
2867 Instruction *Or = BinaryOperator::createOr(X, Together, Op0Name);
2868 InsertNewInstBefore(Or, TheAnd);
2869 return BinaryOperator::createAnd(Or, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002870 }
2871 break;
2872 case Instruction::Add:
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002873 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00002874 // Adding a one to a single bit bit-field should be turned into an XOR
2875 // of the bit. First thing to check is to see if this AND is with a
2876 // single bit constant.
Reid Spencere0fc4df2006-10-20 07:07:24 +00002877 uint64_t AndRHSV = cast<ConstantInt>(AndRHS)->getZExtValue();
Chris Lattnerba1cb382003-09-19 17:17:26 +00002878
2879 // Clear bits that are not part of the constant.
Chris Lattner77defba2006-02-07 07:00:41 +00002880 AndRHSV &= AndRHS->getType()->getIntegralTypeMask();
Chris Lattnerba1cb382003-09-19 17:17:26 +00002881
2882 // If there is only one bit set...
Chris Lattner35167c32004-06-09 07:59:58 +00002883 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00002884 // Ok, at this point, we know that we are masking the result of the
2885 // ADD down to exactly one bit. If the constant we are adding has
2886 // no bits set below this bit, then we can eliminate the ADD.
Reid Spencere0fc4df2006-10-20 07:07:24 +00002887 uint64_t AddRHS = cast<ConstantInt>(OpRHS)->getZExtValue();
Misha Brukmanb1c93172005-04-21 23:48:37 +00002888
Chris Lattnerba1cb382003-09-19 17:17:26 +00002889 // Check to see if any bits below the one bit set in AndRHSV are set.
2890 if ((AddRHS & (AndRHSV-1)) == 0) {
2891 // If not, the only thing that can effect the output of the AND is
2892 // the bit specified by AndRHSV. If that bit is set, the effect of
2893 // the XOR is to toggle the bit. If it is clear, then the ADD has
2894 // no effect.
2895 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
2896 TheAnd.setOperand(0, X);
2897 return &TheAnd;
2898 } else {
2899 std::string Name = Op->getName(); Op->setName("");
2900 // Pull the XOR out of the AND.
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002901 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS, Name);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002902 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002903 return BinaryOperator::createXor(NewAnd, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002904 }
2905 }
2906 }
2907 }
2908 break;
Chris Lattner2da29172003-09-19 19:05:02 +00002909
2910 case Instruction::Shl: {
2911 // We know that the AND will not produce any of the bits shifted in, so if
2912 // the anded constant includes them, clear them now!
2913 //
2914 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner7e794272004-09-24 15:21:34 +00002915 Constant *ShlMask = ConstantExpr::getShl(AllOne, OpRHS);
2916 Constant *CI = ConstantExpr::getAnd(AndRHS, ShlMask);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002917
Chris Lattner7e794272004-09-24 15:21:34 +00002918 if (CI == ShlMask) { // Masking out bits that the shift already masks
2919 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
2920 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner2da29172003-09-19 19:05:02 +00002921 TheAnd.setOperand(1, CI);
2922 return &TheAnd;
2923 }
2924 break;
Misha Brukmanb1c93172005-04-21 23:48:37 +00002925 }
Reid Spencerfdff9382006-11-08 06:47:33 +00002926 case Instruction::LShr:
2927 {
Chris Lattner2da29172003-09-19 19:05:02 +00002928 // We know that the AND will not produce any of the bits shifted in, so if
2929 // the anded constant includes them, clear them now! This only applies to
2930 // unsigned shifts, because a signed shr may bring in set bits!
2931 //
Reid Spencerfdff9382006-11-08 06:47:33 +00002932 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
2933 Constant *ShrMask = ConstantExpr::getLShr(AllOne, OpRHS);
2934 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
Chris Lattner7e794272004-09-24 15:21:34 +00002935
Reid Spencerfdff9382006-11-08 06:47:33 +00002936 if (CI == ShrMask) { // Masking out bits that the shift already masks.
2937 return ReplaceInstUsesWith(TheAnd, Op);
2938 } else if (CI != AndRHS) {
2939 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
2940 return &TheAnd;
2941 }
2942 break;
2943 }
2944 case Instruction::AShr:
2945 // Signed shr.
2946 // See if this is shifting in some sign extension, then masking it out
2947 // with an and.
2948 if (Op->hasOneUse()) {
2949 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
2950 Constant *ShrMask = ConstantExpr::getLShr(AllOne, OpRHS);
Reid Spencer2a499b02006-12-13 17:19:09 +00002951 Constant *C = ConstantExpr::getAnd(AndRHS, ShrMask);
2952 if (C == AndRHS) { // Masking out bits shifted in.
Reid Spencer13bc5d72006-12-12 09:18:51 +00002953 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
Reid Spencerfdff9382006-11-08 06:47:33 +00002954 // Make the argument unsigned.
2955 Value *ShVal = Op->getOperand(0);
Reid Spencer2a499b02006-12-13 17:19:09 +00002956 ShVal = InsertNewInstBefore(new ShiftInst(Instruction::LShr, ShVal,
2957 OpRHS, Op->getName()), TheAnd);
2958 return BinaryOperator::createAnd(ShVal, AndRHS, TheAnd.getName());
Chris Lattner7e794272004-09-24 15:21:34 +00002959 }
Chris Lattner2da29172003-09-19 19:05:02 +00002960 }
2961 break;
Chris Lattnerba1cb382003-09-19 17:17:26 +00002962 }
2963 return 0;
2964}
2965
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002966
Chris Lattner6862fbd2004-09-29 17:40:11 +00002967/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
2968/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
Reid Spencer266e42b2006-12-23 06:05:41 +00002969/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
2970/// whether to treat the V, Lo and HI as signed or not. IB is the location to
Chris Lattner6862fbd2004-09-29 17:40:11 +00002971/// insert new instructions.
2972Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencer266e42b2006-12-23 06:05:41 +00002973 bool isSigned, bool Inside,
2974 Instruction &IB) {
2975 assert(cast<ConstantBool>(ConstantExpr::getICmp((isSigned ?
2976 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getValue() &&
Chris Lattner6862fbd2004-09-29 17:40:11 +00002977 "Lo is not <= Hi in range emission code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00002978
Chris Lattner6862fbd2004-09-29 17:40:11 +00002979 if (Inside) {
2980 if (Lo == Hi) // Trivially false.
Reid Spencer266e42b2006-12-23 06:05:41 +00002981 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002982
Reid Spencer266e42b2006-12-23 06:05:41 +00002983 // V >= Min && V < Hi --> V < Hi
2984 if (cast<ConstantIntegral>(Lo)->isMinValue(isSigned)) {
2985 ICmpInst::Predicate pred = (isSigned ?
2986 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
2987 return new ICmpInst(pred, V, Hi);
2988 }
2989
2990 // Emit V-Lo <u Hi-Lo
2991 Constant *NegLo = ConstantExpr::getNeg(Lo);
2992 Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
Chris Lattner6862fbd2004-09-29 17:40:11 +00002993 InsertNewInstBefore(Add, IB);
Reid Spencer266e42b2006-12-23 06:05:41 +00002994 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
2995 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00002996 }
2997
2998 if (Lo == Hi) // Trivially true.
Reid Spencer266e42b2006-12-23 06:05:41 +00002999 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
Chris Lattner6862fbd2004-09-29 17:40:11 +00003000
Reid Spencer266e42b2006-12-23 06:05:41 +00003001 // V < Min || V >= Hi ->'V > Hi-1'
Chris Lattner6862fbd2004-09-29 17:40:11 +00003002 Hi = SubOne(cast<ConstantInt>(Hi));
Reid Spencer266e42b2006-12-23 06:05:41 +00003003 if (cast<ConstantIntegral>(Lo)->isMinValue(isSigned)) {
3004 ICmpInst::Predicate pred = (isSigned ?
3005 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3006 return new ICmpInst(pred, V, Hi);
3007 }
Reid Spencere0fc4df2006-10-20 07:07:24 +00003008
Reid Spencer266e42b2006-12-23 06:05:41 +00003009 // Emit V-Lo > Hi-1-Lo
3010 Constant *NegLo = ConstantExpr::getNeg(Lo);
3011 Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
Chris Lattner6862fbd2004-09-29 17:40:11 +00003012 InsertNewInstBefore(Add, IB);
Reid Spencer266e42b2006-12-23 06:05:41 +00003013 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3014 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00003015}
3016
Chris Lattnerb4b25302005-09-18 07:22:02 +00003017// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3018// any number of 0s on either side. The 1s are allowed to wrap from LSB to
3019// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3020// not, since all 1s are not contiguous.
3021static bool isRunOfOnes(ConstantIntegral *Val, unsigned &MB, unsigned &ME) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00003022 uint64_t V = Val->getZExtValue();
Chris Lattnerb4b25302005-09-18 07:22:02 +00003023 if (!isShiftedMask_64(V)) return false;
3024
3025 // look for the first zero bit after the run of ones
3026 MB = 64-CountLeadingZeros_64((V - 1) ^ V);
3027 // look for the first non-zero bit
3028 ME = 64-CountLeadingZeros_64(V);
3029 return true;
3030}
3031
3032
3033
3034/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3035/// where isSub determines whether the operator is a sub. If we can fold one of
3036/// the following xforms:
Chris Lattneraf517572005-09-18 04:24:45 +00003037///
3038/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3039/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3040/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3041///
3042/// return (A +/- B).
3043///
3044Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
3045 ConstantIntegral *Mask, bool isSub,
3046 Instruction &I) {
3047 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3048 if (!LHSI || LHSI->getNumOperands() != 2 ||
3049 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3050
3051 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3052
3053 switch (LHSI->getOpcode()) {
3054 default: return 0;
3055 case Instruction::And:
Chris Lattnerb4b25302005-09-18 07:22:02 +00003056 if (ConstantExpr::getAnd(N, Mask) == Mask) {
3057 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Reid Spencere0fc4df2006-10-20 07:07:24 +00003058 if ((Mask->getZExtValue() & Mask->getZExtValue()+1) == 0)
Chris Lattnerb4b25302005-09-18 07:22:02 +00003059 break;
3060
3061 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3062 // part, we don't need any explicit masks to take them out of A. If that
3063 // is all N is, ignore it.
3064 unsigned MB, ME;
3065 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003066 uint64_t Mask = RHS->getType()->getIntegralTypeMask();
3067 Mask >>= 64-MB+1;
3068 if (MaskedValueIsZero(RHS, Mask))
Chris Lattnerb4b25302005-09-18 07:22:02 +00003069 break;
3070 }
3071 }
Chris Lattneraf517572005-09-18 04:24:45 +00003072 return 0;
3073 case Instruction::Or:
3074 case Instruction::Xor:
Chris Lattnerb4b25302005-09-18 07:22:02 +00003075 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Reid Spencere0fc4df2006-10-20 07:07:24 +00003076 if ((Mask->getZExtValue() & Mask->getZExtValue()+1) == 0 &&
Chris Lattnerb4b25302005-09-18 07:22:02 +00003077 ConstantExpr::getAnd(N, Mask)->isNullValue())
Chris Lattneraf517572005-09-18 04:24:45 +00003078 break;
3079 return 0;
3080 }
3081
3082 Instruction *New;
3083 if (isSub)
3084 New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
3085 else
3086 New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
3087 return InsertNewInstBefore(New, I);
3088}
3089
Chris Lattner113f4f42002-06-25 16:13:24 +00003090Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003091 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00003092 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003093
Chris Lattner81a7a232004-10-16 18:11:37 +00003094 if (isa<UndefValue>(Op1)) // X & undef -> 0
3095 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3096
Chris Lattner86102b82005-01-01 16:22:27 +00003097 // and X, X = X
3098 if (Op0 == Op1)
Chris Lattnere6794492002-08-12 21:17:25 +00003099 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003100
Chris Lattner5b2edb12006-02-12 08:02:11 +00003101 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner5997cf92006-02-08 03:25:32 +00003102 // purpose is to compute bits we don't care about.
Chris Lattner0157e7f2006-02-11 09:31:47 +00003103 uint64_t KnownZero, KnownOne;
Chris Lattnerd70d9f52006-03-25 21:58:26 +00003104 if (!isa<PackedType>(I.getType()) &&
3105 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
Chris Lattner0157e7f2006-02-11 09:31:47 +00003106 KnownZero, KnownOne))
Chris Lattner5997cf92006-02-08 03:25:32 +00003107 return &I;
3108
Chris Lattner86102b82005-01-01 16:22:27 +00003109 if (ConstantIntegral *AndRHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00003110 uint64_t AndRHSMask = AndRHS->getZExtValue();
3111 uint64_t TypeMask = Op0->getType()->getIntegralTypeMask();
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00003112 uint64_t NotAndRHS = AndRHSMask^TypeMask;
Chris Lattner86102b82005-01-01 16:22:27 +00003113
Chris Lattnerba1cb382003-09-19 17:17:26 +00003114 // Optimize a variety of ((val OP C1) & C2) combinations...
3115 if (isa<BinaryOperator>(Op0) || isa<ShiftInst>(Op0)) {
3116 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner86102b82005-01-01 16:22:27 +00003117 Value *Op0LHS = Op0I->getOperand(0);
3118 Value *Op0RHS = Op0I->getOperand(1);
3119 switch (Op0I->getOpcode()) {
3120 case Instruction::Xor:
3121 case Instruction::Or:
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00003122 // If the mask is only needed on one incoming arm, push it up.
3123 if (Op0I->hasOneUse()) {
3124 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3125 // Not masking anything out for the LHS, move to RHS.
3126 Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
3127 Op0RHS->getName()+".masked");
3128 InsertNewInstBefore(NewRHS, I);
3129 return BinaryOperator::create(
3130 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003131 }
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003132 if (!isa<Constant>(Op0RHS) &&
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00003133 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3134 // Not masking anything out for the RHS, move to LHS.
3135 Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
3136 Op0LHS->getName()+".masked");
3137 InsertNewInstBefore(NewLHS, I);
3138 return BinaryOperator::create(
3139 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3140 }
3141 }
3142
Chris Lattner86102b82005-01-01 16:22:27 +00003143 break;
Chris Lattneraf517572005-09-18 04:24:45 +00003144 case Instruction::Add:
Chris Lattnerb4b25302005-09-18 07:22:02 +00003145 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3146 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3147 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3148 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
3149 return BinaryOperator::createAnd(V, AndRHS);
3150 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
3151 return BinaryOperator::createAnd(V, AndRHS); // Add commutes
Chris Lattneraf517572005-09-18 04:24:45 +00003152 break;
3153
3154 case Instruction::Sub:
Chris Lattnerb4b25302005-09-18 07:22:02 +00003155 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3156 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3157 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3158 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
3159 return BinaryOperator::createAnd(V, AndRHS);
Chris Lattneraf517572005-09-18 04:24:45 +00003160 break;
Chris Lattner86102b82005-01-01 16:22:27 +00003161 }
3162
Chris Lattner16464b32003-07-23 19:25:52 +00003163 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner86102b82005-01-01 16:22:27 +00003164 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerba1cb382003-09-19 17:17:26 +00003165 return Res;
Chris Lattner86102b82005-01-01 16:22:27 +00003166 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
Chris Lattner2c14cf72005-08-07 07:03:10 +00003167 // If this is an integer truncation or change from signed-to-unsigned, and
3168 // if the source is an and/or with immediate, transform it. This
3169 // frequently occurs for bitfield accesses.
3170 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003171 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
Chris Lattner2c14cf72005-08-07 07:03:10 +00003172 CastOp->getNumOperands() == 2)
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00003173 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1)))
Chris Lattner2c14cf72005-08-07 07:03:10 +00003174 if (CastOp->getOpcode() == Instruction::And) {
3175 // Change: and (cast (and X, C1) to T), C2
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003176 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
3177 // This will fold the two constants together, which may allow
3178 // other simplifications.
Reid Spencerbb65ebf2006-12-12 23:36:14 +00003179 Instruction *NewCast = CastInst::createTruncOrBitCast(
3180 CastOp->getOperand(0), I.getType(),
3181 CastOp->getName()+".shrunk");
Chris Lattner2c14cf72005-08-07 07:03:10 +00003182 NewCast = InsertNewInstBefore(NewCast, I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003183 // trunc_or_bitcast(C1)&C2
Reid Spencerbb65ebf2006-12-12 23:36:14 +00003184 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003185 C3 = ConstantExpr::getAnd(C3, AndRHS);
Chris Lattner2c14cf72005-08-07 07:03:10 +00003186 return BinaryOperator::createAnd(NewCast, C3);
3187 } else if (CastOp->getOpcode() == Instruction::Or) {
3188 // Change: and (cast (or X, C1) to T), C2
3189 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Chris Lattner2dc148e2006-12-12 19:11:20 +00003190 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Chris Lattner2c14cf72005-08-07 07:03:10 +00003191 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
3192 return ReplaceInstUsesWith(I, AndRHS);
3193 }
3194 }
Chris Lattner33217db2003-07-23 19:36:21 +00003195 }
Chris Lattner183b3362004-04-09 19:05:30 +00003196
3197 // Try to fold constant and into select arguments.
3198 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00003199 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00003200 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00003201 if (isa<PHINode>(Op0))
3202 if (Instruction *NV = FoldOpIntoPhi(I))
3203 return NV;
Chris Lattner49b47ae2003-07-23 17:57:01 +00003204 }
3205
Chris Lattnerbb74e222003-03-10 23:06:50 +00003206 Value *Op0NotVal = dyn_castNotVal(Op0);
3207 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00003208
Chris Lattner023a4832004-06-18 06:07:51 +00003209 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
3210 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3211
Misha Brukman9c003d82004-07-30 12:50:08 +00003212 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattnerbb74e222003-03-10 23:06:50 +00003213 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003214 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
3215 I.getName()+".demorgan");
Chris Lattner49b47ae2003-07-23 17:57:01 +00003216 InsertNewInstBefore(Or, I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00003217 return BinaryOperator::createNot(Or);
3218 }
Chris Lattner8b10ab32006-02-13 23:07:23 +00003219
3220 {
3221 Value *A = 0, *B = 0;
Chris Lattner8b10ab32006-02-13 23:07:23 +00003222 if (match(Op0, m_Or(m_Value(A), m_Value(B))))
3223 if (A == Op1 || B == Op1) // (A | ?) & A --> A
3224 return ReplaceInstUsesWith(I, Op1);
3225 if (match(Op1, m_Or(m_Value(A), m_Value(B))))
3226 if (A == Op0 || B == Op0) // A & (A | ?) --> A
3227 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerdcd07922006-04-01 08:03:55 +00003228
3229 if (Op0->hasOneUse() &&
3230 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3231 if (A == Op1) { // (A^B)&A -> A&(A^B)
3232 I.swapOperands(); // Simplify below
3233 std::swap(Op0, Op1);
3234 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
3235 cast<BinaryOperator>(Op0)->swapOperands();
3236 I.swapOperands(); // Simplify below
3237 std::swap(Op0, Op1);
3238 }
3239 }
3240 if (Op1->hasOneUse() &&
3241 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3242 if (B == Op0) { // B&(A^B) -> B&(B^A)
3243 cast<BinaryOperator>(Op1)->swapOperands();
3244 std::swap(A, B);
3245 }
3246 if (A == Op0) { // A&(A^B) -> A & ~B
3247 Instruction *NotB = BinaryOperator::createNot(B, "tmp");
3248 InsertNewInstBefore(NotB, I);
3249 return BinaryOperator::createAnd(A, NotB);
3250 }
3251 }
Chris Lattner8b10ab32006-02-13 23:07:23 +00003252 }
3253
Reid Spencer266e42b2006-12-23 06:05:41 +00003254 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
3255 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3256 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattner3ac7c262003-08-13 20:16:26 +00003257 return R;
3258
Chris Lattner623826c2004-09-28 21:48:02 +00003259 Value *LHSVal, *RHSVal;
3260 ConstantInt *LHSCst, *RHSCst;
Reid Spencer266e42b2006-12-23 06:05:41 +00003261 ICmpInst::Predicate LHSCC, RHSCC;
3262 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3263 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3264 if (LHSVal == RHSVal && // Found (X icmp C1) & (X icmp C2)
3265 // ICMP_[GL]E X, CST is folded to ICMP_[GL]T elsewhere.
3266 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3267 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3268 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
3269 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE) {
Chris Lattner623826c2004-09-28 21:48:02 +00003270 // Ensure that the larger constant is on the RHS.
Reid Spencer266e42b2006-12-23 06:05:41 +00003271 ICmpInst::Predicate GT = ICmpInst::isSignedPredicate(LHSCC) ?
3272 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
3273 Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3274 ICmpInst *LHS = cast<ICmpInst>(Op0);
Chris Lattner623826c2004-09-28 21:48:02 +00003275 if (cast<ConstantBool>(Cmp)->getValue()) {
3276 std::swap(LHS, RHS);
3277 std::swap(LHSCst, RHSCst);
3278 std::swap(LHSCC, RHSCC);
3279 }
3280
Reid Spencer266e42b2006-12-23 06:05:41 +00003281 // At this point, we know we have have two icmp instructions
Chris Lattner623826c2004-09-28 21:48:02 +00003282 // comparing a value against two constants and and'ing the result
3283 // together. Because of the above check, we know that we only have
Reid Spencer266e42b2006-12-23 06:05:41 +00003284 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3285 // (from the FoldICmpLogical check above), that the two constants
3286 // are not equal and that the larger constant is on the RHS
Chris Lattner623826c2004-09-28 21:48:02 +00003287 assert(LHSCst != RHSCst && "Compares not folded above?");
3288
3289 switch (LHSCC) {
3290 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003291 case ICmpInst::ICMP_EQ:
Chris Lattner623826c2004-09-28 21:48:02 +00003292 switch (RHSCC) {
3293 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003294 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
3295 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3296 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
Chris Lattner6ab03f62006-09-28 23:35:22 +00003297 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00003298 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3299 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3300 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
Chris Lattner623826c2004-09-28 21:48:02 +00003301 return ReplaceInstUsesWith(I, LHS);
3302 }
Reid Spencer266e42b2006-12-23 06:05:41 +00003303 case ICmpInst::ICMP_NE:
Chris Lattner623826c2004-09-28 21:48:02 +00003304 switch (RHSCC) {
3305 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003306 case ICmpInst::ICMP_ULT:
3307 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3308 return new ICmpInst(ICmpInst::ICMP_ULT, LHSVal, LHSCst);
3309 break; // (X != 13 & X u< 15) -> no change
3310 case ICmpInst::ICMP_SLT:
3311 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3312 return new ICmpInst(ICmpInst::ICMP_SLT, LHSVal, LHSCst);
3313 break; // (X != 13 & X s< 15) -> no change
3314 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
3315 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
3316 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
Chris Lattner623826c2004-09-28 21:48:02 +00003317 return ReplaceInstUsesWith(I, RHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00003318 case ICmpInst::ICMP_NE:
3319 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
Chris Lattner623826c2004-09-28 21:48:02 +00003320 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3321 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3322 LHSVal->getName()+".off");
3323 InsertNewInstBefore(Add, I);
Reid Spencerc635f472006-12-31 05:48:39 +00003324 return new ICmpInst(ICmpInst::ICMP_UGT, Add, AddCST);
Chris Lattner623826c2004-09-28 21:48:02 +00003325 }
3326 break; // (X != 13 & X != 15) -> no change
3327 }
3328 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00003329 case ICmpInst::ICMP_ULT:
Chris Lattner623826c2004-09-28 21:48:02 +00003330 switch (RHSCC) {
3331 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003332 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
3333 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Chris Lattner6ab03f62006-09-28 23:35:22 +00003334 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00003335 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
3336 break;
3337 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
3338 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
Chris Lattner623826c2004-09-28 21:48:02 +00003339 return ReplaceInstUsesWith(I, LHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00003340 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
3341 break;
Chris Lattner623826c2004-09-28 21:48:02 +00003342 }
Reid Spencer266e42b2006-12-23 06:05:41 +00003343 break;
3344 case ICmpInst::ICMP_SLT:
Chris Lattner623826c2004-09-28 21:48:02 +00003345 switch (RHSCC) {
3346 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003347 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
3348 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
3349 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
3350 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
3351 break;
3352 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
3353 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
Chris Lattner623826c2004-09-28 21:48:02 +00003354 return ReplaceInstUsesWith(I, LHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00003355 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
3356 break;
Chris Lattner623826c2004-09-28 21:48:02 +00003357 }
Reid Spencer266e42b2006-12-23 06:05:41 +00003358 break;
3359 case ICmpInst::ICMP_UGT:
3360 switch (RHSCC) {
3361 default: assert(0 && "Unknown integer condition code!");
3362 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X > 13
3363 return ReplaceInstUsesWith(I, LHS);
3364 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
3365 return ReplaceInstUsesWith(I, RHS);
3366 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
3367 break;
3368 case ICmpInst::ICMP_NE:
3369 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3370 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3371 break; // (X u> 13 & X != 15) -> no change
3372 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) ->(X-14) <u 1
3373 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, false,
3374 true, I);
3375 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
3376 break;
3377 }
3378 break;
3379 case ICmpInst::ICMP_SGT:
3380 switch (RHSCC) {
3381 default: assert(0 && "Unknown integer condition code!");
3382 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X s> 13
3383 return ReplaceInstUsesWith(I, LHS);
3384 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
3385 return ReplaceInstUsesWith(I, RHS);
3386 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
3387 break;
3388 case ICmpInst::ICMP_NE:
3389 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3390 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3391 break; // (X s> 13 & X != 15) -> no change
3392 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) ->(X-14) s< 1
3393 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true,
3394 true, I);
3395 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
3396 break;
3397 }
3398 break;
Chris Lattner623826c2004-09-28 21:48:02 +00003399 }
3400 }
3401 }
3402
Chris Lattner3af10532006-05-05 06:39:07 +00003403 // fold (and (cast A), (cast B)) -> (cast (and A, B))
Reid Spencer799b5bf2006-12-13 08:27:15 +00003404 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
3405 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3406 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
3407 const Type *SrcTy = Op0C->getOperand(0)->getType();
3408 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegral() &&
3409 // Only do this if the casts both really cause code to be generated.
Reid Spencer266e42b2006-12-23 06:05:41 +00003410 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
3411 I.getType(), TD) &&
3412 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
3413 I.getType(), TD)) {
Reid Spencer799b5bf2006-12-13 08:27:15 +00003414 Instruction *NewOp = BinaryOperator::createAnd(Op0C->getOperand(0),
3415 Op1C->getOperand(0),
3416 I.getName());
3417 InsertNewInstBefore(NewOp, I);
3418 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
3419 }
Chris Lattner3af10532006-05-05 06:39:07 +00003420 }
Chris Lattnerf05d69a2006-11-14 07:46:50 +00003421
3422 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
3423 if (ShiftInst *SI1 = dyn_cast<ShiftInst>(Op1)) {
3424 if (ShiftInst *SI0 = dyn_cast<ShiftInst>(Op0))
3425 if (SI0->getOpcode() == SI1->getOpcode() &&
3426 SI0->getOperand(1) == SI1->getOperand(1) &&
3427 (SI0->hasOneUse() || SI1->hasOneUse())) {
3428 Instruction *NewOp =
3429 InsertNewInstBefore(BinaryOperator::createAnd(SI0->getOperand(0),
3430 SI1->getOperand(0),
3431 SI0->getName()), I);
3432 return new ShiftInst(SI1->getOpcode(), NewOp, SI1->getOperand(1));
3433 }
Chris Lattner3af10532006-05-05 06:39:07 +00003434 }
3435
Chris Lattner113f4f42002-06-25 16:13:24 +00003436 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003437}
3438
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003439/// CollectBSwapParts - Look to see if the specified value defines a single byte
3440/// in the result. If it does, and if the specified byte hasn't been filled in
3441/// yet, fill it in and return false.
3442static bool CollectBSwapParts(Value *V, std::vector<Value*> &ByteValues) {
3443 Instruction *I = dyn_cast<Instruction>(V);
3444 if (I == 0) return true;
3445
3446 // If this is an or instruction, it is an inner node of the bswap.
3447 if (I->getOpcode() == Instruction::Or)
3448 return CollectBSwapParts(I->getOperand(0), ByteValues) ||
3449 CollectBSwapParts(I->getOperand(1), ByteValues);
3450
3451 // If this is a shift by a constant int, and it is "24", then its operand
3452 // defines a byte. We only handle unsigned types here.
3453 if (isa<ShiftInst>(I) && isa<ConstantInt>(I->getOperand(1))) {
3454 // Not shifting the entire input by N-1 bytes?
Reid Spencere0fc4df2006-10-20 07:07:24 +00003455 if (cast<ConstantInt>(I->getOperand(1))->getZExtValue() !=
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003456 8*(ByteValues.size()-1))
3457 return true;
3458
3459 unsigned DestNo;
3460 if (I->getOpcode() == Instruction::Shl) {
3461 // X << 24 defines the top byte with the lowest of the input bytes.
3462 DestNo = ByteValues.size()-1;
3463 } else {
3464 // X >>u 24 defines the low byte with the highest of the input bytes.
3465 DestNo = 0;
3466 }
3467
3468 // If the destination byte value is already defined, the values are or'd
3469 // together, which isn't a bswap (unless it's an or of the same bits).
3470 if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
3471 return true;
3472 ByteValues[DestNo] = I->getOperand(0);
3473 return false;
3474 }
3475
3476 // Otherwise, we can only handle and(shift X, imm), imm). Bail out of if we
3477 // don't have this.
3478 Value *Shift = 0, *ShiftLHS = 0;
3479 ConstantInt *AndAmt = 0, *ShiftAmt = 0;
3480 if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
3481 !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
3482 return true;
3483 Instruction *SI = cast<Instruction>(Shift);
3484
3485 // Make sure that the shift amount is by a multiple of 8 and isn't too big.
Reid Spencere0fc4df2006-10-20 07:07:24 +00003486 if (ShiftAmt->getZExtValue() & 7 ||
3487 ShiftAmt->getZExtValue() > 8*ByteValues.size())
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003488 return true;
3489
3490 // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
3491 unsigned DestByte;
3492 for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
Reid Spencere0fc4df2006-10-20 07:07:24 +00003493 if (AndAmt->getZExtValue() == uint64_t(0xFF) << 8*DestByte)
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003494 break;
3495 // Unknown mask for bswap.
3496 if (DestByte == ByteValues.size()) return true;
3497
Reid Spencere0fc4df2006-10-20 07:07:24 +00003498 unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003499 unsigned SrcByte;
3500 if (SI->getOpcode() == Instruction::Shl)
3501 SrcByte = DestByte - ShiftBytes;
3502 else
3503 SrcByte = DestByte + ShiftBytes;
3504
3505 // If the SrcByte isn't a bswapped value from the DestByte, reject it.
3506 if (SrcByte != ByteValues.size()-DestByte-1)
3507 return true;
3508
3509 // If the destination byte value is already defined, the values are or'd
3510 // together, which isn't a bswap (unless it's an or of the same bits).
3511 if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
3512 return true;
3513 ByteValues[DestByte] = SI->getOperand(0);
3514 return false;
3515}
3516
3517/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
3518/// If so, insert the new bswap intrinsic and return it.
3519Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
3520 // We can only handle bswap of unsigned integers, and cannot bswap one byte.
Reid Spencerc635f472006-12-31 05:48:39 +00003521 if (I.getType() == Type::Int8Ty)
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003522 return 0;
3523
3524 /// ByteValues - For each byte of the result, we keep track of which value
3525 /// defines each byte.
3526 std::vector<Value*> ByteValues;
3527 ByteValues.resize(I.getType()->getPrimitiveSize());
3528
3529 // Try to find all the pieces corresponding to the bswap.
3530 if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
3531 CollectBSwapParts(I.getOperand(1), ByteValues))
3532 return 0;
3533
3534 // Check to see if all of the bytes come from the same value.
3535 Value *V = ByteValues[0];
3536 if (V == 0) return 0; // Didn't find a byte? Must be zero.
3537
3538 // Check to make sure that all of the bytes come from the same value.
3539 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
3540 if (ByteValues[i] != V)
3541 return 0;
3542
3543 // If they do then *success* we can turn this into a bswap. Figure out what
3544 // bswap to make it into.
3545 Module *M = I.getParent()->getParent()->getParent();
Chris Lattner091b6ea2006-07-11 18:31:26 +00003546 const char *FnName = 0;
Reid Spencerc635f472006-12-31 05:48:39 +00003547 if (I.getType() == Type::Int16Ty)
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003548 FnName = "llvm.bswap.i16";
Reid Spencerc635f472006-12-31 05:48:39 +00003549 else if (I.getType() == Type::Int32Ty)
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003550 FnName = "llvm.bswap.i32";
Reid Spencerc635f472006-12-31 05:48:39 +00003551 else if (I.getType() == Type::Int64Ty)
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003552 FnName = "llvm.bswap.i64";
3553 else
3554 assert(0 && "Unknown integer type!");
Chris Lattnerfbc524f2007-01-07 06:58:05 +00003555 Constant *F = M->getOrInsertFunction(FnName, I.getType(), I.getType(), NULL);
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003556 return new CallInst(F, V);
3557}
3558
3559
Chris Lattner113f4f42002-06-25 16:13:24 +00003560Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003561 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00003562 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003563
Chris Lattner81a7a232004-10-16 18:11:37 +00003564 if (isa<UndefValue>(Op1))
3565 return ReplaceInstUsesWith(I, // X | undef -> -1
3566 ConstantIntegral::getAllOnesValue(I.getType()));
3567
Chris Lattner5b2edb12006-02-12 08:02:11 +00003568 // or X, X = X
3569 if (Op0 == Op1)
Chris Lattnere6794492002-08-12 21:17:25 +00003570 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003571
Chris Lattner5b2edb12006-02-12 08:02:11 +00003572 // See if we can simplify any instructions used by the instruction whose sole
3573 // purpose is to compute bits we don't care about.
3574 uint64_t KnownZero, KnownOne;
Chris Lattnerd70d9f52006-03-25 21:58:26 +00003575 if (!isa<PackedType>(I.getType()) &&
3576 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
Chris Lattner5b2edb12006-02-12 08:02:11 +00003577 KnownZero, KnownOne))
3578 return &I;
3579
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003580 // or X, -1 == -1
Chris Lattner8f0d1562003-07-23 18:29:44 +00003581 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner330628a2006-01-06 17:59:59 +00003582 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00003583 // (X & C1) | C2 --> (X | C2) & (C1|C2)
3584 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Chris Lattnerb62f5082005-05-09 04:58:36 +00003585 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0->getName());
3586 Op0->setName("");
Chris Lattnerd4252a72004-07-30 07:50:03 +00003587 InsertNewInstBefore(Or, I);
3588 return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, C1));
3589 }
Chris Lattner8f0d1562003-07-23 18:29:44 +00003590
Chris Lattnerd4252a72004-07-30 07:50:03 +00003591 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
3592 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
3593 std::string Op0Name = Op0->getName(); Op0->setName("");
3594 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
3595 InsertNewInstBefore(Or, I);
3596 return BinaryOperator::createXor(Or,
3597 ConstantExpr::getAnd(C1, ConstantExpr::getNot(RHS)));
Chris Lattner8f0d1562003-07-23 18:29:44 +00003598 }
Chris Lattner183b3362004-04-09 19:05:30 +00003599
3600 // Try to fold constant and into select arguments.
3601 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00003602 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00003603 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00003604 if (isa<PHINode>(Op0))
3605 if (Instruction *NV = FoldOpIntoPhi(I))
3606 return NV;
Chris Lattner8f0d1562003-07-23 18:29:44 +00003607 }
3608
Chris Lattner330628a2006-01-06 17:59:59 +00003609 Value *A = 0, *B = 0;
3610 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattner4294cec2005-05-07 23:49:08 +00003611
3612 if (match(Op0, m_And(m_Value(A), m_Value(B))))
3613 if (A == Op1 || B == Op1) // (A & ?) | A --> A
3614 return ReplaceInstUsesWith(I, Op1);
3615 if (match(Op1, m_And(m_Value(A), m_Value(B))))
3616 if (A == Op0 || B == Op0) // A | (A & ?) --> A
3617 return ReplaceInstUsesWith(I, Op0);
3618
Chris Lattnerb7845d62006-07-10 20:25:24 +00003619 // (A | B) | C and A | (B | C) -> bswap if possible.
3620 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003621 if (match(Op0, m_Or(m_Value(), m_Value())) ||
Chris Lattnerb7845d62006-07-10 20:25:24 +00003622 match(Op1, m_Or(m_Value(), m_Value())) ||
3623 (match(Op0, m_Shift(m_Value(), m_Value())) &&
3624 match(Op1, m_Shift(m_Value(), m_Value())))) {
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003625 if (Instruction *BSwap = MatchBSwap(I))
3626 return BSwap;
3627 }
3628
Chris Lattnerb62f5082005-05-09 04:58:36 +00003629 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
3630 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003631 MaskedValueIsZero(Op1, C1->getZExtValue())) {
Chris Lattnerb62f5082005-05-09 04:58:36 +00003632 Instruction *NOr = BinaryOperator::createOr(A, Op1, Op0->getName());
3633 Op0->setName("");
3634 return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
3635 }
3636
3637 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
3638 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003639 MaskedValueIsZero(Op0, C1->getZExtValue())) {
Chris Lattnerb62f5082005-05-09 04:58:36 +00003640 Instruction *NOr = BinaryOperator::createOr(A, Op0, Op1->getName());
3641 Op0->setName("");
3642 return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
3643 }
3644
Chris Lattner15212982005-09-18 03:42:07 +00003645 // (A & C1)|(B & C2)
Chris Lattnerd4252a72004-07-30 07:50:03 +00003646 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattner15212982005-09-18 03:42:07 +00003647 match(Op1, m_And(m_Value(B), m_ConstantInt(C2)))) {
3648
3649 if (A == B) // (A & C1)|(A & C2) == A & (C1|C2)
3650 return BinaryOperator::createAnd(A, ConstantExpr::getOr(C1, C2));
3651
3652
Chris Lattner01f56c62005-09-18 06:02:59 +00003653 // If we have: ((V + N) & C1) | (V & C2)
3654 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
3655 // replace with V+N.
3656 if (C1 == ConstantExpr::getNot(C2)) {
Chris Lattner330628a2006-01-06 17:59:59 +00003657 Value *V1 = 0, *V2 = 0;
Reid Spencere0fc4df2006-10-20 07:07:24 +00003658 if ((C2->getZExtValue() & (C2->getZExtValue()+1)) == 0 && // C2 == 0+1+
Chris Lattner01f56c62005-09-18 06:02:59 +00003659 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
3660 // Add commutes, try both ways.
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003661 if (V1 == B && MaskedValueIsZero(V2, C2->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003662 return ReplaceInstUsesWith(I, A);
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003663 if (V2 == B && MaskedValueIsZero(V1, C2->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003664 return ReplaceInstUsesWith(I, A);
3665 }
3666 // Or commutes, try both ways.
Reid Spencere0fc4df2006-10-20 07:07:24 +00003667 if ((C1->getZExtValue() & (C1->getZExtValue()+1)) == 0 &&
Chris Lattner01f56c62005-09-18 06:02:59 +00003668 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
3669 // Add commutes, try both ways.
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003670 if (V1 == A && MaskedValueIsZero(V2, C1->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003671 return ReplaceInstUsesWith(I, B);
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003672 if (V2 == A && MaskedValueIsZero(V1, C1->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003673 return ReplaceInstUsesWith(I, B);
Chris Lattner15212982005-09-18 03:42:07 +00003674 }
3675 }
3676 }
Chris Lattnerf05d69a2006-11-14 07:46:50 +00003677
3678 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
3679 if (ShiftInst *SI1 = dyn_cast<ShiftInst>(Op1)) {
3680 if (ShiftInst *SI0 = dyn_cast<ShiftInst>(Op0))
3681 if (SI0->getOpcode() == SI1->getOpcode() &&
3682 SI0->getOperand(1) == SI1->getOperand(1) &&
3683 (SI0->hasOneUse() || SI1->hasOneUse())) {
3684 Instruction *NewOp =
3685 InsertNewInstBefore(BinaryOperator::createOr(SI0->getOperand(0),
3686 SI1->getOperand(0),
3687 SI0->getName()), I);
3688 return new ShiftInst(SI1->getOpcode(), NewOp, SI1->getOperand(1));
3689 }
3690 }
Chris Lattner812aab72003-08-12 19:11:07 +00003691
Chris Lattnerd4252a72004-07-30 07:50:03 +00003692 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
3693 if (A == Op1) // ~A | A == -1
Misha Brukmanb1c93172005-04-21 23:48:37 +00003694 return ReplaceInstUsesWith(I,
Chris Lattnerd4252a72004-07-30 07:50:03 +00003695 ConstantIntegral::getAllOnesValue(I.getType()));
3696 } else {
3697 A = 0;
3698 }
Chris Lattner4294cec2005-05-07 23:49:08 +00003699 // Note, A is still live here!
Chris Lattnerd4252a72004-07-30 07:50:03 +00003700 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
3701 if (Op0 == B)
Misha Brukmanb1c93172005-04-21 23:48:37 +00003702 return ReplaceInstUsesWith(I,
Chris Lattnerd4252a72004-07-30 07:50:03 +00003703 ConstantIntegral::getAllOnesValue(I.getType()));
Chris Lattner3e327a42003-03-10 23:13:59 +00003704
Misha Brukman9c003d82004-07-30 12:50:08 +00003705 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattnerd4252a72004-07-30 07:50:03 +00003706 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3707 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
3708 I.getName()+".demorgan"), I);
3709 return BinaryOperator::createNot(And);
3710 }
Chris Lattner3e327a42003-03-10 23:13:59 +00003711 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00003712
Reid Spencer266e42b2006-12-23 06:05:41 +00003713 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
3714 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
3715 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattner3ac7c262003-08-13 20:16:26 +00003716 return R;
3717
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003718 Value *LHSVal, *RHSVal;
3719 ConstantInt *LHSCst, *RHSCst;
Reid Spencer266e42b2006-12-23 06:05:41 +00003720 ICmpInst::Predicate LHSCC, RHSCC;
3721 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3722 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3723 if (LHSVal == RHSVal && // Found (X icmp C1) | (X icmp C2)
3724 // icmp [us][gl]e x, cst is folded to icmp [us][gl]t elsewhere.
3725 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3726 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3727 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
3728 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE) {
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003729 // Ensure that the larger constant is on the RHS.
Reid Spencer266e42b2006-12-23 06:05:41 +00003730 ICmpInst::Predicate GT = ICmpInst::isSignedPredicate(LHSCC) ?
3731 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
3732 Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3733 ICmpInst *LHS = cast<ICmpInst>(Op0);
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003734 if (cast<ConstantBool>(Cmp)->getValue()) {
3735 std::swap(LHS, RHS);
3736 std::swap(LHSCst, RHSCst);
3737 std::swap(LHSCC, RHSCC);
3738 }
3739
Reid Spencer266e42b2006-12-23 06:05:41 +00003740 // At this point, we know we have have two icmp instructions
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003741 // comparing a value against two constants and or'ing the result
3742 // together. Because of the above check, we know that we only have
Reid Spencer266e42b2006-12-23 06:05:41 +00003743 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
3744 // FoldICmpLogical check above), that the two constants are not
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003745 // equal.
3746 assert(LHSCst != RHSCst && "Compares not folded above?");
3747
3748 switch (LHSCC) {
3749 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003750 case ICmpInst::ICMP_EQ:
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003751 switch (RHSCC) {
3752 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003753 case ICmpInst::ICMP_EQ:
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003754 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
3755 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3756 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3757 LHSVal->getName()+".off");
3758 InsertNewInstBefore(Add, I);
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003759 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
Reid Spencer266e42b2006-12-23 06:05:41 +00003760 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003761 }
Reid Spencer266e42b2006-12-23 06:05:41 +00003762 break; // (X == 13 | X == 15) -> no change
3763 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
3764 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
Chris Lattner5c219462005-04-19 06:04:18 +00003765 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00003766 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
3767 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
3768 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003769 return ReplaceInstUsesWith(I, RHS);
3770 }
3771 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00003772 case ICmpInst::ICMP_NE:
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003773 switch (RHSCC) {
3774 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003775 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
3776 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
3777 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003778 return ReplaceInstUsesWith(I, LHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00003779 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
3780 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
3781 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Chris Lattner6ab03f62006-09-28 23:35:22 +00003782 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003783 }
3784 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00003785 case ICmpInst::ICMP_ULT:
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003786 switch (RHSCC) {
3787 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003788 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003789 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00003790 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) ->(X-13) u> 2
3791 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false,
3792 false, I);
3793 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
3794 break;
3795 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
3796 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003797 return ReplaceInstUsesWith(I, RHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00003798 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
3799 break;
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003800 }
3801 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00003802 case ICmpInst::ICMP_SLT:
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003803 switch (RHSCC) {
3804 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003805 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
3806 break;
3807 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) ->(X-13) s> 2
3808 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), true,
3809 false, I);
3810 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
3811 break;
3812 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
3813 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
3814 return ReplaceInstUsesWith(I, RHS);
3815 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
3816 break;
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003817 }
Reid Spencer266e42b2006-12-23 06:05:41 +00003818 break;
3819 case ICmpInst::ICMP_UGT:
3820 switch (RHSCC) {
3821 default: assert(0 && "Unknown integer condition code!");
3822 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
3823 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
3824 return ReplaceInstUsesWith(I, LHS);
3825 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
3826 break;
3827 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
3828 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
3829 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
3830 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
3831 break;
3832 }
3833 break;
3834 case ICmpInst::ICMP_SGT:
3835 switch (RHSCC) {
3836 default: assert(0 && "Unknown integer condition code!");
3837 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
3838 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
3839 return ReplaceInstUsesWith(I, LHS);
3840 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
3841 break;
3842 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
3843 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
3844 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
3845 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
3846 break;
3847 }
3848 break;
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003849 }
3850 }
3851 }
Chris Lattner3af10532006-05-05 06:39:07 +00003852
3853 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Reid Spencer799b5bf2006-12-13 08:27:15 +00003854 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
Chris Lattner3af10532006-05-05 06:39:07 +00003855 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer799b5bf2006-12-13 08:27:15 +00003856 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
3857 const Type *SrcTy = Op0C->getOperand(0)->getType();
3858 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegral() &&
3859 // Only do this if the casts both really cause code to be generated.
Reid Spencer266e42b2006-12-23 06:05:41 +00003860 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
3861 I.getType(), TD) &&
3862 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
3863 I.getType(), TD)) {
Reid Spencer799b5bf2006-12-13 08:27:15 +00003864 Instruction *NewOp = BinaryOperator::createOr(Op0C->getOperand(0),
3865 Op1C->getOperand(0),
3866 I.getName());
3867 InsertNewInstBefore(NewOp, I);
3868 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
3869 }
Chris Lattner3af10532006-05-05 06:39:07 +00003870 }
Chris Lattner3af10532006-05-05 06:39:07 +00003871
Chris Lattner15212982005-09-18 03:42:07 +00003872
Chris Lattner113f4f42002-06-25 16:13:24 +00003873 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003874}
3875
Chris Lattnerc2076352004-02-16 01:20:27 +00003876// XorSelf - Implements: X ^ X --> 0
3877struct XorSelf {
3878 Value *RHS;
3879 XorSelf(Value *rhs) : RHS(rhs) {}
3880 bool shouldApply(Value *LHS) const { return LHS == RHS; }
3881 Instruction *apply(BinaryOperator &Xor) const {
3882 return &Xor;
3883 }
3884};
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003885
3886
Chris Lattner113f4f42002-06-25 16:13:24 +00003887Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003888 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00003889 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003890
Chris Lattner81a7a232004-10-16 18:11:37 +00003891 if (isa<UndefValue>(Op1))
3892 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
3893
Chris Lattnerc2076352004-02-16 01:20:27 +00003894 // xor X, X = 0, even if X is nested in a sequence of Xor's.
3895 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
3896 assert(Result == &I && "AssociativeOpt didn't work?");
Chris Lattnere6794492002-08-12 21:17:25 +00003897 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc2076352004-02-16 01:20:27 +00003898 }
Chris Lattner5b2edb12006-02-12 08:02:11 +00003899
3900 // See if we can simplify any instructions used by the instruction whose sole
3901 // purpose is to compute bits we don't care about.
3902 uint64_t KnownZero, KnownOne;
Chris Lattnerd70d9f52006-03-25 21:58:26 +00003903 if (!isa<PackedType>(I.getType()) &&
3904 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
Chris Lattner5b2edb12006-02-12 08:02:11 +00003905 KnownZero, KnownOne))
3906 return &I;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003907
Chris Lattner97638592003-07-23 21:37:07 +00003908 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00003909 // xor (icmp A, B), true = not (icmp A, B) = !icmp A, B
3910 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
3911 if (RHS == ConstantBool::getTrue() && ICI->hasOneUse())
3912 return new ICmpInst(ICI->getInversePredicate(),
3913 ICI->getOperand(0), ICI->getOperand(1));
Chris Lattnere5806662003-11-04 23:50:51 +00003914
Reid Spencer266e42b2006-12-23 06:05:41 +00003915 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattner8f2f5982003-11-05 01:06:05 +00003916 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003917 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
3918 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003919 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
3920 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003921 ConstantInt::get(I.getType(), 1));
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003922 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003923 }
Chris Lattner023a4832004-06-18 06:07:51 +00003924
3925 // ~(~X & Y) --> (X | ~Y)
3926 if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
3927 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
3928 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
3929 Instruction *NotY =
Misha Brukmanb1c93172005-04-21 23:48:37 +00003930 BinaryOperator::createNot(Op0I->getOperand(1),
Chris Lattner023a4832004-06-18 06:07:51 +00003931 Op0I->getOperand(1)->getName()+".not");
3932 InsertNewInstBefore(NotY, I);
3933 return BinaryOperator::createOr(Op0NotVal, NotY);
3934 }
3935 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003936
Chris Lattner97638592003-07-23 21:37:07 +00003937 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner5b2edb12006-02-12 08:02:11 +00003938 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner0f68fa62003-11-04 23:37:10 +00003939 // ~(X-c) --> (-c-1)-X
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003940 if (RHS->isAllOnesValue()) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003941 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
3942 return BinaryOperator::createSub(
3943 ConstantExpr::getSub(NegOp0CI,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003944 ConstantInt::get(I.getType(), 1)),
Chris Lattner0f68fa62003-11-04 23:37:10 +00003945 Op0I->getOperand(0));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003946 }
Chris Lattnerf78df7c2006-02-26 19:57:54 +00003947 } else if (Op0I->getOpcode() == Instruction::Or) {
3948 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
3949 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getZExtValue())) {
3950 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
3951 // Anything in both C1 and C2 is known to be zero, remove it from
3952 // NewRHS.
3953 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
3954 NewRHS = ConstantExpr::getAnd(NewRHS,
3955 ConstantExpr::getNot(CommonBits));
3956 WorkList.push_back(Op0I);
3957 I.setOperand(0, Op0I->getOperand(0));
3958 I.setOperand(1, NewRHS);
3959 return &I;
3960 }
Chris Lattner97638592003-07-23 21:37:07 +00003961 }
Chris Lattnerb8d6e402002-08-20 18:24:26 +00003962 }
Chris Lattner183b3362004-04-09 19:05:30 +00003963
3964 // Try to fold constant and into select arguments.
3965 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00003966 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00003967 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00003968 if (isa<PHINode>(Op0))
3969 if (Instruction *NV = FoldOpIntoPhi(I))
3970 return NV;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003971 }
3972
Chris Lattnerbb74e222003-03-10 23:06:50 +00003973 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00003974 if (X == Op1)
3975 return ReplaceInstUsesWith(I,
3976 ConstantIntegral::getAllOnesValue(I.getType()));
3977
Chris Lattnerbb74e222003-03-10 23:06:50 +00003978 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00003979 if (X == Op0)
3980 return ReplaceInstUsesWith(I,
3981 ConstantIntegral::getAllOnesValue(I.getType()));
3982
Chris Lattnerdcd07922006-04-01 08:03:55 +00003983 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1))
Chris Lattnerb36d9082004-02-16 03:54:20 +00003984 if (Op1I->getOpcode() == Instruction::Or) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003985 if (Op1I->getOperand(0) == Op0) { // B^(B|A) == (A|B)^B
Chris Lattnerdcd07922006-04-01 08:03:55 +00003986 Op1I->swapOperands();
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003987 I.swapOperands();
3988 std::swap(Op0, Op1);
3989 } else if (Op1I->getOperand(1) == Op0) { // B^(A|B) == (A|B)^B
Chris Lattnerdcd07922006-04-01 08:03:55 +00003990 I.swapOperands(); // Simplified below.
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003991 std::swap(Op0, Op1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003992 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00003993 } else if (Op1I->getOpcode() == Instruction::Xor) {
3994 if (Op0 == Op1I->getOperand(0)) // A^(A^B) == B
3995 return ReplaceInstUsesWith(I, Op1I->getOperand(1));
3996 else if (Op0 == Op1I->getOperand(1)) // A^(B^A) == B
3997 return ReplaceInstUsesWith(I, Op1I->getOperand(0));
Chris Lattnerdcd07922006-04-01 08:03:55 +00003998 } else if (Op1I->getOpcode() == Instruction::And && Op1I->hasOneUse()) {
3999 if (Op1I->getOperand(0) == Op0) // A^(A&B) -> A^(B&A)
4000 Op1I->swapOperands();
4001 if (Op0 == Op1I->getOperand(1)) { // A^(B&A) -> (B&A)^A
4002 I.swapOperands(); // Simplified below.
4003 std::swap(Op0, Op1);
4004 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00004005 }
Chris Lattner1bbb7b62003-03-10 18:24:17 +00004006
Chris Lattnerdcd07922006-04-01 08:03:55 +00004007 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00004008 if (Op0I->getOpcode() == Instruction::Or && Op0I->hasOneUse()) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00004009 if (Op0I->getOperand(0) == Op1) // (B|A)^B == (A|B)^B
Chris Lattnerdcd07922006-04-01 08:03:55 +00004010 Op0I->swapOperands();
Chris Lattnerdcf240a2003-03-10 21:43:22 +00004011 if (Op0I->getOperand(1) == Op1) { // (A|B)^B == A & ~B
Chris Lattnerdcd07922006-04-01 08:03:55 +00004012 Instruction *NotB = BinaryOperator::createNot(Op1, "tmp");
4013 InsertNewInstBefore(NotB, I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004014 return BinaryOperator::createAnd(Op0I->getOperand(0), NotB);
Chris Lattner1bbb7b62003-03-10 18:24:17 +00004015 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00004016 } else if (Op0I->getOpcode() == Instruction::Xor) {
4017 if (Op1 == Op0I->getOperand(0)) // (A^B)^A == B
4018 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
4019 else if (Op1 == Op0I->getOperand(1)) // (B^A)^A == B
4020 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattnerdcd07922006-04-01 08:03:55 +00004021 } else if (Op0I->getOpcode() == Instruction::And && Op0I->hasOneUse()) {
4022 if (Op0I->getOperand(0) == Op1) // (A&B)^A -> (B&A)^A
4023 Op0I->swapOperands();
Chris Lattner6cf49142006-04-01 22:05:01 +00004024 if (Op0I->getOperand(1) == Op1 && // (B&A)^A == ~B & A
4025 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattnerdcd07922006-04-01 08:03:55 +00004026 Instruction *N = BinaryOperator::createNot(Op0I->getOperand(0), "tmp");
4027 InsertNewInstBefore(N, I);
4028 return BinaryOperator::createAnd(N, Op1);
4029 }
Chris Lattner1bbb7b62003-03-10 18:24:17 +00004030 }
4031
Reid Spencer266e42b2006-12-23 06:05:41 +00004032 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
4033 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
4034 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattner3ac7c262003-08-13 20:16:26 +00004035 return R;
4036
Chris Lattner3af10532006-05-05 06:39:07 +00004037 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Reid Spencer799b5bf2006-12-13 08:27:15 +00004038 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
Chris Lattner3af10532006-05-05 06:39:07 +00004039 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer799b5bf2006-12-13 08:27:15 +00004040 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
4041 const Type *SrcTy = Op0C->getOperand(0)->getType();
4042 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegral() &&
4043 // Only do this if the casts both really cause code to be generated.
Reid Spencer266e42b2006-12-23 06:05:41 +00004044 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4045 I.getType(), TD) &&
4046 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4047 I.getType(), TD)) {
Reid Spencer799b5bf2006-12-13 08:27:15 +00004048 Instruction *NewOp = BinaryOperator::createXor(Op0C->getOperand(0),
4049 Op1C->getOperand(0),
4050 I.getName());
4051 InsertNewInstBefore(NewOp, I);
4052 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
4053 }
Chris Lattner3af10532006-05-05 06:39:07 +00004054 }
Chris Lattnerf05d69a2006-11-14 07:46:50 +00004055
4056 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
4057 if (ShiftInst *SI1 = dyn_cast<ShiftInst>(Op1)) {
4058 if (ShiftInst *SI0 = dyn_cast<ShiftInst>(Op0))
4059 if (SI0->getOpcode() == SI1->getOpcode() &&
4060 SI0->getOperand(1) == SI1->getOperand(1) &&
4061 (SI0->hasOneUse() || SI1->hasOneUse())) {
4062 Instruction *NewOp =
4063 InsertNewInstBefore(BinaryOperator::createXor(SI0->getOperand(0),
4064 SI1->getOperand(0),
4065 SI0->getName()), I);
4066 return new ShiftInst(SI1->getOpcode(), NewOp, SI1->getOperand(1));
4067 }
4068 }
Chris Lattner3af10532006-05-05 06:39:07 +00004069
Chris Lattner113f4f42002-06-25 16:13:24 +00004070 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004071}
4072
Chris Lattner6862fbd2004-09-29 17:40:11 +00004073static bool isPositive(ConstantInt *C) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00004074 return C->getSExtValue() >= 0;
Chris Lattner6862fbd2004-09-29 17:40:11 +00004075}
4076
4077/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
4078/// overflowed for this type.
4079static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
4080 ConstantInt *In2) {
4081 Result = cast<ConstantInt>(ConstantExpr::getAdd(In1, In2));
4082
Reid Spencerc635f472006-12-31 05:48:39 +00004083 return cast<ConstantInt>(Result)->getZExtValue() <
4084 cast<ConstantInt>(In1)->getZExtValue();
Chris Lattner6862fbd2004-09-29 17:40:11 +00004085}
4086
Chris Lattner0798af32005-01-13 20:14:25 +00004087/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
4088/// code necessary to compute the offset from the base pointer (without adding
4089/// in the base pointer). Return the result as a signed integer of intptr size.
4090static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
4091 TargetData &TD = IC.getTargetData();
4092 gep_type_iterator GTI = gep_type_begin(GEP);
Reid Spencer266e42b2006-12-23 06:05:41 +00004093 const Type *IntPtrTy = TD.getIntPtrType();
4094 Value *Result = Constant::getNullValue(IntPtrTy);
Chris Lattner0798af32005-01-13 20:14:25 +00004095
4096 // Build a mask for high order bits.
Chris Lattner77defba2006-02-07 07:00:41 +00004097 uint64_t PtrSizeMask = ~0ULL >> (64-TD.getPointerSize()*8);
Chris Lattner0798af32005-01-13 20:14:25 +00004098
Chris Lattner0798af32005-01-13 20:14:25 +00004099 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
4100 Value *Op = GEP->getOperand(i);
Chris Lattnerd35d2102005-01-13 23:26:48 +00004101 uint64_t Size = TD.getTypeSize(GTI.getIndexedType()) & PtrSizeMask;
Reid Spencer266e42b2006-12-23 06:05:41 +00004102 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
Chris Lattner0798af32005-01-13 20:14:25 +00004103 if (Constant *OpC = dyn_cast<Constant>(Op)) {
4104 if (!OpC->isNullValue()) {
Reid Spencer266e42b2006-12-23 06:05:41 +00004105 OpC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
Chris Lattner0798af32005-01-13 20:14:25 +00004106 Scale = ConstantExpr::getMul(OpC, Scale);
4107 if (Constant *RC = dyn_cast<Constant>(Result))
4108 Result = ConstantExpr::getAdd(RC, Scale);
4109 else {
4110 // Emit an add instruction.
4111 Result = IC.InsertNewInstBefore(
4112 BinaryOperator::createAdd(Result, Scale,
4113 GEP->getName()+".offs"), I);
4114 }
4115 }
4116 } else {
Chris Lattner7aa41cf2005-01-14 17:17:59 +00004117 // Convert to correct type.
Reid Spencer266e42b2006-12-23 06:05:41 +00004118 Op = IC.InsertNewInstBefore(CastInst::createSExtOrBitCast(Op, IntPtrTy,
Chris Lattner7aa41cf2005-01-14 17:17:59 +00004119 Op->getName()+".c"), I);
4120 if (Size != 1)
Chris Lattner4cb9fa32005-01-13 20:40:58 +00004121 // We'll let instcombine(mul) convert this to a shl if possible.
4122 Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
4123 GEP->getName()+".idx"), I);
Chris Lattner0798af32005-01-13 20:14:25 +00004124
4125 // Emit an add instruction.
Chris Lattner4cb9fa32005-01-13 20:40:58 +00004126 Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
Chris Lattner0798af32005-01-13 20:14:25 +00004127 GEP->getName()+".offs"), I);
4128 }
4129 }
4130 return Result;
4131}
4132
Reid Spencer266e42b2006-12-23 06:05:41 +00004133/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
Chris Lattner0798af32005-01-13 20:14:25 +00004134/// else. At this point we know that the GEP is on the LHS of the comparison.
Reid Spencer266e42b2006-12-23 06:05:41 +00004135Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
4136 ICmpInst::Predicate Cond,
4137 Instruction &I) {
Chris Lattner0798af32005-01-13 20:14:25 +00004138 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattner81e84172005-01-13 22:25:21 +00004139
4140 if (CastInst *CI = dyn_cast<CastInst>(RHS))
4141 if (isa<PointerType>(CI->getOperand(0)->getType()))
4142 RHS = CI->getOperand(0);
4143
Chris Lattner0798af32005-01-13 20:14:25 +00004144 Value *PtrBase = GEPLHS->getOperand(0);
4145 if (PtrBase == RHS) {
4146 // As an optimization, we don't actually have to compute the actual value of
Reid Spencer266e42b2006-12-23 06:05:41 +00004147 // OFFSET if this is a icmp_eq or icmp_ne comparison, just return whether
4148 // each index is zero or not.
4149 if (Cond == ICmpInst::ICMP_EQ || Cond == ICmpInst::ICMP_NE) {
Chris Lattner81e84172005-01-13 22:25:21 +00004150 Instruction *InVal = 0;
Chris Lattnercd517ff2005-01-28 19:32:01 +00004151 gep_type_iterator GTI = gep_type_begin(GEPLHS);
4152 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i, ++GTI) {
Chris Lattner81e84172005-01-13 22:25:21 +00004153 bool EmitIt = true;
4154 if (Constant *C = dyn_cast<Constant>(GEPLHS->getOperand(i))) {
4155 if (isa<UndefValue>(C)) // undef index -> undef.
4156 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
4157 if (C->isNullValue())
4158 EmitIt = false;
Chris Lattnercd517ff2005-01-28 19:32:01 +00004159 else if (TD->getTypeSize(GTI.getIndexedType()) == 0) {
4160 EmitIt = false; // This is indexing into a zero sized array?
Misha Brukmanb1c93172005-04-21 23:48:37 +00004161 } else if (isa<ConstantInt>(C))
Chris Lattner81e84172005-01-13 22:25:21 +00004162 return ReplaceInstUsesWith(I, // No comparison is needed here.
Reid Spencer266e42b2006-12-23 06:05:41 +00004163 ConstantBool::get(Cond == ICmpInst::ICMP_NE));
Chris Lattner81e84172005-01-13 22:25:21 +00004164 }
4165
4166 if (EmitIt) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00004167 Instruction *Comp =
Reid Spencer266e42b2006-12-23 06:05:41 +00004168 new ICmpInst(Cond, GEPLHS->getOperand(i),
Chris Lattner81e84172005-01-13 22:25:21 +00004169 Constant::getNullValue(GEPLHS->getOperand(i)->getType()));
4170 if (InVal == 0)
4171 InVal = Comp;
4172 else {
4173 InVal = InsertNewInstBefore(InVal, I);
4174 InsertNewInstBefore(Comp, I);
Reid Spencer266e42b2006-12-23 06:05:41 +00004175 if (Cond == ICmpInst::ICMP_NE) // True if any are unequal
Chris Lattner81e84172005-01-13 22:25:21 +00004176 InVal = BinaryOperator::createOr(InVal, Comp);
4177 else // True if all are equal
4178 InVal = BinaryOperator::createAnd(InVal, Comp);
4179 }
4180 }
4181 }
4182
4183 if (InVal)
4184 return InVal;
4185 else
Reid Spencer266e42b2006-12-23 06:05:41 +00004186 // No comparison is needed here, all indexes = 0
4187 ReplaceInstUsesWith(I, ConstantBool::get(Cond == ICmpInst::ICMP_EQ));
Chris Lattner81e84172005-01-13 22:25:21 +00004188 }
Chris Lattner0798af32005-01-13 20:14:25 +00004189
Reid Spencer266e42b2006-12-23 06:05:41 +00004190 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner0798af32005-01-13 20:14:25 +00004191 // the result to fold to a constant!
4192 if (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) {
4193 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
4194 Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
Reid Spencer266e42b2006-12-23 06:05:41 +00004195 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
4196 Constant::getNullValue(Offset->getType()));
Chris Lattner0798af32005-01-13 20:14:25 +00004197 }
4198 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
Chris Lattnera21bf8d2005-04-25 20:17:30 +00004199 // If the base pointers are different, but the indices are the same, just
4200 // compare the base pointer.
4201 if (PtrBase != GEPRHS->getOperand(0)) {
4202 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00004203 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattnerbd43b9d2005-04-26 14:40:41 +00004204 GEPRHS->getOperand(0)->getType();
Chris Lattnera21bf8d2005-04-25 20:17:30 +00004205 if (IndicesTheSame)
4206 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4207 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4208 IndicesTheSame = false;
4209 break;
4210 }
4211
4212 // If all indices are the same, just compare the base pointers.
4213 if (IndicesTheSame)
Reid Spencer266e42b2006-12-23 06:05:41 +00004214 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
4215 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattnera21bf8d2005-04-25 20:17:30 +00004216
4217 // Otherwise, the base pointers are different and the indices are
4218 // different, bail out.
Chris Lattner0798af32005-01-13 20:14:25 +00004219 return 0;
Chris Lattnera21bf8d2005-04-25 20:17:30 +00004220 }
Chris Lattner0798af32005-01-13 20:14:25 +00004221
Chris Lattner81e84172005-01-13 22:25:21 +00004222 // If one of the GEPs has all zero indices, recurse.
4223 bool AllZeros = true;
4224 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4225 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
4226 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
4227 AllZeros = false;
4228 break;
4229 }
4230 if (AllZeros)
Reid Spencer266e42b2006-12-23 06:05:41 +00004231 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
4232 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner4fa89822005-01-14 00:20:05 +00004233
4234 // If the other GEP has all zero indices, recurse.
Chris Lattner81e84172005-01-13 22:25:21 +00004235 AllZeros = true;
4236 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4237 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
4238 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
4239 AllZeros = false;
4240 break;
4241 }
4242 if (AllZeros)
Reid Spencer266e42b2006-12-23 06:05:41 +00004243 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
Chris Lattner81e84172005-01-13 22:25:21 +00004244
Chris Lattner4fa89822005-01-14 00:20:05 +00004245 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
4246 // If the GEPs only differ by one index, compare it.
4247 unsigned NumDifferences = 0; // Keep track of # differences.
4248 unsigned DiffOperand = 0; // The operand that differs.
4249 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4250 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004251 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
4252 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattnerfc4429e2005-01-21 23:06:49 +00004253 // Irreconcilable differences.
Chris Lattner4fa89822005-01-14 00:20:05 +00004254 NumDifferences = 2;
4255 break;
4256 } else {
4257 if (NumDifferences++) break;
4258 DiffOperand = i;
4259 }
4260 }
4261
4262 if (NumDifferences == 0) // SAME GEP?
4263 return ReplaceInstUsesWith(I, // No comparison is needed here.
Reid Spencer266e42b2006-12-23 06:05:41 +00004264 ConstantBool::get(Cond == ICmpInst::ICMP_EQ));
Chris Lattner4fa89822005-01-14 00:20:05 +00004265 else if (NumDifferences == 1) {
Chris Lattnerfc4429e2005-01-21 23:06:49 +00004266 Value *LHSV = GEPLHS->getOperand(DiffOperand);
4267 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Reid Spencer266e42b2006-12-23 06:05:41 +00004268 // Make sure we do a signed comparison here.
4269 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
Chris Lattner4fa89822005-01-14 00:20:05 +00004270 }
4271 }
4272
Reid Spencer266e42b2006-12-23 06:05:41 +00004273 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner0798af32005-01-13 20:14:25 +00004274 // the result to fold to a constant!
4275 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
4276 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
4277 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
4278 Value *L = EmitGEPOffset(GEPLHS, I, *this);
4279 Value *R = EmitGEPOffset(GEPRHS, I, *this);
Reid Spencer266e42b2006-12-23 06:05:41 +00004280 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
Chris Lattner0798af32005-01-13 20:14:25 +00004281 }
4282 }
4283 return 0;
4284}
4285
Reid Spencer266e42b2006-12-23 06:05:41 +00004286Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
4287 bool Changed = SimplifyCompare(I);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004288 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004289
Reid Spencer266e42b2006-12-23 06:05:41 +00004290 // fcmp pred X, X
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004291 if (Op0 == Op1)
4292 return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
Chris Lattner1fc23f32002-05-09 20:11:54 +00004293
Reid Spencer266e42b2006-12-23 06:05:41 +00004294 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
Chris Lattner81a7a232004-10-16 18:11:37 +00004295 return ReplaceInstUsesWith(I, UndefValue::get(Type::BoolTy));
4296
Reid Spencer266e42b2006-12-23 06:05:41 +00004297 // Handle fcmp with constant RHS
4298 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
4299 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4300 switch (LHSI->getOpcode()) {
4301 case Instruction::PHI:
4302 if (Instruction *NV = FoldOpIntoPhi(I))
4303 return NV;
4304 break;
4305 case Instruction::Select:
4306 // If either operand of the select is a constant, we can fold the
4307 // comparison into the select arms, which will cause one to be
4308 // constant folded and the select turned into a bitwise or.
4309 Value *Op1 = 0, *Op2 = 0;
4310 if (LHSI->hasOneUse()) {
4311 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
4312 // Fold the known value into the constant operand.
4313 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
4314 // Insert a new FCmp of the other select operand.
4315 Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
4316 LHSI->getOperand(2), RHSC,
4317 I.getName()), I);
4318 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
4319 // Fold the known value into the constant operand.
4320 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
4321 // Insert a new FCmp of the other select operand.
4322 Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
4323 LHSI->getOperand(1), RHSC,
4324 I.getName()), I);
4325 }
4326 }
4327
4328 if (Op1)
4329 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
4330 break;
4331 }
4332 }
4333
4334 return Changed ? &I : 0;
4335}
4336
4337Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
4338 bool Changed = SimplifyCompare(I);
4339 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4340 const Type *Ty = Op0->getType();
4341
4342 // icmp X, X
4343 if (Op0 == Op1)
4344 return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
4345
4346 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
4347 return ReplaceInstUsesWith(I, UndefValue::get(Type::BoolTy));
4348
4349 // icmp of GlobalValues can never equal each other as long as they aren't
4350 // external weak linkage type.
4351 if (GlobalValue *GV0 = dyn_cast<GlobalValue>(Op0))
4352 if (GlobalValue *GV1 = dyn_cast<GlobalValue>(Op1))
4353 if (!GV0->hasExternalWeakLinkage() || !GV1->hasExternalWeakLinkage())
4354 return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
4355
4356 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
Chris Lattner15ff1e12004-11-14 07:33:16 +00004357 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanb1c93172005-04-21 23:48:37 +00004358 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
4359 isa<ConstantPointerNull>(Op0)) &&
4360 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner15ff1e12004-11-14 07:33:16 +00004361 isa<ConstantPointerNull>(Op1)))
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004362 return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
4363
Reid Spencer266e42b2006-12-23 06:05:41 +00004364 // icmp's with boolean values can always be turned into bitwise operations
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004365 if (Ty == Type::BoolTy) {
Reid Spencer266e42b2006-12-23 06:05:41 +00004366 switch (I.getPredicate()) {
4367 default: assert(0 && "Invalid icmp instruction!");
4368 case ICmpInst::ICMP_EQ: { // icmp eq bool %A, %B -> ~(A^B)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004369 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004370 InsertNewInstBefore(Xor, I);
Chris Lattner16930792003-11-03 04:25:02 +00004371 return BinaryOperator::createNot(Xor);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004372 }
Reid Spencer266e42b2006-12-23 06:05:41 +00004373 case ICmpInst::ICMP_NE: // icmp eq bool %A, %B -> A^B
Chris Lattner4456da62004-08-11 00:50:51 +00004374 return BinaryOperator::createXor(Op0, Op1);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004375
Reid Spencer266e42b2006-12-23 06:05:41 +00004376 case ICmpInst::ICMP_UGT:
4377 case ICmpInst::ICMP_SGT:
4378 std::swap(Op0, Op1); // Change icmp gt -> icmp lt
Chris Lattner4456da62004-08-11 00:50:51 +00004379 // FALL THROUGH
Reid Spencer266e42b2006-12-23 06:05:41 +00004380 case ICmpInst::ICMP_ULT:
4381 case ICmpInst::ICMP_SLT: { // icmp lt bool A, B -> ~X & Y
Chris Lattner4456da62004-08-11 00:50:51 +00004382 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4383 InsertNewInstBefore(Not, I);
4384 return BinaryOperator::createAnd(Not, Op1);
4385 }
Reid Spencer266e42b2006-12-23 06:05:41 +00004386 case ICmpInst::ICMP_UGE:
4387 case ICmpInst::ICMP_SGE:
4388 std::swap(Op0, Op1); // Change icmp ge -> icmp le
Chris Lattner4456da62004-08-11 00:50:51 +00004389 // FALL THROUGH
Reid Spencer266e42b2006-12-23 06:05:41 +00004390 case ICmpInst::ICMP_ULE:
4391 case ICmpInst::ICMP_SLE: { // icmp le bool %A, %B -> ~A | B
Chris Lattner4456da62004-08-11 00:50:51 +00004392 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4393 InsertNewInstBefore(Not, I);
4394 return BinaryOperator::createOr(Not, Op1);
4395 }
4396 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004397 }
4398
Chris Lattner2dd01742004-06-09 04:24:29 +00004399 // See if we are doing a comparison between a constant and an instruction that
4400 // can be folded into the comparison.
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004401 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00004402 switch (I.getPredicate()) {
4403 default: break;
4404 case ICmpInst::ICMP_ULT: // A <u MIN -> FALSE
4405 if (CI->isMinValue(false))
Chris Lattner6ab03f62006-09-28 23:35:22 +00004406 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004407 if (CI->isMaxValue(false)) // A <u MAX -> A != MAX
4408 return new ICmpInst(ICmpInst::ICMP_NE, Op0,Op1);
4409 if (isMinValuePlusOne(CI,false)) // A <u MIN+1 -> A == MIN
4410 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
4411 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00004412
Reid Spencer266e42b2006-12-23 06:05:41 +00004413 case ICmpInst::ICMP_SLT:
4414 if (CI->isMinValue(true)) // A <s MIN -> FALSE
Chris Lattner6ab03f62006-09-28 23:35:22 +00004415 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004416 if (CI->isMaxValue(true)) // A <s MAX -> A != MAX
4417 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4418 if (isMinValuePlusOne(CI,true)) // A <s MIN+1 -> A == MIN
4419 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
4420 break;
4421
4422 case ICmpInst::ICMP_UGT:
4423 if (CI->isMaxValue(false)) // A >u MAX -> FALSE
4424 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4425 if (CI->isMinValue(false)) // A >u MIN -> A != MIN
4426 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4427 if (isMaxValueMinusOne(CI, false)) // A >u MAX-1 -> A == MAX
4428 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
4429 break;
4430
4431 case ICmpInst::ICMP_SGT:
4432 if (CI->isMaxValue(true)) // A >s MAX -> FALSE
4433 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4434 if (CI->isMinValue(true)) // A >s MIN -> A != MIN
4435 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4436 if (isMaxValueMinusOne(CI, true)) // A >s MAX-1 -> A == MAX
4437 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
4438 break;
4439
4440 case ICmpInst::ICMP_ULE:
4441 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
Chris Lattner6ab03f62006-09-28 23:35:22 +00004442 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004443 if (CI->isMinValue(false)) // A <=u MIN -> A == MIN
4444 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4445 if (isMaxValueMinusOne(CI,false)) // A <=u MAX-1 -> A != MAX
4446 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
4447 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00004448
Reid Spencer266e42b2006-12-23 06:05:41 +00004449 case ICmpInst::ICMP_SLE:
4450 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
4451 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4452 if (CI->isMinValue(true)) // A <=s MIN -> A == MIN
4453 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4454 if (isMaxValueMinusOne(CI,true)) // A <=s MAX-1 -> A != MAX
4455 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
4456 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00004457
Reid Spencer266e42b2006-12-23 06:05:41 +00004458 case ICmpInst::ICMP_UGE:
4459 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
4460 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4461 if (CI->isMaxValue(false)) // A >=u MAX -> A == MAX
4462 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4463 if (isMinValuePlusOne(CI,false)) // A >=u MIN-1 -> A != MIN
4464 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
4465 break;
4466
4467 case ICmpInst::ICMP_SGE:
4468 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
4469 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4470 if (CI->isMaxValue(true)) // A >=s MAX -> A == MAX
4471 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4472 if (isMinValuePlusOne(CI,true)) // A >=s MIN-1 -> A != MIN
4473 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
4474 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00004475 }
4476
Reid Spencer266e42b2006-12-23 06:05:41 +00004477 // If we still have a icmp le or icmp ge instruction, turn it into the
4478 // appropriate icmp lt or icmp gt instruction. Since the border cases have
Chris Lattner6862fbd2004-09-29 17:40:11 +00004479 // already been handled above, this requires little checking.
4480 //
Reid Spencer266e42b2006-12-23 06:05:41 +00004481 if (I.getPredicate() == ICmpInst::ICMP_ULE)
4482 return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
4483 if (I.getPredicate() == ICmpInst::ICMP_SLE)
4484 return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
4485 if (I.getPredicate() == ICmpInst::ICMP_UGE)
4486 return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
4487 if (I.getPredicate() == ICmpInst::ICMP_SGE)
4488 return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
Chris Lattneree0f2802006-02-12 02:07:56 +00004489
4490 // See if we can fold the comparison based on bits known to be zero or one
4491 // in the input.
4492 uint64_t KnownZero, KnownOne;
4493 if (SimplifyDemandedBits(Op0, Ty->getIntegralTypeMask(),
4494 KnownZero, KnownOne, 0))
4495 return &I;
4496
4497 // Given the known and unknown bits, compute a range that the LHS could be
4498 // in.
4499 if (KnownOne | KnownZero) {
Reid Spencer266e42b2006-12-23 06:05:41 +00004500 // Compute the Min, Max and RHS values based on the known bits. For the
4501 // EQ and NE we use unsigned values.
Reid Spencer910f23f2006-12-23 19:17:57 +00004502 uint64_t UMin = 0, UMax = 0, URHSVal = 0;
4503 int64_t SMin = 0, SMax = 0, SRHSVal = 0;
Reid Spencer266e42b2006-12-23 06:05:41 +00004504 if (ICmpInst::isSignedPredicate(I.getPredicate())) {
4505 SRHSVal = CI->getSExtValue();
4506 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, SMin,
4507 SMax);
4508 } else {
4509 URHSVal = CI->getZExtValue();
4510 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, UMin,
4511 UMax);
4512 }
4513 switch (I.getPredicate()) { // LE/GE have been folded already.
4514 default: assert(0 && "Unknown icmp opcode!");
4515 case ICmpInst::ICMP_EQ:
4516 if (UMax < URHSVal || UMin > URHSVal)
4517 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4518 break;
4519 case ICmpInst::ICMP_NE:
4520 if (UMax < URHSVal || UMin > URHSVal)
4521 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4522 break;
4523 case ICmpInst::ICMP_ULT:
4524 if (UMax < URHSVal)
4525 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4526 if (UMin > URHSVal)
4527 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4528 break;
4529 case ICmpInst::ICMP_UGT:
4530 if (UMin > URHSVal)
4531 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4532 if (UMax < URHSVal)
4533 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4534 break;
4535 case ICmpInst::ICMP_SLT:
4536 if (SMax < SRHSVal)
4537 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4538 if (SMin > SRHSVal)
4539 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4540 break;
4541 case ICmpInst::ICMP_SGT:
4542 if (SMin > SRHSVal)
4543 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4544 if (SMax < SRHSVal)
4545 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4546 break;
Chris Lattneree0f2802006-02-12 02:07:56 +00004547 }
4548 }
4549
Reid Spencer266e42b2006-12-23 06:05:41 +00004550 // Since the RHS is a ConstantInt (CI), if the left hand side is an
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004551 // instruction, see if that instruction also has constants so that the
Reid Spencer266e42b2006-12-23 06:05:41 +00004552 // instruction can be folded into the icmp
Chris Lattnere1e10e12004-05-25 06:32:08 +00004553 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004554 switch (LHSI->getOpcode()) {
4555 case Instruction::And:
4556 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
4557 LHSI->getOperand(0)->hasOneUse()) {
Chris Lattner4922a0e2006-09-18 05:27:43 +00004558 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
4559
Reid Spencer266e42b2006-12-23 06:05:41 +00004560 // If the LHS is an AND of a truncating cast, we can widen the
Chris Lattner4922a0e2006-09-18 05:27:43 +00004561 // and/compare to be the input width without changing the value
4562 // produced, eliminating a cast.
4563 if (CastInst *Cast = dyn_cast<CastInst>(LHSI->getOperand(0))) {
4564 // We can do this transformation if either the AND constant does not
4565 // have its sign bit set or if it is an equality comparison.
4566 // Extending a relational comparison when we're checking the sign
4567 // bit would not work.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00004568 if (Cast->hasOneUse() && isa<TruncInst>(Cast) &&
Chris Lattner4922a0e2006-09-18 05:27:43 +00004569 (I.isEquality() ||
4570 (AndCST->getZExtValue() == (uint64_t)AndCST->getSExtValue()) &&
4571 (CI->getZExtValue() == (uint64_t)CI->getSExtValue()))) {
4572 ConstantInt *NewCST;
4573 ConstantInt *NewCI;
Reid Spencerc635f472006-12-31 05:48:39 +00004574 NewCST = ConstantInt::get(Cast->getOperand(0)->getType(),
4575 AndCST->getZExtValue());
4576 NewCI = ConstantInt::get(Cast->getOperand(0)->getType(),
4577 CI->getZExtValue());
Chris Lattner4922a0e2006-09-18 05:27:43 +00004578 Instruction *NewAnd =
4579 BinaryOperator::createAnd(Cast->getOperand(0), NewCST,
4580 LHSI->getName());
4581 InsertNewInstBefore(NewAnd, I);
Reid Spencer266e42b2006-12-23 06:05:41 +00004582 return new ICmpInst(I.getPredicate(), NewAnd, NewCI);
Chris Lattner4922a0e2006-09-18 05:27:43 +00004583 }
4584 }
4585
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004586 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
4587 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
4588 // happens a LOT in code produced by the C front-end, for bitfield
4589 // access.
4590 ShiftInst *Shift = dyn_cast<ShiftInst>(LHSI->getOperand(0));
Chris Lattneree0f2802006-02-12 02:07:56 +00004591
4592 // Check to see if there is a noop-cast between the shift and the and.
4593 if (!Shift) {
4594 if (CastInst *CI = dyn_cast<CastInst>(LHSI->getOperand(0)))
Reid Spencer74a528b2006-12-13 18:21:21 +00004595 if (CI->getOpcode() == Instruction::BitCast)
Chris Lattneree0f2802006-02-12 02:07:56 +00004596 Shift = dyn_cast<ShiftInst>(CI->getOperand(0));
4597 }
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004598
Reid Spencere0fc4df2006-10-20 07:07:24 +00004599 ConstantInt *ShAmt;
4600 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
Chris Lattneree0f2802006-02-12 02:07:56 +00004601 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
4602 const Type *AndTy = AndCST->getType(); // Type of the and.
Misha Brukmanb1c93172005-04-21 23:48:37 +00004603
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004604 // We can fold this as long as we can't shift unknown bits
4605 // into the mask. This can only happen with signed shift
4606 // rights, as they sign-extend.
4607 if (ShAmt) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004608 bool CanFold = Shift->isLogicalShift();
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004609 if (!CanFold) {
4610 // To test for the bad case of the signed shr, see if any
4611 // of the bits shifted in could be tested after the mask.
Reid Spencere0fc4df2006-10-20 07:07:24 +00004612 int ShAmtVal = Ty->getPrimitiveSizeInBits()-ShAmt->getZExtValue();
Chris Lattnerc53cb9d2005-06-17 01:29:28 +00004613 if (ShAmtVal < 0) ShAmtVal = 0; // Out of range shift.
4614
Reid Spencerc635f472006-12-31 05:48:39 +00004615 Constant *OShAmt = ConstantInt::get(Type::Int8Ty, ShAmtVal);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004616 Constant *ShVal =
Chris Lattneree0f2802006-02-12 02:07:56 +00004617 ConstantExpr::getShl(ConstantInt::getAllOnesValue(AndTy),
4618 OShAmt);
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004619 if (ConstantExpr::getAnd(ShVal, AndCST)->isNullValue())
4620 CanFold = true;
4621 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004622
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004623 if (CanFold) {
Chris Lattner6afc02f2004-09-28 17:54:07 +00004624 Constant *NewCst;
4625 if (Shift->getOpcode() == Instruction::Shl)
Reid Spencerfdff9382006-11-08 06:47:33 +00004626 NewCst = ConstantExpr::getLShr(CI, ShAmt);
Chris Lattner6afc02f2004-09-28 17:54:07 +00004627 else
4628 NewCst = ConstantExpr::getShl(CI, ShAmt);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004629
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004630 // Check to see if we are shifting out any of the bits being
4631 // compared.
4632 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != CI){
4633 // If we shifted bits out, the fold is not going to work out.
4634 // As a special case, check to see if this means that the
4635 // result is always true or false now.
Reid Spencer266e42b2006-12-23 06:05:41 +00004636 if (I.getPredicate() == ICmpInst::ICMP_EQ)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004637 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004638 if (I.getPredicate() == ICmpInst::ICMP_NE)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004639 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004640 } else {
4641 I.setOperand(1, NewCst);
Chris Lattner6afc02f2004-09-28 17:54:07 +00004642 Constant *NewAndCST;
4643 if (Shift->getOpcode() == Instruction::Shl)
Reid Spencerfdff9382006-11-08 06:47:33 +00004644 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
Chris Lattner6afc02f2004-09-28 17:54:07 +00004645 else
4646 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
4647 LHSI->setOperand(1, NewAndCST);
Reid Spencer6ff3e732007-01-04 05:23:51 +00004648 LHSI->setOperand(0, Shift->getOperand(0));
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004649 WorkList.push_back(Shift); // Shift is dead.
4650 AddUsesToWorkList(I);
4651 return &I;
Chris Lattner1638de42004-07-21 19:50:44 +00004652 }
4653 }
Chris Lattner35167c32004-06-09 07:59:58 +00004654 }
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004655
4656 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
4657 // preferable because it allows the C<<Y expression to be hoisted out
4658 // of a loop if Y is invariant and X is not.
4659 if (Shift && Shift->hasOneUse() && CI->isNullValue() &&
Chris Lattnerde077922006-09-18 18:27:05 +00004660 I.isEquality() && !Shift->isArithmeticShift() &&
4661 isa<Instruction>(Shift->getOperand(0))) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004662 // Compute C << Y.
4663 Value *NS;
Reid Spencerfdff9382006-11-08 06:47:33 +00004664 if (Shift->getOpcode() == Instruction::LShr) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004665 NS = new ShiftInst(Instruction::Shl, AndCST, Shift->getOperand(1),
4666 "tmp");
4667 } else {
Reid Spencer2a499b02006-12-13 17:19:09 +00004668 // Insert a logical shift.
4669 NS = new ShiftInst(Instruction::LShr, AndCST,
Chris Lattner4922a0e2006-09-18 05:27:43 +00004670 Shift->getOperand(1), "tmp");
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004671 }
4672 InsertNewInstBefore(cast<Instruction>(NS), I);
4673
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004674 // Compute X & (C << Y).
Reid Spencer6ff3e732007-01-04 05:23:51 +00004675 Instruction *NewAnd = BinaryOperator::createAnd(
4676 Shift->getOperand(0), NS, LHSI->getName());
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004677 InsertNewInstBefore(NewAnd, I);
4678
4679 I.setOperand(0, NewAnd);
4680 return &I;
4681 }
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004682 }
4683 break;
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004684
Reid Spencer266e42b2006-12-23 06:05:41 +00004685 case Instruction::Shl: // (icmp pred (shl X, ShAmt), CI)
Reid Spencere0fc4df2006-10-20 07:07:24 +00004686 if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004687 if (I.isEquality()) {
Chris Lattner19b57f52005-06-15 20:53:31 +00004688 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
4689
4690 // Check that the shift amount is in range. If not, don't perform
4691 // undefined shifts. When the shift is visited it will be
4692 // simplified.
Reid Spencere0fc4df2006-10-20 07:07:24 +00004693 if (ShAmt->getZExtValue() >= TypeBits)
Chris Lattner19b57f52005-06-15 20:53:31 +00004694 break;
4695
Chris Lattner272d5ca2004-09-28 18:22:15 +00004696 // If we are comparing against bits always shifted out, the
4697 // comparison cannot succeed.
Misha Brukmanb1c93172005-04-21 23:48:37 +00004698 Constant *Comp =
Reid Spencerfdff9382006-11-08 06:47:33 +00004699 ConstantExpr::getShl(ConstantExpr::getLShr(CI, ShAmt), ShAmt);
Chris Lattner272d5ca2004-09-28 18:22:15 +00004700 if (Comp != CI) {// Comparing against a bit that we know is zero.
Reid Spencer266e42b2006-12-23 06:05:41 +00004701 bool IsICMP_NE = I.getPredicate() == ICmpInst::ICMP_NE;
4702 Constant *Cst = ConstantBool::get(IsICMP_NE);
Chris Lattner272d5ca2004-09-28 18:22:15 +00004703 return ReplaceInstUsesWith(I, Cst);
4704 }
4705
4706 if (LHSI->hasOneUse()) {
4707 // Otherwise strength reduce the shift into an and.
Reid Spencere0fc4df2006-10-20 07:07:24 +00004708 unsigned ShAmtVal = (unsigned)ShAmt->getZExtValue();
Chris Lattner272d5ca2004-09-28 18:22:15 +00004709 uint64_t Val = (1ULL << (TypeBits-ShAmtVal))-1;
Reid Spencerc635f472006-12-31 05:48:39 +00004710 Constant *Mask = ConstantInt::get(CI->getType(), Val);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004711
Chris Lattner272d5ca2004-09-28 18:22:15 +00004712 Instruction *AndI =
4713 BinaryOperator::createAnd(LHSI->getOperand(0),
4714 Mask, LHSI->getName()+".mask");
4715 Value *And = InsertNewInstBefore(AndI, I);
Reid Spencer266e42b2006-12-23 06:05:41 +00004716 return new ICmpInst(I.getPredicate(), And,
Reid Spencerfdff9382006-11-08 06:47:33 +00004717 ConstantExpr::getLShr(CI, ShAmt));
Chris Lattner272d5ca2004-09-28 18:22:15 +00004718 }
4719 }
Chris Lattner272d5ca2004-09-28 18:22:15 +00004720 }
4721 break;
4722
Reid Spencer266e42b2006-12-23 06:05:41 +00004723 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
Reid Spencerfdff9382006-11-08 06:47:33 +00004724 case Instruction::AShr:
Reid Spencere0fc4df2006-10-20 07:07:24 +00004725 if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004726 if (I.isEquality()) {
Chris Lattner19b57f52005-06-15 20:53:31 +00004727 // Check that the shift amount is in range. If not, don't perform
4728 // undefined shifts. When the shift is visited it will be
4729 // simplified.
Chris Lattner104002b2005-06-16 01:52:07 +00004730 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
Reid Spencere0fc4df2006-10-20 07:07:24 +00004731 if (ShAmt->getZExtValue() >= TypeBits)
Chris Lattner19b57f52005-06-15 20:53:31 +00004732 break;
4733
Chris Lattner1023b872004-09-27 16:18:50 +00004734 // If we are comparing against bits always shifted out, the
4735 // comparison cannot succeed.
Reid Spencerfdff9382006-11-08 06:47:33 +00004736 Constant *Comp;
Reid Spencerc635f472006-12-31 05:48:39 +00004737 if (LHSI->getOpcode() == Instruction::LShr)
Reid Spencerfdff9382006-11-08 06:47:33 +00004738 Comp = ConstantExpr::getLShr(ConstantExpr::getShl(CI, ShAmt),
4739 ShAmt);
4740 else
4741 Comp = ConstantExpr::getAShr(ConstantExpr::getShl(CI, ShAmt),
4742 ShAmt);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004743
Chris Lattner1023b872004-09-27 16:18:50 +00004744 if (Comp != CI) {// Comparing against a bit that we know is zero.
Reid Spencer266e42b2006-12-23 06:05:41 +00004745 bool IsICMP_NE = I.getPredicate() == ICmpInst::ICMP_NE;
4746 Constant *Cst = ConstantBool::get(IsICMP_NE);
Chris Lattner1023b872004-09-27 16:18:50 +00004747 return ReplaceInstUsesWith(I, Cst);
4748 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004749
Chris Lattner1023b872004-09-27 16:18:50 +00004750 if (LHSI->hasOneUse() || CI->isNullValue()) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00004751 unsigned ShAmtVal = (unsigned)ShAmt->getZExtValue();
Chris Lattner272d5ca2004-09-28 18:22:15 +00004752
Chris Lattner1023b872004-09-27 16:18:50 +00004753 // Otherwise strength reduce the shift into an and.
4754 uint64_t Val = ~0ULL; // All ones.
4755 Val <<= ShAmtVal; // Shift over to the right spot.
Reid Spencerc635f472006-12-31 05:48:39 +00004756 Val &= ~0ULL >> (64-TypeBits);
4757 Constant *Mask = ConstantInt::get(CI->getType(), Val);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004758
Chris Lattner1023b872004-09-27 16:18:50 +00004759 Instruction *AndI =
4760 BinaryOperator::createAnd(LHSI->getOperand(0),
4761 Mask, LHSI->getName()+".mask");
4762 Value *And = InsertNewInstBefore(AndI, I);
Reid Spencer266e42b2006-12-23 06:05:41 +00004763 return new ICmpInst(I.getPredicate(), And,
Chris Lattner1023b872004-09-27 16:18:50 +00004764 ConstantExpr::getShl(CI, ShAmt));
4765 }
Chris Lattner1023b872004-09-27 16:18:50 +00004766 }
4767 }
4768 break;
Chris Lattner7e794272004-09-24 15:21:34 +00004769
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004770 case Instruction::SDiv:
4771 case Instruction::UDiv:
Reid Spencer266e42b2006-12-23 06:05:41 +00004772 // Fold: icmp pred ([us]div X, C1), C2 -> range test
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004773 // Fold this div into the comparison, producing a range check.
4774 // Determine, based on the divide type, what the range is being
4775 // checked. If there is an overflow on the low or high side, remember
4776 // it, otherwise compute the range [low, hi) bounding the new value.
4777 // See: InsertRangeTest above for the kinds of replacements possible.
Chris Lattner6862fbd2004-09-29 17:40:11 +00004778 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004779 // FIXME: If the operand types don't match the type of the divide
4780 // then don't attempt this transform. The code below doesn't have the
4781 // logic to deal with a signed divide and an unsigned compare (and
4782 // vice versa). This is because (x /s C1) <s C2 produces different
4783 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
4784 // (x /u C1) <u C2. Simply casting the operands and result won't
4785 // work. :( The if statement below tests that condition and bails
4786 // if it finds it.
Reid Spencer266e42b2006-12-23 06:05:41 +00004787 bool DivIsSigned = LHSI->getOpcode() == Instruction::SDiv;
4788 if (!I.isEquality() && DivIsSigned != I.isSignedPredicate())
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004789 break;
4790
4791 // Initialize the variables that will indicate the nature of the
4792 // range check.
4793 bool LoOverflow = false, HiOverflow = false;
Chris Lattner6862fbd2004-09-29 17:40:11 +00004794 ConstantInt *LoBound = 0, *HiBound = 0;
4795
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004796 // Compute Prod = CI * DivRHS. We are essentially solving an equation
4797 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
4798 // C2 (CI). By solving for X we can turn this into a range check
4799 // instead of computing a divide.
4800 ConstantInt *Prod =
4801 cast<ConstantInt>(ConstantExpr::getMul(CI, DivRHS));
Chris Lattner6862fbd2004-09-29 17:40:11 +00004802
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004803 // Determine if the product overflows by seeing if the product is
4804 // not equal to the divide. Make sure we do the same kind of divide
4805 // as in the LHS instruction that we're folding.
4806 bool ProdOV = !DivRHS->isNullValue() &&
Reid Spencer266e42b2006-12-23 06:05:41 +00004807 (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004808 ConstantExpr::getUDiv(Prod, DivRHS)) != CI;
4809
Reid Spencer266e42b2006-12-23 06:05:41 +00004810 // Get the ICmp opcode
4811 ICmpInst::Predicate predicate = I.getPredicate();
Chris Lattnera92af962004-10-11 19:40:04 +00004812
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004813 if (DivRHS->isNullValue()) {
4814 // Don't hack on divide by zeros!
Reid Spencer266e42b2006-12-23 06:05:41 +00004815 } else if (!DivIsSigned) { // udiv
Chris Lattner6862fbd2004-09-29 17:40:11 +00004816 LoBound = Prod;
4817 LoOverflow = ProdOV;
4818 HiOverflow = ProdOV || AddWithOverflow(HiBound, LoBound, DivRHS);
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004819 } else if (isPositive(DivRHS)) { // Divisor is > 0.
Chris Lattner6862fbd2004-09-29 17:40:11 +00004820 if (CI->isNullValue()) { // (X / pos) op 0
4821 // Can't overflow.
4822 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
4823 HiBound = DivRHS;
4824 } else if (isPositive(CI)) { // (X / pos) op pos
4825 LoBound = Prod;
4826 LoOverflow = ProdOV;
4827 HiOverflow = ProdOV || AddWithOverflow(HiBound, Prod, DivRHS);
4828 } else { // (X / pos) op neg
4829 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
4830 LoOverflow = AddWithOverflow(LoBound, Prod,
4831 cast<ConstantInt>(DivRHSH));
4832 HiBound = Prod;
4833 HiOverflow = ProdOV;
4834 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004835 } else { // Divisor is < 0.
Chris Lattner6862fbd2004-09-29 17:40:11 +00004836 if (CI->isNullValue()) { // (X / neg) op 0
4837 LoBound = AddOne(DivRHS);
4838 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner73bcba52005-06-17 02:05:55 +00004839 if (HiBound == DivRHS)
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004840 LoBound = 0; // - INTMIN = INTMIN
Chris Lattner6862fbd2004-09-29 17:40:11 +00004841 } else if (isPositive(CI)) { // (X / neg) op pos
4842 HiOverflow = LoOverflow = ProdOV;
4843 if (!LoOverflow)
4844 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS));
4845 HiBound = AddOne(Prod);
4846 } else { // (X / neg) op neg
4847 LoBound = Prod;
4848 LoOverflow = HiOverflow = ProdOV;
4849 HiBound = cast<ConstantInt>(ConstantExpr::getSub(Prod, DivRHS));
4850 }
Chris Lattner0b41e862004-10-08 19:15:44 +00004851
Chris Lattnera92af962004-10-11 19:40:04 +00004852 // Dividing by a negate swaps the condition.
Reid Spencer266e42b2006-12-23 06:05:41 +00004853 predicate = ICmpInst::getSwappedPredicate(predicate);
Chris Lattner6862fbd2004-09-29 17:40:11 +00004854 }
4855
4856 if (LoBound) {
4857 Value *X = LHSI->getOperand(0);
Reid Spencer266e42b2006-12-23 06:05:41 +00004858 switch (predicate) {
4859 default: assert(0 && "Unhandled icmp opcode!");
4860 case ICmpInst::ICMP_EQ:
Chris Lattner6862fbd2004-09-29 17:40:11 +00004861 if (LoOverflow && HiOverflow)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004862 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattner6862fbd2004-09-29 17:40:11 +00004863 else if (HiOverflow)
Reid Spencer266e42b2006-12-23 06:05:41 +00004864 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
4865 ICmpInst::ICMP_UGE, X, LoBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00004866 else if (LoOverflow)
Reid Spencer266e42b2006-12-23 06:05:41 +00004867 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
4868 ICmpInst::ICMP_ULT, X, HiBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00004869 else
Reid Spencer266e42b2006-12-23 06:05:41 +00004870 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned,
4871 true, I);
4872 case ICmpInst::ICMP_NE:
Chris Lattner6862fbd2004-09-29 17:40:11 +00004873 if (LoOverflow && HiOverflow)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004874 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
Chris Lattner6862fbd2004-09-29 17:40:11 +00004875 else if (HiOverflow)
Reid Spencer266e42b2006-12-23 06:05:41 +00004876 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
4877 ICmpInst::ICMP_ULT, X, LoBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00004878 else if (LoOverflow)
Reid Spencer266e42b2006-12-23 06:05:41 +00004879 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
4880 ICmpInst::ICMP_UGE, X, HiBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00004881 else
Reid Spencer266e42b2006-12-23 06:05:41 +00004882 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned,
4883 false, I);
4884 case ICmpInst::ICMP_ULT:
4885 case ICmpInst::ICMP_SLT:
Chris Lattner6862fbd2004-09-29 17:40:11 +00004886 if (LoOverflow)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004887 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004888 return new ICmpInst(predicate, X, LoBound);
4889 case ICmpInst::ICMP_UGT:
4890 case ICmpInst::ICMP_SGT:
Chris Lattner6862fbd2004-09-29 17:40:11 +00004891 if (HiOverflow)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004892 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004893 if (predicate == ICmpInst::ICMP_UGT)
4894 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
4895 else
4896 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00004897 }
4898 }
4899 }
4900 break;
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004901 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004902
Reid Spencer266e42b2006-12-23 06:05:41 +00004903 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004904 if (I.isEquality()) {
Reid Spencer266e42b2006-12-23 06:05:41 +00004905 bool isICMP_NE = I.getPredicate() == ICmpInst::ICMP_NE;
Chris Lattnerd492a0b2003-07-23 17:02:11 +00004906
Reid Spencere0fc4df2006-10-20 07:07:24 +00004907 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
4908 // the second operand is a constant, simplify a bit.
Chris Lattnerc992add2003-08-13 05:33:12 +00004909 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
4910 switch (BO->getOpcode()) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00004911 case Instruction::SRem:
4912 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
4913 if (CI->isNullValue() && isa<ConstantInt>(BO->getOperand(1)) &&
4914 BO->hasOneUse()) {
4915 int64_t V = cast<ConstantInt>(BO->getOperand(1))->getSExtValue();
4916 if (V > 1 && isPowerOf2_64(V)) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00004917 Value *NewRem = InsertNewInstBefore(BinaryOperator::createURem(
4918 BO->getOperand(0), BO->getOperand(1), BO->getName()), I);
Reid Spencer266e42b2006-12-23 06:05:41 +00004919 return new ICmpInst(I.getPredicate(), NewRem,
4920 Constant::getNullValue(BO->getType()));
Chris Lattner23b47b62004-07-06 07:38:18 +00004921 }
Chris Lattner22d00a82005-08-02 19:16:58 +00004922 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004923 break;
Chris Lattnerc992add2003-08-13 05:33:12 +00004924 case Instruction::Add:
Chris Lattner6e079362004-06-27 22:51:36 +00004925 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
4926 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerb121ae12004-09-21 21:35:23 +00004927 if (BO->hasOneUse())
Reid Spencer266e42b2006-12-23 06:05:41 +00004928 return new ICmpInst(I.getPredicate(), BO->getOperand(0),
4929 ConstantExpr::getSub(CI, BOp1C));
Chris Lattner6e079362004-06-27 22:51:36 +00004930 } else if (CI->isNullValue()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00004931 // Replace ((add A, B) != 0) with (A != -B) if A or B is
4932 // efficiently invertible, or if the add has just this one use.
4933 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004934
Chris Lattnerc992add2003-08-13 05:33:12 +00004935 if (Value *NegVal = dyn_castNegVal(BOp1))
Reid Spencer266e42b2006-12-23 06:05:41 +00004936 return new ICmpInst(I.getPredicate(), BOp0, NegVal);
Chris Lattnerc992add2003-08-13 05:33:12 +00004937 else if (Value *NegVal = dyn_castNegVal(BOp0))
Reid Spencer266e42b2006-12-23 06:05:41 +00004938 return new ICmpInst(I.getPredicate(), NegVal, BOp1);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00004939 else if (BO->hasOneUse()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00004940 Instruction *Neg = BinaryOperator::createNeg(BOp1, BO->getName());
4941 BO->setName("");
4942 InsertNewInstBefore(Neg, I);
Reid Spencer266e42b2006-12-23 06:05:41 +00004943 return new ICmpInst(I.getPredicate(), BOp0, Neg);
Chris Lattnerc992add2003-08-13 05:33:12 +00004944 }
4945 }
4946 break;
4947 case Instruction::Xor:
4948 // For the xor case, we can xor two constants together, eliminating
4949 // the explicit xor.
4950 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
Reid Spencer266e42b2006-12-23 06:05:41 +00004951 return new ICmpInst(I.getPredicate(), BO->getOperand(0),
4952 ConstantExpr::getXor(CI, BOC));
Chris Lattnerc992add2003-08-13 05:33:12 +00004953
4954 // FALLTHROUGH
4955 case Instruction::Sub:
4956 // Replace (([sub|xor] A, B) != 0) with (A != B)
4957 if (CI->isNullValue())
Reid Spencer266e42b2006-12-23 06:05:41 +00004958 return new ICmpInst(I.getPredicate(), BO->getOperand(0),
4959 BO->getOperand(1));
Chris Lattnerc992add2003-08-13 05:33:12 +00004960 break;
4961
4962 case Instruction::Or:
4963 // If bits are being or'd in that are not present in the constant we
4964 // are comparing against, then the comparison could never succeed!
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00004965 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Chris Lattnerc8e7e292004-06-10 02:12:35 +00004966 Constant *NotCI = ConstantExpr::getNot(CI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004967 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Reid Spencer266e42b2006-12-23 06:05:41 +00004968 return ReplaceInstUsesWith(I, ConstantBool::get(isICMP_NE));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00004969 }
Chris Lattnerc992add2003-08-13 05:33:12 +00004970 break;
4971
4972 case Instruction::And:
4973 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerd492a0b2003-07-23 17:02:11 +00004974 // If bits are being compared against that are and'd out, then the
4975 // comparison can never succeed!
Chris Lattnerc8e7e292004-06-10 02:12:35 +00004976 if (!ConstantExpr::getAnd(CI,
4977 ConstantExpr::getNot(BOC))->isNullValue())
Reid Spencer266e42b2006-12-23 06:05:41 +00004978 return ReplaceInstUsesWith(I, ConstantBool::get(isICMP_NE));
Chris Lattnerc992add2003-08-13 05:33:12 +00004979
Chris Lattner35167c32004-06-09 07:59:58 +00004980 // If we have ((X & C) == C), turn it into ((X & C) != 0).
Chris Lattneree59d4b2004-06-10 02:33:20 +00004981 if (CI == BOC && isOneBitSet(CI))
Reid Spencer266e42b2006-12-23 06:05:41 +00004982 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
4983 ICmpInst::ICMP_NE, Op0,
4984 Constant::getNullValue(CI->getType()));
Chris Lattner35167c32004-06-09 07:59:58 +00004985
Reid Spencer266e42b2006-12-23 06:05:41 +00004986 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
Chris Lattnerc992add2003-08-13 05:33:12 +00004987 if (isSignBit(BOC)) {
4988 Value *X = BO->getOperand(0);
Reid Spencer266e42b2006-12-23 06:05:41 +00004989 Constant *Zero = Constant::getNullValue(X->getType());
4990 ICmpInst::Predicate pred = isICMP_NE ?
4991 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
4992 return new ICmpInst(pred, X, Zero);
Chris Lattnerc992add2003-08-13 05:33:12 +00004993 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004994
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004995 // ((X & ~7) == 0) --> X < 8
Chris Lattner8fc5af42004-09-23 21:46:38 +00004996 if (CI->isNullValue() && isHighOnes(BOC)) {
4997 Value *X = BO->getOperand(0);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004998 Constant *NegX = ConstantExpr::getNeg(BOC);
Reid Spencer266e42b2006-12-23 06:05:41 +00004999 ICmpInst::Predicate pred = isICMP_NE ?
5000 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
5001 return new ICmpInst(pred, X, NegX);
Chris Lattner8fc5af42004-09-23 21:46:38 +00005002 }
5003
Chris Lattnerd492a0b2003-07-23 17:02:11 +00005004 }
Chris Lattnerc992add2003-08-13 05:33:12 +00005005 default: break;
5006 }
Chris Lattnera7942b72006-11-29 05:02:16 +00005007 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Op0)) {
5008 // Handle set{eq|ne} <intrinsic>, intcst.
5009 switch (II->getIntrinsicID()) {
5010 default: break;
Reid Spencer266e42b2006-12-23 06:05:41 +00005011 case Intrinsic::bswap_i16:
5012 // icmp eq (bswap(x)), c -> icmp eq (x,bswap(c))
Chris Lattnera7942b72006-11-29 05:02:16 +00005013 WorkList.push_back(II); // Dead?
5014 I.setOperand(0, II->getOperand(1));
Reid Spencerc635f472006-12-31 05:48:39 +00005015 I.setOperand(1, ConstantInt::get(Type::Int16Ty,
Chris Lattnera7942b72006-11-29 05:02:16 +00005016 ByteSwap_16(CI->getZExtValue())));
5017 return &I;
Reid Spencer266e42b2006-12-23 06:05:41 +00005018 case Intrinsic::bswap_i32:
5019 // icmp eq (bswap(x)), c -> icmp eq (x,bswap(c))
Chris Lattnera7942b72006-11-29 05:02:16 +00005020 WorkList.push_back(II); // Dead?
5021 I.setOperand(0, II->getOperand(1));
Reid Spencerc635f472006-12-31 05:48:39 +00005022 I.setOperand(1, ConstantInt::get(Type::Int32Ty,
Chris Lattnera7942b72006-11-29 05:02:16 +00005023 ByteSwap_32(CI->getZExtValue())));
5024 return &I;
Reid Spencer266e42b2006-12-23 06:05:41 +00005025 case Intrinsic::bswap_i64:
5026 // icmp eq (bswap(x)), c -> icmp eq (x,bswap(c))
Chris Lattnera7942b72006-11-29 05:02:16 +00005027 WorkList.push_back(II); // Dead?
5028 I.setOperand(0, II->getOperand(1));
Reid Spencerc635f472006-12-31 05:48:39 +00005029 I.setOperand(1, ConstantInt::get(Type::Int64Ty,
Chris Lattnera7942b72006-11-29 05:02:16 +00005030 ByteSwap_64(CI->getZExtValue())));
5031 return &I;
5032 }
Chris Lattnerc992add2003-08-13 05:33:12 +00005033 }
Reid Spencer266e42b2006-12-23 06:05:41 +00005034 } else { // Not a ICMP_EQ/ICMP_NE
5035 // If the LHS is a cast from an integral value of the same size, then
5036 // since we know the RHS is a constant, try to simlify.
Chris Lattner2b55ea32004-02-23 07:16:20 +00005037 if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
5038 Value *CastOp = Cast->getOperand(0);
5039 const Type *SrcTy = CastOp->getType();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005040 unsigned SrcTySize = SrcTy->getPrimitiveSizeInBits();
Reid Spencer266e42b2006-12-23 06:05:41 +00005041 if (SrcTy->isInteger() &&
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005042 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
Reid Spencer266e42b2006-12-23 06:05:41 +00005043 // If this is an unsigned comparison, try to make the comparison use
5044 // smaller constant values.
5045 switch (I.getPredicate()) {
5046 default: break;
5047 case ICmpInst::ICMP_ULT: { // X u< 128 => X s> -1
5048 ConstantInt *CUI = cast<ConstantInt>(CI);
5049 if (CUI->getZExtValue() == 1ULL << (SrcTySize-1))
5050 return new ICmpInst(ICmpInst::ICMP_SGT, CastOp,
5051 ConstantInt::get(SrcTy, -1));
5052 break;
5053 }
5054 case ICmpInst::ICMP_UGT: { // X u> 127 => X s< 0
5055 ConstantInt *CUI = cast<ConstantInt>(CI);
5056 if (CUI->getZExtValue() == (1ULL << (SrcTySize-1))-1)
5057 return new ICmpInst(ICmpInst::ICMP_SLT, CastOp,
5058 Constant::getNullValue(SrcTy));
5059 break;
5060 }
Chris Lattner2b55ea32004-02-23 07:16:20 +00005061 }
Reid Spencer266e42b2006-12-23 06:05:41 +00005062
Chris Lattner2b55ea32004-02-23 07:16:20 +00005063 }
5064 }
Chris Lattnere967b342003-06-04 05:10:11 +00005065 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005066 }
5067
Reid Spencer266e42b2006-12-23 06:05:41 +00005068 // Handle icmp with constant RHS
Chris Lattner77c32c32005-04-23 15:31:55 +00005069 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5070 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5071 switch (LHSI->getOpcode()) {
Chris Lattnera816eee2005-05-01 04:42:15 +00005072 case Instruction::GetElementPtr:
5073 if (RHSC->isNullValue()) {
Reid Spencer266e42b2006-12-23 06:05:41 +00005074 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
Chris Lattnera816eee2005-05-01 04:42:15 +00005075 bool isAllZeros = true;
5076 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
5077 if (!isa<Constant>(LHSI->getOperand(i)) ||
5078 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
5079 isAllZeros = false;
5080 break;
5081 }
5082 if (isAllZeros)
Reid Spencer266e42b2006-12-23 06:05:41 +00005083 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
Chris Lattnera816eee2005-05-01 04:42:15 +00005084 Constant::getNullValue(LHSI->getOperand(0)->getType()));
5085 }
5086 break;
5087
Chris Lattner77c32c32005-04-23 15:31:55 +00005088 case Instruction::PHI:
5089 if (Instruction *NV = FoldOpIntoPhi(I))
5090 return NV;
5091 break;
5092 case Instruction::Select:
5093 // If either operand of the select is a constant, we can fold the
5094 // comparison into the select arms, which will cause one to be
5095 // constant folded and the select turned into a bitwise or.
5096 Value *Op1 = 0, *Op2 = 0;
5097 if (LHSI->hasOneUse()) {
5098 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5099 // Fold the known value into the constant operand.
Reid Spencer266e42b2006-12-23 06:05:41 +00005100 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5101 // Insert a new ICmp of the other select operand.
5102 Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5103 LHSI->getOperand(2), RHSC,
5104 I.getName()), I);
Chris Lattner77c32c32005-04-23 15:31:55 +00005105 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5106 // Fold the known value into the constant operand.
Reid Spencer266e42b2006-12-23 06:05:41 +00005107 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5108 // Insert a new ICmp of the other select operand.
5109 Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5110 LHSI->getOperand(1), RHSC,
5111 I.getName()), I);
Chris Lattner77c32c32005-04-23 15:31:55 +00005112 }
5113 }
Jeff Cohen82639852005-04-23 21:38:35 +00005114
Chris Lattner77c32c32005-04-23 15:31:55 +00005115 if (Op1)
5116 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
5117 break;
5118 }
5119 }
5120
Reid Spencer266e42b2006-12-23 06:05:41 +00005121 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
Chris Lattner0798af32005-01-13 20:14:25 +00005122 if (User *GEP = dyn_castGetElementPtr(Op0))
Reid Spencer266e42b2006-12-23 06:05:41 +00005123 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
Chris Lattner0798af32005-01-13 20:14:25 +00005124 return NI;
5125 if (User *GEP = dyn_castGetElementPtr(Op1))
Reid Spencer266e42b2006-12-23 06:05:41 +00005126 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
5127 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
Chris Lattner0798af32005-01-13 20:14:25 +00005128 return NI;
5129
Reid Spencer266e42b2006-12-23 06:05:41 +00005130 // Test to see if the operands of the icmp are casted versions of other
Chris Lattner64d87b02007-01-06 01:45:59 +00005131 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
5132 // now.
5133 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
5134 if (isa<PointerType>(Op0->getType()) &&
5135 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattner16930792003-11-03 04:25:02 +00005136 // We keep moving the cast from the left operand over to the right
5137 // operand, where it can often be eliminated completely.
Chris Lattner64d87b02007-01-06 01:45:59 +00005138 Op0 = CI->getOperand(0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00005139
Chris Lattner64d87b02007-01-06 01:45:59 +00005140 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
5141 // so eliminate it as well.
5142 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
5143 Op1 = CI2->getOperand(0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00005144
Chris Lattner16930792003-11-03 04:25:02 +00005145 // If Op1 is a constant, we can fold the cast into the constant.
Chris Lattner64d87b02007-01-06 01:45:59 +00005146 if (Op0->getType() != Op1->getType())
Chris Lattner16930792003-11-03 04:25:02 +00005147 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Reid Spencerbb65ebf2006-12-12 23:36:14 +00005148 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
Chris Lattner16930792003-11-03 04:25:02 +00005149 } else {
Reid Spencer266e42b2006-12-23 06:05:41 +00005150 // Otherwise, cast the RHS right before the icmp
Reid Spencer13bc5d72006-12-12 09:18:51 +00005151 Op1 = InsertCastBefore(Instruction::BitCast, Op1, Op0->getType(), I);
Chris Lattner16930792003-11-03 04:25:02 +00005152 }
Reid Spencer266e42b2006-12-23 06:05:41 +00005153 return new ICmpInst(I.getPredicate(), Op0, Op1);
Chris Lattner16930792003-11-03 04:25:02 +00005154 }
Chris Lattner64d87b02007-01-06 01:45:59 +00005155 }
5156
5157 if (isa<CastInst>(Op0)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00005158 // Handle the special case of: icmp (cast bool to X), <cst>
Chris Lattner6444c372003-11-03 05:17:03 +00005159 // This comes up when you have code like
5160 // int X = A < B;
5161 // if (X) ...
5162 // For generality, we handle any zero-extension of any operand comparison
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005163 // with a constant or another cast from the same type.
5164 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
Reid Spencer266e42b2006-12-23 06:05:41 +00005165 if (Instruction *R = visitICmpInstWithCastAndCast(I))
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005166 return R;
Chris Lattner6444c372003-11-03 05:17:03 +00005167 }
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00005168
Chris Lattnerb3f24c92006-09-18 04:22:48 +00005169 if (I.isEquality()) {
Chris Lattner17c7c032007-01-05 03:04:57 +00005170 Value *A, *B, *C, *D;
5171 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
5172 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
5173 Value *OtherVal = A == Op1 ? B : A;
5174 return new ICmpInst(I.getPredicate(), OtherVal,
5175 Constant::getNullValue(A->getType()));
5176 }
5177
5178 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
5179 // A^c1 == C^c2 --> A == C^(c1^c2)
5180 if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
5181 if (ConstantInt *C2 = dyn_cast<ConstantInt>(D))
5182 if (Op1->hasOneUse()) {
5183 Constant *NC = ConstantExpr::getXor(C1, C2);
5184 Instruction *Xor = BinaryOperator::createXor(C, NC, "tmp");
5185 return new ICmpInst(I.getPredicate(), A,
5186 InsertNewInstBefore(Xor, I));
5187 }
5188
5189 // A^B == A^D -> B == D
5190 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
5191 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
5192 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
5193 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
5194 }
5195 }
5196
5197 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
5198 (A == Op0 || B == Op0)) {
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00005199 // A == (A^B) -> B == 0
5200 Value *OtherVal = A == Op0 ? B : A;
Reid Spencer266e42b2006-12-23 06:05:41 +00005201 return new ICmpInst(I.getPredicate(), OtherVal,
5202 Constant::getNullValue(A->getType()));
Chris Lattner17c7c032007-01-05 03:04:57 +00005203 }
5204 if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00005205 // (A-B) == A -> B == 0
Reid Spencer266e42b2006-12-23 06:05:41 +00005206 return new ICmpInst(I.getPredicate(), B,
5207 Constant::getNullValue(B->getType()));
Chris Lattner17c7c032007-01-05 03:04:57 +00005208 }
5209 if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00005210 // A == (A-B) -> B == 0
Reid Spencer266e42b2006-12-23 06:05:41 +00005211 return new ICmpInst(I.getPredicate(), B,
5212 Constant::getNullValue(B->getType()));
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00005213 }
Chris Lattnerd12a4bf2006-11-14 06:06:06 +00005214
Chris Lattnerd12a4bf2006-11-14 06:06:06 +00005215 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
5216 if (Op0->hasOneUse() && Op1->hasOneUse() &&
5217 match(Op0, m_And(m_Value(A), m_Value(B))) &&
5218 match(Op1, m_And(m_Value(C), m_Value(D)))) {
5219 Value *X = 0, *Y = 0, *Z = 0;
5220
5221 if (A == C) {
5222 X = B; Y = D; Z = A;
5223 } else if (A == D) {
5224 X = B; Y = C; Z = A;
5225 } else if (B == C) {
5226 X = A; Y = D; Z = B;
5227 } else if (B == D) {
5228 X = A; Y = C; Z = B;
5229 }
5230
5231 if (X) { // Build (X^Y) & Z
5232 Op1 = InsertNewInstBefore(BinaryOperator::createXor(X, Y, "tmp"), I);
5233 Op1 = InsertNewInstBefore(BinaryOperator::createAnd(Op1, Z, "tmp"), I);
5234 I.setOperand(0, Op1);
5235 I.setOperand(1, Constant::getNullValue(Op1->getType()));
5236 return &I;
5237 }
5238 }
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00005239 }
Chris Lattner113f4f42002-06-25 16:13:24 +00005240 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005241}
5242
Reid Spencer266e42b2006-12-23 06:05:41 +00005243// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005244// We only handle extending casts so far.
5245//
Reid Spencer266e42b2006-12-23 06:05:41 +00005246Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
5247 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005248 Value *LHSCIOp = LHSCI->getOperand(0);
5249 const Type *SrcTy = LHSCIOp->getType();
Reid Spencer266e42b2006-12-23 06:05:41 +00005250 const Type *DestTy = LHSCI->getType();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005251 Value *RHSCIOp;
5252
Reid Spencer266e42b2006-12-23 06:05:41 +00005253 // We only handle extension cast instructions, so far. Enforce this.
5254 if (LHSCI->getOpcode() != Instruction::ZExt &&
5255 LHSCI->getOpcode() != Instruction::SExt)
Chris Lattner03f06f12005-01-17 03:20:02 +00005256 return 0;
5257
Reid Spencer266e42b2006-12-23 06:05:41 +00005258 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
5259 bool isSignedCmp = ICI.isSignedPredicate();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005260
Reid Spencer266e42b2006-12-23 06:05:41 +00005261 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005262 // Not an extension from the same type?
5263 RHSCIOp = CI->getOperand(0);
Reid Spencer266e42b2006-12-23 06:05:41 +00005264 if (RHSCIOp->getType() != LHSCIOp->getType())
5265 return 0;
5266 else
5267 // Okay, just insert a compare of the reduced operands now!
5268 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
Reid Spencer279fa252004-11-28 21:31:15 +00005269 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005270
Reid Spencer266e42b2006-12-23 06:05:41 +00005271 // If we aren't dealing with a constant on the RHS, exit early
5272 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
5273 if (!CI)
5274 return 0;
5275
5276 // Compute the constant that would happen if we truncated to SrcTy then
5277 // reextended to DestTy.
5278 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
5279 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
5280
5281 // If the re-extended constant didn't change...
5282 if (Res2 == CI) {
5283 // Make sure that sign of the Cmp and the sign of the Cast are the same.
5284 // For example, we might have:
5285 // %A = sext short %X to uint
5286 // %B = icmp ugt uint %A, 1330
5287 // It is incorrect to transform this into
5288 // %B = icmp ugt short %X, 1330
5289 // because %A may have negative value.
5290 //
5291 // However, it is OK if SrcTy is bool (See cast-set.ll testcase)
5292 // OR operation is EQ/NE.
5293 if (isSignedExt == isSignedCmp || SrcTy == Type::BoolTy || ICI.isEquality())
5294 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
5295 else
5296 return 0;
5297 }
5298
5299 // The re-extended constant changed so the constant cannot be represented
5300 // in the shorter type. Consequently, we cannot emit a simple comparison.
5301
5302 // First, handle some easy cases. We know the result cannot be equal at this
5303 // point so handle the ICI.isEquality() cases
5304 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
5305 return ReplaceInstUsesWith(ICI, ConstantBool::getFalse());
5306 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
5307 return ReplaceInstUsesWith(ICI, ConstantBool::getTrue());
5308
5309 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
5310 // should have been folded away previously and not enter in here.
5311 Value *Result;
5312 if (isSignedCmp) {
5313 // We're performing a signed comparison.
5314 if (cast<ConstantInt>(CI)->getSExtValue() < 0)
5315 Result = ConstantBool::getFalse(); // X < (small) --> false
5316 else
5317 Result = ConstantBool::getTrue(); // X < (large) --> true
5318 } else {
5319 // We're performing an unsigned comparison.
5320 if (isSignedExt) {
5321 // We're performing an unsigned comp with a sign extended value.
5322 // This is true if the input is >= 0. [aka >s -1]
5323 Constant *NegOne = ConstantIntegral::getAllOnesValue(SrcTy);
5324 Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
5325 NegOne, ICI.getName()), ICI);
5326 } else {
5327 // Unsigned extend & unsigned compare -> always true.
5328 Result = ConstantBool::getTrue();
5329 }
5330 }
5331
5332 // Finally, return the value computed.
5333 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
5334 ICI.getPredicate() == ICmpInst::ICMP_SLT) {
5335 return ReplaceInstUsesWith(ICI, Result);
5336 } else {
5337 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
5338 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
5339 "ICmp should be folded!");
5340 if (Constant *CI = dyn_cast<Constant>(Result))
5341 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
5342 else
5343 return BinaryOperator::createNot(Result);
5344 }
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005345}
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005346
Chris Lattnere8d6c602003-03-10 19:16:08 +00005347Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
Reid Spencerc635f472006-12-31 05:48:39 +00005348 assert(I.getOperand(1)->getType() == Type::Int8Ty);
Chris Lattner113f4f42002-06-25 16:13:24 +00005349 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005350
5351 // shl X, 0 == X and shr X, 0 == X
5352 // shl 0, X == 0 and shr 0, X == 0
Reid Spencerc635f472006-12-31 05:48:39 +00005353 if (Op1 == Constant::getNullValue(Type::Int8Ty) ||
Chris Lattnere6794492002-08-12 21:17:25 +00005354 Op0 == Constant::getNullValue(Op0->getType()))
5355 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf5b4ef72006-02-12 08:07:37 +00005356
Reid Spencer266e42b2006-12-23 06:05:41 +00005357 if (isa<UndefValue>(Op0)) {
5358 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
Chris Lattner67f05452004-10-16 23:28:04 +00005359 return ReplaceInstUsesWith(I, Op0);
Reid Spencer266e42b2006-12-23 06:05:41 +00005360 else // undef << X -> 0, undef >>u X -> 0
Chris Lattner81a7a232004-10-16 18:11:37 +00005361 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5362 }
5363 if (isa<UndefValue>(Op1)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00005364 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
5365 return ReplaceInstUsesWith(I, Op0);
5366 else // X << undef, X >>u undef -> 0
Chris Lattner81a7a232004-10-16 18:11:37 +00005367 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner81a7a232004-10-16 18:11:37 +00005368 }
5369
Chris Lattnerd4dee402006-11-10 23:38:52 +00005370 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
5371 if (I.getOpcode() == Instruction::AShr)
Reid Spencere0fc4df2006-10-20 07:07:24 +00005372 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Chris Lattnerd4dee402006-11-10 23:38:52 +00005373 if (CSI->isAllOnesValue())
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00005374 return ReplaceInstUsesWith(I, CSI);
5375
Chris Lattner183b3362004-04-09 19:05:30 +00005376 // Try to fold constant and into select arguments.
5377 if (isa<Constant>(Op0))
5378 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner86102b82005-01-01 16:22:27 +00005379 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00005380 return R;
5381
Chris Lattnerb18dbbf2005-05-08 17:34:56 +00005382 // See if we can turn a signed shr into an unsigned shr.
Chris Lattnerb3f24c92006-09-18 04:22:48 +00005383 if (I.isArithmeticShift()) {
Chris Lattnerc3ebf402006-02-07 07:27:52 +00005384 if (MaskedValueIsZero(Op0,
5385 1ULL << (I.getType()->getPrimitiveSizeInBits()-1))) {
Reid Spencerfdff9382006-11-08 06:47:33 +00005386 return new ShiftInst(Instruction::LShr, Op0, Op1, I.getName());
Chris Lattnerb18dbbf2005-05-08 17:34:56 +00005387 }
5388 }
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00005389
Reid Spencere0fc4df2006-10-20 07:07:24 +00005390 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
Reid Spencerc635f472006-12-31 05:48:39 +00005391 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
5392 return Res;
Chris Lattner14553932006-01-06 07:12:35 +00005393 return 0;
5394}
5395
Reid Spencere0fc4df2006-10-20 07:07:24 +00005396Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Chris Lattner14553932006-01-06 07:12:35 +00005397 ShiftInst &I) {
Reid Spencer266e42b2006-12-23 06:05:41 +00005398 bool isLeftShift = I.getOpcode() == Instruction::Shl;
5399 bool isSignedShift = I.getOpcode() == Instruction::AShr;
Chris Lattnerb3309392006-01-06 07:22:22 +00005400 bool isUnsignedShift = !isSignedShift;
Chris Lattner14553932006-01-06 07:12:35 +00005401
Chris Lattnerf5b4ef72006-02-12 08:07:37 +00005402 // See if we can simplify any instructions used by the instruction whose sole
5403 // purpose is to compute bits we don't care about.
5404 uint64_t KnownZero, KnownOne;
5405 if (SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
5406 KnownZero, KnownOne))
5407 return &I;
5408
Chris Lattner14553932006-01-06 07:12:35 +00005409 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
5410 // of a signed value.
5411 //
5412 unsigned TypeBits = Op0->getType()->getPrimitiveSizeInBits();
Reid Spencere0fc4df2006-10-20 07:07:24 +00005413 if (Op1->getZExtValue() >= TypeBits) {
Chris Lattnerb3309392006-01-06 07:22:22 +00005414 if (isUnsignedShift || isLeftShift)
Chris Lattner14553932006-01-06 07:12:35 +00005415 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
5416 else {
Reid Spencerc635f472006-12-31 05:48:39 +00005417 I.setOperand(1, ConstantInt::get(Type::Int8Ty, TypeBits-1));
Chris Lattner14553932006-01-06 07:12:35 +00005418 return &I;
Chris Lattnerf5ce2542004-02-23 20:30:06 +00005419 }
Chris Lattner14553932006-01-06 07:12:35 +00005420 }
5421
5422 // ((X*C1) << C2) == (X * (C1 << C2))
5423 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
5424 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
5425 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
5426 return BinaryOperator::createMul(BO->getOperand(0),
5427 ConstantExpr::getShl(BOOp, Op1));
5428
5429 // Try to fold constant and into select arguments.
5430 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5431 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5432 return R;
5433 if (isa<PHINode>(Op0))
5434 if (Instruction *NV = FoldOpIntoPhi(I))
5435 return NV;
5436
5437 if (Op0->hasOneUse()) {
Chris Lattner14553932006-01-06 07:12:35 +00005438 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
5439 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
5440 Value *V1, *V2;
5441 ConstantInt *CC;
5442 switch (Op0BO->getOpcode()) {
Chris Lattner27cb9db2005-09-18 05:12:10 +00005443 default: break;
5444 case Instruction::Add:
5445 case Instruction::And:
5446 case Instruction::Or:
5447 case Instruction::Xor:
5448 // These operators commute.
5449 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner797dee72005-09-18 06:30:59 +00005450 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
5451 match(Op0BO->getOperand(1),
Chris Lattner14553932006-01-06 07:12:35 +00005452 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Chris Lattner797dee72005-09-18 06:30:59 +00005453 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00005454 Op0BO->getOperand(0), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00005455 Op0BO->getName());
5456 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005457 Instruction *X =
5458 BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
5459 Op0BO->getOperand(1)->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00005460 InsertNewInstBefore(X, I); // (X + (Y << C))
5461 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
Chris Lattner14553932006-01-06 07:12:35 +00005462 C2 = ConstantExpr::getShl(C2, Op1);
Chris Lattner797dee72005-09-18 06:30:59 +00005463 return BinaryOperator::createAnd(X, C2);
5464 }
Chris Lattner14553932006-01-06 07:12:35 +00005465
Chris Lattner797dee72005-09-18 06:30:59 +00005466 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
5467 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
5468 match(Op0BO->getOperand(1),
5469 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner14553932006-01-06 07:12:35 +00005470 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005471 cast<BinaryOperator>(Op0BO->getOperand(1))->getOperand(0)->hasOneUse()) {
Chris Lattner797dee72005-09-18 06:30:59 +00005472 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00005473 Op0BO->getOperand(0), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00005474 Op0BO->getName());
5475 InsertNewInstBefore(YS, I); // (Y << C)
5476 Instruction *XM =
Chris Lattner14553932006-01-06 07:12:35 +00005477 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner797dee72005-09-18 06:30:59 +00005478 V1->getName()+".mask");
5479 InsertNewInstBefore(XM, I); // X & (CC << C)
5480
5481 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
5482 }
Chris Lattner14553932006-01-06 07:12:35 +00005483
Chris Lattner797dee72005-09-18 06:30:59 +00005484 // FALL THROUGH.
Chris Lattner27cb9db2005-09-18 05:12:10 +00005485 case Instruction::Sub:
5486 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner797dee72005-09-18 06:30:59 +00005487 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
5488 match(Op0BO->getOperand(0),
Chris Lattner14553932006-01-06 07:12:35 +00005489 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Chris Lattner797dee72005-09-18 06:30:59 +00005490 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00005491 Op0BO->getOperand(1), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00005492 Op0BO->getName());
5493 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005494 Instruction *X =
Chris Lattner1df0e982006-05-31 21:14:00 +00005495 BinaryOperator::create(Op0BO->getOpcode(), V1, YS,
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005496 Op0BO->getOperand(0)->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00005497 InsertNewInstBefore(X, I); // (X + (Y << C))
5498 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
Chris Lattner14553932006-01-06 07:12:35 +00005499 C2 = ConstantExpr::getShl(C2, Op1);
Chris Lattner797dee72005-09-18 06:30:59 +00005500 return BinaryOperator::createAnd(X, C2);
5501 }
Chris Lattner14553932006-01-06 07:12:35 +00005502
Chris Lattner1df0e982006-05-31 21:14:00 +00005503 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner797dee72005-09-18 06:30:59 +00005504 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
5505 match(Op0BO->getOperand(0),
5506 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner14553932006-01-06 07:12:35 +00005507 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005508 cast<BinaryOperator>(Op0BO->getOperand(0))
5509 ->getOperand(0)->hasOneUse()) {
Chris Lattner797dee72005-09-18 06:30:59 +00005510 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00005511 Op0BO->getOperand(1), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00005512 Op0BO->getName());
5513 InsertNewInstBefore(YS, I); // (Y << C)
5514 Instruction *XM =
Chris Lattner14553932006-01-06 07:12:35 +00005515 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner797dee72005-09-18 06:30:59 +00005516 V1->getName()+".mask");
5517 InsertNewInstBefore(XM, I); // X & (CC << C)
5518
Chris Lattner1df0e982006-05-31 21:14:00 +00005519 return BinaryOperator::create(Op0BO->getOpcode(), XM, YS);
Chris Lattner797dee72005-09-18 06:30:59 +00005520 }
Chris Lattner14553932006-01-06 07:12:35 +00005521
Chris Lattner27cb9db2005-09-18 05:12:10 +00005522 break;
Chris Lattner14553932006-01-06 07:12:35 +00005523 }
5524
5525
5526 // If the operand is an bitwise operator with a constant RHS, and the
5527 // shift is the only use, we can pull it out of the shift.
5528 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
5529 bool isValid = true; // Valid only for And, Or, Xor
5530 bool highBitSet = false; // Transform if high bit of constant set?
5531
5532 switch (Op0BO->getOpcode()) {
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00005533 default: isValid = false; break; // Do not perform transform!
Chris Lattner44bd3922004-10-08 03:46:20 +00005534 case Instruction::Add:
5535 isValid = isLeftShift;
5536 break;
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00005537 case Instruction::Or:
5538 case Instruction::Xor:
5539 highBitSet = false;
5540 break;
5541 case Instruction::And:
5542 highBitSet = true;
5543 break;
Chris Lattner14553932006-01-06 07:12:35 +00005544 }
5545
5546 // If this is a signed shift right, and the high bit is modified
5547 // by the logical operation, do not perform the transformation.
5548 // The highBitSet boolean indicates the value of the high bit of
5549 // the constant which would cause it to be modified for this
5550 // operation.
5551 //
Chris Lattnerb3309392006-01-06 07:22:22 +00005552 if (isValid && !isLeftShift && isSignedShift) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00005553 uint64_t Val = Op0C->getZExtValue();
Chris Lattner14553932006-01-06 07:12:35 +00005554 isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
5555 }
5556
5557 if (isValid) {
5558 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
5559
5560 Instruction *NewShift =
5561 new ShiftInst(I.getOpcode(), Op0BO->getOperand(0), Op1,
5562 Op0BO->getName());
5563 Op0BO->setName("");
5564 InsertNewInstBefore(NewShift, I);
5565
5566 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
5567 NewRHS);
5568 }
5569 }
5570 }
5571 }
5572
Chris Lattnereb372a02006-01-06 07:52:12 +00005573 // Find out if this is a shift of a shift by a constant.
5574 ShiftInst *ShiftOp = 0;
Chris Lattner14553932006-01-06 07:12:35 +00005575 if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0))
Chris Lattnereb372a02006-01-06 07:52:12 +00005576 ShiftOp = Op0SI;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005577 else if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
5578 // If this is a noop-integer cast of a shift instruction, use the shift.
5579 if (isa<ShiftInst>(CI->getOperand(0))) {
Chris Lattnereb372a02006-01-06 07:52:12 +00005580 ShiftOp = cast<ShiftInst>(CI->getOperand(0));
5581 }
5582 }
5583
Reid Spencere0fc4df2006-10-20 07:07:24 +00005584 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Chris Lattnereb372a02006-01-06 07:52:12 +00005585 // Find the operands and properties of the input shift. Note that the
5586 // signedness of the input shift may differ from the current shift if there
5587 // is a noop cast between the two.
Reid Spencer266e42b2006-12-23 06:05:41 +00005588 bool isShiftOfLeftShift = ShiftOp->getOpcode() == Instruction::Shl;
5589 bool isShiftOfSignedShift = ShiftOp->getOpcode() == Instruction::AShr;
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005590 bool isShiftOfUnsignedShift = !isShiftOfSignedShift;
Chris Lattnereb372a02006-01-06 07:52:12 +00005591
Reid Spencere0fc4df2006-10-20 07:07:24 +00005592 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Chris Lattnereb372a02006-01-06 07:52:12 +00005593
Reid Spencere0fc4df2006-10-20 07:07:24 +00005594 unsigned ShiftAmt1 = (unsigned)ShiftAmt1C->getZExtValue();
5595 unsigned ShiftAmt2 = (unsigned)Op1->getZExtValue();
Chris Lattnereb372a02006-01-06 07:52:12 +00005596
5597 // Check for (A << c1) << c2 and (A >> c1) >> c2.
5598 if (isLeftShift == isShiftOfLeftShift) {
5599 // Do not fold these shifts if the first one is signed and the second one
5600 // is unsigned and this is a right shift. Further, don't do any folding
5601 // on them.
5602 if (isShiftOfSignedShift && isUnsignedShift && !isLeftShift)
5603 return 0;
Chris Lattner14553932006-01-06 07:12:35 +00005604
Chris Lattnereb372a02006-01-06 07:52:12 +00005605 unsigned Amt = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
5606 if (Amt > Op0->getType()->getPrimitiveSizeInBits())
5607 Amt = Op0->getType()->getPrimitiveSizeInBits();
Chris Lattner14553932006-01-06 07:12:35 +00005608
Chris Lattnereb372a02006-01-06 07:52:12 +00005609 Value *Op = ShiftOp->getOperand(0);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005610 ShiftInst *ShiftResult = new ShiftInst(I.getOpcode(), Op,
Reid Spencerc635f472006-12-31 05:48:39 +00005611 ConstantInt::get(Type::Int8Ty, Amt));
Reid Spencerfdff9382006-11-08 06:47:33 +00005612 if (I.getType() == ShiftResult->getType())
5613 return ShiftResult;
5614 InsertNewInstBefore(ShiftResult, I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005615 return CastInst::create(Instruction::BitCast, ShiftResult, I.getType());
Chris Lattnereb372a02006-01-06 07:52:12 +00005616 }
5617
5618 // Check for (A << c1) >> c2 or (A >> c1) << c2. If we are dealing with
5619 // signed types, we can only support the (A >> c1) << c2 configuration,
5620 // because it can not turn an arbitrary bit of A into a sign bit.
5621 if (isUnsignedShift || isLeftShift) {
5622 // Calculate bitmask for what gets shifted off the edge.
5623 Constant *C = ConstantIntegral::getAllOnesValue(I.getType());
5624 if (isLeftShift)
5625 C = ConstantExpr::getShl(C, ShiftAmt1C);
5626 else
Reid Spencerfdff9382006-11-08 06:47:33 +00005627 C = ConstantExpr::getLShr(C, ShiftAmt1C);
Chris Lattnereb372a02006-01-06 07:52:12 +00005628
5629 Value *Op = ShiftOp->getOperand(0);
Chris Lattnereb372a02006-01-06 07:52:12 +00005630
5631 Instruction *Mask =
5632 BinaryOperator::createAnd(Op, C, Op->getName()+".mask");
5633 InsertNewInstBefore(Mask, I);
5634
5635 // Figure out what flavor of shift we should use...
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005636 if (ShiftAmt1 == ShiftAmt2) {
Chris Lattnereb372a02006-01-06 07:52:12 +00005637 return ReplaceInstUsesWith(I, Mask); // (A << c) >> c === A & c2
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005638 } else if (ShiftAmt1 < ShiftAmt2) {
Chris Lattnereb372a02006-01-06 07:52:12 +00005639 return new ShiftInst(I.getOpcode(), Mask,
Reid Spencerc635f472006-12-31 05:48:39 +00005640 ConstantInt::get(Type::Int8Ty, ShiftAmt2-ShiftAmt1));
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005641 } else if (isShiftOfUnsignedShift || isShiftOfLeftShift) {
5642 if (isShiftOfUnsignedShift && !isShiftOfLeftShift && isSignedShift) {
Reid Spencerfdff9382006-11-08 06:47:33 +00005643 return new ShiftInst(Instruction::LShr, Mask,
Reid Spencerc635f472006-12-31 05:48:39 +00005644 ConstantInt::get(Type::Int8Ty, ShiftAmt1-ShiftAmt2));
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005645 } else {
5646 return new ShiftInst(ShiftOp->getOpcode(), Mask,
Reid Spencerc635f472006-12-31 05:48:39 +00005647 ConstantInt::get(Type::Int8Ty, ShiftAmt1-ShiftAmt2));
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005648 }
5649 } else {
5650 // (X >>s C1) << C2 where C1 > C2 === (X >>s (C1-C2)) & mask
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005651 Instruction *Shift =
Reid Spencer2a499b02006-12-13 17:19:09 +00005652 new ShiftInst(ShiftOp->getOpcode(), Mask,
Reid Spencerc635f472006-12-31 05:48:39 +00005653 ConstantInt::get(Type::Int8Ty, ShiftAmt1-ShiftAmt2));
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005654 InsertNewInstBefore(Shift, I);
5655
5656 C = ConstantIntegral::getAllOnesValue(Shift->getType());
5657 C = ConstantExpr::getShl(C, Op1);
Reid Spencer2a499b02006-12-13 17:19:09 +00005658 return BinaryOperator::createAnd(Shift, C, Op->getName()+".mask");
Chris Lattnereb372a02006-01-06 07:52:12 +00005659 }
5660 } else {
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005661 // We can handle signed (X << C1) >>s C2 if it's a sign extend. In
Chris Lattnereb372a02006-01-06 07:52:12 +00005662 // this case, C1 == C2 and C1 is 8, 16, or 32.
5663 if (ShiftAmt1 == ShiftAmt2) {
5664 const Type *SExtType = 0;
Chris Lattner655d08f2006-04-28 22:21:41 +00005665 switch (Op0->getType()->getPrimitiveSizeInBits() - ShiftAmt1) {
Reid Spencerc635f472006-12-31 05:48:39 +00005666 case 8 : SExtType = Type::Int8Ty; break;
5667 case 16: SExtType = Type::Int16Ty; break;
5668 case 32: SExtType = Type::Int32Ty; break;
Chris Lattnereb372a02006-01-06 07:52:12 +00005669 }
5670
5671 if (SExtType) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005672 Instruction *NewTrunc =
5673 new TruncInst(ShiftOp->getOperand(0), SExtType, "sext");
Chris Lattnereb372a02006-01-06 07:52:12 +00005674 InsertNewInstBefore(NewTrunc, I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005675 return new SExtInst(NewTrunc, I.getType());
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00005676 }
Chris Lattner27cb9db2005-09-18 05:12:10 +00005677 }
Chris Lattner86102b82005-01-01 16:22:27 +00005678 }
Chris Lattnereb372a02006-01-06 07:52:12 +00005679 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005680 return 0;
5681}
5682
Chris Lattner48a44f72002-05-02 17:06:02 +00005683
Chris Lattner8f663e82005-10-29 04:36:15 +00005684/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
5685/// expression. If so, decompose it, returning some value X, such that Val is
5686/// X*Scale+Offset.
5687///
5688static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
5689 unsigned &Offset) {
Reid Spencerc635f472006-12-31 05:48:39 +00005690 assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
Reid Spencere0fc4df2006-10-20 07:07:24 +00005691 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
Reid Spencerc635f472006-12-31 05:48:39 +00005692 Offset = CI->getZExtValue();
5693 Scale = 1;
5694 return ConstantInt::get(Type::Int32Ty, 0);
Chris Lattner8f663e82005-10-29 04:36:15 +00005695 } else if (Instruction *I = dyn_cast<Instruction>(Val)) {
5696 if (I->getNumOperands() == 2) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00005697 if (ConstantInt *CUI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Reid Spencerc635f472006-12-31 05:48:39 +00005698 if (I->getOpcode() == Instruction::Shl) {
5699 // This is a value scaled by '1 << the shift amt'.
5700 Scale = 1U << CUI->getZExtValue();
5701 Offset = 0;
5702 return I->getOperand(0);
5703 } else if (I->getOpcode() == Instruction::Mul) {
5704 // This value is scaled by 'CUI'.
5705 Scale = CUI->getZExtValue();
5706 Offset = 0;
5707 return I->getOperand(0);
5708 } else if (I->getOpcode() == Instruction::Add) {
5709 // We have X+C. Check to see if we really have (X*C2)+C1,
5710 // where C1 is divisible by C2.
5711 unsigned SubScale;
5712 Value *SubVal =
5713 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
5714 Offset += CUI->getZExtValue();
5715 if (SubScale > 1 && (Offset % SubScale == 0)) {
5716 Scale = SubScale;
5717 return SubVal;
Chris Lattner8f663e82005-10-29 04:36:15 +00005718 }
5719 }
5720 }
5721 }
5722 }
5723
5724 // Otherwise, we can't look past this.
5725 Scale = 1;
5726 Offset = 0;
5727 return Val;
5728}
5729
5730
Chris Lattner216be912005-10-24 06:03:58 +00005731/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
5732/// try to eliminate the cast by moving the type information into the alloc.
5733Instruction *InstCombiner::PromoteCastOfAllocation(CastInst &CI,
5734 AllocationInst &AI) {
5735 const PointerType *PTy = dyn_cast<PointerType>(CI.getType());
Chris Lattnerbb171802005-10-27 05:53:56 +00005736 if (!PTy) return 0; // Not casting the allocation to a pointer type.
Chris Lattner216be912005-10-24 06:03:58 +00005737
Chris Lattnerac87beb2005-10-24 06:22:12 +00005738 // Remove any uses of AI that are dead.
5739 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
5740 std::vector<Instruction*> DeadUsers;
5741 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
5742 Instruction *User = cast<Instruction>(*UI++);
5743 if (isInstructionTriviallyDead(User)) {
5744 while (UI != E && *UI == User)
5745 ++UI; // If this instruction uses AI more than once, don't break UI.
5746
5747 // Add operands to the worklist.
5748 AddUsesToWorkList(*User);
5749 ++NumDeadInst;
Bill Wendling5dbf43c2006-11-26 09:46:52 +00005750 DOUT << "IC: DCE: " << *User;
Chris Lattnerac87beb2005-10-24 06:22:12 +00005751
5752 User->eraseFromParent();
5753 removeFromWorkList(User);
5754 }
5755 }
5756
Chris Lattner216be912005-10-24 06:03:58 +00005757 // Get the type really allocated and the type casted to.
5758 const Type *AllocElTy = AI.getAllocatedType();
5759 const Type *CastElTy = PTy->getElementType();
5760 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner355ecc02005-10-24 06:26:18 +00005761
Chris Lattner7d190672006-10-01 19:40:58 +00005762 unsigned AllocElTyAlign = TD->getTypeAlignment(AllocElTy);
5763 unsigned CastElTyAlign = TD->getTypeAlignment(CastElTy);
Chris Lattner355ecc02005-10-24 06:26:18 +00005764 if (CastElTyAlign < AllocElTyAlign) return 0;
5765
Chris Lattner46705b22005-10-24 06:35:18 +00005766 // If the allocation has multiple uses, only promote it if we are strictly
5767 // increasing the alignment of the resultant allocation. If we keep it the
5768 // same, we open the door to infinite loops of various kinds.
5769 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
5770
Chris Lattner216be912005-10-24 06:03:58 +00005771 uint64_t AllocElTySize = TD->getTypeSize(AllocElTy);
5772 uint64_t CastElTySize = TD->getTypeSize(CastElTy);
Chris Lattnerbb171802005-10-27 05:53:56 +00005773 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner355ecc02005-10-24 06:26:18 +00005774
Chris Lattner8270c332005-10-29 03:19:53 +00005775 // See if we can satisfy the modulus by pulling a scale out of the array
5776 // size argument.
Chris Lattner8f663e82005-10-29 04:36:15 +00005777 unsigned ArraySizeScale, ArrayOffset;
5778 Value *NumElements = // See if the array size is a decomposable linear expr.
5779 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
5780
Chris Lattner8270c332005-10-29 03:19:53 +00005781 // If we can now satisfy the modulus, by using a non-1 scale, we really can
5782 // do the xform.
Chris Lattner8f663e82005-10-29 04:36:15 +00005783 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
5784 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattnerb3ecf962005-10-27 06:12:00 +00005785
Chris Lattner8270c332005-10-29 03:19:53 +00005786 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
5787 Value *Amt = 0;
5788 if (Scale == 1) {
5789 Amt = NumElements;
5790 } else {
Reid Spencere0fc4df2006-10-20 07:07:24 +00005791 // If the allocation size is constant, form a constant mul expression
Reid Spencerc635f472006-12-31 05:48:39 +00005792 Amt = ConstantInt::get(Type::Int32Ty, Scale);
5793 if (isa<ConstantInt>(NumElements))
Reid Spencere0fc4df2006-10-20 07:07:24 +00005794 Amt = ConstantExpr::getMul(
5795 cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
5796 // otherwise multiply the amount and the number of elements
Chris Lattner8270c332005-10-29 03:19:53 +00005797 else if (Scale != 1) {
5798 Instruction *Tmp = BinaryOperator::createMul(Amt, NumElements, "tmp");
5799 Amt = InsertNewInstBefore(Tmp, AI);
Chris Lattnerb3ecf962005-10-27 06:12:00 +00005800 }
Chris Lattnerbb171802005-10-27 05:53:56 +00005801 }
5802
Chris Lattner8f663e82005-10-29 04:36:15 +00005803 if (unsigned Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
Reid Spencerc635f472006-12-31 05:48:39 +00005804 Value *Off = ConstantInt::get(Type::Int32Ty, Offset);
Chris Lattner8f663e82005-10-29 04:36:15 +00005805 Instruction *Tmp = BinaryOperator::createAdd(Amt, Off, "tmp");
5806 Amt = InsertNewInstBefore(Tmp, AI);
5807 }
5808
Chris Lattner216be912005-10-24 06:03:58 +00005809 std::string Name = AI.getName(); AI.setName("");
5810 AllocationInst *New;
5811 if (isa<MallocInst>(AI))
Nate Begeman848622f2005-11-05 09:21:28 +00005812 New = new MallocInst(CastElTy, Amt, AI.getAlignment(), Name);
Chris Lattner216be912005-10-24 06:03:58 +00005813 else
Nate Begeman848622f2005-11-05 09:21:28 +00005814 New = new AllocaInst(CastElTy, Amt, AI.getAlignment(), Name);
Chris Lattner216be912005-10-24 06:03:58 +00005815 InsertNewInstBefore(New, AI);
Chris Lattner46705b22005-10-24 06:35:18 +00005816
5817 // If the allocation has multiple uses, insert a cast and change all things
5818 // that used it to use the new cast. This will also hack on CI, but it will
5819 // die soon.
5820 if (!AI.hasOneUse()) {
5821 AddUsesToWorkList(AI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005822 // New is the allocation instruction, pointer typed. AI is the original
5823 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
5824 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
Chris Lattner46705b22005-10-24 06:35:18 +00005825 InsertNewInstBefore(NewCast, AI);
5826 AI.replaceAllUsesWith(NewCast);
5827 }
Chris Lattner216be912005-10-24 06:03:58 +00005828 return ReplaceInstUsesWith(CI, New);
5829}
5830
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005831/// CanEvaluateInDifferentType - Return true if we can take the specified value
5832/// and return it without inserting any new casts. This is used by code that
5833/// tries to decide whether promoting or shrinking integer operations to wider
5834/// or smaller types will allow us to eliminate a truncate or extend.
5835static bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
5836 int &NumCastsRemoved) {
5837 if (isa<Constant>(V)) return true;
5838
5839 Instruction *I = dyn_cast<Instruction>(V);
5840 if (!I || !I->hasOneUse()) return false;
5841
5842 switch (I->getOpcode()) {
5843 case Instruction::And:
5844 case Instruction::Or:
5845 case Instruction::Xor:
5846 // These operators can all arbitrarily be extended or truncated.
5847 return CanEvaluateInDifferentType(I->getOperand(0), Ty, NumCastsRemoved) &&
5848 CanEvaluateInDifferentType(I->getOperand(1), Ty, NumCastsRemoved);
Chris Lattner960acb02006-11-29 07:18:39 +00005849 case Instruction::AShr:
5850 case Instruction::LShr:
5851 case Instruction::Shl:
5852 // If this is just a bitcast changing the sign of the operation, we can
5853 // convert if the operand can be converted.
5854 if (V->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
5855 return CanEvaluateInDifferentType(I->getOperand(0), Ty, NumCastsRemoved);
5856 break;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005857 case Instruction::Trunc:
5858 case Instruction::ZExt:
5859 case Instruction::SExt:
5860 case Instruction::BitCast:
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005861 // If this is a cast from the destination type, we can trivially eliminate
5862 // it, and this will remove a cast overall.
5863 if (I->getOperand(0)->getType() == Ty) {
Chris Lattner3fda3862006-06-28 17:34:50 +00005864 // If the first operand is itself a cast, and is eliminable, do not count
5865 // this as an eliminable cast. We would prefer to eliminate those two
5866 // casts first.
Reid Spencerde46e482006-11-02 20:25:50 +00005867 if (isa<CastInst>(I->getOperand(0)))
Chris Lattner3fda3862006-06-28 17:34:50 +00005868 return true;
5869
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005870 ++NumCastsRemoved;
5871 return true;
5872 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005873 break;
5874 default:
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005875 // TODO: Can handle more cases here.
5876 break;
5877 }
5878
5879 return false;
5880}
5881
5882/// EvaluateInDifferentType - Given an expression that
5883/// CanEvaluateInDifferentType returns true for, actually insert the code to
5884/// evaluate the expression.
Reid Spencer74a528b2006-12-13 18:21:21 +00005885Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
5886 bool isSigned ) {
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005887 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencer74a528b2006-12-13 18:21:21 +00005888 return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005889
5890 // Otherwise, it must be an instruction.
5891 Instruction *I = cast<Instruction>(V);
Chris Lattnerd0622b62006-05-20 23:14:03 +00005892 Instruction *Res = 0;
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005893 switch (I->getOpcode()) {
5894 case Instruction::And:
5895 case Instruction::Or:
5896 case Instruction::Xor: {
Reid Spencer74a528b2006-12-13 18:21:21 +00005897 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
5898 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005899 Res = BinaryOperator::create((Instruction::BinaryOps)I->getOpcode(),
5900 LHS, RHS, I->getName());
5901 break;
5902 }
Chris Lattner960acb02006-11-29 07:18:39 +00005903 case Instruction::AShr:
5904 case Instruction::LShr:
5905 case Instruction::Shl: {
Reid Spencer74a528b2006-12-13 18:21:21 +00005906 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
Chris Lattner960acb02006-11-29 07:18:39 +00005907 Res = new ShiftInst((Instruction::OtherOps)I->getOpcode(), LHS,
5908 I->getOperand(1), I->getName());
5909 break;
5910 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005911 case Instruction::Trunc:
5912 case Instruction::ZExt:
5913 case Instruction::SExt:
5914 case Instruction::BitCast:
5915 // If the source type of the cast is the type we're trying for then we can
5916 // just return the source. There's no need to insert it because its not new.
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005917 if (I->getOperand(0)->getType() == Ty)
5918 return I->getOperand(0);
5919
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005920 // Some other kind of cast, which shouldn't happen, so just ..
5921 // FALL THROUGH
5922 default:
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005923 // TODO: Can handle more cases here.
5924 assert(0 && "Unreachable!");
5925 break;
5926 }
5927
5928 return InsertNewInstBefore(Res, *I);
5929}
5930
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005931/// @brief Implement the transforms common to all CastInst visitors.
5932Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
Chris Lattner55d4bda2003-06-23 21:59:52 +00005933 Value *Src = CI.getOperand(0);
5934
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005935 // Casting undef to anything results in undef so might as just replace it and
5936 // get rid of the cast.
Chris Lattner81a7a232004-10-16 18:11:37 +00005937 if (isa<UndefValue>(Src)) // cast undef -> undef
5938 return ReplaceInstUsesWith(CI, UndefValue::get(CI.getType()));
5939
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005940 // Many cases of "cast of a cast" are eliminable. If its eliminable we just
5941 // eliminate it now.
Chris Lattner86102b82005-01-01 16:22:27 +00005942 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005943 if (Instruction::CastOps opc =
5944 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
5945 // The first cast (CSrc) is eliminable so we need to fix up or replace
5946 // the second cast (CI). CSrc will then have a good chance of being dead.
5947 return CastInst::create(opc, CSrc->getOperand(0), CI.getType());
Chris Lattner650b6da2002-08-02 20:00:25 +00005948 }
5949 }
Chris Lattner03841652004-05-25 04:29:21 +00005950
Chris Lattnerd0d51602003-06-21 23:12:02 +00005951 // If casting the result of a getelementptr instruction with no offset, turn
5952 // this into a cast of the original pointer!
5953 //
Chris Lattner55d4bda2003-06-23 21:59:52 +00005954 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattnerd0d51602003-06-21 23:12:02 +00005955 bool AllZeroOperands = true;
5956 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
5957 if (!isa<Constant>(GEP->getOperand(i)) ||
5958 !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
5959 AllZeroOperands = false;
5960 break;
5961 }
5962 if (AllZeroOperands) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005963 // Changing the cast operand is usually not a good idea but it is safe
5964 // here because the pointer operand is being replaced with another
5965 // pointer operand so the opcode doesn't need to change.
Chris Lattnerd0d51602003-06-21 23:12:02 +00005966 CI.setOperand(0, GEP->getOperand(0));
5967 return &CI;
5968 }
5969 }
Chris Lattnerec45a4c2006-11-21 17:05:13 +00005970
Chris Lattnerf4ad1652003-11-02 05:57:39 +00005971 // If we are casting a malloc or alloca to a pointer to a type of the same
5972 // size, rewrite the allocation instruction to allocate the "right" type.
Chris Lattnerf4ad1652003-11-02 05:57:39 +00005973 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
Chris Lattner216be912005-10-24 06:03:58 +00005974 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
5975 return V;
Chris Lattnerf4ad1652003-11-02 05:57:39 +00005976
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005977 // If we are casting a select then fold the cast into the select
Chris Lattner86102b82005-01-01 16:22:27 +00005978 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
5979 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
5980 return NV;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005981
5982 // If we are casting a PHI then fold the cast into the PHI
Chris Lattner6a4adcd2004-09-29 05:07:12 +00005983 if (isa<PHINode>(Src))
5984 if (Instruction *NV = FoldOpIntoPhi(CI))
5985 return NV;
Chris Lattnerb19a5c62006-04-12 18:09:35 +00005986
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005987 return 0;
5988}
5989
5990/// Only the TRUNC, ZEXT, SEXT, and BITCONVERT can have both operands as
5991/// integers. This function implements the common transforms for all those
5992/// cases.
5993/// @brief Implement the transforms common to CastInst with integer operands
5994Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
5995 if (Instruction *Result = commonCastTransforms(CI))
5996 return Result;
5997
5998 Value *Src = CI.getOperand(0);
5999 const Type *SrcTy = Src->getType();
6000 const Type *DestTy = CI.getType();
6001 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
6002 unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
6003
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006004 // See if we can simplify any instructions used by the LHS whose sole
6005 // purpose is to compute bits we don't care about.
6006 uint64_t KnownZero = 0, KnownOne = 0;
6007 if (SimplifyDemandedBits(&CI, DestTy->getIntegralTypeMask(),
6008 KnownZero, KnownOne))
6009 return &CI;
6010
6011 // If the source isn't an instruction or has more than one use then we
6012 // can't do anything more.
Reid Spencer266e42b2006-12-23 06:05:41 +00006013 Instruction *SrcI = dyn_cast<Instruction>(Src);
6014 if (!SrcI || !Src->hasOneUse())
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006015 return 0;
6016
6017 // Attempt to propagate the cast into the instruction.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006018 int NumCastsRemoved = 0;
6019 if (CanEvaluateInDifferentType(SrcI, DestTy, NumCastsRemoved)) {
6020 // If this cast is a truncate, evaluting in a different type always
6021 // eliminates the cast, so it is always a win. If this is a noop-cast
6022 // this just removes a noop cast which isn't pointful, but simplifies
6023 // the code. If this is a zero-extension, we need to do an AND to
6024 // maintain the clear top-part of the computation, so we require that
6025 // the input have eliminated at least one cast. If this is a sign
6026 // extension, we insert two new casts (to do the extension) so we
6027 // require that two casts have been eliminated.
6028 bool DoXForm = CI.isNoopCast(TD->getIntPtrType());
6029 if (!DoXForm) {
6030 switch (CI.getOpcode()) {
6031 case Instruction::Trunc:
6032 DoXForm = true;
6033 break;
6034 case Instruction::ZExt:
6035 DoXForm = NumCastsRemoved >= 1;
6036 break;
6037 case Instruction::SExt:
6038 DoXForm = NumCastsRemoved >= 2;
6039 break;
6040 case Instruction::BitCast:
6041 DoXForm = false;
6042 break;
6043 default:
6044 // All the others use floating point so we shouldn't actually
6045 // get here because of the check above.
6046 assert(!"Unknown cast type .. unreachable");
6047 break;
6048 }
6049 }
6050
6051 if (DoXForm) {
Reid Spencer74a528b2006-12-13 18:21:21 +00006052 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
6053 CI.getOpcode() == Instruction::SExt);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006054 assert(Res->getType() == DestTy);
6055 switch (CI.getOpcode()) {
6056 default: assert(0 && "Unknown cast type!");
6057 case Instruction::Trunc:
6058 case Instruction::BitCast:
6059 // Just replace this cast with the result.
6060 return ReplaceInstUsesWith(CI, Res);
6061 case Instruction::ZExt: {
6062 // We need to emit an AND to clear the high bits.
6063 assert(SrcBitSize < DestBitSize && "Not a zext?");
6064 Constant *C =
Reid Spencerc635f472006-12-31 05:48:39 +00006065 ConstantInt::get(Type::Int64Ty, (1ULL << SrcBitSize)-1);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006066 if (DestBitSize < 64)
6067 C = ConstantExpr::getTrunc(C, DestTy);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006068 return BinaryOperator::createAnd(Res, C);
6069 }
6070 case Instruction::SExt:
6071 // We need to emit a cast to truncate, then a cast to sext.
6072 return CastInst::create(Instruction::SExt,
Reid Spencer13bc5d72006-12-12 09:18:51 +00006073 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
6074 CI), DestTy);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006075 }
6076 }
6077 }
6078
6079 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
6080 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
6081
6082 switch (SrcI->getOpcode()) {
6083 case Instruction::Add:
6084 case Instruction::Mul:
6085 case Instruction::And:
6086 case Instruction::Or:
6087 case Instruction::Xor:
6088 // If we are discarding information, or just changing the sign,
6089 // rewrite.
6090 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
6091 // Don't insert two casts if they cannot be eliminated. We allow
6092 // two casts to be inserted if the sizes are the same. This could
6093 // only be converting signedness, which is a noop.
6094 if (DestBitSize == SrcBitSize ||
Reid Spencer266e42b2006-12-23 06:05:41 +00006095 !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
6096 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer2a499b02006-12-13 17:19:09 +00006097 Instruction::CastOps opcode = CI.getOpcode();
Reid Spencer13bc5d72006-12-12 09:18:51 +00006098 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
6099 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
6100 return BinaryOperator::create(
6101 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006102 }
6103 }
6104
6105 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
6106 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
6107 SrcI->getOpcode() == Instruction::Xor &&
6108 Op1 == ConstantBool::getTrue() &&
Reid Spencer266e42b2006-12-23 06:05:41 +00006109 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00006110 Value *New = InsertOperandCastBefore(Instruction::ZExt, Op0, DestTy, &CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006111 return BinaryOperator::createXor(New, ConstantInt::get(CI.getType(), 1));
6112 }
6113 break;
6114 case Instruction::SDiv:
6115 case Instruction::UDiv:
6116 case Instruction::SRem:
6117 case Instruction::URem:
6118 // If we are just changing the sign, rewrite.
6119 if (DestBitSize == SrcBitSize) {
6120 // Don't insert two casts if they cannot be eliminated. We allow
6121 // two casts to be inserted if the sizes are the same. This could
6122 // only be converting signedness, which is a noop.
Reid Spencer266e42b2006-12-23 06:05:41 +00006123 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
6124 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00006125 Value *Op0c = InsertOperandCastBefore(Instruction::BitCast,
6126 Op0, DestTy, SrcI);
6127 Value *Op1c = InsertOperandCastBefore(Instruction::BitCast,
6128 Op1, DestTy, SrcI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006129 return BinaryOperator::create(
6130 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
6131 }
6132 }
6133 break;
6134
6135 case Instruction::Shl:
6136 // Allow changing the sign of the source operand. Do not allow
6137 // changing the size of the shift, UNLESS the shift amount is a
6138 // constant. We must not change variable sized shifts to a smaller
6139 // size, because it is undefined to shift more bits out than exist
6140 // in the value.
6141 if (DestBitSize == SrcBitSize ||
6142 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00006143 Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
6144 Instruction::BitCast : Instruction::Trunc);
6145 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006146 return new ShiftInst(Instruction::Shl, Op0c, Op1);
6147 }
6148 break;
6149 case Instruction::AShr:
6150 // If this is a signed shr, and if all bits shifted in are about to be
6151 // truncated off, turn it into an unsigned shr to allow greater
6152 // simplifications.
6153 if (DestBitSize < SrcBitSize &&
6154 isa<ConstantInt>(Op1)) {
6155 unsigned ShiftAmt = cast<ConstantInt>(Op1)->getZExtValue();
6156 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
6157 // Insert the new logical shift right.
6158 return new ShiftInst(Instruction::LShr, Op0, Op1);
6159 }
6160 }
6161 break;
6162
Reid Spencer266e42b2006-12-23 06:05:41 +00006163 case Instruction::ICmp:
6164 // If we are just checking for a icmp eq of a single bit and casting it
6165 // to an integer, then shift the bit to the appropriate place and then
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006166 // cast to integer to avoid the comparison.
6167 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
6168 uint64_t Op1CV = Op1C->getZExtValue();
6169 // cast (X == 0) to int --> X^1 iff X has only the low bit set.
6170 // cast (X == 0) to int --> (X>>1)^1 iff X has only the 2nd bit set.
6171 // cast (X == 1) to int --> X iff X has only the low bit set.
6172 // cast (X == 2) to int --> X>>1 iff X has only the 2nd bit set.
6173 // cast (X != 0) to int --> X iff X has only the low bit set.
6174 // cast (X != 0) to int --> X>>1 iff X has only the 2nd bit set.
6175 // cast (X != 1) to int --> X^1 iff X has only the low bit set.
6176 // cast (X != 2) to int --> (X>>1)^1 iff X has only the 2nd bit set.
6177 if (Op1CV == 0 || isPowerOf2_64(Op1CV)) {
6178 // If Op1C some other power of two, convert:
6179 uint64_t KnownZero, KnownOne;
6180 uint64_t TypeMask = Op1->getType()->getIntegralTypeMask();
6181 ComputeMaskedBits(Op0, TypeMask, KnownZero, KnownOne);
Reid Spencer266e42b2006-12-23 06:05:41 +00006182
6183 // This only works for EQ and NE
6184 ICmpInst::Predicate pred = cast<ICmpInst>(SrcI)->getPredicate();
6185 if (pred != ICmpInst::ICMP_NE && pred != ICmpInst::ICMP_EQ)
6186 break;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006187
6188 if (isPowerOf2_64(KnownZero^TypeMask)) { // Exactly 1 possible 1?
Reid Spencer266e42b2006-12-23 06:05:41 +00006189 bool isNE = pred == ICmpInst::ICMP_NE;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006190 if (Op1CV && (Op1CV != (KnownZero^TypeMask))) {
6191 // (X&4) == 2 --> false
6192 // (X&4) != 2 --> true
Reid Spencer266e42b2006-12-23 06:05:41 +00006193 Constant *Res = ConstantBool::get(isNE);
Reid Spencerbb65ebf2006-12-12 23:36:14 +00006194 Res = ConstantExpr::getZExt(Res, CI.getType());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006195 return ReplaceInstUsesWith(CI, Res);
6196 }
6197
6198 unsigned ShiftAmt = Log2_64(KnownZero^TypeMask);
6199 Value *In = Op0;
6200 if (ShiftAmt) {
6201 // Perform a logical shr by shiftamt.
6202 // Insert the shift to put the result in the low bit.
6203 In = InsertNewInstBefore(
6204 new ShiftInst(Instruction::LShr, In,
Reid Spencerc635f472006-12-31 05:48:39 +00006205 ConstantInt::get(Type::Int8Ty, ShiftAmt),
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006206 In->getName()+".lobit"), CI);
6207 }
6208
Reid Spencer266e42b2006-12-23 06:05:41 +00006209 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006210 Constant *One = ConstantInt::get(In->getType(), 1);
6211 In = BinaryOperator::createXor(In, One, "tmp");
6212 InsertNewInstBefore(cast<Instruction>(In), CI);
6213 }
6214
6215 if (CI.getType() == In->getType())
6216 return ReplaceInstUsesWith(CI, In);
6217 else
Reid Spencerbb65ebf2006-12-12 23:36:14 +00006218 return CastInst::createIntegerCast(In, CI.getType(), false/*ZExt*/);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006219 }
6220 }
6221 }
6222 break;
6223 }
6224 return 0;
6225}
6226
6227Instruction *InstCombiner::visitTrunc(CastInst &CI) {
Chris Lattnerd747f012006-11-29 07:04:07 +00006228 if (Instruction *Result = commonIntCastTransforms(CI))
6229 return Result;
6230
6231 Value *Src = CI.getOperand(0);
6232 const Type *Ty = CI.getType();
6233 unsigned DestBitWidth = Ty->getPrimitiveSizeInBits();
6234
6235 if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
6236 switch (SrcI->getOpcode()) {
6237 default: break;
6238 case Instruction::LShr:
6239 // We can shrink lshr to something smaller if we know the bits shifted in
6240 // are already zeros.
6241 if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
6242 unsigned ShAmt = ShAmtV->getZExtValue();
6243
6244 // Get a mask for the bits shifting in.
6245 uint64_t Mask = (~0ULL >> (64-ShAmt)) << DestBitWidth;
Reid Spencer13bc5d72006-12-12 09:18:51 +00006246 Value* SrcIOp0 = SrcI->getOperand(0);
6247 if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
Chris Lattnerd747f012006-11-29 07:04:07 +00006248 if (ShAmt >= DestBitWidth) // All zeros.
6249 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
6250
6251 // Okay, we can shrink this. Truncate the input, then return a new
6252 // shift.
Reid Spencer2a499b02006-12-13 17:19:09 +00006253 Value *V = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
Chris Lattnerd747f012006-11-29 07:04:07 +00006254 return new ShiftInst(Instruction::LShr, V, SrcI->getOperand(1));
6255 }
Chris Lattnerc209b582006-12-05 01:26:29 +00006256 } else { // This is a variable shr.
6257
6258 // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'. This is
6259 // more LLVM instructions, but allows '1 << Y' to be hoisted if
6260 // loop-invariant and CSE'd.
6261 if (CI.getType() == Type::BoolTy && SrcI->hasOneUse()) {
6262 Value *One = ConstantInt::get(SrcI->getType(), 1);
6263
6264 Value *V = InsertNewInstBefore(new ShiftInst(Instruction::Shl, One,
6265 SrcI->getOperand(1),
6266 "tmp"), CI);
6267 V = InsertNewInstBefore(BinaryOperator::createAnd(V,
6268 SrcI->getOperand(0),
6269 "tmp"), CI);
6270 Value *Zero = Constant::getNullValue(V->getType());
Reid Spencer266e42b2006-12-23 06:05:41 +00006271 return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
Chris Lattnerc209b582006-12-05 01:26:29 +00006272 }
Chris Lattnerd747f012006-11-29 07:04:07 +00006273 }
6274 break;
6275 }
6276 }
6277
6278 return 0;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006279}
6280
6281Instruction *InstCombiner::visitZExt(CastInst &CI) {
6282 // If one of the common conversion will work ..
6283 if (Instruction *Result = commonIntCastTransforms(CI))
6284 return Result;
6285
6286 Value *Src = CI.getOperand(0);
6287
6288 // If this is a cast of a cast
6289 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006290 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
6291 // types and if the sizes are just right we can convert this into a logical
6292 // 'and' which will be much cheaper than the pair of casts.
6293 if (isa<TruncInst>(CSrc)) {
6294 // Get the sizes of the types involved
6295 Value *A = CSrc->getOperand(0);
6296 unsigned SrcSize = A->getType()->getPrimitiveSizeInBits();
6297 unsigned MidSize = CSrc->getType()->getPrimitiveSizeInBits();
6298 unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
6299 // If we're actually extending zero bits and the trunc is a no-op
6300 if (MidSize < DstSize && SrcSize == DstSize) {
6301 // Replace both of the casts with an And of the type mask.
6302 uint64_t AndValue = CSrc->getType()->getIntegralTypeMask();
6303 Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
6304 Instruction *And =
6305 BinaryOperator::createAnd(CSrc->getOperand(0), AndConst);
6306 // Unfortunately, if the type changed, we need to cast it back.
6307 if (And->getType() != CI.getType()) {
6308 And->setName(CSrc->getName()+".mask");
6309 InsertNewInstBefore(And, CI);
Reid Spencerbb65ebf2006-12-12 23:36:14 +00006310 And = CastInst::createIntegerCast(And, CI.getType(), false/*ZExt*/);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006311 }
6312 return And;
6313 }
6314 }
6315 }
6316
6317 return 0;
6318}
6319
6320Instruction *InstCombiner::visitSExt(CastInst &CI) {
6321 return commonIntCastTransforms(CI);
6322}
6323
6324Instruction *InstCombiner::visitFPTrunc(CastInst &CI) {
6325 return commonCastTransforms(CI);
6326}
6327
6328Instruction *InstCombiner::visitFPExt(CastInst &CI) {
6329 return commonCastTransforms(CI);
6330}
6331
6332Instruction *InstCombiner::visitFPToUI(CastInst &CI) {
Reid Spencerad05ee92006-11-30 23:13:36 +00006333 return commonCastTransforms(CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006334}
6335
6336Instruction *InstCombiner::visitFPToSI(CastInst &CI) {
Reid Spencerad05ee92006-11-30 23:13:36 +00006337 return commonCastTransforms(CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006338}
6339
6340Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
6341 return commonCastTransforms(CI);
6342}
6343
6344Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
6345 return commonCastTransforms(CI);
6346}
6347
6348Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
Reid Spencerad05ee92006-11-30 23:13:36 +00006349 return commonCastTransforms(CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006350}
6351
6352Instruction *InstCombiner::visitIntToPtr(CastInst &CI) {
6353 return commonCastTransforms(CI);
6354}
6355
6356Instruction *InstCombiner::visitBitCast(CastInst &CI) {
6357
6358 // If the operands are integer typed then apply the integer transforms,
6359 // otherwise just apply the common ones.
6360 Value *Src = CI.getOperand(0);
6361 const Type *SrcTy = Src->getType();
6362 const Type *DestTy = CI.getType();
6363
6364 if (SrcTy->isInteger() && DestTy->isInteger()) {
6365 if (Instruction *Result = commonIntCastTransforms(CI))
6366 return Result;
6367 } else {
6368 if (Instruction *Result = commonCastTransforms(CI))
6369 return Result;
6370 }
6371
6372
6373 // Get rid of casts from one type to the same type. These are useless and can
6374 // be replaced by the operand.
6375 if (DestTy == Src->getType())
6376 return ReplaceInstUsesWith(CI, Src);
6377
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006378 // If the source and destination are pointers, and this cast is equivalent to
6379 // a getelementptr X, 0, 0, 0... turn it into the appropriate getelementptr.
6380 // This can enhance SROA and other transforms that want type-safe pointers.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006381 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
6382 if (const PointerType *SrcPTy = dyn_cast<PointerType>(SrcTy)) {
6383 const Type *DstElTy = DstPTy->getElementType();
6384 const Type *SrcElTy = SrcPTy->getElementType();
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006385
Reid Spencerc635f472006-12-31 05:48:39 +00006386 Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006387 unsigned NumZeros = 0;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006388 while (SrcElTy != DstElTy &&
6389 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
6390 SrcElTy->getNumContainedTypes() /* not "{}" */) {
6391 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006392 ++NumZeros;
6393 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00006394
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006395 // If we found a path from the src to dest, create the getelementptr now.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006396 if (SrcElTy == DstElTy) {
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006397 std::vector<Value*> Idxs(NumZeros+1, ZeroUInt);
6398 return new GetElementPtrInst(Src, Idxs);
6399 }
6400 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006401 }
Chris Lattnerdfae8be2003-07-24 17:35:25 +00006402
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006403 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
6404 if (SVI->hasOneUse()) {
6405 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
6406 // a bitconvert to a vector with the same # elts.
6407 if (isa<PackedType>(DestTy) &&
6408 cast<PackedType>(DestTy)->getNumElements() ==
6409 SVI->getType()->getNumElements()) {
6410 CastInst *Tmp;
6411 // If either of the operands is a cast from CI.getType(), then
6412 // evaluating the shuffle in the casted destination's type will allow
6413 // us to eliminate at least one cast.
6414 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
6415 Tmp->getOperand(0)->getType() == DestTy) ||
6416 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
6417 Tmp->getOperand(0)->getType() == DestTy)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00006418 Value *LHS = InsertOperandCastBefore(Instruction::BitCast,
6419 SVI->getOperand(0), DestTy, &CI);
6420 Value *RHS = InsertOperandCastBefore(Instruction::BitCast,
6421 SVI->getOperand(1), DestTy, &CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006422 // Return a new shuffle vector. Use the same element ID's, as we
6423 // know the vector types match #elts.
6424 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner99155be2006-05-25 23:24:33 +00006425 }
6426 }
6427 }
6428 }
Chris Lattner260ab202002-04-18 17:39:14 +00006429 return 0;
Chris Lattnerca081252001-12-14 16:52:21 +00006430}
6431
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006432/// GetSelectFoldableOperands - We want to turn code that looks like this:
6433/// %C = or %A, %B
6434/// %D = select %cond, %C, %A
6435/// into:
6436/// %C = select %cond, %B, 0
6437/// %D = or %A, %C
6438///
6439/// Assuming that the specified instruction is an operand to the select, return
6440/// a bitmask indicating which operands of this instruction are foldable if they
6441/// equal the other incoming value of the select.
6442///
6443static unsigned GetSelectFoldableOperands(Instruction *I) {
6444 switch (I->getOpcode()) {
6445 case Instruction::Add:
6446 case Instruction::Mul:
6447 case Instruction::And:
6448 case Instruction::Or:
6449 case Instruction::Xor:
6450 return 3; // Can fold through either operand.
6451 case Instruction::Sub: // Can only fold on the amount subtracted.
6452 case Instruction::Shl: // Can only fold on the shift amount.
Reid Spencerfdff9382006-11-08 06:47:33 +00006453 case Instruction::LShr:
6454 case Instruction::AShr:
Misha Brukmanb1c93172005-04-21 23:48:37 +00006455 return 1;
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006456 default:
6457 return 0; // Cannot fold
6458 }
6459}
6460
6461/// GetSelectFoldableConstant - For the same transformation as the previous
6462/// function, return the identity constant that goes into the select.
6463static Constant *GetSelectFoldableConstant(Instruction *I) {
6464 switch (I->getOpcode()) {
6465 default: assert(0 && "This cannot happen!"); abort();
6466 case Instruction::Add:
6467 case Instruction::Sub:
6468 case Instruction::Or:
6469 case Instruction::Xor:
6470 return Constant::getNullValue(I->getType());
6471 case Instruction::Shl:
Reid Spencerfdff9382006-11-08 06:47:33 +00006472 case Instruction::LShr:
6473 case Instruction::AShr:
Reid Spencerc635f472006-12-31 05:48:39 +00006474 return Constant::getNullValue(Type::Int8Ty);
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006475 case Instruction::And:
6476 return ConstantInt::getAllOnesValue(I->getType());
6477 case Instruction::Mul:
6478 return ConstantInt::get(I->getType(), 1);
6479 }
6480}
6481
Chris Lattner411336f2005-01-19 21:50:18 +00006482/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
6483/// have the same opcode and only one use each. Try to simplify this.
6484Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
6485 Instruction *FI) {
6486 if (TI->getNumOperands() == 1) {
6487 // If this is a non-volatile load or a cast from the same type,
6488 // merge.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006489 if (TI->isCast()) {
Chris Lattner411336f2005-01-19 21:50:18 +00006490 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
6491 return 0;
6492 } else {
6493 return 0; // unknown unary op.
6494 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00006495
Chris Lattner411336f2005-01-19 21:50:18 +00006496 // Fold this by inserting a select from the input values.
6497 SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
6498 FI->getOperand(0), SI.getName()+".v");
6499 InsertNewInstBefore(NewSI, SI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006500 return CastInst::create(Instruction::CastOps(TI->getOpcode()), NewSI,
6501 TI->getType());
Chris Lattner411336f2005-01-19 21:50:18 +00006502 }
6503
Reid Spencer266e42b2006-12-23 06:05:41 +00006504 // Only handle binary, compare and shift operators here.
Reid Spencer43c77d52006-12-23 18:58:04 +00006505 if (!isa<ShiftInst>(TI) && !isa<BinaryOperator>(TI))
Chris Lattner411336f2005-01-19 21:50:18 +00006506 return 0;
6507
6508 // Figure out if the operations have any operands in common.
6509 Value *MatchOp, *OtherOpT, *OtherOpF;
6510 bool MatchIsOpZero;
6511 if (TI->getOperand(0) == FI->getOperand(0)) {
6512 MatchOp = TI->getOperand(0);
6513 OtherOpT = TI->getOperand(1);
6514 OtherOpF = FI->getOperand(1);
6515 MatchIsOpZero = true;
6516 } else if (TI->getOperand(1) == FI->getOperand(1)) {
6517 MatchOp = TI->getOperand(1);
6518 OtherOpT = TI->getOperand(0);
6519 OtherOpF = FI->getOperand(0);
6520 MatchIsOpZero = false;
6521 } else if (!TI->isCommutative()) {
6522 return 0;
6523 } else if (TI->getOperand(0) == FI->getOperand(1)) {
6524 MatchOp = TI->getOperand(0);
6525 OtherOpT = TI->getOperand(1);
6526 OtherOpF = FI->getOperand(0);
6527 MatchIsOpZero = true;
6528 } else if (TI->getOperand(1) == FI->getOperand(0)) {
6529 MatchOp = TI->getOperand(1);
6530 OtherOpT = TI->getOperand(0);
6531 OtherOpF = FI->getOperand(1);
6532 MatchIsOpZero = true;
6533 } else {
6534 return 0;
6535 }
6536
6537 // If we reach here, they do have operations in common.
6538 SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
6539 OtherOpF, SI.getName()+".v");
6540 InsertNewInstBefore(NewSI, SI);
6541
6542 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
6543 if (MatchIsOpZero)
6544 return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
6545 else
6546 return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
Chris Lattner411336f2005-01-19 21:50:18 +00006547 }
Reid Spencer43c77d52006-12-23 18:58:04 +00006548
6549 assert(isa<ShiftInst>(TI) && "Should only have Shift here");
6550 if (MatchIsOpZero)
6551 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), MatchOp, NewSI);
6552 else
6553 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), NewSI, MatchOp);
Chris Lattner411336f2005-01-19 21:50:18 +00006554}
6555
Chris Lattnerb909e8b2004-03-12 05:52:32 +00006556Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattner533bc492004-03-30 19:37:13 +00006557 Value *CondVal = SI.getCondition();
6558 Value *TrueVal = SI.getTrueValue();
6559 Value *FalseVal = SI.getFalseValue();
6560
6561 // select true, X, Y -> X
6562 // select false, X, Y -> Y
6563 if (ConstantBool *C = dyn_cast<ConstantBool>(CondVal))
Chris Lattner6ab03f62006-09-28 23:35:22 +00006564 return ReplaceInstUsesWith(SI, C->getValue() ? TrueVal : FalseVal);
Chris Lattner533bc492004-03-30 19:37:13 +00006565
6566 // select C, X, X -> X
6567 if (TrueVal == FalseVal)
6568 return ReplaceInstUsesWith(SI, TrueVal);
6569
Chris Lattner81a7a232004-10-16 18:11:37 +00006570 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
6571 return ReplaceInstUsesWith(SI, FalseVal);
6572 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
6573 return ReplaceInstUsesWith(SI, TrueVal);
6574 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
6575 if (isa<Constant>(TrueVal))
6576 return ReplaceInstUsesWith(SI, TrueVal);
6577 else
6578 return ReplaceInstUsesWith(SI, FalseVal);
6579 }
6580
Chris Lattner1c631e82004-04-08 04:43:23 +00006581 if (SI.getType() == Type::BoolTy)
6582 if (ConstantBool *C = dyn_cast<ConstantBool>(TrueVal)) {
Chris Lattner6ab03f62006-09-28 23:35:22 +00006583 if (C->getValue()) {
Chris Lattner1c631e82004-04-08 04:43:23 +00006584 // Change: A = select B, true, C --> A = or B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00006585 return BinaryOperator::createOr(CondVal, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00006586 } else {
6587 // Change: A = select B, false, C --> A = and !B, C
6588 Value *NotCond =
6589 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
6590 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00006591 return BinaryOperator::createAnd(NotCond, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00006592 }
6593 } else if (ConstantBool *C = dyn_cast<ConstantBool>(FalseVal)) {
Chris Lattner6ab03f62006-09-28 23:35:22 +00006594 if (C->getValue() == false) {
Chris Lattner1c631e82004-04-08 04:43:23 +00006595 // Change: A = select B, C, false --> A = and B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00006596 return BinaryOperator::createAnd(CondVal, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00006597 } else {
6598 // Change: A = select B, C, true --> A = or !B, C
6599 Value *NotCond =
6600 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
6601 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00006602 return BinaryOperator::createOr(NotCond, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00006603 }
6604 }
6605
Chris Lattner183b3362004-04-09 19:05:30 +00006606 // Selecting between two integer constants?
6607 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
6608 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
6609 // select C, 1, 0 -> cast C to int
Reid Spencere0fc4df2006-10-20 07:07:24 +00006610 if (FalseValC->isNullValue() && TrueValC->getZExtValue() == 1) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006611 return CastInst::create(Instruction::ZExt, CondVal, SI.getType());
Reid Spencere0fc4df2006-10-20 07:07:24 +00006612 } else if (TrueValC->isNullValue() && FalseValC->getZExtValue() == 1) {
Chris Lattner183b3362004-04-09 19:05:30 +00006613 // select C, 0, 1 -> cast !C to int
6614 Value *NotCond =
6615 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
Chris Lattnercf7baf32004-04-09 18:19:44 +00006616 "not."+CondVal->getName()), SI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006617 return CastInst::create(Instruction::ZExt, NotCond, SI.getType());
Chris Lattnercf7baf32004-04-09 18:19:44 +00006618 }
Chris Lattner35167c32004-06-09 07:59:58 +00006619
Reid Spencer266e42b2006-12-23 06:05:41 +00006620 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Chris Lattner380c7e92006-09-20 04:44:59 +00006621
Reid Spencer266e42b2006-12-23 06:05:41 +00006622 // (x <s 0) ? -1 : 0 -> ashr x, 31
6623 // (x >u 2147483647) ? -1 : 0 -> ashr x, 31
Chris Lattner380c7e92006-09-20 04:44:59 +00006624 if (TrueValC->isAllOnesValue() && FalseValC->isNullValue())
6625 if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
6626 bool CanXForm = false;
Reid Spencer266e42b2006-12-23 06:05:41 +00006627 if (IC->isSignedPredicate())
Chris Lattner380c7e92006-09-20 04:44:59 +00006628 CanXForm = CmpCst->isNullValue() &&
Reid Spencer266e42b2006-12-23 06:05:41 +00006629 IC->getPredicate() == ICmpInst::ICMP_SLT;
Chris Lattner380c7e92006-09-20 04:44:59 +00006630 else {
6631 unsigned Bits = CmpCst->getType()->getPrimitiveSizeInBits();
Reid Spencere0fc4df2006-10-20 07:07:24 +00006632 CanXForm = (CmpCst->getZExtValue() == ~0ULL >> (64-Bits+1)) &&
Reid Spencer266e42b2006-12-23 06:05:41 +00006633 IC->getPredicate() == ICmpInst::ICMP_UGT;
Chris Lattner380c7e92006-09-20 04:44:59 +00006634 }
6635
6636 if (CanXForm) {
6637 // The comparison constant and the result are not neccessarily the
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006638 // same width. Make an all-ones value by inserting a AShr.
Chris Lattner380c7e92006-09-20 04:44:59 +00006639 Value *X = IC->getOperand(0);
Chris Lattner380c7e92006-09-20 04:44:59 +00006640 unsigned Bits = X->getType()->getPrimitiveSizeInBits();
Reid Spencerc635f472006-12-31 05:48:39 +00006641 Constant *ShAmt = ConstantInt::get(Type::Int8Ty, Bits-1);
Reid Spencerfdff9382006-11-08 06:47:33 +00006642 Instruction *SRA = new ShiftInst(Instruction::AShr, X,
Chris Lattner380c7e92006-09-20 04:44:59 +00006643 ShAmt, "ones");
6644 InsertNewInstBefore(SRA, SI);
6645
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006646 // Finally, convert to the type of the select RHS. We figure out
6647 // if this requires a SExt, Trunc or BitCast based on the sizes.
6648 Instruction::CastOps opc = Instruction::BitCast;
6649 unsigned SRASize = SRA->getType()->getPrimitiveSizeInBits();
6650 unsigned SISize = SI.getType()->getPrimitiveSizeInBits();
6651 if (SRASize < SISize)
6652 opc = Instruction::SExt;
6653 else if (SRASize > SISize)
6654 opc = Instruction::Trunc;
6655 return CastInst::create(opc, SRA, SI.getType());
Chris Lattner380c7e92006-09-20 04:44:59 +00006656 }
6657 }
6658
6659
6660 // If one of the constants is zero (we know they can't both be) and we
Reid Spencer266e42b2006-12-23 06:05:41 +00006661 // have a fcmp instruction with zero, and we have an 'and' with the
Chris Lattner380c7e92006-09-20 04:44:59 +00006662 // non-constant value, eliminate this whole mess. This corresponds to
6663 // cases like this: ((X & 27) ? 27 : 0)
6664 if (TrueValC->isNullValue() || FalseValC->isNullValue())
Chris Lattnerb3f24c92006-09-18 04:22:48 +00006665 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner35167c32004-06-09 07:59:58 +00006666 cast<Constant>(IC->getOperand(1))->isNullValue())
6667 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
6668 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00006669 isa<ConstantInt>(ICA->getOperand(1)) &&
6670 (ICA->getOperand(1) == TrueValC ||
6671 ICA->getOperand(1) == FalseValC) &&
Chris Lattner35167c32004-06-09 07:59:58 +00006672 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
6673 // Okay, now we know that everything is set up, we just don't
Reid Spencer266e42b2006-12-23 06:05:41 +00006674 // know whether we have a icmp_ne or icmp_eq and whether the
6675 // true or false val is the zero.
Chris Lattner35167c32004-06-09 07:59:58 +00006676 bool ShouldNotVal = !TrueValC->isNullValue();
Reid Spencer266e42b2006-12-23 06:05:41 +00006677 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
Chris Lattner35167c32004-06-09 07:59:58 +00006678 Value *V = ICA;
6679 if (ShouldNotVal)
6680 V = InsertNewInstBefore(BinaryOperator::create(
6681 Instruction::Xor, V, ICA->getOperand(1)), SI);
6682 return ReplaceInstUsesWith(SI, V);
6683 }
Chris Lattner380c7e92006-09-20 04:44:59 +00006684 }
Chris Lattner533bc492004-03-30 19:37:13 +00006685 }
Chris Lattner623fba12004-04-10 22:21:27 +00006686
6687 // See if we are selecting two values based on a comparison of the two values.
Reid Spencer266e42b2006-12-23 06:05:41 +00006688 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
6689 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
Chris Lattner623fba12004-04-10 22:21:27 +00006690 // Transform (X == Y) ? X : Y -> Y
Reid Spencer266e42b2006-12-23 06:05:41 +00006691 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ)
Chris Lattner623fba12004-04-10 22:21:27 +00006692 return ReplaceInstUsesWith(SI, FalseVal);
6693 // Transform (X != Y) ? X : Y -> X
Reid Spencer266e42b2006-12-23 06:05:41 +00006694 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
Chris Lattner623fba12004-04-10 22:21:27 +00006695 return ReplaceInstUsesWith(SI, TrueVal);
6696 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6697
Reid Spencer266e42b2006-12-23 06:05:41 +00006698 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
Chris Lattner623fba12004-04-10 22:21:27 +00006699 // Transform (X == Y) ? Y : X -> X
Reid Spencer266e42b2006-12-23 06:05:41 +00006700 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ)
Chris Lattner24cf0202004-04-11 01:39:19 +00006701 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattner623fba12004-04-10 22:21:27 +00006702 // Transform (X != Y) ? Y : X -> Y
Reid Spencer266e42b2006-12-23 06:05:41 +00006703 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
6704 return ReplaceInstUsesWith(SI, TrueVal);
6705 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6706 }
6707 }
6708
6709 // See if we are selecting two values based on a comparison of the two values.
6710 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal)) {
6711 if (ICI->getOperand(0) == TrueVal && ICI->getOperand(1) == FalseVal) {
6712 // Transform (X == Y) ? X : Y -> Y
6713 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
6714 return ReplaceInstUsesWith(SI, FalseVal);
6715 // Transform (X != Y) ? X : Y -> X
6716 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
6717 return ReplaceInstUsesWith(SI, TrueVal);
6718 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6719
6720 } else if (ICI->getOperand(0) == FalseVal && ICI->getOperand(1) == TrueVal){
6721 // Transform (X == Y) ? Y : X -> X
6722 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
6723 return ReplaceInstUsesWith(SI, FalseVal);
6724 // Transform (X != Y) ? Y : X -> Y
6725 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
Chris Lattner24cf0202004-04-11 01:39:19 +00006726 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattner623fba12004-04-10 22:21:27 +00006727 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6728 }
6729 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00006730
Chris Lattnera04c9042005-01-13 22:52:24 +00006731 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
6732 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
6733 if (TI->hasOneUse() && FI->hasOneUse()) {
Chris Lattnera04c9042005-01-13 22:52:24 +00006734 Instruction *AddOp = 0, *SubOp = 0;
6735
Chris Lattner411336f2005-01-19 21:50:18 +00006736 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
6737 if (TI->getOpcode() == FI->getOpcode())
6738 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
6739 return IV;
6740
6741 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
6742 // even legal for FP.
Chris Lattnera04c9042005-01-13 22:52:24 +00006743 if (TI->getOpcode() == Instruction::Sub &&
6744 FI->getOpcode() == Instruction::Add) {
6745 AddOp = FI; SubOp = TI;
6746 } else if (FI->getOpcode() == Instruction::Sub &&
6747 TI->getOpcode() == Instruction::Add) {
6748 AddOp = TI; SubOp = FI;
6749 }
6750
6751 if (AddOp) {
6752 Value *OtherAddOp = 0;
6753 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
6754 OtherAddOp = AddOp->getOperand(1);
6755 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
6756 OtherAddOp = AddOp->getOperand(0);
6757 }
6758
6759 if (OtherAddOp) {
Chris Lattnerb580d262006-02-24 18:05:58 +00006760 // So at this point we know we have (Y -> OtherAddOp):
6761 // select C, (add X, Y), (sub X, Z)
6762 Value *NegVal; // Compute -Z
6763 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
6764 NegVal = ConstantExpr::getNeg(C);
6765 } else {
6766 NegVal = InsertNewInstBefore(
6767 BinaryOperator::createNeg(SubOp->getOperand(1), "tmp"), SI);
Chris Lattnera04c9042005-01-13 22:52:24 +00006768 }
Chris Lattnerb580d262006-02-24 18:05:58 +00006769
6770 Value *NewTrueOp = OtherAddOp;
6771 Value *NewFalseOp = NegVal;
6772 if (AddOp != TI)
6773 std::swap(NewTrueOp, NewFalseOp);
6774 Instruction *NewSel =
6775 new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
6776
6777 NewSel = InsertNewInstBefore(NewSel, SI);
6778 return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
Chris Lattnera04c9042005-01-13 22:52:24 +00006779 }
6780 }
6781 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00006782
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006783 // See if we can fold the select into one of our operands.
6784 if (SI.getType()->isInteger()) {
6785 // See the comment above GetSelectFoldableOperands for a description of the
6786 // transformation we are doing here.
6787 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
6788 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
6789 !isa<Constant>(FalseVal))
6790 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
6791 unsigned OpToFold = 0;
6792 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
6793 OpToFold = 1;
6794 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
6795 OpToFold = 2;
6796 }
6797
6798 if (OpToFold) {
6799 Constant *C = GetSelectFoldableConstant(TVI);
6800 std::string Name = TVI->getName(); TVI->setName("");
6801 Instruction *NewSel =
6802 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C,
6803 Name);
6804 InsertNewInstBefore(NewSel, SI);
6805 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
6806 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
6807 else if (ShiftInst *SI = dyn_cast<ShiftInst>(TVI))
6808 return new ShiftInst(SI->getOpcode(), FalseVal, NewSel);
6809 else {
6810 assert(0 && "Unknown instruction!!");
6811 }
6812 }
6813 }
Chris Lattner6862fbd2004-09-29 17:40:11 +00006814
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006815 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
6816 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
6817 !isa<Constant>(TrueVal))
6818 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
6819 unsigned OpToFold = 0;
6820 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
6821 OpToFold = 1;
6822 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
6823 OpToFold = 2;
6824 }
6825
6826 if (OpToFold) {
6827 Constant *C = GetSelectFoldableConstant(FVI);
6828 std::string Name = FVI->getName(); FVI->setName("");
6829 Instruction *NewSel =
6830 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold),
6831 Name);
6832 InsertNewInstBefore(NewSel, SI);
6833 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
6834 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
6835 else if (ShiftInst *SI = dyn_cast<ShiftInst>(FVI))
6836 return new ShiftInst(SI->getOpcode(), TrueVal, NewSel);
6837 else {
6838 assert(0 && "Unknown instruction!!");
6839 }
6840 }
6841 }
6842 }
Chris Lattnerd6f636a2005-04-24 07:30:14 +00006843
6844 if (BinaryOperator::isNot(CondVal)) {
6845 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
6846 SI.setOperand(1, FalseVal);
6847 SI.setOperand(2, TrueVal);
6848 return &SI;
6849 }
6850
Chris Lattnerb909e8b2004-03-12 05:52:32 +00006851 return 0;
6852}
6853
Chris Lattner82f2ef22006-03-06 20:18:44 +00006854/// GetKnownAlignment - If the specified pointer has an alignment that we can
6855/// determine, return it, otherwise return 0.
6856static unsigned GetKnownAlignment(Value *V, TargetData *TD) {
6857 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
6858 unsigned Align = GV->getAlignment();
6859 if (Align == 0 && TD)
6860 Align = TD->getTypeAlignment(GV->getType()->getElementType());
6861 return Align;
6862 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
6863 unsigned Align = AI->getAlignment();
6864 if (Align == 0 && TD) {
6865 if (isa<AllocaInst>(AI))
6866 Align = TD->getTypeAlignment(AI->getType()->getElementType());
6867 else if (isa<MallocInst>(AI)) {
6868 // Malloc returns maximally aligned memory.
6869 Align = TD->getTypeAlignment(AI->getType()->getElementType());
6870 Align = std::max(Align, (unsigned)TD->getTypeAlignment(Type::DoubleTy));
Reid Spencerc635f472006-12-31 05:48:39 +00006871 Align = std::max(Align, (unsigned)TD->getTypeAlignment(Type::Int64Ty));
Chris Lattner82f2ef22006-03-06 20:18:44 +00006872 }
6873 }
6874 return Align;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006875 } else if (isa<BitCastInst>(V) ||
Chris Lattner53ef5a02006-03-07 01:28:57 +00006876 (isa<ConstantExpr>(V) &&
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006877 cast<ConstantExpr>(V)->getOpcode() == Instruction::BitCast)) {
Chris Lattner53ef5a02006-03-07 01:28:57 +00006878 User *CI = cast<User>(V);
Chris Lattner82f2ef22006-03-06 20:18:44 +00006879 if (isa<PointerType>(CI->getOperand(0)->getType()))
6880 return GetKnownAlignment(CI->getOperand(0), TD);
6881 return 0;
Chris Lattner53ef5a02006-03-07 01:28:57 +00006882 } else if (isa<GetElementPtrInst>(V) ||
6883 (isa<ConstantExpr>(V) &&
6884 cast<ConstantExpr>(V)->getOpcode()==Instruction::GetElementPtr)) {
6885 User *GEPI = cast<User>(V);
Chris Lattner82f2ef22006-03-06 20:18:44 +00006886 unsigned BaseAlignment = GetKnownAlignment(GEPI->getOperand(0), TD);
6887 if (BaseAlignment == 0) return 0;
6888
6889 // If all indexes are zero, it is just the alignment of the base pointer.
6890 bool AllZeroOperands = true;
6891 for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
6892 if (!isa<Constant>(GEPI->getOperand(i)) ||
6893 !cast<Constant>(GEPI->getOperand(i))->isNullValue()) {
6894 AllZeroOperands = false;
6895 break;
6896 }
6897 if (AllZeroOperands)
6898 return BaseAlignment;
6899
6900 // Otherwise, if the base alignment is >= the alignment we expect for the
6901 // base pointer type, then we know that the resultant pointer is aligned at
6902 // least as much as its type requires.
6903 if (!TD) return 0;
6904
6905 const Type *BasePtrTy = GEPI->getOperand(0)->getType();
6906 if (TD->getTypeAlignment(cast<PointerType>(BasePtrTy)->getElementType())
Chris Lattner53ef5a02006-03-07 01:28:57 +00006907 <= BaseAlignment) {
6908 const Type *GEPTy = GEPI->getType();
6909 return TD->getTypeAlignment(cast<PointerType>(GEPTy)->getElementType());
6910 }
Chris Lattner82f2ef22006-03-06 20:18:44 +00006911 return 0;
6912 }
6913 return 0;
6914}
6915
Chris Lattnerb909e8b2004-03-12 05:52:32 +00006916
Chris Lattnerc66b2232006-01-13 20:11:04 +00006917/// visitCallInst - CallInst simplification. This mostly only handles folding
6918/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
6919/// the heavy lifting.
6920///
Chris Lattner970c33a2003-06-19 17:00:31 +00006921Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattnerc66b2232006-01-13 20:11:04 +00006922 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
6923 if (!II) return visitCallSite(&CI);
6924
Chris Lattner51ea1272004-02-28 05:22:00 +00006925 // Intrinsics cannot occur in an invoke, so handle them here instead of in
6926 // visitCallSite.
Chris Lattnerc66b2232006-01-13 20:11:04 +00006927 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner00648e12004-10-12 04:52:52 +00006928 bool Changed = false;
6929
6930 // memmove/cpy/set of zero bytes is a noop.
6931 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
6932 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
6933
Chris Lattner00648e12004-10-12 04:52:52 +00006934 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencere0fc4df2006-10-20 07:07:24 +00006935 if (CI->getZExtValue() == 1) {
Chris Lattner00648e12004-10-12 04:52:52 +00006936 // Replace the instruction with just byte operations. We would
6937 // transform other cases to loads/stores, but we don't know if
6938 // alignment is sufficient.
6939 }
Chris Lattner51ea1272004-02-28 05:22:00 +00006940 }
6941
Chris Lattner00648e12004-10-12 04:52:52 +00006942 // If we have a memmove and the source operation is a constant global,
6943 // then the source and dest pointers can't alias, so we can change this
6944 // into a call to memcpy.
Chris Lattner82f2ef22006-03-06 20:18:44 +00006945 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(II)) {
Chris Lattner00648e12004-10-12 04:52:52 +00006946 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
6947 if (GVSrc->isConstant()) {
6948 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner681ef2f2006-03-03 01:34:17 +00006949 const char *Name;
Andrew Lenharth0ebb0b02006-11-03 22:45:50 +00006950 if (CI.getCalledFunction()->getFunctionType()->getParamType(2) ==
Reid Spencerc635f472006-12-31 05:48:39 +00006951 Type::Int32Ty)
Chris Lattner681ef2f2006-03-03 01:34:17 +00006952 Name = "llvm.memcpy.i32";
6953 else
6954 Name = "llvm.memcpy.i64";
Chris Lattnerfbc524f2007-01-07 06:58:05 +00006955 Constant *MemCpy = M->getOrInsertFunction(Name,
Chris Lattner00648e12004-10-12 04:52:52 +00006956 CI.getCalledFunction()->getFunctionType());
6957 CI.setOperand(0, MemCpy);
6958 Changed = true;
6959 }
Chris Lattner82f2ef22006-03-06 20:18:44 +00006960 }
Chris Lattner00648e12004-10-12 04:52:52 +00006961
Chris Lattner82f2ef22006-03-06 20:18:44 +00006962 // If we can determine a pointer alignment that is bigger than currently
6963 // set, update the alignment.
6964 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
6965 unsigned Alignment1 = GetKnownAlignment(MI->getOperand(1), TD);
6966 unsigned Alignment2 = GetKnownAlignment(MI->getOperand(2), TD);
6967 unsigned Align = std::min(Alignment1, Alignment2);
Reid Spencere0fc4df2006-10-20 07:07:24 +00006968 if (MI->getAlignment()->getZExtValue() < Align) {
Reid Spencerc635f472006-12-31 05:48:39 +00006969 MI->setAlignment(ConstantInt::get(Type::Int32Ty, Align));
Chris Lattner82f2ef22006-03-06 20:18:44 +00006970 Changed = true;
6971 }
6972 } else if (isa<MemSetInst>(MI)) {
6973 unsigned Alignment = GetKnownAlignment(MI->getDest(), TD);
Reid Spencere0fc4df2006-10-20 07:07:24 +00006974 if (MI->getAlignment()->getZExtValue() < Alignment) {
Reid Spencerc635f472006-12-31 05:48:39 +00006975 MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
Chris Lattner82f2ef22006-03-06 20:18:44 +00006976 Changed = true;
6977 }
6978 }
6979
Chris Lattnerc66b2232006-01-13 20:11:04 +00006980 if (Changed) return II;
Chris Lattner503221f2006-01-13 21:28:09 +00006981 } else {
6982 switch (II->getIntrinsicID()) {
6983 default: break;
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00006984 case Intrinsic::ppc_altivec_lvx:
6985 case Intrinsic::ppc_altivec_lvxl:
Chris Lattner36dd7c92006-04-17 22:26:56 +00006986 case Intrinsic::x86_sse_loadu_ps:
6987 case Intrinsic::x86_sse2_loadu_pd:
6988 case Intrinsic::x86_sse2_loadu_dq:
6989 // Turn PPC lvx -> load if the pointer is known aligned.
6990 // Turn X86 loadups -> load if the pointer is known aligned.
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00006991 if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00006992 Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(1),
Chris Lattnere79d2492006-04-06 19:19:17 +00006993 PointerType::get(II->getType()), CI);
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00006994 return new LoadInst(Ptr);
6995 }
6996 break;
6997 case Intrinsic::ppc_altivec_stvx:
6998 case Intrinsic::ppc_altivec_stvxl:
6999 // Turn stvx -> store if the pointer is known aligned.
7000 if (GetKnownAlignment(II->getOperand(2), TD) >= 16) {
Chris Lattnere79d2492006-04-06 19:19:17 +00007001 const Type *OpPtrTy = PointerType::get(II->getOperand(1)->getType());
Reid Spencer13bc5d72006-12-12 09:18:51 +00007002 Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(2),
7003 OpPtrTy, CI);
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00007004 return new StoreInst(II->getOperand(1), Ptr);
7005 }
7006 break;
Chris Lattner36dd7c92006-04-17 22:26:56 +00007007 case Intrinsic::x86_sse_storeu_ps:
7008 case Intrinsic::x86_sse2_storeu_pd:
7009 case Intrinsic::x86_sse2_storeu_dq:
7010 case Intrinsic::x86_sse2_storel_dq:
7011 // Turn X86 storeu -> store if the pointer is known aligned.
7012 if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
7013 const Type *OpPtrTy = PointerType::get(II->getOperand(2)->getType());
Reid Spencer13bc5d72006-12-12 09:18:51 +00007014 Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(1),
7015 OpPtrTy, CI);
Chris Lattner36dd7c92006-04-17 22:26:56 +00007016 return new StoreInst(II->getOperand(2), Ptr);
7017 }
7018 break;
Chris Lattner2deeaea2006-10-05 06:55:50 +00007019
7020 case Intrinsic::x86_sse_cvttss2si: {
7021 // These intrinsics only demands the 0th element of its input vector. If
7022 // we can simplify the input based on that, do so now.
7023 uint64_t UndefElts;
7024 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1,
7025 UndefElts)) {
7026 II->setOperand(1, V);
7027 return II;
7028 }
7029 break;
7030 }
7031
Chris Lattnere79d2492006-04-06 19:19:17 +00007032 case Intrinsic::ppc_altivec_vperm:
7033 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
7034 if (ConstantPacked *Mask = dyn_cast<ConstantPacked>(II->getOperand(3))) {
7035 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
7036
7037 // Check that all of the elements are integer constants or undefs.
7038 bool AllEltsOk = true;
7039 for (unsigned i = 0; i != 16; ++i) {
7040 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
7041 !isa<UndefValue>(Mask->getOperand(i))) {
7042 AllEltsOk = false;
7043 break;
7044 }
7045 }
7046
7047 if (AllEltsOk) {
7048 // Cast the input vectors to byte vectors.
Reid Spencer13bc5d72006-12-12 09:18:51 +00007049 Value *Op0 = InsertCastBefore(Instruction::BitCast,
7050 II->getOperand(1), Mask->getType(), CI);
7051 Value *Op1 = InsertCastBefore(Instruction::BitCast,
7052 II->getOperand(2), Mask->getType(), CI);
Chris Lattnere79d2492006-04-06 19:19:17 +00007053 Value *Result = UndefValue::get(Op0->getType());
7054
7055 // Only extract each element once.
7056 Value *ExtractedElts[32];
7057 memset(ExtractedElts, 0, sizeof(ExtractedElts));
7058
7059 for (unsigned i = 0; i != 16; ++i) {
7060 if (isa<UndefValue>(Mask->getOperand(i)))
7061 continue;
Reid Spencere0fc4df2006-10-20 07:07:24 +00007062 unsigned Idx =cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
Chris Lattnere79d2492006-04-06 19:19:17 +00007063 Idx &= 31; // Match the hardware behavior.
7064
7065 if (ExtractedElts[Idx] == 0) {
7066 Instruction *Elt =
Chris Lattner2deeaea2006-10-05 06:55:50 +00007067 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
Chris Lattnere79d2492006-04-06 19:19:17 +00007068 InsertNewInstBefore(Elt, CI);
7069 ExtractedElts[Idx] = Elt;
7070 }
7071
7072 // Insert this value into the result vector.
Chris Lattner2deeaea2006-10-05 06:55:50 +00007073 Result = new InsertElementInst(Result, ExtractedElts[Idx], i,"tmp");
Chris Lattnere79d2492006-04-06 19:19:17 +00007074 InsertNewInstBefore(cast<Instruction>(Result), CI);
7075 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007076 return CastInst::create(Instruction::BitCast, Result, CI.getType());
Chris Lattnere79d2492006-04-06 19:19:17 +00007077 }
7078 }
7079 break;
7080
Chris Lattner503221f2006-01-13 21:28:09 +00007081 case Intrinsic::stackrestore: {
7082 // If the save is right next to the restore, remove the restore. This can
7083 // happen when variable allocas are DCE'd.
7084 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
7085 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
7086 BasicBlock::iterator BI = SS;
7087 if (&*++BI == II)
7088 return EraseInstFromFunction(CI);
7089 }
7090 }
7091
7092 // If the stack restore is in a return/unwind block and if there are no
7093 // allocas or calls between the restore and the return, nuke the restore.
7094 TerminatorInst *TI = II->getParent()->getTerminator();
7095 if (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)) {
7096 BasicBlock::iterator BI = II;
7097 bool CannotRemove = false;
7098 for (++BI; &*BI != TI; ++BI) {
7099 if (isa<AllocaInst>(BI) ||
7100 (isa<CallInst>(BI) && !isa<IntrinsicInst>(BI))) {
7101 CannotRemove = true;
7102 break;
7103 }
7104 }
7105 if (!CannotRemove)
7106 return EraseInstFromFunction(CI);
7107 }
7108 break;
7109 }
7110 }
Chris Lattner00648e12004-10-12 04:52:52 +00007111 }
7112
Chris Lattnerc66b2232006-01-13 20:11:04 +00007113 return visitCallSite(II);
Chris Lattner970c33a2003-06-19 17:00:31 +00007114}
7115
7116// InvokeInst simplification
7117//
7118Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattneraec3d942003-10-07 22:32:43 +00007119 return visitCallSite(&II);
Chris Lattner970c33a2003-06-19 17:00:31 +00007120}
7121
Chris Lattneraec3d942003-10-07 22:32:43 +00007122// visitCallSite - Improvements for call and invoke instructions.
7123//
7124Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner75b4d1d2003-10-07 22:54:13 +00007125 bool Changed = false;
7126
7127 // If the callee is a constexpr cast of a function, attempt to move the cast
7128 // to the arguments of the call/invoke.
Chris Lattneraec3d942003-10-07 22:32:43 +00007129 if (transformConstExprCastCall(CS)) return 0;
7130
Chris Lattner75b4d1d2003-10-07 22:54:13 +00007131 Value *Callee = CS.getCalledValue();
Chris Lattner81a7a232004-10-16 18:11:37 +00007132
Chris Lattner61d9d812005-05-13 07:09:09 +00007133 if (Function *CalleeF = dyn_cast<Function>(Callee))
7134 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
7135 Instruction *OldCall = CS.getInstruction();
7136 // If the call and callee calling conventions don't match, this call must
7137 // be unreachable, as the call is undefined.
Chris Lattner6ab03f62006-09-28 23:35:22 +00007138 new StoreInst(ConstantBool::getTrue(),
Chris Lattner61d9d812005-05-13 07:09:09 +00007139 UndefValue::get(PointerType::get(Type::BoolTy)), OldCall);
7140 if (!OldCall->use_empty())
7141 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
7142 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
7143 return EraseInstFromFunction(*OldCall);
7144 return 0;
7145 }
7146
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007147 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
7148 // This instruction is not reachable, just remove it. We insert a store to
7149 // undef so that we know that this code is not reachable, despite the fact
7150 // that we can't modify the CFG here.
Chris Lattner6ab03f62006-09-28 23:35:22 +00007151 new StoreInst(ConstantBool::getTrue(),
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007152 UndefValue::get(PointerType::get(Type::BoolTy)),
7153 CS.getInstruction());
7154
7155 if (!CS.getInstruction()->use_empty())
7156 CS.getInstruction()->
7157 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
7158
7159 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
7160 // Don't break the CFG, insert a dummy cond branch.
7161 new BranchInst(II->getNormalDest(), II->getUnwindDest(),
Chris Lattner6ab03f62006-09-28 23:35:22 +00007162 ConstantBool::getTrue(), II);
Chris Lattner81a7a232004-10-16 18:11:37 +00007163 }
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007164 return EraseInstFromFunction(*CS.getInstruction());
7165 }
Chris Lattner81a7a232004-10-16 18:11:37 +00007166
Chris Lattner75b4d1d2003-10-07 22:54:13 +00007167 const PointerType *PTy = cast<PointerType>(Callee->getType());
7168 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
7169 if (FTy->isVarArg()) {
7170 // See if we can optimize any arguments passed through the varargs area of
7171 // the call.
7172 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
7173 E = CS.arg_end(); I != E; ++I)
7174 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
7175 // If this cast does not effect the value passed through the varargs
7176 // area, we can eliminate the use of the cast.
7177 Value *Op = CI->getOperand(0);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007178 if (CI->isLosslessCast()) {
Chris Lattner75b4d1d2003-10-07 22:54:13 +00007179 *I = Op;
7180 Changed = true;
7181 }
7182 }
7183 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00007184
Chris Lattner75b4d1d2003-10-07 22:54:13 +00007185 return Changed ? CS.getInstruction() : 0;
Chris Lattneraec3d942003-10-07 22:32:43 +00007186}
7187
Chris Lattner970c33a2003-06-19 17:00:31 +00007188// transformConstExprCastCall - If the callee is a constexpr cast of a function,
7189// attempt to move the cast to the arguments of the call/invoke.
7190//
7191bool InstCombiner::transformConstExprCastCall(CallSite CS) {
7192 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
7193 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007194 if (CE->getOpcode() != Instruction::BitCast ||
7195 !isa<Function>(CE->getOperand(0)))
Chris Lattner970c33a2003-06-19 17:00:31 +00007196 return false;
Reid Spencer87436872004-07-18 00:38:32 +00007197 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner970c33a2003-06-19 17:00:31 +00007198 Instruction *Caller = CS.getInstruction();
7199
7200 // Okay, this is a cast from a function to a different type. Unless doing so
7201 // would cause a type conversion of one of our arguments, change this call to
7202 // be a direct call with arguments casted to the appropriate types.
7203 //
7204 const FunctionType *FT = Callee->getFunctionType();
7205 const Type *OldRetTy = Caller->getType();
7206
Chris Lattner1f7942f2004-01-14 06:06:08 +00007207 // Check to see if we are changing the return type...
7208 if (OldRetTy != FT->getReturnType()) {
Chris Lattner400f9592007-01-06 02:09:32 +00007209 if (Callee->isExternal() && !Caller->use_empty() &&
Chris Lattner7051d752007-01-06 19:53:32 +00007210 OldRetTy != FT->getReturnType() &&
7211 // Conversion is ok if changing from pointer to int of same size.
7212 !(isa<PointerType>(FT->getReturnType()) &&
7213 TD->getIntPtrType() == OldRetTy))
Chris Lattner400f9592007-01-06 02:09:32 +00007214 return false; // Cannot transform this return value.
Chris Lattner1f7942f2004-01-14 06:06:08 +00007215
7216 // If the callsite is an invoke instruction, and the return value is used by
7217 // a PHI node in a successor, we cannot change the return type of the call
7218 // because there is no place to put the cast instruction (without breaking
7219 // the critical edge). Bail out in this case.
7220 if (!Caller->use_empty())
7221 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
7222 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
7223 UI != E; ++UI)
7224 if (PHINode *PN = dyn_cast<PHINode>(*UI))
7225 if (PN->getParent() == II->getNormalDest() ||
Chris Lattnerfae8ab32004-02-08 21:44:31 +00007226 PN->getParent() == II->getUnwindDest())
Chris Lattner1f7942f2004-01-14 06:06:08 +00007227 return false;
7228 }
Chris Lattner970c33a2003-06-19 17:00:31 +00007229
7230 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
7231 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanb1c93172005-04-21 23:48:37 +00007232
Chris Lattner970c33a2003-06-19 17:00:31 +00007233 CallSite::arg_iterator AI = CS.arg_begin();
7234 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
7235 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthebfa24e2006-06-28 01:01:52 +00007236 const Type *ActTy = (*AI)->getType();
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007237 ConstantInt *c = dyn_cast<ConstantInt>(*AI);
Andrew Lenharthebfa24e2006-06-28 01:01:52 +00007238 //Either we can cast directly, or we can upconvert the argument
Chris Lattner400f9592007-01-06 02:09:32 +00007239 bool isConvertible = ActTy == ParamTy ||
Chris Lattner7051d752007-01-06 19:53:32 +00007240 (isa<PointerType>(ParamTy) && isa<PointerType>(ActTy)) ||
Andrew Lenharthebfa24e2006-06-28 01:01:52 +00007241 (ParamTy->isIntegral() && ActTy->isIntegral() &&
Andrew Lenharthebfa24e2006-06-28 01:01:52 +00007242 ParamTy->getPrimitiveSize() >= ActTy->getPrimitiveSize()) ||
7243 (c && ParamTy->getPrimitiveSize() >= ActTy->getPrimitiveSize() &&
Reid Spencere0fc4df2006-10-20 07:07:24 +00007244 c->getSExtValue() > 0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00007245 if (Callee->isExternal() && !isConvertible) return false;
Chris Lattner970c33a2003-06-19 17:00:31 +00007246 }
7247
7248 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
7249 Callee->isExternal())
7250 return false; // Do not delete arguments unless we have a function body...
7251
7252 // Okay, we decided that this is a safe thing to do: go ahead and start
7253 // inserting cast instructions as necessary...
7254 std::vector<Value*> Args;
7255 Args.reserve(NumActualArgs);
7256
7257 AI = CS.arg_begin();
7258 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
7259 const Type *ParamTy = FT->getParamType(i);
7260 if ((*AI)->getType() == ParamTy) {
7261 Args.push_back(*AI);
7262 } else {
Reid Spencer668d90f2006-12-18 08:47:13 +00007263 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
Reid Spencerc635f472006-12-31 05:48:39 +00007264 false, ParamTy, false);
Reid Spencer668d90f2006-12-18 08:47:13 +00007265 CastInst *NewCast = CastInst::create(opcode, *AI, ParamTy, "tmp");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007266 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
Chris Lattner970c33a2003-06-19 17:00:31 +00007267 }
7268 }
7269
7270 // If the function takes more arguments than the call was taking, add them
7271 // now...
7272 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
7273 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
7274
7275 // If we are removing arguments to the function, emit an obnoxious warning...
7276 if (FT->getNumParams() < NumActualArgs)
7277 if (!FT->isVarArg()) {
Bill Wendlingf3baad32006-12-07 01:30:32 +00007278 cerr << "WARNING: While resolving call to function '"
7279 << Callee->getName() << "' arguments were dropped!\n";
Chris Lattner970c33a2003-06-19 17:00:31 +00007280 } else {
7281 // Add all of the arguments in their promoted form to the arg list...
7282 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
7283 const Type *PTy = getPromotedType((*AI)->getType());
7284 if (PTy != (*AI)->getType()) {
7285 // Must promote to pass through va_arg area!
Reid Spencerc635f472006-12-31 05:48:39 +00007286 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false,
7287 PTy, false);
Reid Spencer668d90f2006-12-18 08:47:13 +00007288 Instruction *Cast = CastInst::create(opcode, *AI, PTy, "tmp");
Chris Lattner970c33a2003-06-19 17:00:31 +00007289 InsertNewInstBefore(Cast, *Caller);
7290 Args.push_back(Cast);
7291 } else {
7292 Args.push_back(*AI);
7293 }
7294 }
7295 }
7296
7297 if (FT->getReturnType() == Type::VoidTy)
7298 Caller->setName(""); // Void type should not have a name...
7299
7300 Instruction *NC;
7301 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Chris Lattnerfae8ab32004-02-08 21:44:31 +00007302 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
Chris Lattner970c33a2003-06-19 17:00:31 +00007303 Args, Caller->getName(), Caller);
Chris Lattner05c703e2005-05-14 12:25:32 +00007304 cast<InvokeInst>(II)->setCallingConv(II->getCallingConv());
Chris Lattner970c33a2003-06-19 17:00:31 +00007305 } else {
7306 NC = new CallInst(Callee, Args, Caller->getName(), Caller);
Chris Lattner6aacb0f2005-05-06 06:48:21 +00007307 if (cast<CallInst>(Caller)->isTailCall())
7308 cast<CallInst>(NC)->setTailCall();
Chris Lattner05c703e2005-05-14 12:25:32 +00007309 cast<CallInst>(NC)->setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Chris Lattner970c33a2003-06-19 17:00:31 +00007310 }
7311
7312 // Insert a cast of the return type as necessary...
7313 Value *NV = NC;
7314 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
7315 if (NV->getType() != Type::VoidTy) {
Reid Spencer668d90f2006-12-18 08:47:13 +00007316 const Type *CallerTy = Caller->getType();
Reid Spencerc635f472006-12-31 05:48:39 +00007317 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
7318 CallerTy, false);
Reid Spencer668d90f2006-12-18 08:47:13 +00007319 NV = NC = CastInst::create(opcode, NC, CallerTy, "tmp");
Chris Lattner686767f2003-10-30 00:46:41 +00007320
7321 // If this is an invoke instruction, we should insert it after the first
7322 // non-phi, instruction in the normal successor block.
7323 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
7324 BasicBlock::iterator I = II->getNormalDest()->begin();
7325 while (isa<PHINode>(I)) ++I;
7326 InsertNewInstBefore(NC, *I);
7327 } else {
7328 // Otherwise, it's a call, just insert cast right after the call instr
7329 InsertNewInstBefore(NC, *Caller);
7330 }
Chris Lattner51ea1272004-02-28 05:22:00 +00007331 AddUsersToWorkList(*Caller);
Chris Lattner970c33a2003-06-19 17:00:31 +00007332 } else {
Chris Lattnere29d6342004-10-17 21:22:38 +00007333 NV = UndefValue::get(Caller->getType());
Chris Lattner970c33a2003-06-19 17:00:31 +00007334 }
7335 }
7336
7337 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
7338 Caller->replaceAllUsesWith(NV);
7339 Caller->getParent()->getInstList().erase(Caller);
7340 removeFromWorkList(Caller);
7341 return true;
7342}
7343
Chris Lattnercadac0c2006-11-01 04:51:18 +00007344/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
7345/// and if a/b/c/d and the add's all have a single use, turn this into two phi's
7346/// and a single binop.
7347Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
7348 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Chris Lattnereebea432006-11-01 07:43:41 +00007349 assert(isa<BinaryOperator>(FirstInst) || isa<ShiftInst>(FirstInst) ||
Reid Spencer266e42b2006-12-23 06:05:41 +00007350 isa<GetElementPtrInst>(FirstInst) || isa<CmpInst>(FirstInst));
Chris Lattnercadac0c2006-11-01 04:51:18 +00007351 unsigned Opc = FirstInst->getOpcode();
Chris Lattnercd62f112006-11-08 19:29:23 +00007352 Value *LHSVal = FirstInst->getOperand(0);
7353 Value *RHSVal = FirstInst->getOperand(1);
7354
7355 const Type *LHSType = LHSVal->getType();
7356 const Type *RHSType = RHSVal->getType();
Chris Lattnercadac0c2006-11-01 04:51:18 +00007357
7358 // Scan to see if all operands are the same opcode, all have one use, and all
7359 // kill their operands (i.e. the operands have one use).
Chris Lattnerdc826fc2006-11-01 04:55:47 +00007360 for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
Chris Lattnercadac0c2006-11-01 04:51:18 +00007361 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Chris Lattnerdc826fc2006-11-01 04:55:47 +00007362 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
Reid Spencer266e42b2006-12-23 06:05:41 +00007363 // Verify type of the LHS matches so we don't fold cmp's of different
Chris Lattnereebea432006-11-01 07:43:41 +00007364 // types or GEP's with different index types.
7365 I->getOperand(0)->getType() != LHSType ||
7366 I->getOperand(1)->getType() != RHSType)
Chris Lattnercadac0c2006-11-01 04:51:18 +00007367 return 0;
Reid Spencer266e42b2006-12-23 06:05:41 +00007368
7369 // If they are CmpInst instructions, check their predicates
7370 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
7371 if (cast<CmpInst>(I)->getPredicate() !=
7372 cast<CmpInst>(FirstInst)->getPredicate())
7373 return 0;
Chris Lattnercd62f112006-11-08 19:29:23 +00007374
7375 // Keep track of which operand needs a phi node.
7376 if (I->getOperand(0) != LHSVal) LHSVal = 0;
7377 if (I->getOperand(1) != RHSVal) RHSVal = 0;
Chris Lattnercadac0c2006-11-01 04:51:18 +00007378 }
7379
Chris Lattner4f218d52006-11-08 19:42:28 +00007380 // Otherwise, this is safe to transform, determine if it is profitable.
7381
7382 // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
7383 // Indexes are often folded into load/store instructions, so we don't want to
7384 // hide them behind a phi.
7385 if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
7386 return 0;
7387
Chris Lattnercadac0c2006-11-01 04:51:18 +00007388 Value *InLHS = FirstInst->getOperand(0);
Chris Lattnercadac0c2006-11-01 04:51:18 +00007389 Value *InRHS = FirstInst->getOperand(1);
Chris Lattner4f218d52006-11-08 19:42:28 +00007390 PHINode *NewLHS = 0, *NewRHS = 0;
Chris Lattnercd62f112006-11-08 19:29:23 +00007391 if (LHSVal == 0) {
7392 NewLHS = new PHINode(LHSType, FirstInst->getOperand(0)->getName()+".pn");
7393 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
7394 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
Chris Lattnereebea432006-11-01 07:43:41 +00007395 InsertNewInstBefore(NewLHS, PN);
7396 LHSVal = NewLHS;
7397 }
Chris Lattnercd62f112006-11-08 19:29:23 +00007398
7399 if (RHSVal == 0) {
7400 NewRHS = new PHINode(RHSType, FirstInst->getOperand(1)->getName()+".pn");
7401 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
7402 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
Chris Lattnereebea432006-11-01 07:43:41 +00007403 InsertNewInstBefore(NewRHS, PN);
7404 RHSVal = NewRHS;
7405 }
7406
Chris Lattnercd62f112006-11-08 19:29:23 +00007407 // Add all operands to the new PHIs.
7408 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7409 if (NewLHS) {
7410 Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
7411 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
7412 }
7413 if (NewRHS) {
7414 Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
7415 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
7416 }
7417 }
7418
Chris Lattnercadac0c2006-11-01 04:51:18 +00007419 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattnereebea432006-11-01 07:43:41 +00007420 return BinaryOperator::create(BinOp->getOpcode(), LHSVal, RHSVal);
Reid Spencer266e42b2006-12-23 06:05:41 +00007421 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
7422 return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal,
7423 RHSVal);
Chris Lattnereebea432006-11-01 07:43:41 +00007424 else if (ShiftInst *SI = dyn_cast<ShiftInst>(FirstInst))
7425 return new ShiftInst(SI->getOpcode(), LHSVal, RHSVal);
7426 else {
7427 assert(isa<GetElementPtrInst>(FirstInst));
7428 return new GetElementPtrInst(LHSVal, RHSVal);
7429 }
Chris Lattnercadac0c2006-11-01 04:51:18 +00007430}
7431
Chris Lattner14f82c72006-11-01 07:13:54 +00007432/// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
7433/// of the block that defines it. This means that it must be obvious the value
7434/// of the load is not changed from the point of the load to the end of the
7435/// block it is in.
7436static bool isSafeToSinkLoad(LoadInst *L) {
7437 BasicBlock::iterator BBI = L, E = L->getParent()->end();
7438
7439 for (++BBI; BBI != E; ++BBI)
7440 if (BBI->mayWriteToMemory())
7441 return false;
7442 return true;
7443}
7444
Chris Lattner970c33a2003-06-19 17:00:31 +00007445
Chris Lattner7515cab2004-11-14 19:13:23 +00007446// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
7447// operator and they all are only used by the PHI, PHI together their
7448// inputs, and do the operation once, to the result of the PHI.
7449Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
7450 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
7451
7452 // Scan the instruction, looking for input operations that can be folded away.
7453 // If all input operands to the phi are the same instruction (e.g. a cast from
7454 // the same type or "+42") we can pull the operation through the PHI, reducing
7455 // code size and simplifying code.
7456 Constant *ConstantOp = 0;
7457 const Type *CastSrcTy = 0;
Chris Lattner14f82c72006-11-01 07:13:54 +00007458 bool isVolatile = false;
Chris Lattner7515cab2004-11-14 19:13:23 +00007459 if (isa<CastInst>(FirstInst)) {
7460 CastSrcTy = FirstInst->getOperand(0)->getType();
Reid Spencer266e42b2006-12-23 06:05:41 +00007461 } else if (isa<BinaryOperator>(FirstInst) || isa<ShiftInst>(FirstInst) ||
7462 isa<CmpInst>(FirstInst)) {
7463 // Can fold binop, compare or shift here if the RHS is a constant,
7464 // otherwise call FoldPHIArgBinOpIntoPHI.
Chris Lattner7515cab2004-11-14 19:13:23 +00007465 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Chris Lattnercadac0c2006-11-01 04:51:18 +00007466 if (ConstantOp == 0)
7467 return FoldPHIArgBinOpIntoPHI(PN);
Chris Lattner14f82c72006-11-01 07:13:54 +00007468 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
7469 isVolatile = LI->isVolatile();
7470 // We can't sink the load if the loaded value could be modified between the
7471 // load and the PHI.
7472 if (LI->getParent() != PN.getIncomingBlock(0) ||
7473 !isSafeToSinkLoad(LI))
7474 return 0;
Chris Lattnereebea432006-11-01 07:43:41 +00007475 } else if (isa<GetElementPtrInst>(FirstInst)) {
Chris Lattner4f218d52006-11-08 19:42:28 +00007476 if (FirstInst->getNumOperands() == 2)
Chris Lattnereebea432006-11-01 07:43:41 +00007477 return FoldPHIArgBinOpIntoPHI(PN);
7478 // Can't handle general GEPs yet.
7479 return 0;
Chris Lattner7515cab2004-11-14 19:13:23 +00007480 } else {
7481 return 0; // Cannot fold this operation.
7482 }
7483
7484 // Check to see if all arguments are the same operation.
7485 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7486 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
7487 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
Reid Spencer266e42b2006-12-23 06:05:41 +00007488 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
Chris Lattner7515cab2004-11-14 19:13:23 +00007489 return 0;
7490 if (CastSrcTy) {
7491 if (I->getOperand(0)->getType() != CastSrcTy)
7492 return 0; // Cast operation must match.
Chris Lattner14f82c72006-11-01 07:13:54 +00007493 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00007494 // We can't sink the load if the loaded value could be modified between
7495 // the load and the PHI.
Chris Lattner14f82c72006-11-01 07:13:54 +00007496 if (LI->isVolatile() != isVolatile ||
7497 LI->getParent() != PN.getIncomingBlock(i) ||
7498 !isSafeToSinkLoad(LI))
7499 return 0;
Chris Lattner7515cab2004-11-14 19:13:23 +00007500 } else if (I->getOperand(1) != ConstantOp) {
7501 return 0;
7502 }
7503 }
7504
7505 // Okay, they are all the same operation. Create a new PHI node of the
7506 // correct type, and PHI together all of the LHS's of the instructions.
7507 PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
7508 PN.getName()+".in");
Chris Lattnerd8e20182005-01-29 00:39:08 +00007509 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattner46dd5a62004-11-14 19:29:34 +00007510
7511 Value *InVal = FirstInst->getOperand(0);
7512 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattner7515cab2004-11-14 19:13:23 +00007513
7514 // Add all operands to the new PHI.
Chris Lattner46dd5a62004-11-14 19:29:34 +00007515 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7516 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
7517 if (NewInVal != InVal)
7518 InVal = 0;
7519 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
7520 }
7521
7522 Value *PhiVal;
7523 if (InVal) {
7524 // The new PHI unions all of the same values together. This is really
7525 // common, so we handle it intelligently here for compile-time speed.
7526 PhiVal = InVal;
7527 delete NewPN;
7528 } else {
7529 InsertNewInstBefore(NewPN, PN);
7530 PhiVal = NewPN;
7531 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00007532
Chris Lattner7515cab2004-11-14 19:13:23 +00007533 // Insert and return the new operation.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007534 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
7535 return CastInst::create(FirstCI->getOpcode(), PhiVal, PN.getType());
Reid Spencerde46e482006-11-02 20:25:50 +00007536 else if (isa<LoadInst>(FirstInst))
Chris Lattner14f82c72006-11-01 07:13:54 +00007537 return new LoadInst(PhiVal, "", isVolatile);
Chris Lattner7515cab2004-11-14 19:13:23 +00007538 else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattner46dd5a62004-11-14 19:29:34 +00007539 return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
Reid Spencer266e42b2006-12-23 06:05:41 +00007540 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
7541 return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(),
7542 PhiVal, ConstantOp);
Chris Lattner7515cab2004-11-14 19:13:23 +00007543 else
7544 return new ShiftInst(cast<ShiftInst>(FirstInst)->getOpcode(),
Chris Lattner46dd5a62004-11-14 19:29:34 +00007545 PhiVal, ConstantOp);
Chris Lattner7515cab2004-11-14 19:13:23 +00007546}
Chris Lattner48a44f72002-05-02 17:06:02 +00007547
Chris Lattner71536432005-01-17 05:10:15 +00007548/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
7549/// that is dead.
7550static bool DeadPHICycle(PHINode *PN, std::set<PHINode*> &PotentiallyDeadPHIs) {
7551 if (PN->use_empty()) return true;
7552 if (!PN->hasOneUse()) return false;
7553
7554 // Remember this node, and if we find the cycle, return.
7555 if (!PotentiallyDeadPHIs.insert(PN).second)
7556 return true;
7557
7558 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
7559 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanb1c93172005-04-21 23:48:37 +00007560
Chris Lattner71536432005-01-17 05:10:15 +00007561 return false;
7562}
7563
Chris Lattnerbbbdd852002-05-06 18:06:38 +00007564// PHINode simplification
7565//
Chris Lattner113f4f42002-06-25 16:13:24 +00007566Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonbbf89902006-07-10 22:15:25 +00007567 // If LCSSA is around, don't mess with Phi nodes
7568 if (mustPreserveAnalysisID(LCSSAID)) return 0;
Owen Andersona6968f82006-07-10 19:03:49 +00007569
Owen Andersonae8aa642006-07-10 22:03:18 +00007570 if (Value *V = PN.hasConstantValue())
7571 return ReplaceInstUsesWith(PN, V);
7572
Owen Andersonae8aa642006-07-10 22:03:18 +00007573 // If all PHI operands are the same operation, pull them through the PHI,
7574 // reducing code size.
7575 if (isa<Instruction>(PN.getIncomingValue(0)) &&
7576 PN.getIncomingValue(0)->hasOneUse())
7577 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
7578 return Result;
7579
7580 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
7581 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
7582 // PHI)... break the cycle.
7583 if (PN.hasOneUse())
7584 if (PHINode *PU = dyn_cast<PHINode>(PN.use_back())) {
7585 std::set<PHINode*> PotentiallyDeadPHIs;
7586 PotentiallyDeadPHIs.insert(&PN);
7587 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
7588 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
7589 }
7590
Chris Lattner91daeb52003-12-19 05:58:40 +00007591 return 0;
Chris Lattnerbbbdd852002-05-06 18:06:38 +00007592}
7593
Reid Spencer13bc5d72006-12-12 09:18:51 +00007594static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
7595 Instruction *InsertPoint,
7596 InstCombiner *IC) {
Reid Spencer2a499b02006-12-13 17:19:09 +00007597 unsigned PtrSize = DTy->getPrimitiveSize();
Reid Spencer13bc5d72006-12-12 09:18:51 +00007598 unsigned VTySize = V->getType()->getPrimitiveSize();
7599 // We must cast correctly to the pointer type. Ensure that we
7600 // sign extend the integer value if it is smaller as this is
7601 // used for address computation.
7602 Instruction::CastOps opcode =
7603 (VTySize < PtrSize ? Instruction::SExt :
7604 (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
7605 return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
Chris Lattner69193f92004-04-05 01:30:19 +00007606}
7607
Chris Lattner48a44f72002-05-02 17:06:02 +00007608
Chris Lattner113f4f42002-06-25 16:13:24 +00007609Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner5f667a62004-05-07 22:09:22 +00007610 Value *PtrOp = GEP.getOperand(0);
Chris Lattner471bd762003-05-22 19:07:21 +00007611 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
Chris Lattner113f4f42002-06-25 16:13:24 +00007612 // If so, eliminate the noop.
Chris Lattner8d0bacb2004-02-22 05:25:17 +00007613 if (GEP.getNumOperands() == 1)
Chris Lattner5f667a62004-05-07 22:09:22 +00007614 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner8d0bacb2004-02-22 05:25:17 +00007615
Chris Lattner81a7a232004-10-16 18:11:37 +00007616 if (isa<UndefValue>(GEP.getOperand(0)))
7617 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
7618
Chris Lattner8d0bacb2004-02-22 05:25:17 +00007619 bool HasZeroPointerIndex = false;
7620 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
7621 HasZeroPointerIndex = C->isNullValue();
7622
7623 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner5f667a62004-05-07 22:09:22 +00007624 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner48a44f72002-05-02 17:06:02 +00007625
Chris Lattner69193f92004-04-05 01:30:19 +00007626 // Eliminate unneeded casts for indices.
7627 bool MadeChange = false;
Chris Lattner2b2412d2004-04-07 18:38:20 +00007628 gep_type_iterator GTI = gep_type_begin(GEP);
7629 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI)
7630 if (isa<SequentialType>(*GTI)) {
7631 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
7632 Value *Src = CI->getOperand(0);
7633 const Type *SrcTy = Src->getType();
7634 const Type *DestTy = CI->getType();
7635 if (Src->getType()->isInteger()) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00007636 if (SrcTy->getPrimitiveSizeInBits() ==
7637 DestTy->getPrimitiveSizeInBits()) {
Chris Lattner2b2412d2004-04-07 18:38:20 +00007638 // We can always eliminate a cast from ulong or long to the other.
7639 // We can always eliminate a cast from uint to int or the other on
7640 // 32-bit pointer platforms.
Chris Lattnerd1f46d32005-04-24 06:59:08 +00007641 if (DestTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()){
Chris Lattner2b2412d2004-04-07 18:38:20 +00007642 MadeChange = true;
7643 GEP.setOperand(i, Src);
7644 }
7645 } else if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
7646 SrcTy->getPrimitiveSize() == 4) {
Reid Spencer266e42b2006-12-23 06:05:41 +00007647 // We can eliminate a cast from [u]int to [u]long iff the target
7648 // is a 32-bit pointer target.
7649 if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
Chris Lattner2b2412d2004-04-07 18:38:20 +00007650 MadeChange = true;
7651 GEP.setOperand(i, Src);
7652 }
Chris Lattner69193f92004-04-05 01:30:19 +00007653 }
7654 }
7655 }
Chris Lattner2b2412d2004-04-07 18:38:20 +00007656 // If we are using a wider index than needed for this platform, shrink it
7657 // to what we need. If the incoming value needs a cast instruction,
7658 // insert it. This explicit cast can make subsequent optimizations more
7659 // obvious.
7660 Value *Op = GEP.getOperand(i);
7661 if (Op->getType()->getPrimitiveSize() > TD->getPointerSize())
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00007662 if (Constant *C = dyn_cast<Constant>(Op)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00007663 GEP.setOperand(i, ConstantExpr::getTrunc(C, TD->getIntPtrType()));
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00007664 MadeChange = true;
7665 } else {
Reid Spencer13bc5d72006-12-12 09:18:51 +00007666 Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
7667 GEP);
Chris Lattner2b2412d2004-04-07 18:38:20 +00007668 GEP.setOperand(i, Op);
7669 MadeChange = true;
7670 }
Chris Lattner69193f92004-04-05 01:30:19 +00007671 }
7672 if (MadeChange) return &GEP;
7673
Chris Lattnerae7a0d32002-08-02 19:29:35 +00007674 // Combine Indices - If the source pointer to this getelementptr instruction
7675 // is a getelementptr instruction, combine the indices of the two
7676 // getelementptr instructions into a single instruction.
7677 //
Chris Lattner57c67b02004-03-25 22:59:29 +00007678 std::vector<Value*> SrcGEPOperands;
Chris Lattner0798af32005-01-13 20:14:25 +00007679 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattner57c67b02004-03-25 22:59:29 +00007680 SrcGEPOperands.assign(Src->op_begin(), Src->op_end());
Chris Lattner57c67b02004-03-25 22:59:29 +00007681
7682 if (!SrcGEPOperands.empty()) {
Chris Lattner5f667a62004-05-07 22:09:22 +00007683 // Note that if our source is a gep chain itself that we wait for that
7684 // chain to be resolved before we perform this transformation. This
7685 // avoids us creating a TON of code in some cases.
7686 //
7687 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
7688 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
7689 return 0; // Wait until our source is folded to completion.
7690
Chris Lattnerae7a0d32002-08-02 19:29:35 +00007691 std::vector<Value *> Indices;
Chris Lattner5f667a62004-05-07 22:09:22 +00007692
7693 // Find out whether the last index in the source GEP is a sequential idx.
7694 bool EndsWithSequential = false;
7695 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
7696 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattner8ec5f882004-05-08 22:41:42 +00007697 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00007698
Chris Lattnerae7a0d32002-08-02 19:29:35 +00007699 // Can we combine the two pointer arithmetics offsets?
Chris Lattner5f667a62004-05-07 22:09:22 +00007700 if (EndsWithSequential) {
Chris Lattner235af562003-03-05 22:33:14 +00007701 // Replace: gep (gep %P, long B), long A, ...
7702 // With: T = long A+B; gep %P, T, ...
7703 //
Chris Lattner5f667a62004-05-07 22:09:22 +00007704 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner69193f92004-04-05 01:30:19 +00007705 if (SO1 == Constant::getNullValue(SO1->getType())) {
7706 Sum = GO1;
7707 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
7708 Sum = SO1;
7709 } else {
7710 // If they aren't the same type, convert both to an integer of the
7711 // target's pointer size.
7712 if (SO1->getType() != GO1->getType()) {
7713 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00007714 SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
Chris Lattner69193f92004-04-05 01:30:19 +00007715 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00007716 GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
Chris Lattner69193f92004-04-05 01:30:19 +00007717 } else {
7718 unsigned PS = TD->getPointerSize();
Chris Lattner69193f92004-04-05 01:30:19 +00007719 if (SO1->getType()->getPrimitiveSize() == PS) {
7720 // Convert GO1 to SO1's type.
Reid Spencer13bc5d72006-12-12 09:18:51 +00007721 GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
Chris Lattner69193f92004-04-05 01:30:19 +00007722
7723 } else if (GO1->getType()->getPrimitiveSize() == PS) {
7724 // Convert SO1 to GO1's type.
Reid Spencer13bc5d72006-12-12 09:18:51 +00007725 SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
Chris Lattner69193f92004-04-05 01:30:19 +00007726 } else {
7727 const Type *PT = TD->getIntPtrType();
Reid Spencer13bc5d72006-12-12 09:18:51 +00007728 SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
7729 GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
Chris Lattner69193f92004-04-05 01:30:19 +00007730 }
7731 }
7732 }
Chris Lattner5f667a62004-05-07 22:09:22 +00007733 if (isa<Constant>(SO1) && isa<Constant>(GO1))
7734 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
7735 else {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00007736 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
7737 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner5f667a62004-05-07 22:09:22 +00007738 }
Chris Lattner69193f92004-04-05 01:30:19 +00007739 }
Chris Lattner5f667a62004-05-07 22:09:22 +00007740
7741 // Recycle the GEP we already have if possible.
7742 if (SrcGEPOperands.size() == 2) {
7743 GEP.setOperand(0, SrcGEPOperands[0]);
7744 GEP.setOperand(1, Sum);
7745 return &GEP;
7746 } else {
7747 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
7748 SrcGEPOperands.end()-1);
7749 Indices.push_back(Sum);
7750 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
7751 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00007752 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner69193f92004-04-05 01:30:19 +00007753 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00007754 SrcGEPOperands.size() != 1) {
Chris Lattnerae7a0d32002-08-02 19:29:35 +00007755 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattner57c67b02004-03-25 22:59:29 +00007756 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
7757 SrcGEPOperands.end());
Chris Lattnerae7a0d32002-08-02 19:29:35 +00007758 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
7759 }
7760
7761 if (!Indices.empty())
Chris Lattner57c67b02004-03-25 22:59:29 +00007762 return new GetElementPtrInst(SrcGEPOperands[0], Indices, GEP.getName());
Chris Lattnerc59af1d2002-08-17 22:21:59 +00007763
Chris Lattner5f667a62004-05-07 22:09:22 +00007764 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattnerc59af1d2002-08-17 22:21:59 +00007765 // GEP of global variable. If all of the indices for this GEP are
7766 // constants, we can promote this to a constexpr instead of an instruction.
7767
7768 // Scan for nonconstants...
7769 std::vector<Constant*> Indices;
7770 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
7771 for (; I != E && isa<Constant>(*I); ++I)
7772 Indices.push_back(cast<Constant>(*I));
7773
7774 if (I == E) { // If they are all constants...
Chris Lattnerf3edc492004-07-18 18:59:44 +00007775 Constant *CE = ConstantExpr::getGetElementPtr(GV, Indices);
Chris Lattnerc59af1d2002-08-17 22:21:59 +00007776
7777 // Replace all uses of the GEP with the new constexpr...
7778 return ReplaceInstUsesWith(GEP, CE);
7779 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007780 } else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast?
Chris Lattner567b81f2005-09-13 00:40:14 +00007781 if (!isa<PointerType>(X->getType())) {
7782 // Not interesting. Source pointer must be a cast from pointer.
7783 } else if (HasZeroPointerIndex) {
7784 // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
7785 // into : GEP [10 x ubyte]* X, long 0, ...
7786 //
7787 // This occurs when the program declares an array extern like "int X[];"
7788 //
7789 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
7790 const PointerType *XTy = cast<PointerType>(X->getType());
7791 if (const ArrayType *XATy =
7792 dyn_cast<ArrayType>(XTy->getElementType()))
7793 if (const ArrayType *CATy =
7794 dyn_cast<ArrayType>(CPTy->getElementType()))
7795 if (CATy->getElementType() == XATy->getElementType()) {
7796 // At this point, we know that the cast source type is a pointer
7797 // to an array of the same type as the destination pointer
7798 // array. Because the array type is never stepped over (there
7799 // is a leading zero) we can fold the cast into this GEP.
7800 GEP.setOperand(0, X);
7801 return &GEP;
7802 }
7803 } else if (GEP.getNumOperands() == 2) {
7804 // Transform things like:
Chris Lattner2a893292005-09-13 18:36:04 +00007805 // %t = getelementptr ubyte* cast ([2 x int]* %str to uint*), uint %V
7806 // into: %t1 = getelementptr [2 x int*]* %str, int 0, uint %V; cast
Chris Lattner567b81f2005-09-13 00:40:14 +00007807 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
7808 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
7809 if (isa<ArrayType>(SrcElTy) &&
7810 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
7811 TD->getTypeSize(ResElTy)) {
7812 Value *V = InsertNewInstBefore(
Reid Spencerc635f472006-12-31 05:48:39 +00007813 new GetElementPtrInst(X, Constant::getNullValue(Type::Int32Ty),
Chris Lattner567b81f2005-09-13 00:40:14 +00007814 GEP.getOperand(1), GEP.getName()), GEP);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007815 // V and GEP are both pointer types --> BitCast
7816 return new BitCastInst(V, GEP.getType());
Chris Lattner8d0bacb2004-02-22 05:25:17 +00007817 }
Chris Lattner2a893292005-09-13 18:36:04 +00007818
7819 // Transform things like:
7820 // getelementptr sbyte* cast ([100 x double]* X to sbyte*), int %tmp
7821 // (where tmp = 8*tmp2) into:
7822 // getelementptr [100 x double]* %arr, int 0, int %tmp.2
7823
7824 if (isa<ArrayType>(SrcElTy) &&
Reid Spencerc635f472006-12-31 05:48:39 +00007825 (ResElTy == Type::Int8Ty || ResElTy == Type::Int8Ty)) {
Chris Lattner2a893292005-09-13 18:36:04 +00007826 uint64_t ArrayEltSize =
7827 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType());
7828
7829 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
7830 // allow either a mul, shift, or constant here.
7831 Value *NewIdx = 0;
7832 ConstantInt *Scale = 0;
7833 if (ArrayEltSize == 1) {
7834 NewIdx = GEP.getOperand(1);
7835 Scale = ConstantInt::get(NewIdx->getType(), 1);
7836 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Chris Lattnera393e4d2005-09-14 17:32:56 +00007837 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner2a893292005-09-13 18:36:04 +00007838 Scale = CI;
7839 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
7840 if (Inst->getOpcode() == Instruction::Shl &&
7841 isa<ConstantInt>(Inst->getOperand(1))) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00007842 unsigned ShAmt =
7843 cast<ConstantInt>(Inst->getOperand(1))->getZExtValue();
Reid Spencer266e42b2006-12-23 06:05:41 +00007844 Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmt);
Chris Lattner2a893292005-09-13 18:36:04 +00007845 NewIdx = Inst->getOperand(0);
7846 } else if (Inst->getOpcode() == Instruction::Mul &&
7847 isa<ConstantInt>(Inst->getOperand(1))) {
7848 Scale = cast<ConstantInt>(Inst->getOperand(1));
7849 NewIdx = Inst->getOperand(0);
7850 }
7851 }
7852
7853 // If the index will be to exactly the right offset with the scale taken
7854 // out, perform the transformation.
Reid Spencere0fc4df2006-10-20 07:07:24 +00007855 if (Scale && Scale->getZExtValue() % ArrayEltSize == 0) {
Reid Spencerde46e482006-11-02 20:25:50 +00007856 if (isa<ConstantInt>(Scale))
Reid Spencere0fc4df2006-10-20 07:07:24 +00007857 Scale = ConstantInt::get(Scale->getType(),
7858 Scale->getZExtValue() / ArrayEltSize);
7859 if (Scale->getZExtValue() != 1) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00007860 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
7861 true /*SExt*/);
Chris Lattner2a893292005-09-13 18:36:04 +00007862 Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
7863 NewIdx = InsertNewInstBefore(Sc, GEP);
7864 }
7865
7866 // Insert the new GEP instruction.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007867 Instruction *NewGEP =
Reid Spencerc635f472006-12-31 05:48:39 +00007868 new GetElementPtrInst(X, Constant::getNullValue(Type::Int32Ty),
Chris Lattner2a893292005-09-13 18:36:04 +00007869 NewIdx, GEP.getName());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007870 NewGEP = InsertNewInstBefore(NewGEP, GEP);
7871 // The NewGEP must be pointer typed, so must the old one -> BitCast
7872 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner2a893292005-09-13 18:36:04 +00007873 }
7874 }
Chris Lattner8d0bacb2004-02-22 05:25:17 +00007875 }
Chris Lattnerca081252001-12-14 16:52:21 +00007876 }
7877
Chris Lattnerca081252001-12-14 16:52:21 +00007878 return 0;
7879}
7880
Chris Lattner1085bdf2002-11-04 16:18:53 +00007881Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
7882 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
7883 if (AI.isArrayAllocation()) // Check C != 1
Reid Spencere0fc4df2006-10-20 07:07:24 +00007884 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
7885 const Type *NewTy =
7886 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Chris Lattnera2620ac2002-11-09 00:49:43 +00007887 AllocationInst *New = 0;
Chris Lattner1085bdf2002-11-04 16:18:53 +00007888
7889 // Create and insert the replacement instruction...
7890 if (isa<MallocInst>(AI))
Nate Begeman848622f2005-11-05 09:21:28 +00007891 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00007892 else {
7893 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Nate Begeman848622f2005-11-05 09:21:28 +00007894 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00007895 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00007896
7897 InsertNewInstBefore(New, AI);
Misha Brukmanb1c93172005-04-21 23:48:37 +00007898
Chris Lattner1085bdf2002-11-04 16:18:53 +00007899 // Scan to the end of the allocation instructions, to skip over a block of
7900 // allocas if possible...
7901 //
7902 BasicBlock::iterator It = New;
7903 while (isa<AllocationInst>(*It)) ++It;
7904
7905 // Now that I is pointing to the first non-allocation-inst in the block,
7906 // insert our getelementptr instruction...
7907 //
Reid Spencerc635f472006-12-31 05:48:39 +00007908 Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
Chris Lattner809dfac2005-05-04 19:10:26 +00007909 Value *V = new GetElementPtrInst(New, NullIdx, NullIdx,
7910 New->getName()+".sub", It);
Chris Lattner1085bdf2002-11-04 16:18:53 +00007911
7912 // Now make everything use the getelementptr instead of the original
7913 // allocation.
Chris Lattnerabb77c92004-03-19 06:08:10 +00007914 return ReplaceInstUsesWith(AI, V);
Chris Lattner81a7a232004-10-16 18:11:37 +00007915 } else if (isa<UndefValue>(AI.getArraySize())) {
7916 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner1085bdf2002-11-04 16:18:53 +00007917 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00007918
7919 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
7920 // Note that we only do this for alloca's, because malloc should allocate and
7921 // return a unique pointer, even for a zero byte allocation.
Misha Brukmanb1c93172005-04-21 23:48:37 +00007922 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
Chris Lattner49df6ce2004-07-02 22:55:47 +00007923 TD->getTypeSize(AI.getAllocatedType()) == 0)
Chris Lattnerabb77c92004-03-19 06:08:10 +00007924 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
7925
Chris Lattner1085bdf2002-11-04 16:18:53 +00007926 return 0;
7927}
7928
Chris Lattner8427bff2003-12-07 01:24:23 +00007929Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
7930 Value *Op = FI.getOperand(0);
7931
7932 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
7933 if (CastInst *CI = dyn_cast<CastInst>(Op))
7934 if (isa<PointerType>(CI->getOperand(0)->getType())) {
7935 FI.setOperand(0, CI->getOperand(0));
7936 return &FI;
7937 }
7938
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007939 // free undef -> unreachable.
7940 if (isa<UndefValue>(Op)) {
7941 // Insert a new store to null because we cannot modify the CFG here.
Chris Lattner6ab03f62006-09-28 23:35:22 +00007942 new StoreInst(ConstantBool::getTrue(),
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007943 UndefValue::get(PointerType::get(Type::BoolTy)), &FI);
7944 return EraseInstFromFunction(FI);
7945 }
7946
Chris Lattnerf3a36602004-02-28 04:57:37 +00007947 // If we have 'free null' delete the instruction. This can happen in stl code
7948 // when lots of inlining happens.
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007949 if (isa<ConstantPointerNull>(Op))
Chris Lattner51ea1272004-02-28 05:22:00 +00007950 return EraseInstFromFunction(FI);
Chris Lattnerf3a36602004-02-28 04:57:37 +00007951
Chris Lattner8427bff2003-12-07 01:24:23 +00007952 return 0;
7953}
7954
7955
Chris Lattner72684fe2005-01-31 05:51:45 +00007956/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Chris Lattner35e24772004-07-13 01:49:43 +00007957static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
7958 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00007959 Value *CastOp = CI->getOperand(0);
Chris Lattner35e24772004-07-13 01:49:43 +00007960
7961 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00007962 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Chris Lattner35e24772004-07-13 01:49:43 +00007963 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00007964
Chris Lattnerebca4762006-04-02 05:37:12 +00007965 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
7966 isa<PackedType>(DestPTy)) {
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00007967 // If the source is an array, the code below will not succeed. Check to
7968 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
7969 // constants.
7970 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
7971 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
7972 if (ASrcTy->getNumElements() != 0) {
Reid Spencerc635f472006-12-31 05:48:39 +00007973 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::Int32Ty));
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00007974 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
7975 SrcTy = cast<PointerType>(CastOp->getType());
7976 SrcPTy = SrcTy->getElementType();
7977 }
7978
Chris Lattnerebca4762006-04-02 05:37:12 +00007979 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
7980 isa<PackedType>(SrcPTy)) &&
Chris Lattnerecfa9b52005-03-29 06:37:47 +00007981 // Do not allow turning this into a load of an integer, which is then
7982 // casted to a pointer, this pessimizes pointer analysis a lot.
7983 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00007984 IC.getTargetData().getTypeSize(SrcPTy) ==
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00007985 IC.getTargetData().getTypeSize(DestPTy)) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00007986
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00007987 // Okay, we are casting from one integer or pointer type to another of
7988 // the same size. Instead of casting the pointer before the load, cast
7989 // the result of the loaded value.
7990 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
7991 CI->getName(),
7992 LI.isVolatile()),LI);
7993 // Now cast the result of the load.
Reid Spencerbb65ebf2006-12-12 23:36:14 +00007994 return new BitCastInst(NewLoad, LI.getType());
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00007995 }
Chris Lattner35e24772004-07-13 01:49:43 +00007996 }
7997 }
7998 return 0;
7999}
8000
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008001/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattnere6f13092004-09-19 19:18:10 +00008002/// from this value cannot trap. If it is not obviously safe to load from the
8003/// specified pointer, we do a quick local scan of the basic block containing
8004/// ScanFrom, to determine if the address is already accessed.
8005static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
8006 // If it is an alloca or global variable, it is always safe to load from.
8007 if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
8008
8009 // Otherwise, be a little bit agressive by scanning the local block where we
8010 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00008011 // from/to. If so, the previous load or store would have already trapped,
8012 // so there is no harm doing an extra load (also, CSE will later eliminate
8013 // the load entirely).
Chris Lattnere6f13092004-09-19 19:18:10 +00008014 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
8015
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00008016 while (BBI != E) {
Chris Lattnere6f13092004-09-19 19:18:10 +00008017 --BBI;
8018
8019 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
8020 if (LI->getOperand(0) == V) return true;
8021 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
8022 if (SI->getOperand(1) == V) return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +00008023
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00008024 }
Chris Lattnere6f13092004-09-19 19:18:10 +00008025 return false;
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008026}
8027
Chris Lattner0f1d8a32003-06-26 05:06:25 +00008028Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
8029 Value *Op = LI.getOperand(0);
Chris Lattner7e8af382004-01-12 04:13:56 +00008030
Chris Lattnera9d84e32005-05-01 04:24:53 +00008031 // load (cast X) --> cast (load X) iff safe
Reid Spencerde46e482006-11-02 20:25:50 +00008032 if (isa<CastInst>(Op))
Chris Lattnera9d84e32005-05-01 04:24:53 +00008033 if (Instruction *Res = InstCombineLoadCast(*this, LI))
8034 return Res;
8035
8036 // None of the following transforms are legal for volatile loads.
8037 if (LI.isVolatile()) return 0;
Chris Lattnerb990f7d2005-09-12 22:00:15 +00008038
Chris Lattnerb990f7d2005-09-12 22:00:15 +00008039 if (&LI.getParent()->front() != &LI) {
8040 BasicBlock::iterator BBI = &LI; --BBI;
Chris Lattnere0bfdf12005-09-12 22:21:03 +00008041 // If the instruction immediately before this is a store to the same
8042 // address, do a simple form of store->load forwarding.
Chris Lattnerb990f7d2005-09-12 22:00:15 +00008043 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
8044 if (SI->getOperand(1) == LI.getOperand(0))
8045 return ReplaceInstUsesWith(LI, SI->getOperand(0));
Chris Lattnere0bfdf12005-09-12 22:21:03 +00008046 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
8047 if (LIB->getOperand(0) == LI.getOperand(0))
8048 return ReplaceInstUsesWith(LI, LIB);
Chris Lattnerb990f7d2005-09-12 22:00:15 +00008049 }
Chris Lattnera9d84e32005-05-01 04:24:53 +00008050
8051 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op))
8052 if (isa<ConstantPointerNull>(GEPI->getOperand(0)) ||
8053 isa<UndefValue>(GEPI->getOperand(0))) {
8054 // Insert a new store to null instruction before the load to indicate
8055 // that this code is not reachable. We do this instead of inserting
8056 // an unreachable instruction directly because we cannot modify the
8057 // CFG.
8058 new StoreInst(UndefValue::get(LI.getType()),
8059 Constant::getNullValue(Op->getType()), &LI);
8060 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
8061 }
8062
Chris Lattner81a7a232004-10-16 18:11:37 +00008063 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattnera9d84e32005-05-01 04:24:53 +00008064 // load null/undef -> undef
8065 if ((C->isNullValue() || isa<UndefValue>(C))) {
Chris Lattner8ba9ec92004-10-18 02:59:09 +00008066 // Insert a new store to null instruction before the load to indicate that
8067 // this code is not reachable. We do this instead of inserting an
8068 // unreachable instruction directly because we cannot modify the CFG.
Chris Lattnera9d84e32005-05-01 04:24:53 +00008069 new StoreInst(UndefValue::get(LI.getType()),
8070 Constant::getNullValue(Op->getType()), &LI);
Chris Lattner81a7a232004-10-16 18:11:37 +00008071 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner8ba9ec92004-10-18 02:59:09 +00008072 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00008073
Chris Lattner81a7a232004-10-16 18:11:37 +00008074 // Instcombine load (constant global) into the value loaded.
8075 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
8076 if (GV->isConstant() && !GV->isExternal())
8077 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanb1c93172005-04-21 23:48:37 +00008078
Chris Lattner81a7a232004-10-16 18:11:37 +00008079 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
8080 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
8081 if (CE->getOpcode() == Instruction::GetElementPtr) {
8082 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
8083 if (GV->isConstant() && !GV->isExternal())
Chris Lattner0b011ec2005-09-26 05:28:06 +00008084 if (Constant *V =
8085 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
Chris Lattner81a7a232004-10-16 18:11:37 +00008086 return ReplaceInstUsesWith(LI, V);
Chris Lattnera9d84e32005-05-01 04:24:53 +00008087 if (CE->getOperand(0)->isNullValue()) {
8088 // Insert a new store to null instruction before the load to indicate
8089 // that this code is not reachable. We do this instead of inserting
8090 // an unreachable instruction directly because we cannot modify the
8091 // CFG.
8092 new StoreInst(UndefValue::get(LI.getType()),
8093 Constant::getNullValue(Op->getType()), &LI);
8094 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
8095 }
8096
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008097 } else if (CE->isCast()) {
Chris Lattner81a7a232004-10-16 18:11:37 +00008098 if (Instruction *Res = InstCombineLoadCast(*this, LI))
8099 return Res;
8100 }
8101 }
Chris Lattnere228ee52004-04-08 20:39:49 +00008102
Chris Lattnera9d84e32005-05-01 04:24:53 +00008103 if (Op->hasOneUse()) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008104 // Change select and PHI nodes to select values instead of addresses: this
8105 // helps alias analysis out a lot, allows many others simplifications, and
8106 // exposes redundancy in the code.
8107 //
8108 // Note that we cannot do the transformation unless we know that the
8109 // introduced loads cannot trap! Something like this is valid as long as
8110 // the condition is always false: load (select bool %C, int* null, int* %G),
8111 // but it would not be valid if we transformed it to load from null
8112 // unconditionally.
8113 //
8114 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
8115 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattnere6f13092004-09-19 19:18:10 +00008116 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
8117 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008118 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner42618552004-09-20 10:15:10 +00008119 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008120 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner42618552004-09-20 10:15:10 +00008121 SI->getOperand(2)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008122 return new SelectInst(SI->getCondition(), V1, V2);
8123 }
8124
Chris Lattnerbdcf41a2004-09-23 15:46:00 +00008125 // load (select (cond, null, P)) -> load P
8126 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
8127 if (C->isNullValue()) {
8128 LI.setOperand(0, SI->getOperand(2));
8129 return &LI;
8130 }
8131
8132 // load (select (cond, P, null)) -> load P
8133 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
8134 if (C->isNullValue()) {
8135 LI.setOperand(0, SI->getOperand(1));
8136 return &LI;
8137 }
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008138 }
8139 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00008140 return 0;
8141}
8142
Chris Lattner72684fe2005-01-31 05:51:45 +00008143/// InstCombineStoreToCast - Fold 'store V, (cast P)' -> store (cast V), P'
8144/// when possible.
8145static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
8146 User *CI = cast<User>(SI.getOperand(1));
8147 Value *CastOp = CI->getOperand(0);
8148
8149 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
8150 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
8151 const Type *SrcPTy = SrcTy->getElementType();
8152
8153 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
8154 // If the source is an array, the code below will not succeed. Check to
8155 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
8156 // constants.
8157 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
8158 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
8159 if (ASrcTy->getNumElements() != 0) {
Reid Spencerc635f472006-12-31 05:48:39 +00008160 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::Int32Ty));
Chris Lattner72684fe2005-01-31 05:51:45 +00008161 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
8162 SrcTy = cast<PointerType>(CastOp->getType());
8163 SrcPTy = SrcTy->getElementType();
8164 }
8165
8166 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00008167 IC.getTargetData().getTypeSize(SrcPTy) ==
Chris Lattner72684fe2005-01-31 05:51:45 +00008168 IC.getTargetData().getTypeSize(DestPTy)) {
8169
8170 // Okay, we are casting from one integer or pointer type to another of
8171 // the same size. Instead of casting the pointer before the store, cast
8172 // the value to be stored.
8173 Value *NewCast;
Reid Spencerbb65ebf2006-12-12 23:36:14 +00008174 Instruction::CastOps opcode = Instruction::BitCast;
8175 Value *SIOp0 = SI.getOperand(0);
Reid Spencer74a528b2006-12-13 18:21:21 +00008176 if (isa<PointerType>(SrcPTy)) {
Reid Spencerbb65ebf2006-12-12 23:36:14 +00008177 if (SIOp0->getType()->isIntegral())
8178 opcode = Instruction::IntToPtr;
8179 } else if (SrcPTy->isIntegral()) {
Reid Spencer74a528b2006-12-13 18:21:21 +00008180 if (isa<PointerType>(SIOp0->getType()))
Reid Spencerbb65ebf2006-12-12 23:36:14 +00008181 opcode = Instruction::PtrToInt;
8182 }
8183 if (Constant *C = dyn_cast<Constant>(SIOp0))
8184 NewCast = ConstantExpr::getCast(opcode, C, SrcPTy);
Chris Lattner72684fe2005-01-31 05:51:45 +00008185 else
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008186 NewCast = IC.InsertNewInstBefore(
Reid Spencerbb65ebf2006-12-12 23:36:14 +00008187 CastInst::create(opcode, SIOp0, SrcPTy, SIOp0->getName()+".c"), SI);
Chris Lattner72684fe2005-01-31 05:51:45 +00008188 return new StoreInst(NewCast, CastOp);
8189 }
8190 }
8191 }
8192 return 0;
8193}
8194
Chris Lattner31f486c2005-01-31 05:36:43 +00008195Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
8196 Value *Val = SI.getOperand(0);
8197 Value *Ptr = SI.getOperand(1);
8198
8199 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner5997cf92006-02-08 03:25:32 +00008200 EraseInstFromFunction(SI);
Chris Lattner31f486c2005-01-31 05:36:43 +00008201 ++NumCombined;
8202 return 0;
8203 }
8204
Chris Lattner5997cf92006-02-08 03:25:32 +00008205 // Do really simple DSE, to catch cases where there are several consequtive
8206 // stores to the same location, separated by a few arithmetic operations. This
8207 // situation often occurs with bitfield accesses.
8208 BasicBlock::iterator BBI = &SI;
8209 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
8210 --ScanInsts) {
8211 --BBI;
8212
8213 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
8214 // Prev store isn't volatile, and stores to the same location?
8215 if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
8216 ++NumDeadStore;
8217 ++BBI;
8218 EraseInstFromFunction(*PrevSI);
8219 continue;
8220 }
8221 break;
8222 }
8223
Chris Lattnerdab43b22006-05-26 19:19:20 +00008224 // If this is a load, we have to stop. However, if the loaded value is from
8225 // the pointer we're loading and is producing the pointer we're storing,
8226 // then *this* store is dead (X = load P; store X -> P).
8227 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
8228 if (LI == Val && LI->getOperand(0) == Ptr) {
8229 EraseInstFromFunction(SI);
8230 ++NumCombined;
8231 return 0;
8232 }
8233 // Otherwise, this is a load from some other location. Stores before it
8234 // may not be dead.
8235 break;
8236 }
8237
Chris Lattner5997cf92006-02-08 03:25:32 +00008238 // Don't skip over loads or things that can modify memory.
Chris Lattnerdab43b22006-05-26 19:19:20 +00008239 if (BBI->mayWriteToMemory())
Chris Lattner5997cf92006-02-08 03:25:32 +00008240 break;
8241 }
8242
8243
8244 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner31f486c2005-01-31 05:36:43 +00008245
8246 // store X, null -> turns into 'unreachable' in SimplifyCFG
8247 if (isa<ConstantPointerNull>(Ptr)) {
8248 if (!isa<UndefValue>(Val)) {
8249 SI.setOperand(0, UndefValue::get(Val->getType()));
8250 if (Instruction *U = dyn_cast<Instruction>(Val))
8251 WorkList.push_back(U); // Dropped a use.
8252 ++NumCombined;
8253 }
8254 return 0; // Do not modify these!
8255 }
8256
8257 // store undef, Ptr -> noop
8258 if (isa<UndefValue>(Val)) {
Chris Lattner5997cf92006-02-08 03:25:32 +00008259 EraseInstFromFunction(SI);
Chris Lattner31f486c2005-01-31 05:36:43 +00008260 ++NumCombined;
8261 return 0;
8262 }
8263
Chris Lattner72684fe2005-01-31 05:51:45 +00008264 // If the pointer destination is a cast, see if we can fold the cast into the
8265 // source instead.
Reid Spencerde46e482006-11-02 20:25:50 +00008266 if (isa<CastInst>(Ptr))
Chris Lattner72684fe2005-01-31 05:51:45 +00008267 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
8268 return Res;
8269 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008270 if (CE->isCast())
Chris Lattner72684fe2005-01-31 05:51:45 +00008271 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
8272 return Res;
8273
Chris Lattner219175c2005-09-12 23:23:25 +00008274
8275 // If this store is the last instruction in the basic block, and if the block
8276 // ends with an unconditional branch, try to move it to the successor block.
Chris Lattner5997cf92006-02-08 03:25:32 +00008277 BBI = &SI; ++BBI;
Chris Lattner219175c2005-09-12 23:23:25 +00008278 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
8279 if (BI->isUnconditional()) {
8280 // Check to see if the successor block has exactly two incoming edges. If
8281 // so, see if the other predecessor contains a store to the same location.
8282 // if so, insert a PHI node (if needed) and move the stores down.
8283 BasicBlock *Dest = BI->getSuccessor(0);
8284
8285 pred_iterator PI = pred_begin(Dest);
8286 BasicBlock *Other = 0;
8287 if (*PI != BI->getParent())
8288 Other = *PI;
8289 ++PI;
8290 if (PI != pred_end(Dest)) {
8291 if (*PI != BI->getParent())
8292 if (Other)
8293 Other = 0;
8294 else
8295 Other = *PI;
8296 if (++PI != pred_end(Dest))
8297 Other = 0;
8298 }
8299 if (Other) { // If only one other pred...
8300 BBI = Other->getTerminator();
8301 // Make sure this other block ends in an unconditional branch and that
8302 // there is an instruction before the branch.
8303 if (isa<BranchInst>(BBI) && cast<BranchInst>(BBI)->isUnconditional() &&
8304 BBI != Other->begin()) {
8305 --BBI;
8306 StoreInst *OtherStore = dyn_cast<StoreInst>(BBI);
8307
8308 // If this instruction is a store to the same location.
8309 if (OtherStore && OtherStore->getOperand(1) == SI.getOperand(1)) {
8310 // Okay, we know we can perform this transformation. Insert a PHI
8311 // node now if we need it.
8312 Value *MergedVal = OtherStore->getOperand(0);
8313 if (MergedVal != SI.getOperand(0)) {
8314 PHINode *PN = new PHINode(MergedVal->getType(), "storemerge");
8315 PN->reserveOperandSpace(2);
8316 PN->addIncoming(SI.getOperand(0), SI.getParent());
8317 PN->addIncoming(OtherStore->getOperand(0), Other);
8318 MergedVal = InsertNewInstBefore(PN, Dest->front());
8319 }
8320
8321 // Advance to a place where it is safe to insert the new store and
8322 // insert it.
8323 BBI = Dest->begin();
8324 while (isa<PHINode>(BBI)) ++BBI;
8325 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
8326 OtherStore->isVolatile()), *BBI);
8327
8328 // Nuke the old stores.
Chris Lattner5997cf92006-02-08 03:25:32 +00008329 EraseInstFromFunction(SI);
8330 EraseInstFromFunction(*OtherStore);
Chris Lattner219175c2005-09-12 23:23:25 +00008331 ++NumCombined;
8332 return 0;
8333 }
8334 }
8335 }
8336 }
8337
Chris Lattner31f486c2005-01-31 05:36:43 +00008338 return 0;
8339}
8340
8341
Chris Lattner9eef8a72003-06-04 04:46:00 +00008342Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
8343 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4fdd96c2005-06-18 17:37:34 +00008344 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00008345 BasicBlock *TrueDest;
8346 BasicBlock *FalseDest;
8347 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
8348 !isa<Constant>(X)) {
8349 // Swap Destinations and condition...
8350 BI.setCondition(X);
8351 BI.setSuccessor(0, FalseDest);
8352 BI.setSuccessor(1, TrueDest);
8353 return &BI;
8354 }
8355
Reid Spencer266e42b2006-12-23 06:05:41 +00008356 // Cannonicalize fcmp_one -> fcmp_oeq
8357 FCmpInst::Predicate FPred; Value *Y;
8358 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
8359 TrueDest, FalseDest)))
8360 if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
8361 FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
8362 FCmpInst *I = cast<FCmpInst>(BI.getCondition());
Chris Lattnerd4252a72004-07-30 07:50:03 +00008363 std::string Name = I->getName(); I->setName("");
Reid Spencer266e42b2006-12-23 06:05:41 +00008364 FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
8365 Value *NewSCC = new FCmpInst(NewPred, X, Y, Name, I);
8366 // Swap Destinations and condition...
8367 BI.setCondition(NewSCC);
8368 BI.setSuccessor(0, FalseDest);
8369 BI.setSuccessor(1, TrueDest);
8370 removeFromWorkList(I);
8371 I->getParent()->getInstList().erase(I);
8372 WorkList.push_back(cast<Instruction>(NewSCC));
8373 return &BI;
8374 }
8375
8376 // Cannonicalize icmp_ne -> icmp_eq
8377 ICmpInst::Predicate IPred;
8378 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
8379 TrueDest, FalseDest)))
8380 if ((IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
8381 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
8382 IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
8383 ICmpInst *I = cast<ICmpInst>(BI.getCondition());
8384 std::string Name = I->getName(); I->setName("");
8385 ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
8386 Value *NewSCC = new ICmpInst(NewPred, X, Y, Name, I);
Chris Lattnere967b342003-06-04 05:10:11 +00008387 // Swap Destinations and condition...
Chris Lattnerd4252a72004-07-30 07:50:03 +00008388 BI.setCondition(NewSCC);
Chris Lattnere967b342003-06-04 05:10:11 +00008389 BI.setSuccessor(0, FalseDest);
8390 BI.setSuccessor(1, TrueDest);
Chris Lattnerd4252a72004-07-30 07:50:03 +00008391 removeFromWorkList(I);
8392 I->getParent()->getInstList().erase(I);
8393 WorkList.push_back(cast<Instruction>(NewSCC));
Chris Lattnere967b342003-06-04 05:10:11 +00008394 return &BI;
8395 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00008396
Chris Lattner9eef8a72003-06-04 04:46:00 +00008397 return 0;
8398}
Chris Lattner1085bdf2002-11-04 16:18:53 +00008399
Chris Lattner4c9c20a2004-07-03 00:26:11 +00008400Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
8401 Value *Cond = SI.getCondition();
8402 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
8403 if (I->getOpcode() == Instruction::Add)
8404 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
8405 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
8406 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattner81a7a232004-10-16 18:11:37 +00008407 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner4c9c20a2004-07-03 00:26:11 +00008408 AddRHS));
8409 SI.setOperand(0, I->getOperand(0));
8410 WorkList.push_back(I);
8411 return &SI;
8412 }
8413 }
8414 return 0;
8415}
8416
Chris Lattner6bc98652006-03-05 00:22:33 +00008417/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
8418/// is to leave as a vector operation.
8419static bool CheapToScalarize(Value *V, bool isConstant) {
8420 if (isa<ConstantAggregateZero>(V))
8421 return true;
8422 if (ConstantPacked *C = dyn_cast<ConstantPacked>(V)) {
8423 if (isConstant) return true;
8424 // If all elts are the same, we can extract.
8425 Constant *Op0 = C->getOperand(0);
8426 for (unsigned i = 1; i < C->getNumOperands(); ++i)
8427 if (C->getOperand(i) != Op0)
8428 return false;
8429 return true;
8430 }
8431 Instruction *I = dyn_cast<Instruction>(V);
8432 if (!I) return false;
8433
8434 // Insert element gets simplified to the inserted element or is deleted if
8435 // this is constant idx extract element and its a constant idx insertelt.
8436 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
8437 isa<ConstantInt>(I->getOperand(2)))
8438 return true;
8439 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
8440 return true;
8441 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
8442 if (BO->hasOneUse() &&
8443 (CheapToScalarize(BO->getOperand(0), isConstant) ||
8444 CheapToScalarize(BO->getOperand(1), isConstant)))
8445 return true;
Reid Spencer266e42b2006-12-23 06:05:41 +00008446 if (CmpInst *CI = dyn_cast<CmpInst>(I))
8447 if (CI->hasOneUse() &&
8448 (CheapToScalarize(CI->getOperand(0), isConstant) ||
8449 CheapToScalarize(CI->getOperand(1), isConstant)))
8450 return true;
Chris Lattner6bc98652006-03-05 00:22:33 +00008451
8452 return false;
8453}
8454
Chris Lattner12249be2006-05-25 23:48:38 +00008455/// getShuffleMask - Read and decode a shufflevector mask. It turns undef
8456/// elements into values that are larger than the #elts in the input.
8457static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
8458 unsigned NElts = SVI->getType()->getNumElements();
8459 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
8460 return std::vector<unsigned>(NElts, 0);
8461 if (isa<UndefValue>(SVI->getOperand(2)))
8462 return std::vector<unsigned>(NElts, 2*NElts);
8463
8464 std::vector<unsigned> Result;
8465 const ConstantPacked *CP = cast<ConstantPacked>(SVI->getOperand(2));
8466 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
8467 if (isa<UndefValue>(CP->getOperand(i)))
8468 Result.push_back(NElts*2); // undef -> 8
8469 else
Reid Spencere0fc4df2006-10-20 07:07:24 +00008470 Result.push_back(cast<ConstantInt>(CP->getOperand(i))->getZExtValue());
Chris Lattner12249be2006-05-25 23:48:38 +00008471 return Result;
8472}
8473
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008474/// FindScalarElement - Given a vector and an element number, see if the scalar
8475/// value is already around as a register, for example if it were inserted then
8476/// extracted from the vector.
8477static Value *FindScalarElement(Value *V, unsigned EltNo) {
8478 assert(isa<PackedType>(V->getType()) && "Not looking at a vector?");
8479 const PackedType *PTy = cast<PackedType>(V->getType());
Chris Lattner2d37f922006-04-10 23:06:36 +00008480 unsigned Width = PTy->getNumElements();
8481 if (EltNo >= Width) // Out of range access.
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008482 return UndefValue::get(PTy->getElementType());
8483
8484 if (isa<UndefValue>(V))
8485 return UndefValue::get(PTy->getElementType());
8486 else if (isa<ConstantAggregateZero>(V))
8487 return Constant::getNullValue(PTy->getElementType());
8488 else if (ConstantPacked *CP = dyn_cast<ConstantPacked>(V))
8489 return CP->getOperand(EltNo);
8490 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
8491 // If this is an insert to a variable element, we don't know what it is.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008492 if (!isa<ConstantInt>(III->getOperand(2)))
8493 return 0;
8494 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008495
8496 // If this is an insert to the element we are looking for, return the
8497 // inserted value.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008498 if (EltNo == IIElt)
8499 return III->getOperand(1);
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008500
8501 // Otherwise, the insertelement doesn't modify the value, recurse on its
8502 // vector input.
8503 return FindScalarElement(III->getOperand(0), EltNo);
Chris Lattner2d37f922006-04-10 23:06:36 +00008504 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Chris Lattner12249be2006-05-25 23:48:38 +00008505 unsigned InEl = getShuffleMask(SVI)[EltNo];
8506 if (InEl < Width)
8507 return FindScalarElement(SVI->getOperand(0), InEl);
8508 else if (InEl < Width*2)
8509 return FindScalarElement(SVI->getOperand(1), InEl - Width);
8510 else
8511 return UndefValue::get(PTy->getElementType());
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008512 }
8513
8514 // Otherwise, we don't know.
8515 return 0;
8516}
8517
Robert Bocchinoa8352962006-01-13 22:48:06 +00008518Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008519
Chris Lattner92346c32006-03-31 18:25:14 +00008520 // If packed val is undef, replace extract with scalar undef.
8521 if (isa<UndefValue>(EI.getOperand(0)))
8522 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
8523
8524 // If packed val is constant 0, replace extract with scalar 0.
8525 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
8526 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
8527
Robert Bocchinoa8352962006-01-13 22:48:06 +00008528 if (ConstantPacked *C = dyn_cast<ConstantPacked>(EI.getOperand(0))) {
8529 // If packed val is constant with uniform operands, replace EI
8530 // with that operand
Chris Lattner6bc98652006-03-05 00:22:33 +00008531 Constant *op0 = C->getOperand(0);
Robert Bocchinoa8352962006-01-13 22:48:06 +00008532 for (unsigned i = 1; i < C->getNumOperands(); ++i)
Chris Lattner6bc98652006-03-05 00:22:33 +00008533 if (C->getOperand(i) != op0) {
8534 op0 = 0;
8535 break;
8536 }
8537 if (op0)
8538 return ReplaceInstUsesWith(EI, op0);
Robert Bocchinoa8352962006-01-13 22:48:06 +00008539 }
Chris Lattner6bc98652006-03-05 00:22:33 +00008540
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008541 // If extracting a specified index from the vector, see if we can recursively
8542 // find a previously computed scalar that was inserted into the vector.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008543 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Chris Lattner2deeaea2006-10-05 06:55:50 +00008544 // This instruction only demands the single element from the input vector.
8545 // If the input vector has a single use, simplify it based on this use
8546 // property.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008547 uint64_t IndexVal = IdxC->getZExtValue();
Chris Lattner2deeaea2006-10-05 06:55:50 +00008548 if (EI.getOperand(0)->hasOneUse()) {
8549 uint64_t UndefElts;
8550 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Reid Spencere0fc4df2006-10-20 07:07:24 +00008551 1 << IndexVal,
Chris Lattner2deeaea2006-10-05 06:55:50 +00008552 UndefElts)) {
8553 EI.setOperand(0, V);
8554 return &EI;
8555 }
8556 }
8557
Reid Spencere0fc4df2006-10-20 07:07:24 +00008558 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008559 return ReplaceInstUsesWith(EI, Elt);
Chris Lattner2d37f922006-04-10 23:06:36 +00008560 }
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008561
Chris Lattner83f65782006-05-25 22:53:38 +00008562 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Robert Bocchinoa8352962006-01-13 22:48:06 +00008563 if (I->hasOneUse()) {
8564 // Push extractelement into predecessor operation if legal and
8565 // profitable to do so
8566 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Chris Lattner6bc98652006-03-05 00:22:33 +00008567 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
8568 if (CheapToScalarize(BO, isConstantElt)) {
8569 ExtractElementInst *newEI0 =
8570 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
8571 EI.getName()+".lhs");
8572 ExtractElementInst *newEI1 =
8573 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
8574 EI.getName()+".rhs");
8575 InsertNewInstBefore(newEI0, EI);
8576 InsertNewInstBefore(newEI1, EI);
8577 return BinaryOperator::create(BO->getOpcode(), newEI0, newEI1);
8578 }
Reid Spencerde46e482006-11-02 20:25:50 +00008579 } else if (isa<LoadInst>(I)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00008580 Value *Ptr = InsertCastBefore(Instruction::BitCast, I->getOperand(0),
Robert Bocchinoa8352962006-01-13 22:48:06 +00008581 PointerType::get(EI.getType()), EI);
8582 GetElementPtrInst *GEP =
Reid Spencera736fdf2006-11-29 01:11:01 +00008583 new GetElementPtrInst(Ptr, EI.getOperand(1), I->getName() + ".gep");
Robert Bocchinoa8352962006-01-13 22:48:06 +00008584 InsertNewInstBefore(GEP, EI);
8585 return new LoadInst(GEP);
Chris Lattner83f65782006-05-25 22:53:38 +00008586 }
8587 }
8588 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
8589 // Extracting the inserted element?
8590 if (IE->getOperand(2) == EI.getOperand(1))
8591 return ReplaceInstUsesWith(EI, IE->getOperand(1));
8592 // If the inserted and extracted elements are constants, they must not
8593 // be the same value, extract from the pre-inserted value instead.
8594 if (isa<Constant>(IE->getOperand(2)) &&
8595 isa<Constant>(EI.getOperand(1))) {
8596 AddUsesToWorkList(EI);
8597 EI.setOperand(0, IE->getOperand(0));
8598 return &EI;
8599 }
8600 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
8601 // If this is extracting an element from a shufflevector, figure out where
8602 // it came from and extract from the appropriate input element instead.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008603 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
8604 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
Chris Lattner12249be2006-05-25 23:48:38 +00008605 Value *Src;
8606 if (SrcIdx < SVI->getType()->getNumElements())
8607 Src = SVI->getOperand(0);
8608 else if (SrcIdx < SVI->getType()->getNumElements()*2) {
8609 SrcIdx -= SVI->getType()->getNumElements();
8610 Src = SVI->getOperand(1);
8611 } else {
8612 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattner612fa8e2006-03-30 22:02:40 +00008613 }
Chris Lattner2deeaea2006-10-05 06:55:50 +00008614 return new ExtractElementInst(Src, SrcIdx);
Robert Bocchinoa8352962006-01-13 22:48:06 +00008615 }
8616 }
Chris Lattner83f65782006-05-25 22:53:38 +00008617 }
Robert Bocchinoa8352962006-01-13 22:48:06 +00008618 return 0;
8619}
8620
Chris Lattner90951862006-04-16 00:51:47 +00008621/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
8622/// elements from either LHS or RHS, return the shuffle mask and true.
8623/// Otherwise, return false.
8624static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
8625 std::vector<Constant*> &Mask) {
8626 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
8627 "Invalid CollectSingleShuffleElements");
8628 unsigned NumElts = cast<PackedType>(V->getType())->getNumElements();
8629
8630 if (isa<UndefValue>(V)) {
Reid Spencerc635f472006-12-31 05:48:39 +00008631 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattner90951862006-04-16 00:51:47 +00008632 return true;
8633 } else if (V == LHS) {
8634 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc635f472006-12-31 05:48:39 +00008635 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattner90951862006-04-16 00:51:47 +00008636 return true;
8637 } else if (V == RHS) {
8638 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc635f472006-12-31 05:48:39 +00008639 Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
Chris Lattner90951862006-04-16 00:51:47 +00008640 return true;
8641 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
8642 // If this is an insert of an extract from some other vector, include it.
8643 Value *VecOp = IEI->getOperand(0);
8644 Value *ScalarOp = IEI->getOperand(1);
8645 Value *IdxOp = IEI->getOperand(2);
8646
Chris Lattnerb6cb64b2006-04-27 21:14:21 +00008647 if (!isa<ConstantInt>(IdxOp))
8648 return false;
Reid Spencere0fc4df2006-10-20 07:07:24 +00008649 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerb6cb64b2006-04-27 21:14:21 +00008650
8651 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
8652 // Okay, we can handle this if the vector we are insertinting into is
8653 // transitively ok.
8654 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
8655 // If so, update the mask to reflect the inserted undef.
Reid Spencerc635f472006-12-31 05:48:39 +00008656 Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
Chris Lattnerb6cb64b2006-04-27 21:14:21 +00008657 return true;
8658 }
8659 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
8660 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner90951862006-04-16 00:51:47 +00008661 EI->getOperand(0)->getType() == V->getType()) {
8662 unsigned ExtractedIdx =
Reid Spencere0fc4df2006-10-20 07:07:24 +00008663 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattner90951862006-04-16 00:51:47 +00008664
8665 // This must be extracting from either LHS or RHS.
8666 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
8667 // Okay, we can handle this if the vector we are insertinting into is
8668 // transitively ok.
8669 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
8670 // If so, update the mask to reflect the inserted value.
8671 if (EI->getOperand(0) == LHS) {
8672 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc635f472006-12-31 05:48:39 +00008673 ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattner90951862006-04-16 00:51:47 +00008674 } else {
8675 assert(EI->getOperand(0) == RHS);
8676 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc635f472006-12-31 05:48:39 +00008677 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
Chris Lattner90951862006-04-16 00:51:47 +00008678
8679 }
8680 return true;
8681 }
8682 }
8683 }
8684 }
8685 }
8686 // TODO: Handle shufflevector here!
8687
8688 return false;
8689}
8690
8691/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
8692/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
8693/// that computes V and the LHS value of the shuffle.
Chris Lattner39fac442006-04-15 01:39:45 +00008694static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Chris Lattner90951862006-04-16 00:51:47 +00008695 Value *&RHS) {
8696 assert(isa<PackedType>(V->getType()) &&
8697 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattner39fac442006-04-15 01:39:45 +00008698 "Invalid shuffle!");
8699 unsigned NumElts = cast<PackedType>(V->getType())->getNumElements();
8700
8701 if (isa<UndefValue>(V)) {
Reid Spencerc635f472006-12-31 05:48:39 +00008702 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattner39fac442006-04-15 01:39:45 +00008703 return V;
8704 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencerc635f472006-12-31 05:48:39 +00008705 Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
Chris Lattner39fac442006-04-15 01:39:45 +00008706 return V;
8707 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
8708 // If this is an insert of an extract from some other vector, include it.
8709 Value *VecOp = IEI->getOperand(0);
8710 Value *ScalarOp = IEI->getOperand(1);
8711 Value *IdxOp = IEI->getOperand(2);
8712
8713 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
8714 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
8715 EI->getOperand(0)->getType() == V->getType()) {
8716 unsigned ExtractedIdx =
Reid Spencere0fc4df2006-10-20 07:07:24 +00008717 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
8718 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattner39fac442006-04-15 01:39:45 +00008719
8720 // Either the extracted from or inserted into vector must be RHSVec,
8721 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner90951862006-04-16 00:51:47 +00008722 if (EI->getOperand(0) == RHS || RHS == 0) {
8723 RHS = EI->getOperand(0);
8724 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
Chris Lattner39fac442006-04-15 01:39:45 +00008725 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc635f472006-12-31 05:48:39 +00008726 ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
Chris Lattner39fac442006-04-15 01:39:45 +00008727 return V;
8728 }
8729
Chris Lattner90951862006-04-16 00:51:47 +00008730 if (VecOp == RHS) {
8731 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
Chris Lattner39fac442006-04-15 01:39:45 +00008732 // Everything but the extracted element is replaced with the RHS.
8733 for (unsigned i = 0; i != NumElts; ++i) {
8734 if (i != InsertedIdx)
Reid Spencerc635f472006-12-31 05:48:39 +00008735 Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
Chris Lattner39fac442006-04-15 01:39:45 +00008736 }
8737 return V;
8738 }
Chris Lattner90951862006-04-16 00:51:47 +00008739
8740 // If this insertelement is a chain that comes from exactly these two
8741 // vectors, return the vector and the effective shuffle.
8742 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
8743 return EI->getOperand(0);
8744
Chris Lattner39fac442006-04-15 01:39:45 +00008745 }
8746 }
8747 }
Chris Lattner90951862006-04-16 00:51:47 +00008748 // TODO: Handle shufflevector here!
Chris Lattner39fac442006-04-15 01:39:45 +00008749
8750 // Otherwise, can't do anything fancy. Return an identity vector.
8751 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc635f472006-12-31 05:48:39 +00008752 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattner39fac442006-04-15 01:39:45 +00008753 return V;
8754}
8755
8756Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
8757 Value *VecOp = IE.getOperand(0);
8758 Value *ScalarOp = IE.getOperand(1);
8759 Value *IdxOp = IE.getOperand(2);
8760
8761 // If the inserted element was extracted from some other vector, and if the
8762 // indexes are constant, try to turn this into a shufflevector operation.
8763 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
8764 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
8765 EI->getOperand(0)->getType() == IE.getType()) {
8766 unsigned NumVectorElts = IE.getType()->getNumElements();
Reid Spencere0fc4df2006-10-20 07:07:24 +00008767 unsigned ExtractedIdx=cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
8768 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattner39fac442006-04-15 01:39:45 +00008769
8770 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
8771 return ReplaceInstUsesWith(IE, VecOp);
8772
8773 if (InsertedIdx >= NumVectorElts) // Out of range insert.
8774 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
8775
8776 // If we are extracting a value from a vector, then inserting it right
8777 // back into the same place, just use the input vector.
8778 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
8779 return ReplaceInstUsesWith(IE, VecOp);
8780
8781 // We could theoretically do this for ANY input. However, doing so could
8782 // turn chains of insertelement instructions into a chain of shufflevector
8783 // instructions, and right now we do not merge shufflevectors. As such,
8784 // only do this in a situation where it is clear that there is benefit.
8785 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
8786 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
8787 // the values of VecOp, except then one read from EIOp0.
8788 // Build a new shuffle mask.
8789 std::vector<Constant*> Mask;
8790 if (isa<UndefValue>(VecOp))
Reid Spencerc635f472006-12-31 05:48:39 +00008791 Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
Chris Lattner39fac442006-04-15 01:39:45 +00008792 else {
8793 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
Reid Spencerc635f472006-12-31 05:48:39 +00008794 Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
Chris Lattner39fac442006-04-15 01:39:45 +00008795 NumVectorElts));
8796 }
Reid Spencerc635f472006-12-31 05:48:39 +00008797 Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattner39fac442006-04-15 01:39:45 +00008798 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
8799 ConstantPacked::get(Mask));
8800 }
8801
8802 // If this insertelement isn't used by some other insertelement, turn it
8803 // (and any insertelements it points to), into one big shuffle.
8804 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
8805 std::vector<Constant*> Mask;
Chris Lattner90951862006-04-16 00:51:47 +00008806 Value *RHS = 0;
8807 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
8808 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
8809 // We now have a shuffle of LHS, RHS, Mask.
8810 return new ShuffleVectorInst(LHS, RHS, ConstantPacked::get(Mask));
Chris Lattner39fac442006-04-15 01:39:45 +00008811 }
8812 }
8813 }
8814
8815 return 0;
8816}
8817
8818
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008819Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
8820 Value *LHS = SVI.getOperand(0);
8821 Value *RHS = SVI.getOperand(1);
Chris Lattner12249be2006-05-25 23:48:38 +00008822 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008823
8824 bool MadeChange = false;
8825
Chris Lattner2deeaea2006-10-05 06:55:50 +00008826 // Undefined shuffle mask -> undefined value.
Chris Lattner12249be2006-05-25 23:48:38 +00008827 if (isa<UndefValue>(SVI.getOperand(2)))
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008828 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
8829
Chris Lattnerd7b6ea12007-01-05 07:36:08 +00008830 // If we have shuffle(x, undef, mask) and any elements of mask refer to
Chris Lattner39fac442006-04-15 01:39:45 +00008831 // the undef, change them to undefs.
Chris Lattnerd7b6ea12007-01-05 07:36:08 +00008832 if (isa<UndefValue>(SVI.getOperand(1))) {
8833 // Scan to see if there are any references to the RHS. If so, replace them
8834 // with undef element refs and set MadeChange to true.
8835 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
8836 if (Mask[i] >= e && Mask[i] != 2*e) {
8837 Mask[i] = 2*e;
8838 MadeChange = true;
8839 }
8840 }
8841
8842 if (MadeChange) {
8843 // Remap any references to RHS to use LHS.
8844 std::vector<Constant*> Elts;
8845 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
8846 if (Mask[i] == 2*e)
8847 Elts.push_back(UndefValue::get(Type::Int32Ty));
8848 else
8849 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
8850 }
8851 SVI.setOperand(2, ConstantPacked::get(Elts));
8852 }
8853 }
Chris Lattner39fac442006-04-15 01:39:45 +00008854
Chris Lattner12249be2006-05-25 23:48:38 +00008855 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
8856 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
8857 if (LHS == RHS || isa<UndefValue>(LHS)) {
8858 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008859 // shuffle(undef,undef,mask) -> undef.
8860 return ReplaceInstUsesWith(SVI, LHS);
8861 }
8862
Chris Lattner12249be2006-05-25 23:48:38 +00008863 // Remap any references to RHS to use LHS.
8864 std::vector<Constant*> Elts;
8865 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner0e477162006-05-26 00:29:06 +00008866 if (Mask[i] >= 2*e)
Reid Spencerc635f472006-12-31 05:48:39 +00008867 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner0e477162006-05-26 00:29:06 +00008868 else {
8869 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
8870 (Mask[i] < e && isa<UndefValue>(LHS)))
8871 Mask[i] = 2*e; // Turn into undef.
8872 else
8873 Mask[i] &= (e-1); // Force to LHS.
Reid Spencerc635f472006-12-31 05:48:39 +00008874 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
Chris Lattner0e477162006-05-26 00:29:06 +00008875 }
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008876 }
Chris Lattner12249be2006-05-25 23:48:38 +00008877 SVI.setOperand(0, SVI.getOperand(1));
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008878 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Chris Lattner12249be2006-05-25 23:48:38 +00008879 SVI.setOperand(2, ConstantPacked::get(Elts));
Chris Lattner0e477162006-05-26 00:29:06 +00008880 LHS = SVI.getOperand(0);
8881 RHS = SVI.getOperand(1);
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008882 MadeChange = true;
8883 }
8884
Chris Lattner0e477162006-05-26 00:29:06 +00008885 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner12249be2006-05-25 23:48:38 +00008886 bool isLHSID = true, isRHSID = true;
Chris Lattner34cebe72006-04-16 00:03:56 +00008887
Chris Lattner12249be2006-05-25 23:48:38 +00008888 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
8889 if (Mask[i] >= e*2) continue; // Ignore undef values.
8890 // Is this an identity shuffle of the LHS value?
8891 isLHSID &= (Mask[i] == i);
8892
8893 // Is this an identity shuffle of the RHS value?
8894 isRHSID &= (Mask[i]-e == i);
Chris Lattner34cebe72006-04-16 00:03:56 +00008895 }
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008896
Chris Lattner12249be2006-05-25 23:48:38 +00008897 // Eliminate identity shuffles.
8898 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
8899 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008900
Chris Lattner0e477162006-05-26 00:29:06 +00008901 // If the LHS is a shufflevector itself, see if we can combine it with this
8902 // one without producing an unusual shuffle. Here we are really conservative:
8903 // we are absolutely afraid of producing a shuffle mask not in the input
8904 // program, because the code gen may not be smart enough to turn a merged
8905 // shuffle into two specific shuffles: it may produce worse code. As such,
8906 // we only merge two shuffles if the result is one of the two input shuffle
8907 // masks. In this case, merging the shuffles just removes one instruction,
8908 // which we know is safe. This is good for things like turning:
8909 // (splat(splat)) -> splat.
8910 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
8911 if (isa<UndefValue>(RHS)) {
8912 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
8913
8914 std::vector<unsigned> NewMask;
8915 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
8916 if (Mask[i] >= 2*e)
8917 NewMask.push_back(2*e);
8918 else
8919 NewMask.push_back(LHSMask[Mask[i]]);
8920
8921 // If the result mask is equal to the src shuffle or this shuffle mask, do
8922 // the replacement.
8923 if (NewMask == LHSMask || NewMask == Mask) {
8924 std::vector<Constant*> Elts;
8925 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
8926 if (NewMask[i] >= e*2) {
Reid Spencerc635f472006-12-31 05:48:39 +00008927 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner0e477162006-05-26 00:29:06 +00008928 } else {
Reid Spencerc635f472006-12-31 05:48:39 +00008929 Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
Chris Lattner0e477162006-05-26 00:29:06 +00008930 }
8931 }
8932 return new ShuffleVectorInst(LHSSVI->getOperand(0),
8933 LHSSVI->getOperand(1),
8934 ConstantPacked::get(Elts));
8935 }
8936 }
8937 }
8938
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008939 return MadeChange ? &SVI : 0;
8940}
8941
8942
Robert Bocchinoa8352962006-01-13 22:48:06 +00008943
Chris Lattner99f48c62002-09-02 04:59:56 +00008944void InstCombiner::removeFromWorkList(Instruction *I) {
8945 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
8946 WorkList.end());
8947}
8948
Chris Lattner39c98bb2004-12-08 23:43:58 +00008949
8950/// TryToSinkInstruction - Try to move the specified instruction from its
8951/// current block into the beginning of DestBlock, which can only happen if it's
8952/// safe to move the instruction past all of the instructions between it and the
8953/// end of its block.
8954static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
8955 assert(I->hasOneUse() && "Invariants didn't hold!");
8956
Chris Lattnerc4f67e62005-10-27 17:13:11 +00008957 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
8958 if (isa<PHINode>(I) || I->mayWriteToMemory()) return false;
Misha Brukmanb1c93172005-04-21 23:48:37 +00008959
Chris Lattner39c98bb2004-12-08 23:43:58 +00008960 // Do not sink alloca instructions out of the entry block.
8961 if (isa<AllocaInst>(I) && I->getParent() == &DestBlock->getParent()->front())
8962 return false;
8963
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00008964 // We can only sink load instructions if there is nothing between the load and
8965 // the end of block that could change the value.
8966 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00008967 for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
8968 Scan != E; ++Scan)
8969 if (Scan->mayWriteToMemory())
8970 return false;
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00008971 }
Chris Lattner39c98bb2004-12-08 23:43:58 +00008972
8973 BasicBlock::iterator InsertPos = DestBlock->begin();
8974 while (isa<PHINode>(InsertPos)) ++InsertPos;
8975
Chris Lattner9f269e42005-08-08 19:11:57 +00008976 I->moveBefore(InsertPos);
Chris Lattner39c98bb2004-12-08 23:43:58 +00008977 ++NumSunkInst;
8978 return true;
8979}
8980
Chris Lattner1443bc52006-05-11 17:11:52 +00008981/// OptimizeConstantExpr - Given a constant expression and target data layout
Reid Spencer13bc5d72006-12-12 09:18:51 +00008982/// information, symbolically evaluate the constant expr to something simpler
Chris Lattner1443bc52006-05-11 17:11:52 +00008983/// if possible.
8984static Constant *OptimizeConstantExpr(ConstantExpr *CE, const TargetData *TD) {
8985 if (!TD) return CE;
8986
8987 Constant *Ptr = CE->getOperand(0);
8988 if (CE->getOpcode() == Instruction::GetElementPtr && Ptr->isNullValue() &&
8989 cast<PointerType>(Ptr->getType())->getElementType()->isSized()) {
8990 // If this is a constant expr gep that is effectively computing an
8991 // "offsetof", fold it into 'cast int Size to T*' instead of 'gep 0, 0, 12'
8992 bool isFoldableGEP = true;
8993 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
8994 if (!isa<ConstantInt>(CE->getOperand(i)))
8995 isFoldableGEP = false;
8996 if (isFoldableGEP) {
8997 std::vector<Value*> Ops(CE->op_begin()+1, CE->op_end());
8998 uint64_t Offset = TD->getIndexedOffset(Ptr->getType(), Ops);
Reid Spencer2a499b02006-12-13 17:19:09 +00008999 Constant *C = ConstantInt::get(TD->getIntPtrType(), Offset);
Reid Spencer13bc5d72006-12-12 09:18:51 +00009000 return ConstantExpr::getIntToPtr(C, CE->getType());
Chris Lattner1443bc52006-05-11 17:11:52 +00009001 }
9002 }
9003
9004 return CE;
9005}
9006
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009007
9008/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
9009/// all reachable code to the worklist.
9010///
9011/// This has a couple of tricks to make the code faster and more powerful. In
9012/// particular, we constant fold and DCE instructions as we go, to avoid adding
9013/// them to the worklist (this significantly speeds up instcombine on code where
9014/// many instructions are dead or constant). Additionally, if we find a branch
9015/// whose condition is a known constant, we only visit the reachable successors.
9016///
9017static void AddReachableCodeToWorklist(BasicBlock *BB,
9018 std::set<BasicBlock*> &Visited,
Chris Lattner1443bc52006-05-11 17:11:52 +00009019 std::vector<Instruction*> &WorkList,
9020 const TargetData *TD) {
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009021 // We have now visited this block! If we've already been here, bail out.
9022 if (!Visited.insert(BB).second) return;
9023
9024 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
9025 Instruction *Inst = BBI++;
9026
9027 // DCE instruction if trivially dead.
9028 if (isInstructionTriviallyDead(Inst)) {
9029 ++NumDeadInst;
Bill Wendling5dbf43c2006-11-26 09:46:52 +00009030 DOUT << "IC: DCE: " << *Inst;
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009031 Inst->eraseFromParent();
9032 continue;
9033 }
9034
9035 // ConstantProp instruction if trivially constant.
9036 if (Constant *C = ConstantFoldInstruction(Inst)) {
Chris Lattner1443bc52006-05-11 17:11:52 +00009037 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
9038 C = OptimizeConstantExpr(CE, TD);
Bill Wendling5dbf43c2006-11-26 09:46:52 +00009039 DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009040 Inst->replaceAllUsesWith(C);
9041 ++NumConstProp;
9042 Inst->eraseFromParent();
9043 continue;
9044 }
9045
9046 WorkList.push_back(Inst);
9047 }
9048
9049 // Recursively visit successors. If this is a branch or switch on a constant,
9050 // only visit the reachable successor.
9051 TerminatorInst *TI = BB->getTerminator();
9052 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
9053 if (BI->isConditional() && isa<ConstantBool>(BI->getCondition())) {
9054 bool CondVal = cast<ConstantBool>(BI->getCondition())->getValue();
Chris Lattner1443bc52006-05-11 17:11:52 +00009055 AddReachableCodeToWorklist(BI->getSuccessor(!CondVal), Visited, WorkList,
9056 TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009057 return;
9058 }
9059 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
9060 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
9061 // See if this is an explicit destination.
9062 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
9063 if (SI->getCaseValue(i) == Cond) {
Chris Lattner1443bc52006-05-11 17:11:52 +00009064 AddReachableCodeToWorklist(SI->getSuccessor(i), Visited, WorkList,TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009065 return;
9066 }
9067
9068 // Otherwise it is the default destination.
Chris Lattner1443bc52006-05-11 17:11:52 +00009069 AddReachableCodeToWorklist(SI->getSuccessor(0), Visited, WorkList, TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009070 return;
9071 }
9072 }
9073
9074 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
Chris Lattner1443bc52006-05-11 17:11:52 +00009075 AddReachableCodeToWorklist(TI->getSuccessor(i), Visited, WorkList, TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009076}
9077
Chris Lattner113f4f42002-06-25 16:13:24 +00009078bool InstCombiner::runOnFunction(Function &F) {
Chris Lattner260ab202002-04-18 17:39:14 +00009079 bool Changed = false;
Chris Lattnerf4ad1652003-11-02 05:57:39 +00009080 TD = &getAnalysis<TargetData>();
Chris Lattnerca081252001-12-14 16:52:21 +00009081
Chris Lattner4ed40f72005-07-07 20:40:38 +00009082 {
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009083 // Do a depth-first traversal of the function, populate the worklist with
9084 // the reachable instructions. Ignore blocks that are not reachable. Keep
9085 // track of which blocks we visit.
Chris Lattner4ed40f72005-07-07 20:40:38 +00009086 std::set<BasicBlock*> Visited;
Chris Lattner1443bc52006-05-11 17:11:52 +00009087 AddReachableCodeToWorklist(F.begin(), Visited, WorkList, TD);
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00009088
Chris Lattner4ed40f72005-07-07 20:40:38 +00009089 // Do a quick scan over the function. If we find any blocks that are
9090 // unreachable, remove any instructions inside of them. This prevents
9091 // the instcombine code from having to deal with some bad special cases.
9092 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
9093 if (!Visited.count(BB)) {
9094 Instruction *Term = BB->getTerminator();
9095 while (Term != BB->begin()) { // Remove instrs bottom-up
9096 BasicBlock::iterator I = Term; --I;
Chris Lattner2d3a7a62004-04-27 15:13:33 +00009097
Bill Wendling5dbf43c2006-11-26 09:46:52 +00009098 DOUT << "IC: DCE: " << *I;
Chris Lattner4ed40f72005-07-07 20:40:38 +00009099 ++NumDeadInst;
9100
9101 if (!I->use_empty())
9102 I->replaceAllUsesWith(UndefValue::get(I->getType()));
9103 I->eraseFromParent();
9104 }
9105 }
9106 }
Chris Lattnerca081252001-12-14 16:52:21 +00009107
9108 while (!WorkList.empty()) {
9109 Instruction *I = WorkList.back(); // Get an instruction from the worklist
9110 WorkList.pop_back();
9111
Chris Lattner1443bc52006-05-11 17:11:52 +00009112 // Check to see if we can DCE the instruction.
Chris Lattner99f48c62002-09-02 04:59:56 +00009113 if (isInstructionTriviallyDead(I)) {
Chris Lattner1443bc52006-05-11 17:11:52 +00009114 // Add operands to the worklist.
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009115 if (I->getNumOperands() < 4)
Chris Lattner51ea1272004-02-28 05:22:00 +00009116 AddUsesToWorkList(*I);
Chris Lattner99f48c62002-09-02 04:59:56 +00009117 ++NumDeadInst;
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009118
Bill Wendling5dbf43c2006-11-26 09:46:52 +00009119 DOUT << "IC: DCE: " << *I;
Chris Lattnercd517ff2005-01-28 19:32:01 +00009120
9121 I->eraseFromParent();
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009122 removeFromWorkList(I);
9123 continue;
9124 }
Chris Lattner99f48c62002-09-02 04:59:56 +00009125
Chris Lattner1443bc52006-05-11 17:11:52 +00009126 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattner99f48c62002-09-02 04:59:56 +00009127 if (Constant *C = ConstantFoldInstruction(I)) {
Chris Lattner1443bc52006-05-11 17:11:52 +00009128 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
9129 C = OptimizeConstantExpr(CE, TD);
Bill Wendling5dbf43c2006-11-26 09:46:52 +00009130 DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
Chris Lattnercd517ff2005-01-28 19:32:01 +00009131
Chris Lattner1443bc52006-05-11 17:11:52 +00009132 // Add operands to the worklist.
Chris Lattner51ea1272004-02-28 05:22:00 +00009133 AddUsesToWorkList(*I);
Chris Lattnerc6509f42002-12-05 22:41:53 +00009134 ReplaceInstUsesWith(*I, C);
9135
Chris Lattner99f48c62002-09-02 04:59:56 +00009136 ++NumConstProp;
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009137 I->eraseFromParent();
Chris Lattner800aaaf2003-10-07 15:17:02 +00009138 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009139 continue;
Chris Lattner99f48c62002-09-02 04:59:56 +00009140 }
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009141
Chris Lattner39c98bb2004-12-08 23:43:58 +00009142 // See if we can trivially sink this instruction to a successor basic block.
9143 if (I->hasOneUse()) {
9144 BasicBlock *BB = I->getParent();
9145 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
9146 if (UserParent != BB) {
9147 bool UserIsSuccessor = false;
9148 // See if the user is one of our successors.
9149 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
9150 if (*SI == UserParent) {
9151 UserIsSuccessor = true;
9152 break;
9153 }
9154
9155 // If the user is one of our immediate successors, and if that successor
9156 // only has us as a predecessors (we'd have to split the critical edge
9157 // otherwise), we can keep going.
9158 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
9159 next(pred_begin(UserParent)) == pred_end(UserParent))
9160 // Okay, the CFG is simple enough, try to sink this instruction.
9161 Changed |= TryToSinkInstruction(I, UserParent);
9162 }
9163 }
9164
Chris Lattnerca081252001-12-14 16:52:21 +00009165 // Now that we have an instruction, try combining it to simplify it...
Chris Lattnerae7a0d32002-08-02 19:29:35 +00009166 if (Instruction *Result = visit(*I)) {
Chris Lattner0b18c1d2002-05-10 15:38:35 +00009167 ++NumCombined;
Chris Lattner260ab202002-04-18 17:39:14 +00009168 // Should we replace the old instruction with a new one?
Chris Lattner053c0932002-05-14 15:24:07 +00009169 if (Result != I) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +00009170 DOUT << "IC: Old = " << *I
9171 << " New = " << *Result;
Chris Lattner7d2a5392004-03-13 23:54:27 +00009172
Chris Lattner396dbfe2004-06-09 05:08:07 +00009173 // Everything uses the new instruction now.
9174 I->replaceAllUsesWith(Result);
9175
9176 // Push the new instruction and any users onto the worklist.
9177 WorkList.push_back(Result);
9178 AddUsersToWorkList(*Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009179
9180 // Move the name to the new instruction first...
9181 std::string OldName = I->getName(); I->setName("");
Chris Lattner950fc782003-10-07 22:58:41 +00009182 Result->setName(OldName);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009183
9184 // Insert the new instruction into the basic block...
9185 BasicBlock *InstParent = I->getParent();
Chris Lattner7515cab2004-11-14 19:13:23 +00009186 BasicBlock::iterator InsertPos = I;
9187
9188 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
9189 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
9190 ++InsertPos;
9191
9192 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009193
Chris Lattner63d75af2004-05-01 23:27:23 +00009194 // Make sure that we reprocess all operands now that we reduced their
9195 // use counts.
Chris Lattnerb643a9e2004-05-01 23:19:52 +00009196 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
9197 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
9198 WorkList.push_back(OpI);
9199
Chris Lattner396dbfe2004-06-09 05:08:07 +00009200 // Instructions can end up on the worklist more than once. Make sure
9201 // we do not process an instruction that has been deleted.
9202 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009203
9204 // Erase the old instruction.
9205 InstParent->getInstList().erase(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00009206 } else {
Bill Wendling5dbf43c2006-11-26 09:46:52 +00009207 DOUT << "IC: MOD = " << *I;
Chris Lattner7d2a5392004-03-13 23:54:27 +00009208
Chris Lattnerae7a0d32002-08-02 19:29:35 +00009209 // If the instruction was modified, it's possible that it is now dead.
9210 // if so, remove it.
Chris Lattner63d75af2004-05-01 23:27:23 +00009211 if (isInstructionTriviallyDead(I)) {
9212 // Make sure we process all operands now that we are reducing their
9213 // use counts.
9214 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
9215 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
9216 WorkList.push_back(OpI);
Misha Brukmanb1c93172005-04-21 23:48:37 +00009217
Chris Lattner63d75af2004-05-01 23:27:23 +00009218 // Instructions may end up in the worklist more than once. Erase all
Robert Bocchinoa8352962006-01-13 22:48:06 +00009219 // occurrences of this instruction.
Chris Lattner99f48c62002-09-02 04:59:56 +00009220 removeFromWorkList(I);
Chris Lattner31f486c2005-01-31 05:36:43 +00009221 I->eraseFromParent();
Chris Lattner396dbfe2004-06-09 05:08:07 +00009222 } else {
9223 WorkList.push_back(Result);
9224 AddUsersToWorkList(*Result);
Chris Lattnerae7a0d32002-08-02 19:29:35 +00009225 }
Chris Lattner053c0932002-05-14 15:24:07 +00009226 }
Chris Lattner260ab202002-04-18 17:39:14 +00009227 Changed = true;
Chris Lattnerca081252001-12-14 16:52:21 +00009228 }
9229 }
9230
Chris Lattner260ab202002-04-18 17:39:14 +00009231 return Changed;
Chris Lattner04805fa2002-02-26 21:46:54 +00009232}
9233
Brian Gaeke38b79e82004-07-27 17:43:21 +00009234FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattner260ab202002-04-18 17:39:14 +00009235 return new InstCombiner();
Chris Lattner04805fa2002-02-26 21:46:54 +00009236}
Brian Gaeke960707c2003-11-11 22:41:34 +00009237