blob: aba50dca3e70be8333b204d6c7a57778c350832d [file] [log] [blame]
Chris Lattnere6794492002-08-12 21:17:25 +00001//===- InstructionCombining.cpp - Combine multiple instructions -----------===//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
John Criswell482202a2003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
Misha Brukmanb1c93172005-04-21 23:48:37 +00007//
John Criswell482202a2003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattnerca081252001-12-14 16:52:21 +00009//
10// InstructionCombining - Combine instructions to form fewer, simple
Chris Lattner99f48c62002-09-02 04:59:56 +000011// instructions. This pass does not modify the CFG This pass is where algebraic
12// simplification happens.
Chris Lattnerca081252001-12-14 16:52:21 +000013//
14// This pass combines things like:
Chris Lattnerdd1a86d2004-05-04 15:19:33 +000015// %Y = add int %X, 1
16// %Z = add int %Y, 1
Chris Lattnerca081252001-12-14 16:52:21 +000017// into:
Chris Lattnerdd1a86d2004-05-04 15:19:33 +000018// %Z = add int %X, 2
Chris Lattnerca081252001-12-14 16:52:21 +000019//
20// This is a simple worklist driven algorithm.
21//
Chris Lattner216c7b82003-09-10 05:29:43 +000022// This pass guarantees that the following canonicalizations are performed on
Chris Lattnerbfb1d032003-07-23 21:41:57 +000023// the program:
24// 1. If a binary operator has a constant operand, it is moved to the RHS
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +000025// 2. Bitwise operators with constant operands are always grouped so that
26// shifts are performed first, then or's, then and's, then xor's.
Reid Spencer266e42b2006-12-23 06:05:41 +000027// 3. Compare instructions are converted from <,>,<=,>= to ==,!= if possible
28// 4. All cmp instructions on boolean values are replaced with logical ops
Chris Lattnerede3fe02003-08-13 04:18:28 +000029// 5. add X, X is represented as (X*2) => (X << 1)
30// 6. Multiplies with a power-of-two constant argument are transformed into
31// shifts.
Chris Lattner7515cab2004-11-14 19:13:23 +000032// ... etc.
Chris Lattnerbfb1d032003-07-23 21:41:57 +000033//
Chris Lattnerca081252001-12-14 16:52:21 +000034//===----------------------------------------------------------------------===//
35
Chris Lattner7d2a5392004-03-13 23:54:27 +000036#define DEBUG_TYPE "instcombine"
Chris Lattnerb4cfa7f2002-05-07 20:03:00 +000037#include "llvm/Transforms/Scalar.h"
Chris Lattner00648e12004-10-12 04:52:52 +000038#include "llvm/IntrinsicInst.h"
Chris Lattner04805fa2002-02-26 21:46:54 +000039#include "llvm/Pass.h"
Chris Lattner1085bdf2002-11-04 16:18:53 +000040#include "llvm/DerivedTypes.h"
Chris Lattner0f1d8a32003-06-26 05:06:25 +000041#include "llvm/GlobalVariable.h"
Chris Lattnerf4ad1652003-11-02 05:57:39 +000042#include "llvm/Target/TargetData.h"
43#include "llvm/Transforms/Utils/BasicBlockUtils.h"
44#include "llvm/Transforms/Utils/Local.h"
Chris Lattner69193f92004-04-05 01:30:19 +000045#include "llvm/Support/CallSite.h"
Chris Lattner39c98bb2004-12-08 23:43:58 +000046#include "llvm/Support/Debug.h"
Chris Lattner69193f92004-04-05 01:30:19 +000047#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner260ab202002-04-18 17:39:14 +000048#include "llvm/Support/InstVisitor.h"
Chris Lattner22d00a82005-08-02 19:16:58 +000049#include "llvm/Support/MathExtras.h"
Chris Lattnerd4252a72004-07-30 07:50:03 +000050#include "llvm/Support/PatternMatch.h"
Chris Lattner3d27be12006-08-27 12:54:02 +000051#include "llvm/Support/Compiler.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000052#include "llvm/ADT/Statistic.h"
Chris Lattner39c98bb2004-12-08 23:43:58 +000053#include "llvm/ADT/STLExtras.h"
Chris Lattner053c0932002-05-14 15:24:07 +000054#include <algorithm>
Chris Lattner8427bff2003-12-07 01:24:23 +000055using namespace llvm;
Chris Lattnerd4252a72004-07-30 07:50:03 +000056using namespace llvm::PatternMatch;
Brian Gaeke960707c2003-11-11 22:41:34 +000057
Chris Lattner79a42ac2006-12-19 21:40:18 +000058STATISTIC(NumCombined , "Number of insts combined");
59STATISTIC(NumConstProp, "Number of constant folds");
60STATISTIC(NumDeadInst , "Number of dead inst eliminated");
61STATISTIC(NumDeadStore, "Number of dead stores eliminated");
62STATISTIC(NumSunkInst , "Number of instructions sunk");
Chris Lattnerbf3a0992002-10-01 22:38:41 +000063
Chris Lattner79a42ac2006-12-19 21:40:18 +000064namespace {
Chris Lattner4a4c7fe2006-06-28 22:08:15 +000065 class VISIBILITY_HIDDEN InstCombiner
66 : public FunctionPass,
67 public InstVisitor<InstCombiner, Instruction*> {
Chris Lattner260ab202002-04-18 17:39:14 +000068 // Worklist of all of the instructions that need to be simplified.
69 std::vector<Instruction*> WorkList;
Chris Lattnerf4ad1652003-11-02 05:57:39 +000070 TargetData *TD;
Chris Lattner260ab202002-04-18 17:39:14 +000071
Chris Lattner51ea1272004-02-28 05:22:00 +000072 /// AddUsersToWorkList - When an instruction is simplified, add all users of
73 /// the instruction to the work lists because they might get more simplified
74 /// now.
75 ///
Chris Lattner2590e512006-02-07 06:56:34 +000076 void AddUsersToWorkList(Value &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +000077 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
Chris Lattner260ab202002-04-18 17:39:14 +000078 UI != UE; ++UI)
79 WorkList.push_back(cast<Instruction>(*UI));
80 }
81
Chris Lattner51ea1272004-02-28 05:22:00 +000082 /// AddUsesToWorkList - When an instruction is simplified, add operands to
83 /// the work lists because they might get more simplified now.
84 ///
85 void AddUsesToWorkList(Instruction &I) {
86 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
87 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i)))
88 WorkList.push_back(Op);
89 }
Chris Lattner2deeaea2006-10-05 06:55:50 +000090
91 /// AddSoonDeadInstToWorklist - The specified instruction is about to become
92 /// dead. Add all of its operands to the worklist, turning them into
93 /// undef's to reduce the number of uses of those instructions.
94 ///
95 /// Return the specified operand before it is turned into an undef.
96 ///
97 Value *AddSoonDeadInstToWorklist(Instruction &I, unsigned op) {
98 Value *R = I.getOperand(op);
99
100 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
101 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i))) {
102 WorkList.push_back(Op);
103 // Set the operand to undef to drop the use.
104 I.setOperand(i, UndefValue::get(Op->getType()));
105 }
106
107 return R;
108 }
Chris Lattner51ea1272004-02-28 05:22:00 +0000109
Chris Lattner99f48c62002-09-02 04:59:56 +0000110 // removeFromWorkList - remove all instances of I from the worklist.
111 void removeFromWorkList(Instruction *I);
Chris Lattner260ab202002-04-18 17:39:14 +0000112 public:
Chris Lattner113f4f42002-06-25 16:13:24 +0000113 virtual bool runOnFunction(Function &F);
Chris Lattner260ab202002-04-18 17:39:14 +0000114
Chris Lattnerf12cc842002-04-28 21:27:06 +0000115 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnerf4ad1652003-11-02 05:57:39 +0000116 AU.addRequired<TargetData>();
Owen Andersona6968f82006-07-10 19:03:49 +0000117 AU.addPreservedID(LCSSAID);
Chris Lattner820d9712002-10-21 20:00:28 +0000118 AU.setPreservesCFG();
Chris Lattnerf12cc842002-04-28 21:27:06 +0000119 }
120
Chris Lattner69193f92004-04-05 01:30:19 +0000121 TargetData &getTargetData() const { return *TD; }
122
Chris Lattner260ab202002-04-18 17:39:14 +0000123 // Visitation implementation - Implement instruction combining for different
124 // instruction types. The semantics are as follows:
125 // Return Value:
126 // null - No change was made
Chris Lattnere6794492002-08-12 21:17:25 +0000127 // I - Change was made, I is still valid, I may be dead though
Chris Lattner260ab202002-04-18 17:39:14 +0000128 // otherwise - Change was made, replace I with returned instruction
Misha Brukmanb1c93172005-04-21 23:48:37 +0000129 //
Chris Lattner113f4f42002-06-25 16:13:24 +0000130 Instruction *visitAdd(BinaryOperator &I);
131 Instruction *visitSub(BinaryOperator &I);
132 Instruction *visitMul(BinaryOperator &I);
Reid Spencer7eb55b32006-11-02 01:53:59 +0000133 Instruction *visitURem(BinaryOperator &I);
134 Instruction *visitSRem(BinaryOperator &I);
135 Instruction *visitFRem(BinaryOperator &I);
136 Instruction *commonRemTransforms(BinaryOperator &I);
137 Instruction *commonIRemTransforms(BinaryOperator &I);
Reid Spencer7e80b0b2006-10-26 06:15:43 +0000138 Instruction *commonDivTransforms(BinaryOperator &I);
139 Instruction *commonIDivTransforms(BinaryOperator &I);
140 Instruction *visitUDiv(BinaryOperator &I);
141 Instruction *visitSDiv(BinaryOperator &I);
142 Instruction *visitFDiv(BinaryOperator &I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000143 Instruction *visitAnd(BinaryOperator &I);
144 Instruction *visitOr (BinaryOperator &I);
145 Instruction *visitXor(BinaryOperator &I);
Reid Spencer266e42b2006-12-23 06:05:41 +0000146 Instruction *visitFCmpInst(FCmpInst &I);
147 Instruction *visitICmpInst(ICmpInst &I);
148 Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
Chris Lattnerd1f46d32005-04-24 06:59:08 +0000149
Reid Spencer266e42b2006-12-23 06:05:41 +0000150 Instruction *FoldGEPICmp(User *GEPLHS, Value *RHS,
151 ICmpInst::Predicate Cond, Instruction &I);
Chris Lattnere8d6c602003-03-10 19:16:08 +0000152 Instruction *visitShiftInst(ShiftInst &I);
Reid Spencere0fc4df2006-10-20 07:07:24 +0000153 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Chris Lattner14553932006-01-06 07:12:35 +0000154 ShiftInst &I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000155 Instruction *commonCastTransforms(CastInst &CI);
156 Instruction *commonIntCastTransforms(CastInst &CI);
157 Instruction *visitTrunc(CastInst &CI);
158 Instruction *visitZExt(CastInst &CI);
159 Instruction *visitSExt(CastInst &CI);
160 Instruction *visitFPTrunc(CastInst &CI);
161 Instruction *visitFPExt(CastInst &CI);
162 Instruction *visitFPToUI(CastInst &CI);
163 Instruction *visitFPToSI(CastInst &CI);
164 Instruction *visitUIToFP(CastInst &CI);
165 Instruction *visitSIToFP(CastInst &CI);
166 Instruction *visitPtrToInt(CastInst &CI);
167 Instruction *visitIntToPtr(CastInst &CI);
168 Instruction *visitBitCast(CastInst &CI);
Chris Lattner411336f2005-01-19 21:50:18 +0000169 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
170 Instruction *FI);
Chris Lattnerb909e8b2004-03-12 05:52:32 +0000171 Instruction *visitSelectInst(SelectInst &CI);
Chris Lattner970c33a2003-06-19 17:00:31 +0000172 Instruction *visitCallInst(CallInst &CI);
173 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner113f4f42002-06-25 16:13:24 +0000174 Instruction *visitPHINode(PHINode &PN);
175 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Chris Lattner1085bdf2002-11-04 16:18:53 +0000176 Instruction *visitAllocationInst(AllocationInst &AI);
Chris Lattner8427bff2003-12-07 01:24:23 +0000177 Instruction *visitFreeInst(FreeInst &FI);
Chris Lattner0f1d8a32003-06-26 05:06:25 +0000178 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattner31f486c2005-01-31 05:36:43 +0000179 Instruction *visitStoreInst(StoreInst &SI);
Chris Lattner9eef8a72003-06-04 04:46:00 +0000180 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner4c9c20a2004-07-03 00:26:11 +0000181 Instruction *visitSwitchInst(SwitchInst &SI);
Chris Lattner39fac442006-04-15 01:39:45 +0000182 Instruction *visitInsertElementInst(InsertElementInst &IE);
Robert Bocchinoa8352962006-01-13 22:48:06 +0000183 Instruction *visitExtractElementInst(ExtractElementInst &EI);
Chris Lattnerfbb77a42006-04-10 22:45:52 +0000184 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
Chris Lattner260ab202002-04-18 17:39:14 +0000185
186 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner113f4f42002-06-25 16:13:24 +0000187 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000188
Chris Lattner970c33a2003-06-19 17:00:31 +0000189 private:
Chris Lattneraec3d942003-10-07 22:32:43 +0000190 Instruction *visitCallSite(CallSite CS);
Chris Lattner970c33a2003-06-19 17:00:31 +0000191 bool transformConstExprCastCall(CallSite CS);
192
Chris Lattner69193f92004-04-05 01:30:19 +0000193 public:
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000194 // InsertNewInstBefore - insert an instruction New before instruction Old
195 // in the program. Add the new instruction to the worklist.
196 //
Chris Lattner623826c2004-09-28 21:48:02 +0000197 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattner65217ff2002-08-23 18:32:43 +0000198 assert(New && New->getParent() == 0 &&
199 "New instruction already inserted into a basic block!");
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000200 BasicBlock *BB = Old.getParent();
201 BB->getInstList().insert(&Old, New); // Insert inst
202 WorkList.push_back(New); // Add to worklist
Chris Lattnere79e8542004-02-23 06:38:22 +0000203 return New;
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000204 }
205
Chris Lattner7e794272004-09-24 15:21:34 +0000206 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
207 /// This also adds the cast to the worklist. Finally, this returns the
208 /// cast.
Reid Spencer13bc5d72006-12-12 09:18:51 +0000209 Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
210 Instruction &Pos) {
Chris Lattner7e794272004-09-24 15:21:34 +0000211 if (V->getType() == Ty) return V;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000212
Chris Lattnere79d2492006-04-06 19:19:17 +0000213 if (Constant *CV = dyn_cast<Constant>(V))
Reid Spencer13bc5d72006-12-12 09:18:51 +0000214 return ConstantExpr::getCast(opc, CV, Ty);
Chris Lattnere79d2492006-04-06 19:19:17 +0000215
Reid Spencer13bc5d72006-12-12 09:18:51 +0000216 Instruction *C = CastInst::create(opc, V, Ty, V->getName(), &Pos);
Chris Lattner7e794272004-09-24 15:21:34 +0000217 WorkList.push_back(C);
218 return C;
219 }
220
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000221 // ReplaceInstUsesWith - This method is to be used when an instruction is
222 // found to be dead, replacable with another preexisting expression. Here
223 // we add all uses of I to the worklist, replace all uses of I with the new
224 // value, then return I, so that the inst combiner will know that I was
225 // modified.
226 //
227 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattner51ea1272004-02-28 05:22:00 +0000228 AddUsersToWorkList(I); // Add all modified instrs to worklist
Chris Lattner8953b902004-04-05 02:10:19 +0000229 if (&I != V) {
230 I.replaceAllUsesWith(V);
231 return &I;
232 } else {
233 // If we are replacing the instruction with itself, this must be in a
234 // segment of unreachable code, so just clobber the instruction.
Chris Lattner8ba9ec92004-10-18 02:59:09 +0000235 I.replaceAllUsesWith(UndefValue::get(I.getType()));
Chris Lattner8953b902004-04-05 02:10:19 +0000236 return &I;
237 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000238 }
Chris Lattner51ea1272004-02-28 05:22:00 +0000239
Chris Lattner2590e512006-02-07 06:56:34 +0000240 // UpdateValueUsesWith - This method is to be used when an value is
241 // found to be replacable with another preexisting expression or was
242 // updated. Here we add all uses of I to the worklist, replace all uses of
243 // I with the new value (unless the instruction was just updated), then
244 // return true, so that the inst combiner will know that I was modified.
245 //
246 bool UpdateValueUsesWith(Value *Old, Value *New) {
247 AddUsersToWorkList(*Old); // Add all modified instrs to worklist
248 if (Old != New)
249 Old->replaceAllUsesWith(New);
250 if (Instruction *I = dyn_cast<Instruction>(Old))
251 WorkList.push_back(I);
Chris Lattner5b2edb12006-02-12 08:02:11 +0000252 if (Instruction *I = dyn_cast<Instruction>(New))
253 WorkList.push_back(I);
Chris Lattner2590e512006-02-07 06:56:34 +0000254 return true;
255 }
256
Chris Lattner51ea1272004-02-28 05:22:00 +0000257 // EraseInstFromFunction - When dealing with an instruction that has side
258 // effects or produces a void value, we can't rely on DCE to delete the
259 // instruction. Instead, visit methods should return the value returned by
260 // this function.
261 Instruction *EraseInstFromFunction(Instruction &I) {
262 assert(I.use_empty() && "Cannot erase instruction that is used!");
263 AddUsesToWorkList(I);
264 removeFromWorkList(&I);
Chris Lattner95307542004-11-18 21:41:39 +0000265 I.eraseFromParent();
Chris Lattner51ea1272004-02-28 05:22:00 +0000266 return 0; // Don't do anything with FI
267 }
268
Chris Lattner3ac7c262003-08-13 20:16:26 +0000269 private:
Chris Lattnerdfae8be2003-07-24 17:35:25 +0000270 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
271 /// InsertBefore instruction. This is specialized a bit to avoid inserting
272 /// casts that are known to not do anything...
273 ///
Reid Spencer13bc5d72006-12-12 09:18:51 +0000274 Value *InsertOperandCastBefore(Instruction::CastOps opcode,
275 Value *V, const Type *DestTy,
Chris Lattnerdfae8be2003-07-24 17:35:25 +0000276 Instruction *InsertBefore);
277
Reid Spencer266e42b2006-12-23 06:05:41 +0000278 /// SimplifyCommutative - This performs a few simplifications for
279 /// commutative operators.
Chris Lattner7fb29e12003-03-11 00:12:48 +0000280 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerba1cb382003-09-19 17:17:26 +0000281
Reid Spencer266e42b2006-12-23 06:05:41 +0000282 /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
283 /// most-complex to least-complex order.
284 bool SimplifyCompare(CmpInst &I);
285
Chris Lattner0157e7f2006-02-11 09:31:47 +0000286 bool SimplifyDemandedBits(Value *V, uint64_t Mask,
287 uint64_t &KnownZero, uint64_t &KnownOne,
288 unsigned Depth = 0);
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000289
Chris Lattner2deeaea2006-10-05 06:55:50 +0000290 Value *SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
291 uint64_t &UndefElts, unsigned Depth = 0);
292
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000293 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
294 // PHI node as operand #0, see if we can fold the instruction into the PHI
295 // (which is only possible if all operands to the PHI are constants).
296 Instruction *FoldOpIntoPhi(Instruction &I);
297
Chris Lattner7515cab2004-11-14 19:13:23 +0000298 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
299 // operator and they all are only used by the PHI, PHI together their
300 // inputs, and do the operation once, to the result of the PHI.
301 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
Chris Lattnercadac0c2006-11-01 04:51:18 +0000302 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
303
304
Chris Lattnerba1cb382003-09-19 17:17:26 +0000305 Instruction *OptAndOp(Instruction *Op, ConstantIntegral *OpRHS,
306 ConstantIntegral *AndRHS, BinaryOperator &TheAnd);
Chris Lattneraf517572005-09-18 04:24:45 +0000307
308 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantIntegral *Mask,
309 bool isSub, Instruction &I);
Chris Lattner6862fbd2004-09-29 17:40:11 +0000310 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencer266e42b2006-12-23 06:05:41 +0000311 bool isSigned, bool Inside, Instruction &IB);
Chris Lattner216be912005-10-24 06:03:58 +0000312 Instruction *PromoteCastOfAllocation(CastInst &CI, AllocationInst &AI);
Chris Lattnerc482a9e2006-06-15 19:07:26 +0000313 Instruction *MatchBSwap(BinaryOperator &I);
314
Reid Spencer74a528b2006-12-13 18:21:21 +0000315 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
Chris Lattner260ab202002-04-18 17:39:14 +0000316 };
Chris Lattnerb28b6802002-07-23 18:06:35 +0000317
Chris Lattnerc2d3d312006-08-27 22:42:52 +0000318 RegisterPass<InstCombiner> X("instcombine", "Combine redundant instructions");
Chris Lattner260ab202002-04-18 17:39:14 +0000319}
320
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000321// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattner81a7a232004-10-16 18:11:37 +0000322// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000323static unsigned getComplexity(Value *V) {
324 if (isa<Instruction>(V)) {
325 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
Chris Lattner81a7a232004-10-16 18:11:37 +0000326 return 3;
327 return 4;
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000328 }
Chris Lattner81a7a232004-10-16 18:11:37 +0000329 if (isa<Argument>(V)) return 3;
330 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000331}
Chris Lattner260ab202002-04-18 17:39:14 +0000332
Chris Lattner7fb29e12003-03-11 00:12:48 +0000333// isOnlyUse - Return true if this instruction will be deleted if we stop using
334// it.
335static bool isOnlyUse(Value *V) {
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000336 return V->hasOneUse() || isa<Constant>(V);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000337}
338
Chris Lattnere79e8542004-02-23 06:38:22 +0000339// getPromotedType - Return the specified type promoted as it would be to pass
340// though a va_arg area...
341static const Type *getPromotedType(const Type *Ty) {
Chris Lattner97bfcea2004-06-17 18:16:02 +0000342 switch (Ty->getTypeID()) {
Reid Spencerc635f472006-12-31 05:48:39 +0000343 case Type::Int8TyID:
344 case Type::Int16TyID: return Type::Int32Ty;
Chris Lattnere79e8542004-02-23 06:38:22 +0000345 case Type::FloatTyID: return Type::DoubleTy;
346 default: return Ty;
347 }
348}
349
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000350/// getBitCastOperand - If the specified operand is a CastInst or a constant
351/// expression bitcast, return the operand value, otherwise return null.
352static Value *getBitCastOperand(Value *V) {
353 if (BitCastInst *I = dyn_cast<BitCastInst>(V))
Chris Lattner567b81f2005-09-13 00:40:14 +0000354 return I->getOperand(0);
355 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000356 if (CE->getOpcode() == Instruction::BitCast)
Chris Lattner567b81f2005-09-13 00:40:14 +0000357 return CE->getOperand(0);
358 return 0;
359}
360
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000361/// This function is a wrapper around CastInst::isEliminableCastPair. It
362/// simply extracts arguments and returns what that function returns.
363/// @Determine if it is valid to eliminate a Convert pair
364static Instruction::CastOps
365isEliminableCastPair(
366 const CastInst *CI, ///< The first cast instruction
367 unsigned opcode, ///< The opcode of the second cast instruction
368 const Type *DstTy, ///< The target type for the second cast instruction
369 TargetData *TD ///< The target data for pointer size
370) {
371
372 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
373 const Type *MidTy = CI->getType(); // B from above
Chris Lattner1d441ad2006-05-06 09:00:16 +0000374
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000375 // Get the opcodes of the two Cast instructions
376 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
377 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
Chris Lattner1d441ad2006-05-06 09:00:16 +0000378
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000379 return Instruction::CastOps(
380 CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
381 DstTy, TD->getIntPtrType()));
Chris Lattner1d441ad2006-05-06 09:00:16 +0000382}
383
384/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
385/// in any code being generated. It does not require codegen if V is simple
386/// enough or if the cast can be folded into other casts.
Reid Spencer266e42b2006-12-23 06:05:41 +0000387static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
388 const Type *Ty, TargetData *TD) {
Chris Lattner1d441ad2006-05-06 09:00:16 +0000389 if (V->getType() == Ty || isa<Constant>(V)) return false;
390
391 // If this is a noop cast, it isn't real codegen.
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000392 if (V->getType()->canLosslesslyBitCastTo(Ty))
Chris Lattner1d441ad2006-05-06 09:00:16 +0000393 return false;
394
Chris Lattner99155be2006-05-25 23:24:33 +0000395 // If this is another cast that can be eliminated, it isn't codegen either.
Chris Lattner1d441ad2006-05-06 09:00:16 +0000396 if (const CastInst *CI = dyn_cast<CastInst>(V))
Reid Spencer266e42b2006-12-23 06:05:41 +0000397 if (isEliminableCastPair(CI, opcode, Ty, TD))
Chris Lattner1d441ad2006-05-06 09:00:16 +0000398 return false;
399 return true;
400}
401
402/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
403/// InsertBefore instruction. This is specialized a bit to avoid inserting
404/// casts that are known to not do anything...
405///
Reid Spencer13bc5d72006-12-12 09:18:51 +0000406Value *InstCombiner::InsertOperandCastBefore(Instruction::CastOps opcode,
407 Value *V, const Type *DestTy,
Chris Lattner1d441ad2006-05-06 09:00:16 +0000408 Instruction *InsertBefore) {
409 if (V->getType() == DestTy) return V;
410 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencer13bc5d72006-12-12 09:18:51 +0000411 return ConstantExpr::getCast(opcode, C, DestTy);
Chris Lattner1d441ad2006-05-06 09:00:16 +0000412
Reid Spencer13bc5d72006-12-12 09:18:51 +0000413 return InsertCastBefore(opcode, V, DestTy, *InsertBefore);
Chris Lattner1d441ad2006-05-06 09:00:16 +0000414}
415
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000416// SimplifyCommutative - This performs a few simplifications for commutative
417// operators:
Chris Lattner260ab202002-04-18 17:39:14 +0000418//
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000419// 1. Order operands such that they are listed from right (least complex) to
420// left (most complex). This puts constants before unary operators before
421// binary operators.
422//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000423// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
424// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000425//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000426bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000427 bool Changed = false;
428 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
429 Changed = !I.swapOperands();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000430
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000431 if (!I.isAssociative()) return Changed;
432 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattner7fb29e12003-03-11 00:12:48 +0000433 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
434 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
435 if (isa<Constant>(I.getOperand(1))) {
Chris Lattner34428442003-05-27 16:40:51 +0000436 Constant *Folded = ConstantExpr::get(I.getOpcode(),
437 cast<Constant>(I.getOperand(1)),
438 cast<Constant>(Op->getOperand(1)));
Chris Lattner7fb29e12003-03-11 00:12:48 +0000439 I.setOperand(0, Op->getOperand(0));
440 I.setOperand(1, Folded);
441 return true;
442 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
443 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
444 isOnlyUse(Op) && isOnlyUse(Op1)) {
445 Constant *C1 = cast<Constant>(Op->getOperand(1));
446 Constant *C2 = cast<Constant>(Op1->getOperand(1));
447
448 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner34428442003-05-27 16:40:51 +0000449 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000450 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
451 Op1->getOperand(0),
452 Op1->getName(), &I);
453 WorkList.push_back(New);
454 I.setOperand(0, New);
455 I.setOperand(1, Folded);
456 return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000457 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000458 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000459 return Changed;
Chris Lattner260ab202002-04-18 17:39:14 +0000460}
Chris Lattnerca081252001-12-14 16:52:21 +0000461
Reid Spencer266e42b2006-12-23 06:05:41 +0000462/// SimplifyCompare - For a CmpInst this function just orders the operands
463/// so that theyare listed from right (least complex) to left (most complex).
464/// This puts constants before unary operators before binary operators.
465bool InstCombiner::SimplifyCompare(CmpInst &I) {
466 if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
467 return false;
468 I.swapOperands();
469 // Compare instructions are not associative so there's nothing else we can do.
470 return true;
471}
472
Chris Lattnerbb74e222003-03-10 23:06:50 +0000473// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
474// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattner9fa53de2002-05-06 16:49:18 +0000475//
Chris Lattnerbb74e222003-03-10 23:06:50 +0000476static inline Value *dyn_castNegVal(Value *V) {
477 if (BinaryOperator::isNeg(V))
Chris Lattnerd6f636a2005-04-24 07:30:14 +0000478 return BinaryOperator::getNegArgument(V);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000479
Chris Lattner9ad0d552004-12-14 20:08:06 +0000480 // Constants can be considered to be negated values if they can be folded.
481 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
482 return ConstantExpr::getNeg(C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000483 return 0;
Chris Lattner9fa53de2002-05-06 16:49:18 +0000484}
485
Chris Lattnerbb74e222003-03-10 23:06:50 +0000486static inline Value *dyn_castNotVal(Value *V) {
487 if (BinaryOperator::isNot(V))
Chris Lattnerd6f636a2005-04-24 07:30:14 +0000488 return BinaryOperator::getNotArgument(V);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000489
490 // Constants can be considered to be not'ed values...
Chris Lattnerdd65d862003-04-30 22:34:06 +0000491 if (ConstantIntegral *C = dyn_cast<ConstantIntegral>(V))
Chris Lattnerc8e7e292004-06-10 02:12:35 +0000492 return ConstantExpr::getNot(C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000493 return 0;
494}
495
Chris Lattner7fb29e12003-03-11 00:12:48 +0000496// dyn_castFoldableMul - If this value is a multiply that can be folded into
497// other computations (because it has a constant operand), return the
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000498// non-constant operand of the multiply, and set CST to point to the multiplier.
499// Otherwise, return null.
Chris Lattner7fb29e12003-03-11 00:12:48 +0000500//
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000501static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000502 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000503 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattner7fb29e12003-03-11 00:12:48 +0000504 if (I->getOpcode() == Instruction::Mul)
Chris Lattner970136362004-11-15 05:54:07 +0000505 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattner7fb29e12003-03-11 00:12:48 +0000506 return I->getOperand(0);
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000507 if (I->getOpcode() == Instruction::Shl)
Chris Lattner970136362004-11-15 05:54:07 +0000508 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000509 // The multiplier is really 1 << CST.
510 Constant *One = ConstantInt::get(V->getType(), 1);
511 CST = cast<ConstantInt>(ConstantExpr::getShl(One, CST));
512 return I->getOperand(0);
513 }
514 }
Chris Lattner7fb29e12003-03-11 00:12:48 +0000515 return 0;
Chris Lattner3082c5a2003-02-18 19:28:33 +0000516}
Chris Lattner31ae8632002-08-14 17:51:49 +0000517
Chris Lattner0798af32005-01-13 20:14:25 +0000518/// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
519/// expression, return it.
520static User *dyn_castGetElementPtr(Value *V) {
521 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
522 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
523 if (CE->getOpcode() == Instruction::GetElementPtr)
524 return cast<User>(V);
525 return false;
526}
527
Chris Lattner623826c2004-09-28 21:48:02 +0000528// AddOne, SubOne - Add or subtract a constant one from an integer constant...
Chris Lattner6862fbd2004-09-29 17:40:11 +0000529static ConstantInt *AddOne(ConstantInt *C) {
530 return cast<ConstantInt>(ConstantExpr::getAdd(C,
531 ConstantInt::get(C->getType(), 1)));
Chris Lattner623826c2004-09-28 21:48:02 +0000532}
Chris Lattner6862fbd2004-09-29 17:40:11 +0000533static ConstantInt *SubOne(ConstantInt *C) {
534 return cast<ConstantInt>(ConstantExpr::getSub(C,
535 ConstantInt::get(C->getType(), 1)));
Chris Lattner623826c2004-09-28 21:48:02 +0000536}
537
Chris Lattner0157e7f2006-02-11 09:31:47 +0000538/// GetConstantInType - Return a ConstantInt with the specified type and value.
539///
Chris Lattneree0f2802006-02-12 02:07:56 +0000540static ConstantIntegral *GetConstantInType(const Type *Ty, uint64_t Val) {
Reid Spencerc635f472006-12-31 05:48:39 +0000541 if (Ty->getTypeID() == Type::BoolTyID)
Chris Lattneree0f2802006-02-12 02:07:56 +0000542 return ConstantBool::get(Val);
Reid Spencerc635f472006-12-31 05:48:39 +0000543 return ConstantInt::get(Ty, Val);
Chris Lattner0157e7f2006-02-11 09:31:47 +0000544}
545
546
Chris Lattner4534dd592006-02-09 07:38:58 +0000547/// ComputeMaskedBits - Determine which of the bits specified in Mask are
548/// known to be either zero or one and return them in the KnownZero/KnownOne
549/// bitsets. This code only analyzes bits in Mask, in order to short-circuit
550/// processing.
551static void ComputeMaskedBits(Value *V, uint64_t Mask, uint64_t &KnownZero,
552 uint64_t &KnownOne, unsigned Depth = 0) {
Chris Lattner0b3557f2005-09-24 23:43:33 +0000553 // Note, we cannot consider 'undef' to be "IsZero" here. The problem is that
554 // we cannot optimize based on the assumption that it is zero without changing
Chris Lattnerc3ebf402006-02-07 07:27:52 +0000555 // it to be an explicit zero. If we don't change it to zero, other code could
Chris Lattner0b3557f2005-09-24 23:43:33 +0000556 // optimized based on the contradictory assumption that it is non-zero.
557 // Because instcombine aggressively folds operations with undef args anyway,
558 // this won't lose us code quality.
Chris Lattner4534dd592006-02-09 07:38:58 +0000559 if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(V)) {
560 // We know all of the bits for a constant!
Chris Lattner0157e7f2006-02-11 09:31:47 +0000561 KnownOne = CI->getZExtValue() & Mask;
Chris Lattner4534dd592006-02-09 07:38:58 +0000562 KnownZero = ~KnownOne & Mask;
563 return;
564 }
565
566 KnownZero = KnownOne = 0; // Don't know anything.
Chris Lattner92a68652006-02-07 08:05:22 +0000567 if (Depth == 6 || Mask == 0)
Chris Lattner4534dd592006-02-09 07:38:58 +0000568 return; // Limit search depth.
569
570 uint64_t KnownZero2, KnownOne2;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000571 Instruction *I = dyn_cast<Instruction>(V);
572 if (!I) return;
573
Chris Lattnerfb296922006-05-04 17:33:35 +0000574 Mask &= V->getType()->getIntegralTypeMask();
575
Chris Lattner0157e7f2006-02-11 09:31:47 +0000576 switch (I->getOpcode()) {
577 case Instruction::And:
578 // If either the LHS or the RHS are Zero, the result is zero.
579 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
580 Mask &= ~KnownZero;
581 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
582 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
583 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
584
585 // Output known-1 bits are only known if set in both the LHS & RHS.
586 KnownOne &= KnownOne2;
587 // Output known-0 are known to be clear if zero in either the LHS | RHS.
588 KnownZero |= KnownZero2;
589 return;
590 case Instruction::Or:
591 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
592 Mask &= ~KnownOne;
593 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
594 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
595 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
596
597 // Output known-0 bits are only known if clear in both the LHS & RHS.
598 KnownZero &= KnownZero2;
599 // Output known-1 are known to be set if set in either the LHS | RHS.
600 KnownOne |= KnownOne2;
601 return;
602 case Instruction::Xor: {
603 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
604 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
605 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
606 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
607
608 // Output known-0 bits are known if clear or set in both the LHS & RHS.
609 uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
610 // Output known-1 are known to be set if set in only one of the LHS, RHS.
611 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
612 KnownZero = KnownZeroOut;
613 return;
614 }
615 case Instruction::Select:
616 ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
617 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
618 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
619 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
620
621 // Only known if known in both the LHS and RHS.
622 KnownOne &= KnownOne2;
623 KnownZero &= KnownZero2;
624 return;
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000625 case Instruction::FPTrunc:
626 case Instruction::FPExt:
627 case Instruction::FPToUI:
628 case Instruction::FPToSI:
629 case Instruction::SIToFP:
630 case Instruction::PtrToInt:
631 case Instruction::UIToFP:
632 case Instruction::IntToPtr:
633 return; // Can't work with floating point or pointers
634 case Instruction::Trunc:
635 // All these have integer operands
636 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
637 return;
638 case Instruction::BitCast: {
Chris Lattner0157e7f2006-02-11 09:31:47 +0000639 const Type *SrcTy = I->getOperand(0)->getType();
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000640 if (SrcTy->isIntegral()) {
Chris Lattner0157e7f2006-02-11 09:31:47 +0000641 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
Chris Lattner4534dd592006-02-09 07:38:58 +0000642 return;
643 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000644 break;
645 }
646 case Instruction::ZExt: {
647 // Compute the bits in the result that are not present in the input.
648 const Type *SrcTy = I->getOperand(0)->getType();
Chris Lattner0157e7f2006-02-11 09:31:47 +0000649 uint64_t NotIn = ~SrcTy->getIntegralTypeMask();
650 uint64_t NewBits = I->getType()->getIntegralTypeMask() & NotIn;
Chris Lattner62010c42005-10-09 06:36:35 +0000651
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000652 Mask &= SrcTy->getIntegralTypeMask();
653 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
654 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
655 // The top bits are known to be zero.
656 KnownZero |= NewBits;
657 return;
658 }
659 case Instruction::SExt: {
660 // Compute the bits in the result that are not present in the input.
661 const Type *SrcTy = I->getOperand(0)->getType();
662 uint64_t NotIn = ~SrcTy->getIntegralTypeMask();
663 uint64_t NewBits = I->getType()->getIntegralTypeMask() & NotIn;
664
665 Mask &= SrcTy->getIntegralTypeMask();
666 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
667 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattner92a68652006-02-07 08:05:22 +0000668
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000669 // If the sign bit of the input is known set or clear, then we know the
670 // top bits of the result.
671 uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
672 if (KnownZero & InSignBit) { // Input sign bit known zero
673 KnownZero |= NewBits;
674 KnownOne &= ~NewBits;
675 } else if (KnownOne & InSignBit) { // Input sign bit known set
676 KnownOne |= NewBits;
677 KnownZero &= ~NewBits;
678 } else { // Input sign bit unknown
679 KnownZero &= ~NewBits;
680 KnownOne &= ~NewBits;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000681 }
682 return;
683 }
684 case Instruction::Shl:
685 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
Reid Spencere0fc4df2006-10-20 07:07:24 +0000686 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
687 uint64_t ShiftAmt = SA->getZExtValue();
688 Mask >>= ShiftAmt;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000689 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
690 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Reid Spencere0fc4df2006-10-20 07:07:24 +0000691 KnownZero <<= ShiftAmt;
692 KnownOne <<= ShiftAmt;
693 KnownZero |= (1ULL << ShiftAmt)-1; // low bits known zero.
Chris Lattner0157e7f2006-02-11 09:31:47 +0000694 return;
695 }
696 break;
Reid Spencerfdff9382006-11-08 06:47:33 +0000697 case Instruction::LShr:
Chris Lattner0157e7f2006-02-11 09:31:47 +0000698 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
Reid Spencere0fc4df2006-10-20 07:07:24 +0000699 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Chris Lattner0157e7f2006-02-11 09:31:47 +0000700 // Compute the new bits that are at the top now.
Reid Spencere0fc4df2006-10-20 07:07:24 +0000701 uint64_t ShiftAmt = SA->getZExtValue();
702 uint64_t HighBits = (1ULL << ShiftAmt)-1;
703 HighBits <<= I->getType()->getPrimitiveSizeInBits()-ShiftAmt;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000704
Reid Spencerfdff9382006-11-08 06:47:33 +0000705 // Unsigned shift right.
706 Mask <<= ShiftAmt;
707 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
708 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
709 KnownZero >>= ShiftAmt;
710 KnownOne >>= ShiftAmt;
711 KnownZero |= HighBits; // high bits known zero.
712 return;
713 }
714 break;
715 case Instruction::AShr:
716 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
717 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
718 // Compute the new bits that are at the top now.
719 uint64_t ShiftAmt = SA->getZExtValue();
720 uint64_t HighBits = (1ULL << ShiftAmt)-1;
721 HighBits <<= I->getType()->getPrimitiveSizeInBits()-ShiftAmt;
722
723 // Signed shift right.
724 Mask <<= ShiftAmt;
725 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
726 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
727 KnownZero >>= ShiftAmt;
728 KnownOne >>= ShiftAmt;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000729
Reid Spencerfdff9382006-11-08 06:47:33 +0000730 // Handle the sign bits.
731 uint64_t SignBit = 1ULL << (I->getType()->getPrimitiveSizeInBits()-1);
732 SignBit >>= ShiftAmt; // Adjust to where it is now in the mask.
Chris Lattner0157e7f2006-02-11 09:31:47 +0000733
Reid Spencerfdff9382006-11-08 06:47:33 +0000734 if (KnownZero & SignBit) { // New bits are known zero.
735 KnownZero |= HighBits;
736 } else if (KnownOne & SignBit) { // New bits are known one.
737 KnownOne |= HighBits;
Chris Lattner4534dd592006-02-09 07:38:58 +0000738 }
739 return;
Chris Lattner62010c42005-10-09 06:36:35 +0000740 }
Chris Lattner0157e7f2006-02-11 09:31:47 +0000741 break;
Chris Lattner0b3557f2005-09-24 23:43:33 +0000742 }
Chris Lattner92a68652006-02-07 08:05:22 +0000743}
744
745/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
746/// this predicate to simplify operations downstream. Mask is known to be zero
747/// for bits that V cannot have.
748static bool MaskedValueIsZero(Value *V, uint64_t Mask, unsigned Depth = 0) {
Chris Lattner4534dd592006-02-09 07:38:58 +0000749 uint64_t KnownZero, KnownOne;
750 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
751 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
752 return (KnownZero & Mask) == Mask;
Chris Lattner0b3557f2005-09-24 23:43:33 +0000753}
754
Chris Lattner0157e7f2006-02-11 09:31:47 +0000755/// ShrinkDemandedConstant - Check to see if the specified operand of the
756/// specified instruction is a constant integer. If so, check to see if there
757/// are any bits set in the constant that are not demanded. If so, shrink the
758/// constant and return true.
759static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
760 uint64_t Demanded) {
761 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
762 if (!OpC) return false;
763
764 // If there are no bits set that aren't demanded, nothing to do.
765 if ((~Demanded & OpC->getZExtValue()) == 0)
766 return false;
767
768 // This is producing any bits that are not needed, shrink the RHS.
769 uint64_t Val = Demanded & OpC->getZExtValue();
770 I->setOperand(OpNo, GetConstantInType(OpC->getType(), Val));
771 return true;
772}
773
Chris Lattneree0f2802006-02-12 02:07:56 +0000774// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
775// set of known zero and one bits, compute the maximum and minimum values that
776// could have the specified known zero and known one bits, returning them in
777// min/max.
778static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
779 uint64_t KnownZero,
780 uint64_t KnownOne,
781 int64_t &Min, int64_t &Max) {
782 uint64_t TypeBits = Ty->getIntegralTypeMask();
783 uint64_t UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
784
785 uint64_t SignBit = 1ULL << (Ty->getPrimitiveSizeInBits()-1);
786
787 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
788 // bit if it is unknown.
789 Min = KnownOne;
790 Max = KnownOne|UnknownBits;
791
792 if (SignBit & UnknownBits) { // Sign bit is unknown
793 Min |= SignBit;
794 Max &= ~SignBit;
795 }
796
797 // Sign extend the min/max values.
798 int ShAmt = 64-Ty->getPrimitiveSizeInBits();
799 Min = (Min << ShAmt) >> ShAmt;
800 Max = (Max << ShAmt) >> ShAmt;
801}
802
803// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
804// a set of known zero and one bits, compute the maximum and minimum values that
805// could have the specified known zero and known one bits, returning them in
806// min/max.
807static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
808 uint64_t KnownZero,
809 uint64_t KnownOne,
810 uint64_t &Min,
811 uint64_t &Max) {
812 uint64_t TypeBits = Ty->getIntegralTypeMask();
813 uint64_t UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
814
815 // The minimum value is when the unknown bits are all zeros.
816 Min = KnownOne;
817 // The maximum value is when the unknown bits are all ones.
818 Max = KnownOne|UnknownBits;
819}
Chris Lattner0157e7f2006-02-11 09:31:47 +0000820
821
822/// SimplifyDemandedBits - Look at V. At this point, we know that only the
823/// DemandedMask bits of the result of V are ever used downstream. If we can
824/// use this information to simplify V, do so and return true. Otherwise,
825/// analyze the expression and return a mask of KnownOne and KnownZero bits for
826/// the expression (used to simplify the caller). The KnownZero/One bits may
827/// only be accurate for those bits in the DemandedMask.
828bool InstCombiner::SimplifyDemandedBits(Value *V, uint64_t DemandedMask,
829 uint64_t &KnownZero, uint64_t &KnownOne,
Chris Lattner2590e512006-02-07 06:56:34 +0000830 unsigned Depth) {
Chris Lattner0157e7f2006-02-11 09:31:47 +0000831 if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(V)) {
832 // We know all of the bits for a constant!
833 KnownOne = CI->getZExtValue() & DemandedMask;
834 KnownZero = ~KnownOne & DemandedMask;
835 return false;
836 }
837
838 KnownZero = KnownOne = 0;
Chris Lattner2590e512006-02-07 06:56:34 +0000839 if (!V->hasOneUse()) { // Other users may use these bits.
Chris Lattner0157e7f2006-02-11 09:31:47 +0000840 if (Depth != 0) { // Not at the root.
841 // Just compute the KnownZero/KnownOne bits to simplify things downstream.
842 ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
Chris Lattner2590e512006-02-07 06:56:34 +0000843 return false;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000844 }
Chris Lattner2590e512006-02-07 06:56:34 +0000845 // If this is the root being simplified, allow it to have multiple uses,
Chris Lattner0157e7f2006-02-11 09:31:47 +0000846 // just set the DemandedMask to all bits.
847 DemandedMask = V->getType()->getIntegralTypeMask();
848 } else if (DemandedMask == 0) { // Not demanding any bits from V.
Chris Lattner92a68652006-02-07 08:05:22 +0000849 if (V != UndefValue::get(V->getType()))
850 return UpdateValueUsesWith(V, UndefValue::get(V->getType()));
851 return false;
Chris Lattner2590e512006-02-07 06:56:34 +0000852 } else if (Depth == 6) { // Limit search depth.
853 return false;
854 }
855
856 Instruction *I = dyn_cast<Instruction>(V);
857 if (!I) return false; // Only analyze instructions.
858
Chris Lattnerfb296922006-05-04 17:33:35 +0000859 DemandedMask &= V->getType()->getIntegralTypeMask();
860
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000861 uint64_t KnownZero2 = 0, KnownOne2 = 0;
Chris Lattner2590e512006-02-07 06:56:34 +0000862 switch (I->getOpcode()) {
863 default: break;
864 case Instruction::And:
Chris Lattner0157e7f2006-02-11 09:31:47 +0000865 // If either the LHS or the RHS are Zero, the result is zero.
866 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
867 KnownZero, KnownOne, Depth+1))
868 return true;
869 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
870
871 // If something is known zero on the RHS, the bits aren't demanded on the
872 // LHS.
873 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownZero,
874 KnownZero2, KnownOne2, Depth+1))
875 return true;
876 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
877
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000878 // If all of the demanded bits are known 1 on one side, return the other.
Chris Lattner0157e7f2006-02-11 09:31:47 +0000879 // These bits cannot contribute to the result of the 'and'.
880 if ((DemandedMask & ~KnownZero2 & KnownOne) == (DemandedMask & ~KnownZero2))
881 return UpdateValueUsesWith(I, I->getOperand(0));
882 if ((DemandedMask & ~KnownZero & KnownOne2) == (DemandedMask & ~KnownZero))
883 return UpdateValueUsesWith(I, I->getOperand(1));
Chris Lattner5b2edb12006-02-12 08:02:11 +0000884
885 // If all of the demanded bits in the inputs are known zeros, return zero.
886 if ((DemandedMask & (KnownZero|KnownZero2)) == DemandedMask)
887 return UpdateValueUsesWith(I, Constant::getNullValue(I->getType()));
888
Chris Lattner0157e7f2006-02-11 09:31:47 +0000889 // If the RHS is a constant, see if we can simplify it.
Chris Lattner5b2edb12006-02-12 08:02:11 +0000890 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~KnownZero2))
Chris Lattner0157e7f2006-02-11 09:31:47 +0000891 return UpdateValueUsesWith(I, I);
892
893 // Output known-1 bits are only known if set in both the LHS & RHS.
894 KnownOne &= KnownOne2;
895 // Output known-0 are known to be clear if zero in either the LHS | RHS.
896 KnownZero |= KnownZero2;
897 break;
898 case Instruction::Or:
899 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
900 KnownZero, KnownOne, Depth+1))
901 return true;
902 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
903 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownOne,
904 KnownZero2, KnownOne2, Depth+1))
905 return true;
906 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
907
908 // If all of the demanded bits are known zero on one side, return the other.
909 // These bits cannot contribute to the result of the 'or'.
Jeff Cohen0add83e2006-02-18 03:20:33 +0000910 if ((DemandedMask & ~KnownOne2 & KnownZero) == (DemandedMask & ~KnownOne2))
Chris Lattner0157e7f2006-02-11 09:31:47 +0000911 return UpdateValueUsesWith(I, I->getOperand(0));
Jeff Cohen0add83e2006-02-18 03:20:33 +0000912 if ((DemandedMask & ~KnownOne & KnownZero2) == (DemandedMask & ~KnownOne))
Chris Lattner0157e7f2006-02-11 09:31:47 +0000913 return UpdateValueUsesWith(I, I->getOperand(1));
Chris Lattner5b2edb12006-02-12 08:02:11 +0000914
915 // If all of the potentially set bits on one side are known to be set on
916 // the other side, just use the 'other' side.
917 if ((DemandedMask & (~KnownZero) & KnownOne2) ==
918 (DemandedMask & (~KnownZero)))
919 return UpdateValueUsesWith(I, I->getOperand(0));
Nate Begeman8a77efe2006-02-16 21:11:51 +0000920 if ((DemandedMask & (~KnownZero2) & KnownOne) ==
921 (DemandedMask & (~KnownZero2)))
922 return UpdateValueUsesWith(I, I->getOperand(1));
Chris Lattner0157e7f2006-02-11 09:31:47 +0000923
924 // If the RHS is a constant, see if we can simplify it.
925 if (ShrinkDemandedConstant(I, 1, DemandedMask))
926 return UpdateValueUsesWith(I, I);
927
928 // Output known-0 bits are only known if clear in both the LHS & RHS.
929 KnownZero &= KnownZero2;
930 // Output known-1 are known to be set if set in either the LHS | RHS.
931 KnownOne |= KnownOne2;
932 break;
933 case Instruction::Xor: {
934 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
935 KnownZero, KnownOne, Depth+1))
936 return true;
937 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
938 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
939 KnownZero2, KnownOne2, Depth+1))
940 return true;
941 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
942
943 // If all of the demanded bits are known zero on one side, return the other.
944 // These bits cannot contribute to the result of the 'xor'.
945 if ((DemandedMask & KnownZero) == DemandedMask)
946 return UpdateValueUsesWith(I, I->getOperand(0));
947 if ((DemandedMask & KnownZero2) == DemandedMask)
948 return UpdateValueUsesWith(I, I->getOperand(1));
949
950 // Output known-0 bits are known if clear or set in both the LHS & RHS.
951 uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
952 // Output known-1 are known to be set if set in only one of the LHS, RHS.
953 uint64_t KnownOneOut = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
954
Chris Lattner8e9a7b72006-11-27 19:55:07 +0000955 // If all of the demanded bits are known to be zero on one side or the
956 // other, turn this into an *inclusive* or.
Chris Lattner5b2edb12006-02-12 08:02:11 +0000957 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattner8e9a7b72006-11-27 19:55:07 +0000958 if ((DemandedMask & ~KnownZero & ~KnownZero2) == 0) {
959 Instruction *Or =
960 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
961 I->getName());
962 InsertNewInstBefore(Or, *I);
963 return UpdateValueUsesWith(I, Or);
Chris Lattner2590e512006-02-07 06:56:34 +0000964 }
Chris Lattner0157e7f2006-02-11 09:31:47 +0000965
Chris Lattner5b2edb12006-02-12 08:02:11 +0000966 // If all of the demanded bits on one side are known, and all of the set
967 // bits on that side are also known to be set on the other side, turn this
968 // into an AND, as we know the bits will be cleared.
969 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
970 if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask) { // all known
971 if ((KnownOne & KnownOne2) == KnownOne) {
972 Constant *AndC = GetConstantInType(I->getType(),
973 ~KnownOne & DemandedMask);
974 Instruction *And =
975 BinaryOperator::createAnd(I->getOperand(0), AndC, "tmp");
976 InsertNewInstBefore(And, *I);
977 return UpdateValueUsesWith(I, And);
978 }
979 }
980
Chris Lattner0157e7f2006-02-11 09:31:47 +0000981 // If the RHS is a constant, see if we can simplify it.
982 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
983 if (ShrinkDemandedConstant(I, 1, DemandedMask))
984 return UpdateValueUsesWith(I, I);
985
986 KnownZero = KnownZeroOut;
987 KnownOne = KnownOneOut;
988 break;
989 }
990 case Instruction::Select:
991 if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
992 KnownZero, KnownOne, Depth+1))
993 return true;
994 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
995 KnownZero2, KnownOne2, Depth+1))
996 return true;
997 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
998 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
999
1000 // If the operands are constants, see if we can simplify them.
1001 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1002 return UpdateValueUsesWith(I, I);
1003 if (ShrinkDemandedConstant(I, 2, DemandedMask))
1004 return UpdateValueUsesWith(I, I);
1005
1006 // Only known if known in both the LHS and RHS.
1007 KnownOne &= KnownOne2;
1008 KnownZero &= KnownZero2;
1009 break;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001010 case Instruction::Trunc:
1011 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1012 KnownZero, KnownOne, Depth+1))
1013 return true;
1014 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1015 break;
1016 case Instruction::BitCast:
1017 if (!I->getOperand(0)->getType()->isIntegral())
1018 return false;
Chris Lattner850465d2006-09-16 03:14:10 +00001019
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001020 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1021 KnownZero, KnownOne, Depth+1))
1022 return true;
1023 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1024 break;
1025 case Instruction::ZExt: {
1026 // Compute the bits in the result that are not present in the input.
1027 const Type *SrcTy = I->getOperand(0)->getType();
Chris Lattner0157e7f2006-02-11 09:31:47 +00001028 uint64_t NotIn = ~SrcTy->getIntegralTypeMask();
1029 uint64_t NewBits = I->getType()->getIntegralTypeMask() & NotIn;
1030
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001031 DemandedMask &= SrcTy->getIntegralTypeMask();
1032 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1033 KnownZero, KnownOne, Depth+1))
1034 return true;
1035 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1036 // The top bits are known to be zero.
1037 KnownZero |= NewBits;
1038 break;
1039 }
1040 case Instruction::SExt: {
1041 // Compute the bits in the result that are not present in the input.
1042 const Type *SrcTy = I->getOperand(0)->getType();
1043 uint64_t NotIn = ~SrcTy->getIntegralTypeMask();
1044 uint64_t NewBits = I->getType()->getIntegralTypeMask() & NotIn;
1045
1046 // Get the sign bit for the source type
1047 uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
1048 int64_t InputDemandedBits = DemandedMask & SrcTy->getIntegralTypeMask();
Chris Lattner7d852282006-02-13 22:41:07 +00001049
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001050 // If any of the sign extended bits are demanded, we know that the sign
1051 // bit is demanded.
1052 if (NewBits & DemandedMask)
1053 InputDemandedBits |= InSignBit;
Chris Lattner7d852282006-02-13 22:41:07 +00001054
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001055 if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
1056 KnownZero, KnownOne, Depth+1))
1057 return true;
1058 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattner0157e7f2006-02-11 09:31:47 +00001059
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001060 // If the sign bit of the input is known set or clear, then we know the
1061 // top bits of the result.
Chris Lattner2590e512006-02-07 06:56:34 +00001062
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001063 // If the input sign bit is known zero, or if the NewBits are not demanded
1064 // convert this into a zero extension.
1065 if ((KnownZero & InSignBit) || (NewBits & ~DemandedMask) == NewBits) {
1066 // Convert to ZExt cast
1067 CastInst *NewCast = CastInst::create(
1068 Instruction::ZExt, I->getOperand(0), I->getType(), I->getName(), I);
1069 return UpdateValueUsesWith(I, NewCast);
1070 } else if (KnownOne & InSignBit) { // Input sign bit known set
1071 KnownOne |= NewBits;
1072 KnownZero &= ~NewBits;
1073 } else { // Input sign bit unknown
1074 KnownZero &= ~NewBits;
1075 KnownOne &= ~NewBits;
Chris Lattner2590e512006-02-07 06:56:34 +00001076 }
Chris Lattner0157e7f2006-02-11 09:31:47 +00001077 break;
Chris Lattner2590e512006-02-07 06:56:34 +00001078 }
Chris Lattner6e2c15c2006-11-09 05:12:27 +00001079 case Instruction::Add:
1080 // If there is a constant on the RHS, there are a variety of xformations
1081 // we can do.
1082 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1083 // If null, this should be simplified elsewhere. Some of the xforms here
1084 // won't work if the RHS is zero.
1085 if (RHS->isNullValue())
1086 break;
1087
1088 // Figure out what the input bits are. If the top bits of the and result
1089 // are not demanded, then the add doesn't demand them from its input
1090 // either.
1091
1092 // Shift the demanded mask up so that it's at the top of the uint64_t.
1093 unsigned BitWidth = I->getType()->getPrimitiveSizeInBits();
1094 unsigned NLZ = CountLeadingZeros_64(DemandedMask << (64-BitWidth));
1095
1096 // If the top bit of the output is demanded, demand everything from the
1097 // input. Otherwise, we demand all the input bits except NLZ top bits.
1098 uint64_t InDemandedBits = ~0ULL >> 64-BitWidth+NLZ;
1099
1100 // Find information about known zero/one bits in the input.
1101 if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits,
1102 KnownZero2, KnownOne2, Depth+1))
1103 return true;
1104
1105 // If the RHS of the add has bits set that can't affect the input, reduce
1106 // the constant.
1107 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1108 return UpdateValueUsesWith(I, I);
1109
1110 // Avoid excess work.
1111 if (KnownZero2 == 0 && KnownOne2 == 0)
1112 break;
1113
1114 // Turn it into OR if input bits are zero.
1115 if ((KnownZero2 & RHS->getZExtValue()) == RHS->getZExtValue()) {
1116 Instruction *Or =
1117 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1118 I->getName());
1119 InsertNewInstBefore(Or, *I);
1120 return UpdateValueUsesWith(I, Or);
1121 }
1122
1123 // We can say something about the output known-zero and known-one bits,
1124 // depending on potential carries from the input constant and the
1125 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1126 // bits set and the RHS constant is 0x01001, then we know we have a known
1127 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1128
1129 // To compute this, we first compute the potential carry bits. These are
1130 // the bits which may be modified. I'm not aware of a better way to do
1131 // this scan.
1132 uint64_t RHSVal = RHS->getZExtValue();
1133
1134 bool CarryIn = false;
1135 uint64_t CarryBits = 0;
1136 uint64_t CurBit = 1;
1137 for (unsigned i = 0; i != BitWidth; ++i, CurBit <<= 1) {
1138 // Record the current carry in.
1139 if (CarryIn) CarryBits |= CurBit;
1140
1141 bool CarryOut;
1142
1143 // This bit has a carry out unless it is "zero + zero" or
1144 // "zero + anything" with no carry in.
1145 if ((KnownZero2 & CurBit) && ((RHSVal & CurBit) == 0)) {
1146 CarryOut = false; // 0 + 0 has no carry out, even with carry in.
1147 } else if (!CarryIn &&
1148 ((KnownZero2 & CurBit) || ((RHSVal & CurBit) == 0))) {
1149 CarryOut = false; // 0 + anything has no carry out if no carry in.
1150 } else {
1151 // Otherwise, we have to assume we have a carry out.
1152 CarryOut = true;
1153 }
1154
1155 // This stage's carry out becomes the next stage's carry-in.
1156 CarryIn = CarryOut;
1157 }
1158
1159 // Now that we know which bits have carries, compute the known-1/0 sets.
1160
1161 // Bits are known one if they are known zero in one operand and one in the
1162 // other, and there is no input carry.
1163 KnownOne = ((KnownZero2 & RHSVal) | (KnownOne2 & ~RHSVal)) & ~CarryBits;
1164
1165 // Bits are known zero if they are known zero in both operands and there
1166 // is no input carry.
1167 KnownZero = KnownZero2 & ~RHSVal & ~CarryBits;
1168 }
1169 break;
Chris Lattner2590e512006-02-07 06:56:34 +00001170 case Instruction::Shl:
Reid Spencere0fc4df2006-10-20 07:07:24 +00001171 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1172 uint64_t ShiftAmt = SA->getZExtValue();
1173 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask >> ShiftAmt,
Chris Lattner0157e7f2006-02-11 09:31:47 +00001174 KnownZero, KnownOne, Depth+1))
1175 return true;
1176 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Reid Spencere0fc4df2006-10-20 07:07:24 +00001177 KnownZero <<= ShiftAmt;
1178 KnownOne <<= ShiftAmt;
1179 KnownZero |= (1ULL << ShiftAmt) - 1; // low bits known zero.
Chris Lattner0157e7f2006-02-11 09:31:47 +00001180 }
Chris Lattner2590e512006-02-07 06:56:34 +00001181 break;
Reid Spencerfdff9382006-11-08 06:47:33 +00001182 case Instruction::LShr:
1183 // For a logical shift right
1184 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1185 unsigned ShiftAmt = SA->getZExtValue();
1186
1187 // Compute the new bits that are at the top now.
1188 uint64_t HighBits = (1ULL << ShiftAmt)-1;
1189 HighBits <<= I->getType()->getPrimitiveSizeInBits() - ShiftAmt;
1190 uint64_t TypeMask = I->getType()->getIntegralTypeMask();
1191 // Unsigned shift right.
1192 if (SimplifyDemandedBits(I->getOperand(0),
1193 (DemandedMask << ShiftAmt) & TypeMask,
1194 KnownZero, KnownOne, Depth+1))
1195 return true;
1196 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1197 KnownZero &= TypeMask;
1198 KnownOne &= TypeMask;
1199 KnownZero >>= ShiftAmt;
1200 KnownOne >>= ShiftAmt;
1201 KnownZero |= HighBits; // high bits known zero.
1202 }
1203 break;
1204 case Instruction::AShr:
Chris Lattner420c4bc2006-09-18 04:31:40 +00001205 // If this is an arithmetic shift right and only the low-bit is set, we can
1206 // always convert this into a logical shr, even if the shift amount is
1207 // variable. The low bit of the shift cannot be an input sign bit unless
1208 // the shift amount is >= the size of the datatype, which is undefined.
Reid Spencerfdff9382006-11-08 06:47:33 +00001209 if (DemandedMask == 1) {
1210 // Perform the logical shift right.
1211 Value *NewVal = new ShiftInst(Instruction::LShr, I->getOperand(0),
1212 I->getOperand(1), I->getName());
Reid Spencer00c482b2006-10-26 19:19:06 +00001213 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
Chris Lattner420c4bc2006-09-18 04:31:40 +00001214 return UpdateValueUsesWith(I, NewVal);
1215 }
1216
Reid Spencere0fc4df2006-10-20 07:07:24 +00001217 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1218 unsigned ShiftAmt = SA->getZExtValue();
Chris Lattner0157e7f2006-02-11 09:31:47 +00001219
1220 // Compute the new bits that are at the top now.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001221 uint64_t HighBits = (1ULL << ShiftAmt)-1;
1222 HighBits <<= I->getType()->getPrimitiveSizeInBits() - ShiftAmt;
Chris Lattner68e74752006-02-13 06:09:08 +00001223 uint64_t TypeMask = I->getType()->getIntegralTypeMask();
Reid Spencerfdff9382006-11-08 06:47:33 +00001224 // Signed shift right.
1225 if (SimplifyDemandedBits(I->getOperand(0),
1226 (DemandedMask << ShiftAmt) & TypeMask,
1227 KnownZero, KnownOne, Depth+1))
1228 return true;
1229 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1230 KnownZero &= TypeMask;
1231 KnownOne &= TypeMask;
1232 KnownZero >>= ShiftAmt;
1233 KnownOne >>= ShiftAmt;
Chris Lattner0157e7f2006-02-11 09:31:47 +00001234
Reid Spencerfdff9382006-11-08 06:47:33 +00001235 // Handle the sign bits.
1236 uint64_t SignBit = 1ULL << (I->getType()->getPrimitiveSizeInBits()-1);
1237 SignBit >>= ShiftAmt; // Adjust to where it is now in the mask.
Chris Lattner0157e7f2006-02-11 09:31:47 +00001238
Reid Spencerfdff9382006-11-08 06:47:33 +00001239 // If the input sign bit is known to be zero, or if none of the top bits
1240 // are demanded, turn this into an unsigned shift right.
1241 if ((KnownZero & SignBit) || (HighBits & ~DemandedMask) == HighBits) {
1242 // Perform the logical shift right.
1243 Value *NewVal = new ShiftInst(Instruction::LShr, I->getOperand(0),
1244 SA, I->getName());
1245 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1246 return UpdateValueUsesWith(I, NewVal);
1247 } else if (KnownOne & SignBit) { // New bits are known one.
1248 KnownOne |= HighBits;
Chris Lattner2590e512006-02-07 06:56:34 +00001249 }
Chris Lattner0157e7f2006-02-11 09:31:47 +00001250 }
Chris Lattner2590e512006-02-07 06:56:34 +00001251 break;
1252 }
Chris Lattner0157e7f2006-02-11 09:31:47 +00001253
1254 // If the client is only demanding bits that we know, return the known
1255 // constant.
1256 if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask)
1257 return UpdateValueUsesWith(I, GetConstantInType(I->getType(), KnownOne));
Chris Lattner2590e512006-02-07 06:56:34 +00001258 return false;
1259}
1260
Chris Lattner2deeaea2006-10-05 06:55:50 +00001261
1262/// SimplifyDemandedVectorElts - The specified value producecs a vector with
1263/// 64 or fewer elements. DemandedElts contains the set of elements that are
1264/// actually used by the caller. This method analyzes which elements of the
1265/// operand are undef and returns that information in UndefElts.
1266///
1267/// If the information about demanded elements can be used to simplify the
1268/// operation, the operation is simplified, then the resultant value is
1269/// returned. This returns null if no change was made.
1270Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1271 uint64_t &UndefElts,
1272 unsigned Depth) {
1273 unsigned VWidth = cast<PackedType>(V->getType())->getNumElements();
1274 assert(VWidth <= 64 && "Vector too wide to analyze!");
1275 uint64_t EltMask = ~0ULL >> (64-VWidth);
1276 assert(DemandedElts != EltMask && (DemandedElts & ~EltMask) == 0 &&
1277 "Invalid DemandedElts!");
1278
1279 if (isa<UndefValue>(V)) {
1280 // If the entire vector is undefined, just return this info.
1281 UndefElts = EltMask;
1282 return 0;
1283 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1284 UndefElts = EltMask;
1285 return UndefValue::get(V->getType());
1286 }
1287
1288 UndefElts = 0;
1289 if (ConstantPacked *CP = dyn_cast<ConstantPacked>(V)) {
1290 const Type *EltTy = cast<PackedType>(V->getType())->getElementType();
1291 Constant *Undef = UndefValue::get(EltTy);
1292
1293 std::vector<Constant*> Elts;
1294 for (unsigned i = 0; i != VWidth; ++i)
1295 if (!(DemandedElts & (1ULL << i))) { // If not demanded, set to undef.
1296 Elts.push_back(Undef);
1297 UndefElts |= (1ULL << i);
1298 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1299 Elts.push_back(Undef);
1300 UndefElts |= (1ULL << i);
1301 } else { // Otherwise, defined.
1302 Elts.push_back(CP->getOperand(i));
1303 }
1304
1305 // If we changed the constant, return it.
1306 Constant *NewCP = ConstantPacked::get(Elts);
1307 return NewCP != CP ? NewCP : 0;
1308 } else if (isa<ConstantAggregateZero>(V)) {
1309 // Simplify the CAZ to a ConstantPacked where the non-demanded elements are
1310 // set to undef.
1311 const Type *EltTy = cast<PackedType>(V->getType())->getElementType();
1312 Constant *Zero = Constant::getNullValue(EltTy);
1313 Constant *Undef = UndefValue::get(EltTy);
1314 std::vector<Constant*> Elts;
1315 for (unsigned i = 0; i != VWidth; ++i)
1316 Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1317 UndefElts = DemandedElts ^ EltMask;
1318 return ConstantPacked::get(Elts);
1319 }
1320
1321 if (!V->hasOneUse()) { // Other users may use these bits.
1322 if (Depth != 0) { // Not at the root.
1323 // TODO: Just compute the UndefElts information recursively.
1324 return false;
1325 }
1326 return false;
1327 } else if (Depth == 10) { // Limit search depth.
1328 return false;
1329 }
1330
1331 Instruction *I = dyn_cast<Instruction>(V);
1332 if (!I) return false; // Only analyze instructions.
1333
1334 bool MadeChange = false;
1335 uint64_t UndefElts2;
1336 Value *TmpV;
1337 switch (I->getOpcode()) {
1338 default: break;
1339
1340 case Instruction::InsertElement: {
1341 // If this is a variable index, we don't know which element it overwrites.
1342 // demand exactly the same input as we produce.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001343 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
Chris Lattner2deeaea2006-10-05 06:55:50 +00001344 if (Idx == 0) {
1345 // Note that we can't propagate undef elt info, because we don't know
1346 // which elt is getting updated.
1347 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1348 UndefElts2, Depth+1);
1349 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1350 break;
1351 }
1352
1353 // If this is inserting an element that isn't demanded, remove this
1354 // insertelement.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001355 unsigned IdxNo = Idx->getZExtValue();
Chris Lattner2deeaea2006-10-05 06:55:50 +00001356 if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1357 return AddSoonDeadInstToWorklist(*I, 0);
1358
1359 // Otherwise, the element inserted overwrites whatever was there, so the
1360 // input demanded set is simpler than the output set.
1361 TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1362 DemandedElts & ~(1ULL << IdxNo),
1363 UndefElts, Depth+1);
1364 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1365
1366 // The inserted element is defined.
1367 UndefElts |= 1ULL << IdxNo;
1368 break;
1369 }
1370
1371 case Instruction::And:
1372 case Instruction::Or:
1373 case Instruction::Xor:
1374 case Instruction::Add:
1375 case Instruction::Sub:
1376 case Instruction::Mul:
1377 // div/rem demand all inputs, because they don't want divide by zero.
1378 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1379 UndefElts, Depth+1);
1380 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1381 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1382 UndefElts2, Depth+1);
1383 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1384
1385 // Output elements are undefined if both are undefined. Consider things
1386 // like undef&0. The result is known zero, not undef.
1387 UndefElts &= UndefElts2;
1388 break;
1389
1390 case Instruction::Call: {
1391 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1392 if (!II) break;
1393 switch (II->getIntrinsicID()) {
1394 default: break;
1395
1396 // Binary vector operations that work column-wise. A dest element is a
1397 // function of the corresponding input elements from the two inputs.
1398 case Intrinsic::x86_sse_sub_ss:
1399 case Intrinsic::x86_sse_mul_ss:
1400 case Intrinsic::x86_sse_min_ss:
1401 case Intrinsic::x86_sse_max_ss:
1402 case Intrinsic::x86_sse2_sub_sd:
1403 case Intrinsic::x86_sse2_mul_sd:
1404 case Intrinsic::x86_sse2_min_sd:
1405 case Intrinsic::x86_sse2_max_sd:
1406 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1407 UndefElts, Depth+1);
1408 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1409 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1410 UndefElts2, Depth+1);
1411 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1412
1413 // If only the low elt is demanded and this is a scalarizable intrinsic,
1414 // scalarize it now.
1415 if (DemandedElts == 1) {
1416 switch (II->getIntrinsicID()) {
1417 default: break;
1418 case Intrinsic::x86_sse_sub_ss:
1419 case Intrinsic::x86_sse_mul_ss:
1420 case Intrinsic::x86_sse2_sub_sd:
1421 case Intrinsic::x86_sse2_mul_sd:
1422 // TODO: Lower MIN/MAX/ABS/etc
1423 Value *LHS = II->getOperand(1);
1424 Value *RHS = II->getOperand(2);
1425 // Extract the element as scalars.
1426 LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1427 RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1428
1429 switch (II->getIntrinsicID()) {
1430 default: assert(0 && "Case stmts out of sync!");
1431 case Intrinsic::x86_sse_sub_ss:
1432 case Intrinsic::x86_sse2_sub_sd:
1433 TmpV = InsertNewInstBefore(BinaryOperator::createSub(LHS, RHS,
1434 II->getName()), *II);
1435 break;
1436 case Intrinsic::x86_sse_mul_ss:
1437 case Intrinsic::x86_sse2_mul_sd:
1438 TmpV = InsertNewInstBefore(BinaryOperator::createMul(LHS, RHS,
1439 II->getName()), *II);
1440 break;
1441 }
1442
1443 Instruction *New =
1444 new InsertElementInst(UndefValue::get(II->getType()), TmpV, 0U,
1445 II->getName());
1446 InsertNewInstBefore(New, *II);
1447 AddSoonDeadInstToWorklist(*II, 0);
1448 return New;
1449 }
1450 }
1451
1452 // Output elements are undefined if both are undefined. Consider things
1453 // like undef&0. The result is known zero, not undef.
1454 UndefElts &= UndefElts2;
1455 break;
1456 }
1457 break;
1458 }
1459 }
1460 return MadeChange ? I : 0;
1461}
1462
Reid Spencer266e42b2006-12-23 06:05:41 +00001463/// @returns true if the specified compare instruction is
1464/// true when both operands are equal...
1465/// @brief Determine if the ICmpInst returns true if both operands are equal
1466static bool isTrueWhenEqual(ICmpInst &ICI) {
1467 ICmpInst::Predicate pred = ICI.getPredicate();
1468 return pred == ICmpInst::ICMP_EQ || pred == ICmpInst::ICMP_UGE ||
1469 pred == ICmpInst::ICMP_SGE || pred == ICmpInst::ICMP_ULE ||
1470 pred == ICmpInst::ICMP_SLE;
1471}
1472
1473/// @returns true if the specified compare instruction is
1474/// true when both operands are equal...
1475/// @brief Determine if the FCmpInst returns true if both operands are equal
1476static bool isTrueWhenEqual(FCmpInst &FCI) {
1477 FCmpInst::Predicate pred = FCI.getPredicate();
1478 return pred == FCmpInst::FCMP_OEQ || pred == FCmpInst::FCMP_UEQ ||
1479 pred == FCmpInst::FCMP_OGE || pred == FCmpInst::FCMP_UGE ||
1480 pred == FCmpInst::FCMP_OLE || pred == FCmpInst::FCMP_ULE;
Chris Lattner623826c2004-09-28 21:48:02 +00001481}
Chris Lattnerb8b97502003-08-13 19:01:45 +00001482
1483/// AssociativeOpt - Perform an optimization on an associative operator. This
1484/// function is designed to check a chain of associative operators for a
1485/// potential to apply a certain optimization. Since the optimization may be
1486/// applicable if the expression was reassociated, this checks the chain, then
1487/// reassociates the expression as necessary to expose the optimization
1488/// opportunity. This makes use of a special Functor, which must define
1489/// 'shouldApply' and 'apply' methods.
1490///
1491template<typename Functor>
1492Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1493 unsigned Opcode = Root.getOpcode();
1494 Value *LHS = Root.getOperand(0);
1495
1496 // Quick check, see if the immediate LHS matches...
1497 if (F.shouldApply(LHS))
1498 return F.apply(Root);
1499
1500 // Otherwise, if the LHS is not of the same opcode as the root, return.
1501 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001502 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattnerb8b97502003-08-13 19:01:45 +00001503 // Should we apply this transform to the RHS?
1504 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1505
1506 // If not to the RHS, check to see if we should apply to the LHS...
1507 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1508 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1509 ShouldApply = true;
1510 }
1511
1512 // If the functor wants to apply the optimization to the RHS of LHSI,
1513 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1514 if (ShouldApply) {
1515 BasicBlock *BB = Root.getParent();
Misha Brukmanb1c93172005-04-21 23:48:37 +00001516
Chris Lattnerb8b97502003-08-13 19:01:45 +00001517 // Now all of the instructions are in the current basic block, go ahead
1518 // and perform the reassociation.
1519 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1520
1521 // First move the selected RHS to the LHS of the root...
1522 Root.setOperand(0, LHSI->getOperand(1));
1523
1524 // Make what used to be the LHS of the root be the user of the root...
1525 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner284d3b02004-04-16 18:08:07 +00001526 if (&Root == TmpLHSI) {
Chris Lattner8953b902004-04-05 02:10:19 +00001527 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1528 return 0;
1529 }
Chris Lattner284d3b02004-04-16 18:08:07 +00001530 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattnerb8b97502003-08-13 19:01:45 +00001531 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner284d3b02004-04-16 18:08:07 +00001532 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
1533 BasicBlock::iterator ARI = &Root; ++ARI;
1534 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
1535 ARI = Root;
Chris Lattnerb8b97502003-08-13 19:01:45 +00001536
1537 // Now propagate the ExtraOperand down the chain of instructions until we
1538 // get to LHSI.
1539 while (TmpLHSI != LHSI) {
1540 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner284d3b02004-04-16 18:08:07 +00001541 // Move the instruction to immediately before the chain we are
1542 // constructing to avoid breaking dominance properties.
1543 NextLHSI->getParent()->getInstList().remove(NextLHSI);
1544 BB->getInstList().insert(ARI, NextLHSI);
1545 ARI = NextLHSI;
1546
Chris Lattnerb8b97502003-08-13 19:01:45 +00001547 Value *NextOp = NextLHSI->getOperand(1);
1548 NextLHSI->setOperand(1, ExtraOperand);
1549 TmpLHSI = NextLHSI;
1550 ExtraOperand = NextOp;
1551 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001552
Chris Lattnerb8b97502003-08-13 19:01:45 +00001553 // Now that the instructions are reassociated, have the functor perform
1554 // the transformation...
1555 return F.apply(Root);
1556 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001557
Chris Lattnerb8b97502003-08-13 19:01:45 +00001558 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1559 }
1560 return 0;
1561}
1562
1563
1564// AddRHS - Implements: X + X --> X << 1
1565struct AddRHS {
1566 Value *RHS;
1567 AddRHS(Value *rhs) : RHS(rhs) {}
1568 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1569 Instruction *apply(BinaryOperator &Add) const {
1570 return new ShiftInst(Instruction::Shl, Add.getOperand(0),
Reid Spencerc635f472006-12-31 05:48:39 +00001571 ConstantInt::get(Type::Int8Ty, 1));
Chris Lattnerb8b97502003-08-13 19:01:45 +00001572 }
1573};
1574
1575// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1576// iff C1&C2 == 0
1577struct AddMaskingAnd {
1578 Constant *C2;
1579 AddMaskingAnd(Constant *c) : C2(c) {}
1580 bool shouldApply(Value *LHS) const {
Chris Lattnerd4252a72004-07-30 07:50:03 +00001581 ConstantInt *C1;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001582 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Chris Lattnerd4252a72004-07-30 07:50:03 +00001583 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattnerb8b97502003-08-13 19:01:45 +00001584 }
1585 Instruction *apply(BinaryOperator &Add) const {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001586 return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattnerb8b97502003-08-13 19:01:45 +00001587 }
1588};
1589
Chris Lattner86102b82005-01-01 16:22:27 +00001590static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner183b3362004-04-09 19:05:30 +00001591 InstCombiner *IC) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001592 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
Chris Lattner86102b82005-01-01 16:22:27 +00001593 if (Constant *SOC = dyn_cast<Constant>(SO))
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001594 return ConstantExpr::getCast(CI->getOpcode(), SOC, I.getType());
Misha Brukmanb1c93172005-04-21 23:48:37 +00001595
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001596 return IC->InsertNewInstBefore(CastInst::create(
1597 CI->getOpcode(), SO, I.getType(), SO->getName() + ".cast"), I);
Chris Lattner86102b82005-01-01 16:22:27 +00001598 }
1599
Chris Lattner183b3362004-04-09 19:05:30 +00001600 // Figure out if the constant is the left or the right argument.
Chris Lattner86102b82005-01-01 16:22:27 +00001601 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1602 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattnerb8b97502003-08-13 19:01:45 +00001603
Chris Lattner183b3362004-04-09 19:05:30 +00001604 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1605 if (ConstIsRHS)
Chris Lattner86102b82005-01-01 16:22:27 +00001606 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1607 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner183b3362004-04-09 19:05:30 +00001608 }
1609
1610 Value *Op0 = SO, *Op1 = ConstOperand;
1611 if (!ConstIsRHS)
1612 std::swap(Op0, Op1);
1613 Instruction *New;
Chris Lattner86102b82005-01-01 16:22:27 +00001614 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1615 New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
Reid Spencer266e42b2006-12-23 06:05:41 +00001616 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1617 New = CmpInst::create(CI->getOpcode(), CI->getPredicate(), Op0, Op1,
1618 SO->getName()+".cmp");
Chris Lattner86102b82005-01-01 16:22:27 +00001619 else if (ShiftInst *SI = dyn_cast<ShiftInst>(&I))
1620 New = new ShiftInst(SI->getOpcode(), Op0, Op1, SO->getName()+".sh");
Chris Lattnerf9d96652004-04-10 19:15:56 +00001621 else {
Chris Lattner183b3362004-04-09 19:05:30 +00001622 assert(0 && "Unknown binary instruction type!");
Chris Lattnerf9d96652004-04-10 19:15:56 +00001623 abort();
1624 }
Chris Lattner86102b82005-01-01 16:22:27 +00001625 return IC->InsertNewInstBefore(New, I);
1626}
1627
1628// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1629// constant as the other operand, try to fold the binary operator into the
1630// select arguments. This also works for Cast instructions, which obviously do
1631// not have a second operand.
1632static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1633 InstCombiner *IC) {
1634 // Don't modify shared select instructions
1635 if (!SI->hasOneUse()) return 0;
1636 Value *TV = SI->getOperand(1);
1637 Value *FV = SI->getOperand(2);
1638
1639 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner374e6592005-04-21 05:43:13 +00001640 // Bool selects with constant operands can be folded to logical ops.
1641 if (SI->getType() == Type::BoolTy) return 0;
1642
Chris Lattner86102b82005-01-01 16:22:27 +00001643 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1644 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1645
1646 return new SelectInst(SI->getCondition(), SelectTrueVal,
1647 SelectFalseVal);
1648 }
1649 return 0;
Chris Lattner183b3362004-04-09 19:05:30 +00001650}
1651
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001652
1653/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1654/// node as operand #0, see if we can fold the instruction into the PHI (which
1655/// is only possible if all operands to the PHI are constants).
1656Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1657 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattner7515cab2004-11-14 19:13:23 +00001658 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner04689872006-09-09 22:02:56 +00001659 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001660
Chris Lattner04689872006-09-09 22:02:56 +00001661 // Check to see if all of the operands of the PHI are constants. If there is
1662 // one non-constant value, remember the BB it is. If there is more than one
1663 // bail out.
1664 BasicBlock *NonConstBB = 0;
1665 for (unsigned i = 0; i != NumPHIValues; ++i)
1666 if (!isa<Constant>(PN->getIncomingValue(i))) {
1667 if (NonConstBB) return 0; // More than one non-const value.
1668 NonConstBB = PN->getIncomingBlock(i);
1669
1670 // If the incoming non-constant value is in I's block, we have an infinite
1671 // loop.
1672 if (NonConstBB == I.getParent())
1673 return 0;
1674 }
1675
1676 // If there is exactly one non-constant value, we can insert a copy of the
1677 // operation in that block. However, if this is a critical edge, we would be
1678 // inserting the computation one some other paths (e.g. inside a loop). Only
1679 // do this if the pred block is unconditionally branching into the phi block.
1680 if (NonConstBB) {
1681 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1682 if (!BI || !BI->isUnconditional()) return 0;
1683 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001684
1685 // Okay, we can do the transformation: create the new PHI node.
1686 PHINode *NewPN = new PHINode(I.getType(), I.getName());
1687 I.setName("");
Chris Lattnerd8e20182005-01-29 00:39:08 +00001688 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001689 InsertNewInstBefore(NewPN, *PN);
1690
1691 // Next, add all of the operands to the PHI.
1692 if (I.getNumOperands() == 2) {
1693 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattner7515cab2004-11-14 19:13:23 +00001694 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner04689872006-09-09 22:02:56 +00001695 Value *InV;
1696 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencer266e42b2006-12-23 06:05:41 +00001697 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1698 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
1699 else
1700 InV = ConstantExpr::get(I.getOpcode(), InC, C);
Chris Lattner04689872006-09-09 22:02:56 +00001701 } else {
1702 assert(PN->getIncomingBlock(i) == NonConstBB);
1703 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1704 InV = BinaryOperator::create(BO->getOpcode(),
1705 PN->getIncomingValue(i), C, "phitmp",
1706 NonConstBB->getTerminator());
Reid Spencer266e42b2006-12-23 06:05:41 +00001707 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1708 InV = CmpInst::create(CI->getOpcode(),
1709 CI->getPredicate(),
1710 PN->getIncomingValue(i), C, "phitmp",
1711 NonConstBB->getTerminator());
Chris Lattner04689872006-09-09 22:02:56 +00001712 else if (ShiftInst *SI = dyn_cast<ShiftInst>(&I))
1713 InV = new ShiftInst(SI->getOpcode(),
1714 PN->getIncomingValue(i), C, "phitmp",
1715 NonConstBB->getTerminator());
1716 else
1717 assert(0 && "Unknown binop!");
1718
1719 WorkList.push_back(cast<Instruction>(InV));
1720 }
1721 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001722 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001723 } else {
1724 CastInst *CI = cast<CastInst>(&I);
1725 const Type *RetTy = CI->getType();
Chris Lattner7515cab2004-11-14 19:13:23 +00001726 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner04689872006-09-09 22:02:56 +00001727 Value *InV;
1728 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001729 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Chris Lattner04689872006-09-09 22:02:56 +00001730 } else {
1731 assert(PN->getIncomingBlock(i) == NonConstBB);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001732 InV = CastInst::create(CI->getOpcode(), PN->getIncomingValue(i),
1733 I.getType(), "phitmp",
1734 NonConstBB->getTerminator());
Chris Lattner04689872006-09-09 22:02:56 +00001735 WorkList.push_back(cast<Instruction>(InV));
1736 }
1737 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001738 }
1739 }
1740 return ReplaceInstUsesWith(I, NewPN);
1741}
1742
Chris Lattner113f4f42002-06-25 16:13:24 +00001743Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001744 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00001745 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattner9fa53de2002-05-06 16:49:18 +00001746
Chris Lattnercf4a9962004-04-10 22:01:55 +00001747 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattner81a7a232004-10-16 18:11:37 +00001748 // X + undef -> undef
1749 if (isa<UndefValue>(RHS))
1750 return ReplaceInstUsesWith(I, RHS);
1751
Chris Lattnercf4a9962004-04-10 22:01:55 +00001752 // X + 0 --> X
Chris Lattner7a002fe2006-12-02 00:13:08 +00001753 if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
Chris Lattner7fde91e2005-10-17 17:56:38 +00001754 if (RHSC->isNullValue())
1755 return ReplaceInstUsesWith(I, LHS);
Chris Lattnerda1b1522005-10-17 20:18:38 +00001756 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
1757 if (CFP->isExactlyValue(-0.0))
1758 return ReplaceInstUsesWith(I, LHS);
Chris Lattner7fde91e2005-10-17 17:56:38 +00001759 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001760
Chris Lattnercf4a9962004-04-10 22:01:55 +00001761 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattner6e2c15c2006-11-09 05:12:27 +00001762 // X + (signbit) --> X ^ signbit
Chris Lattner92a68652006-02-07 08:05:22 +00001763 uint64_t Val = CI->getZExtValue();
Chris Lattner77defba2006-02-07 07:00:41 +00001764 if (Val == (1ULL << (CI->getType()->getPrimitiveSizeInBits()-1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001765 return BinaryOperator::createXor(LHS, RHS);
Chris Lattner6e2c15c2006-11-09 05:12:27 +00001766
1767 // See if SimplifyDemandedBits can simplify this. This handles stuff like
1768 // (X & 254)+1 -> (X&254)|1
1769 uint64_t KnownZero, KnownOne;
1770 if (!isa<PackedType>(I.getType()) &&
1771 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
1772 KnownZero, KnownOne))
1773 return &I;
Chris Lattnercf4a9962004-04-10 22:01:55 +00001774 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001775
1776 if (isa<PHINode>(LHS))
1777 if (Instruction *NV = FoldOpIntoPhi(I))
1778 return NV;
Chris Lattner0b3557f2005-09-24 23:43:33 +00001779
Chris Lattner330628a2006-01-06 17:59:59 +00001780 ConstantInt *XorRHS = 0;
1781 Value *XorLHS = 0;
Chris Lattner0b3557f2005-09-24 23:43:33 +00001782 if (match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
1783 unsigned TySizeBits = I.getType()->getPrimitiveSizeInBits();
1784 int64_t RHSSExt = cast<ConstantInt>(RHSC)->getSExtValue();
1785 uint64_t RHSZExt = cast<ConstantInt>(RHSC)->getZExtValue();
1786
1787 uint64_t C0080Val = 1ULL << 31;
1788 int64_t CFF80Val = -C0080Val;
1789 unsigned Size = 32;
1790 do {
1791 if (TySizeBits > Size) {
1792 bool Found = false;
1793 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
1794 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
1795 if (RHSSExt == CFF80Val) {
1796 if (XorRHS->getZExtValue() == C0080Val)
1797 Found = true;
1798 } else if (RHSZExt == C0080Val) {
1799 if (XorRHS->getSExtValue() == CFF80Val)
1800 Found = true;
1801 }
1802 if (Found) {
1803 // This is a sign extend if the top bits are known zero.
Chris Lattner4534dd592006-02-09 07:38:58 +00001804 uint64_t Mask = ~0ULL;
Chris Lattnerc3ebf402006-02-07 07:27:52 +00001805 Mask <<= 64-(TySizeBits-Size);
Chris Lattner4534dd592006-02-09 07:38:58 +00001806 Mask &= XorLHS->getType()->getIntegralTypeMask();
Chris Lattnerc3ebf402006-02-07 07:27:52 +00001807 if (!MaskedValueIsZero(XorLHS, Mask))
Chris Lattner0b3557f2005-09-24 23:43:33 +00001808 Size = 0; // Not a sign ext, but can't be any others either.
1809 goto FoundSExt;
1810 }
1811 }
1812 Size >>= 1;
1813 C0080Val >>= Size;
1814 CFF80Val >>= Size;
1815 } while (Size >= 8);
1816
1817FoundSExt:
1818 const Type *MiddleType = 0;
1819 switch (Size) {
1820 default: break;
Reid Spencerc635f472006-12-31 05:48:39 +00001821 case 32: MiddleType = Type::Int32Ty; break;
1822 case 16: MiddleType = Type::Int16Ty; break;
1823 case 8: MiddleType = Type::Int8Ty; break;
Chris Lattner0b3557f2005-09-24 23:43:33 +00001824 }
1825 if (MiddleType) {
Reid Spencerbb65ebf2006-12-12 23:36:14 +00001826 Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
Chris Lattner0b3557f2005-09-24 23:43:33 +00001827 InsertNewInstBefore(NewTrunc, I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001828 return new SExtInst(NewTrunc, I.getType());
Chris Lattner0b3557f2005-09-24 23:43:33 +00001829 }
1830 }
Chris Lattnercf4a9962004-04-10 22:01:55 +00001831 }
Chris Lattner9fa53de2002-05-06 16:49:18 +00001832
Chris Lattnerb8b97502003-08-13 19:01:45 +00001833 // X + X --> X << 1
Robert Bocchino7b5b86c2004-07-27 21:02:21 +00001834 if (I.getType()->isInteger()) {
Chris Lattnerb8b97502003-08-13 19:01:45 +00001835 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Chris Lattner47060462005-04-07 17:14:51 +00001836
1837 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
1838 if (RHSI->getOpcode() == Instruction::Sub)
1839 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
1840 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
1841 }
1842 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
1843 if (LHSI->getOpcode() == Instruction::Sub)
1844 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
1845 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
1846 }
Robert Bocchino7b5b86c2004-07-27 21:02:21 +00001847 }
Chris Lattnerede3fe02003-08-13 04:18:28 +00001848
Chris Lattner147e9752002-05-08 22:46:53 +00001849 // -A + B --> B - A
Chris Lattnerbb74e222003-03-10 23:06:50 +00001850 if (Value *V = dyn_castNegVal(LHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001851 return BinaryOperator::createSub(RHS, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +00001852
1853 // A + -B --> A - B
Chris Lattnerbb74e222003-03-10 23:06:50 +00001854 if (!isa<Constant>(RHS))
1855 if (Value *V = dyn_castNegVal(RHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001856 return BinaryOperator::createSub(LHS, V);
Chris Lattner260ab202002-04-18 17:39:14 +00001857
Misha Brukmanb1c93172005-04-21 23:48:37 +00001858
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001859 ConstantInt *C2;
1860 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
1861 if (X == RHS) // X*C + X --> X * (C+1)
1862 return BinaryOperator::createMul(RHS, AddOne(C2));
1863
1864 // X*C1 + X*C2 --> X * (C1+C2)
1865 ConstantInt *C1;
1866 if (X == dyn_castFoldableMul(RHS, C1))
1867 return BinaryOperator::createMul(X, ConstantExpr::getAdd(C1, C2));
Chris Lattner57c8d992003-02-18 19:57:07 +00001868 }
1869
1870 // X + X*C --> X * (C+1)
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001871 if (dyn_castFoldableMul(RHS, C2) == LHS)
1872 return BinaryOperator::createMul(LHS, AddOne(C2));
1873
Chris Lattner23eb8ec2007-01-05 02:17:46 +00001874 // X + ~X --> -1 since ~X = -X-1
1875 if (dyn_castNotVal(LHS) == RHS ||
1876 dyn_castNotVal(RHS) == LHS)
1877 return ReplaceInstUsesWith(I, ConstantInt::getAllOnesValue(I.getType()));
1878
Chris Lattner57c8d992003-02-18 19:57:07 +00001879
Chris Lattnerb8b97502003-08-13 19:01:45 +00001880 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattnerd4252a72004-07-30 07:50:03 +00001881 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattner23eb8ec2007-01-05 02:17:46 +00001882 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
1883 return R;
Chris Lattner7fb29e12003-03-11 00:12:48 +00001884
Chris Lattnerb9cde762003-10-02 15:11:26 +00001885 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner330628a2006-01-06 17:59:59 +00001886 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00001887 if (match(LHS, m_Not(m_Value(X)))) { // ~X + C --> (C-1) - X
1888 Constant *C= ConstantExpr::getSub(CRHS, ConstantInt::get(I.getType(), 1));
1889 return BinaryOperator::createSub(C, X);
Chris Lattnerb9cde762003-10-02 15:11:26 +00001890 }
Chris Lattnerd4252a72004-07-30 07:50:03 +00001891
Chris Lattnerbff91d92004-10-08 05:07:56 +00001892 // (X & FF00) + xx00 -> (X+xx00) & FF00
1893 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
1894 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
1895 if (Anded == CRHS) {
1896 // See if all bits from the first bit set in the Add RHS up are included
1897 // in the mask. First, get the rightmost bit.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001898 uint64_t AddRHSV = CRHS->getZExtValue();
Chris Lattnerbff91d92004-10-08 05:07:56 +00001899
1900 // Form a mask of all bits from the lowest bit added through the top.
1901 uint64_t AddRHSHighBits = ~((AddRHSV & -AddRHSV)-1);
Chris Lattner77defba2006-02-07 07:00:41 +00001902 AddRHSHighBits &= C2->getType()->getIntegralTypeMask();
Chris Lattnerbff91d92004-10-08 05:07:56 +00001903
1904 // See if the and mask includes all of these bits.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001905 uint64_t AddRHSHighBitsAnd = AddRHSHighBits & C2->getZExtValue();
Misha Brukmanb1c93172005-04-21 23:48:37 +00001906
Chris Lattnerbff91d92004-10-08 05:07:56 +00001907 if (AddRHSHighBits == AddRHSHighBitsAnd) {
1908 // Okay, the xform is safe. Insert the new add pronto.
1909 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
1910 LHS->getName()), I);
1911 return BinaryOperator::createAnd(NewAdd, C2);
1912 }
1913 }
1914 }
1915
Chris Lattnerd4252a72004-07-30 07:50:03 +00001916 // Try to fold constant add into select arguments.
1917 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner86102b82005-01-01 16:22:27 +00001918 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattnerd4252a72004-07-30 07:50:03 +00001919 return R;
Chris Lattnerb9cde762003-10-02 15:11:26 +00001920 }
1921
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001922 // add (cast *A to intptrtype) B ->
1923 // cast (GEP (cast *A to sbyte*) B) ->
1924 // intptrtype
Andrew Lenharth4f339be2006-09-19 18:24:51 +00001925 {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001926 CastInst *CI = dyn_cast<CastInst>(LHS);
1927 Value *Other = RHS;
Andrew Lenharth4f339be2006-09-19 18:24:51 +00001928 if (!CI) {
1929 CI = dyn_cast<CastInst>(RHS);
1930 Other = LHS;
1931 }
Andrew Lenharth44cb67a2006-09-20 15:37:57 +00001932 if (CI && CI->getType()->isSized() &&
1933 (CI->getType()->getPrimitiveSize() ==
1934 TD->getIntPtrType()->getPrimitiveSize())
1935 && isa<PointerType>(CI->getOperand(0)->getType())) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00001936 Value *I2 = InsertCastBefore(Instruction::BitCast, CI->getOperand(0),
Reid Spencerc635f472006-12-31 05:48:39 +00001937 PointerType::get(Type::Int8Ty), I);
Andrew Lenharth44cb67a2006-09-20 15:37:57 +00001938 I2 = InsertNewInstBefore(new GetElementPtrInst(I2, Other, "ctg2"), I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001939 return new PtrToIntInst(I2, CI->getType());
Andrew Lenharth4f339be2006-09-19 18:24:51 +00001940 }
1941 }
1942
Chris Lattner113f4f42002-06-25 16:13:24 +00001943 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +00001944}
1945
Chris Lattnerbdb0ce02003-07-22 21:46:59 +00001946// isSignBit - Return true if the value represented by the constant only has the
1947// highest order bit set.
1948static bool isSignBit(ConstantInt *CI) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001949 unsigned NumBits = CI->getType()->getPrimitiveSizeInBits();
Reid Spencere0fc4df2006-10-20 07:07:24 +00001950 return (CI->getZExtValue() & (~0ULL >> (64-NumBits))) == (1ULL << (NumBits-1));
Chris Lattnerbdb0ce02003-07-22 21:46:59 +00001951}
1952
Chris Lattner022167f2004-03-13 00:11:49 +00001953/// RemoveNoopCast - Strip off nonconverting casts from the value.
1954///
1955static Value *RemoveNoopCast(Value *V) {
1956 if (CastInst *CI = dyn_cast<CastInst>(V)) {
1957 const Type *CTy = CI->getType();
1958 const Type *OpTy = CI->getOperand(0)->getType();
1959 if (CTy->isInteger() && OpTy->isInteger()) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001960 if (CTy->getPrimitiveSizeInBits() == OpTy->getPrimitiveSizeInBits())
Chris Lattner022167f2004-03-13 00:11:49 +00001961 return RemoveNoopCast(CI->getOperand(0));
1962 } else if (isa<PointerType>(CTy) && isa<PointerType>(OpTy))
1963 return RemoveNoopCast(CI->getOperand(0));
1964 }
1965 return V;
1966}
1967
Chris Lattner113f4f42002-06-25 16:13:24 +00001968Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +00001969 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001970
Chris Lattnere6794492002-08-12 21:17:25 +00001971 if (Op0 == Op1) // sub X, X -> 0
1972 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner260ab202002-04-18 17:39:14 +00001973
Chris Lattnere6794492002-08-12 21:17:25 +00001974 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattnerbb74e222003-03-10 23:06:50 +00001975 if (Value *V = dyn_castNegVal(Op1))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001976 return BinaryOperator::createAdd(Op0, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +00001977
Chris Lattner81a7a232004-10-16 18:11:37 +00001978 if (isa<UndefValue>(Op0))
1979 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
1980 if (isa<UndefValue>(Op1))
1981 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
1982
Chris Lattner8f2f5982003-11-05 01:06:05 +00001983 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
1984 // Replace (-1 - A) with (~A)...
Chris Lattner3082c5a2003-02-18 19:28:33 +00001985 if (C->isAllOnesValue())
1986 return BinaryOperator::createNot(Op1);
Chris Lattnerad3c4952002-05-09 01:29:19 +00001987
Chris Lattner8f2f5982003-11-05 01:06:05 +00001988 // C - ~X == X + (1+C)
Reid Spencer4fdd96c2005-06-18 17:37:34 +00001989 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00001990 if (match(Op1, m_Not(m_Value(X))))
1991 return BinaryOperator::createAdd(X,
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001992 ConstantExpr::getAdd(C, ConstantInt::get(I.getType(), 1)));
Chris Lattner92295c52004-03-12 23:53:13 +00001993 // -((uint)X >> 31) -> ((int)X >> 31)
1994 // -((int)X >> 31) -> ((uint)X >> 31)
Chris Lattner022167f2004-03-13 00:11:49 +00001995 if (C->isNullValue()) {
1996 Value *NoopCastedRHS = RemoveNoopCast(Op1);
1997 if (ShiftInst *SI = dyn_cast<ShiftInst>(NoopCastedRHS))
Reid Spencerfdff9382006-11-08 06:47:33 +00001998 if (SI->getOpcode() == Instruction::LShr) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00001999 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
Chris Lattner92295c52004-03-12 23:53:13 +00002000 // Check to see if we are shifting out everything but the sign bit.
Reid Spencere0fc4df2006-10-20 07:07:24 +00002001 if (CU->getZExtValue() ==
2002 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerfdff9382006-11-08 06:47:33 +00002003 // Ok, the transformation is safe. Insert AShr.
Reid Spencer193df252006-12-24 00:40:59 +00002004 // FIXME: Once integer types are signless, this cast should be
2005 // removed.
2006 Value *ShiftOp = SI->getOperand(0);
Reid Spencer193df252006-12-24 00:40:59 +00002007 return new ShiftInst(Instruction::AShr, ShiftOp, CU,
2008 SI->getName());
Chris Lattner92295c52004-03-12 23:53:13 +00002009 }
2010 }
Reid Spencerfdff9382006-11-08 06:47:33 +00002011 }
2012 else if (SI->getOpcode() == Instruction::AShr) {
2013 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2014 // Check to see if we are shifting out everything but the sign bit.
2015 if (CU->getZExtValue() ==
2016 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerc635f472006-12-31 05:48:39 +00002017
2018 // Ok, the transformation is safe. Insert LShr.
2019 return new ShiftInst(Instruction::LShr, SI->getOperand(0), CU,
2020 SI->getName());
Reid Spencerfdff9382006-11-08 06:47:33 +00002021 }
2022 }
2023 }
Chris Lattner022167f2004-03-13 00:11:49 +00002024 }
Chris Lattner183b3362004-04-09 19:05:30 +00002025
2026 // Try to fold constant sub into select arguments.
2027 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner86102b82005-01-01 16:22:27 +00002028 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00002029 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002030
2031 if (isa<PHINode>(Op0))
2032 if (Instruction *NV = FoldOpIntoPhi(I))
2033 return NV;
Chris Lattner8f2f5982003-11-05 01:06:05 +00002034 }
2035
Chris Lattnera9be4492005-04-07 16:15:25 +00002036 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2037 if (Op1I->getOpcode() == Instruction::Add &&
Chris Lattner7a002fe2006-12-02 00:13:08 +00002038 !Op0->getType()->isFPOrFPVector()) {
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00002039 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Chris Lattnera9be4492005-04-07 16:15:25 +00002040 return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00002041 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Chris Lattnera9be4492005-04-07 16:15:25 +00002042 return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00002043 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2044 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2045 // C1-(X+C2) --> (C1-C2)-X
2046 return BinaryOperator::createSub(ConstantExpr::getSub(CI1, CI2),
2047 Op1I->getOperand(0));
2048 }
Chris Lattnera9be4492005-04-07 16:15:25 +00002049 }
2050
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002051 if (Op1I->hasOneUse()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00002052 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2053 // is not used by anyone else...
2054 //
Chris Lattnerc2f0aa52004-02-02 20:09:56 +00002055 if (Op1I->getOpcode() == Instruction::Sub &&
Chris Lattner7a002fe2006-12-02 00:13:08 +00002056 !Op1I->getType()->isFPOrFPVector()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00002057 // Swap the two operands of the subexpr...
2058 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2059 Op1I->setOperand(0, IIOp1);
2060 Op1I->setOperand(1, IIOp0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002061
Chris Lattner3082c5a2003-02-18 19:28:33 +00002062 // Create the new top level add instruction...
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002063 return BinaryOperator::createAdd(Op0, Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002064 }
2065
2066 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2067 //
2068 if (Op1I->getOpcode() == Instruction::And &&
2069 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2070 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2071
Chris Lattner396dbfe2004-06-09 05:08:07 +00002072 Value *NewNot =
2073 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002074 return BinaryOperator::createAnd(Op0, NewNot);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002075 }
Chris Lattner57c8d992003-02-18 19:57:07 +00002076
Reid Spencer3c514952006-10-16 23:08:08 +00002077 // 0 - (X sdiv C) -> (X sdiv -C)
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002078 if (Op1I->getOpcode() == Instruction::SDiv)
Reid Spencere0fc4df2006-10-20 07:07:24 +00002079 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002080 if (CSI->isNullValue())
Chris Lattner0aee4b72004-10-06 15:08:25 +00002081 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002082 return BinaryOperator::createSDiv(Op1I->getOperand(0),
Chris Lattner0aee4b72004-10-06 15:08:25 +00002083 ConstantExpr::getNeg(DivRHS));
2084
Chris Lattner57c8d992003-02-18 19:57:07 +00002085 // X - X*C --> X * (1-C)
Reid Spencer4fdd96c2005-06-18 17:37:34 +00002086 ConstantInt *C2 = 0;
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002087 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00002088 Constant *CP1 =
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002089 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1), C2);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002090 return BinaryOperator::createMul(Op0, CP1);
Chris Lattner57c8d992003-02-18 19:57:07 +00002091 }
Chris Lattnerad3c4952002-05-09 01:29:19 +00002092 }
Chris Lattnera9be4492005-04-07 16:15:25 +00002093 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00002094
Chris Lattner7a002fe2006-12-02 00:13:08 +00002095 if (!Op0->getType()->isFPOrFPVector())
Chris Lattner47060462005-04-07 17:14:51 +00002096 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2097 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner411336f2005-01-19 21:50:18 +00002098 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2099 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2100 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2101 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner47060462005-04-07 17:14:51 +00002102 } else if (Op0I->getOpcode() == Instruction::Sub) {
2103 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
2104 return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
Chris Lattner411336f2005-01-19 21:50:18 +00002105 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002106
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002107 ConstantInt *C1;
2108 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2109 if (X == Op1) { // X*C - X --> X * (C-1)
2110 Constant *CP1 = ConstantExpr::getSub(C1, ConstantInt::get(I.getType(),1));
2111 return BinaryOperator::createMul(Op1, CP1);
2112 }
Chris Lattner57c8d992003-02-18 19:57:07 +00002113
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002114 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
2115 if (X == dyn_castFoldableMul(Op1, C2))
2116 return BinaryOperator::createMul(Op1, ConstantExpr::getSub(C1, C2));
2117 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002118 return 0;
Chris Lattner260ab202002-04-18 17:39:14 +00002119}
2120
Reid Spencer266e42b2006-12-23 06:05:41 +00002121/// isSignBitCheck - Given an exploded icmp instruction, return true if it
Chris Lattnere79e8542004-02-23 06:38:22 +00002122/// really just returns true if the most significant (sign) bit is set.
Reid Spencer266e42b2006-12-23 06:05:41 +00002123static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS) {
2124 switch (pred) {
2125 case ICmpInst::ICMP_SLT:
2126 // True if LHS s< RHS and RHS == 0
2127 return RHS->isNullValue();
2128 case ICmpInst::ICMP_SLE:
2129 // True if LHS s<= RHS and RHS == -1
2130 return RHS->isAllOnesValue();
2131 case ICmpInst::ICMP_UGE:
2132 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2133 return RHS->getZExtValue() == (1ULL <<
2134 (RHS->getType()->getPrimitiveSizeInBits()-1));
2135 case ICmpInst::ICMP_UGT:
2136 // True if LHS u> RHS and RHS == high-bit-mask - 1
2137 return RHS->getZExtValue() ==
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002138 (1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1))-1;
Reid Spencer266e42b2006-12-23 06:05:41 +00002139 default:
2140 return false;
Chris Lattnere79e8542004-02-23 06:38:22 +00002141 }
Chris Lattnere79e8542004-02-23 06:38:22 +00002142}
2143
Chris Lattner113f4f42002-06-25 16:13:24 +00002144Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00002145 bool Changed = SimplifyCommutative(I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002146 Value *Op0 = I.getOperand(0);
Chris Lattner260ab202002-04-18 17:39:14 +00002147
Chris Lattner81a7a232004-10-16 18:11:37 +00002148 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
2149 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2150
Chris Lattnere6794492002-08-12 21:17:25 +00002151 // Simplify mul instructions with a constant RHS...
Chris Lattner3082c5a2003-02-18 19:28:33 +00002152 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2153 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerede3fe02003-08-13 04:18:28 +00002154
2155 // ((X << C1)*C2) == (X * (C2 << C1))
2156 if (ShiftInst *SI = dyn_cast<ShiftInst>(Op0))
2157 if (SI->getOpcode() == Instruction::Shl)
2158 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002159 return BinaryOperator::createMul(SI->getOperand(0),
2160 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanb1c93172005-04-21 23:48:37 +00002161
Chris Lattnercce81be2003-09-11 22:24:54 +00002162 if (CI->isNullValue())
2163 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2164 if (CI->equalsInt(1)) // X * 1 == X
2165 return ReplaceInstUsesWith(I, Op0);
2166 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Chris Lattner35236d82003-06-25 17:09:20 +00002167 return BinaryOperator::createNeg(Op0, I.getName());
Chris Lattner31ba1292002-04-29 22:24:47 +00002168
Reid Spencere0fc4df2006-10-20 07:07:24 +00002169 int64_t Val = (int64_t)cast<ConstantInt>(CI)->getZExtValue();
Chris Lattner22d00a82005-08-02 19:16:58 +00002170 if (isPowerOf2_64(Val)) { // Replace X*(2^C) with X << C
2171 uint64_t C = Log2_64(Val);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002172 return new ShiftInst(Instruction::Shl, Op0,
Reid Spencerc635f472006-12-31 05:48:39 +00002173 ConstantInt::get(Type::Int8Ty, C));
Chris Lattner22d00a82005-08-02 19:16:58 +00002174 }
Robert Bocchino7b5b86c2004-07-27 21:02:21 +00002175 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00002176 if (Op1F->isNullValue())
2177 return ReplaceInstUsesWith(I, Op1);
Chris Lattner31ba1292002-04-29 22:24:47 +00002178
Chris Lattner3082c5a2003-02-18 19:28:33 +00002179 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2180 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2181 if (Op1F->getValue() == 1.0)
2182 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
2183 }
Chris Lattner32c01df2006-03-04 06:04:02 +00002184
2185 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2186 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2187 isa<ConstantInt>(Op0I->getOperand(1))) {
2188 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2189 Instruction *Add = BinaryOperator::createMul(Op0I->getOperand(0),
2190 Op1, "tmp");
2191 InsertNewInstBefore(Add, I);
2192 Value *C1C2 = ConstantExpr::getMul(Op1,
2193 cast<Constant>(Op0I->getOperand(1)));
2194 return BinaryOperator::createAdd(Add, C1C2);
2195
2196 }
Chris Lattner183b3362004-04-09 19:05:30 +00002197
2198 // Try to fold constant mul into select arguments.
2199 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00002200 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00002201 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002202
2203 if (isa<PHINode>(Op0))
2204 if (Instruction *NV = FoldOpIntoPhi(I))
2205 return NV;
Chris Lattner260ab202002-04-18 17:39:14 +00002206 }
2207
Chris Lattner934a64cf2003-03-10 23:23:04 +00002208 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
2209 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002210 return BinaryOperator::createMul(Op0v, Op1v);
Chris Lattner934a64cf2003-03-10 23:23:04 +00002211
Chris Lattner2635b522004-02-23 05:39:21 +00002212 // If one of the operands of the multiply is a cast from a boolean value, then
2213 // we know the bool is either zero or one, so this is a 'masking' multiply.
2214 // See if we can simplify things based on how the boolean was originally
2215 // formed.
2216 CastInst *BoolCast = 0;
Reid Spencer74a528b2006-12-13 18:21:21 +00002217 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(0)))
2218 if (CI->getOperand(0)->getType() == Type::BoolTy)
Chris Lattner2635b522004-02-23 05:39:21 +00002219 BoolCast = CI;
2220 if (!BoolCast)
Reid Spencer74a528b2006-12-13 18:21:21 +00002221 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
2222 if (CI->getOperand(0)->getType() == Type::BoolTy)
Chris Lattner2635b522004-02-23 05:39:21 +00002223 BoolCast = CI;
2224 if (BoolCast) {
Reid Spencer266e42b2006-12-23 06:05:41 +00002225 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
Chris Lattner2635b522004-02-23 05:39:21 +00002226 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2227 const Type *SCOpTy = SCIOp0->getType();
2228
Reid Spencer266e42b2006-12-23 06:05:41 +00002229 // If the icmp is true iff the sign bit of X is set, then convert this
Chris Lattnere79e8542004-02-23 06:38:22 +00002230 // multiply into a shift/and combination.
2231 if (isa<ConstantInt>(SCIOp1) &&
Reid Spencer266e42b2006-12-23 06:05:41 +00002232 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1))) {
Chris Lattner2635b522004-02-23 05:39:21 +00002233 // Shift the X value right to turn it into "all signbits".
Reid Spencerc635f472006-12-31 05:48:39 +00002234 Constant *Amt = ConstantInt::get(Type::Int8Ty,
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002235 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattnere79e8542004-02-23 06:38:22 +00002236 Value *V =
Reid Spencerfdff9382006-11-08 06:47:33 +00002237 InsertNewInstBefore(new ShiftInst(Instruction::AShr, SCIOp0, Amt,
Chris Lattnere79e8542004-02-23 06:38:22 +00002238 BoolCast->getOperand(0)->getName()+
2239 ".mask"), I);
Chris Lattner2635b522004-02-23 05:39:21 +00002240
2241 // If the multiply type is not the same as the source type, sign extend
2242 // or truncate to the multiply type.
Reid Spencer13bc5d72006-12-12 09:18:51 +00002243 if (I.getType() != V->getType()) {
2244 unsigned SrcBits = V->getType()->getPrimitiveSizeInBits();
2245 unsigned DstBits = I.getType()->getPrimitiveSizeInBits();
2246 Instruction::CastOps opcode =
2247 (SrcBits == DstBits ? Instruction::BitCast :
2248 (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2249 V = InsertCastBefore(opcode, V, I.getType(), I);
2250 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002251
Chris Lattner2635b522004-02-23 05:39:21 +00002252 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002253 return BinaryOperator::createAnd(V, OtherOp);
Chris Lattner2635b522004-02-23 05:39:21 +00002254 }
2255 }
2256 }
2257
Chris Lattner113f4f42002-06-25 16:13:24 +00002258 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +00002259}
2260
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002261/// This function implements the transforms on div instructions that work
2262/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2263/// used by the visitors to those instructions.
2264/// @brief Transforms common to all three div instructions
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002265Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002266 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner81a7a232004-10-16 18:11:37 +00002267
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002268 // undef / X -> 0
2269 if (isa<UndefValue>(Op0))
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002270 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002271
2272 // X / undef -> undef
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002273 if (isa<UndefValue>(Op1))
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002274 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002275
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002276 // Handle cases involving: div X, (select Cond, Y, Z)
Chris Lattnerd79dc792006-09-09 20:26:32 +00002277 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2278 // div X, (Cond ? 0 : Y) -> div X, Y. If the div and the select are in the
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002279 // same basic block, then we replace the select with Y, and the condition
2280 // of the select with false (if the cond value is in the same BB). If the
Chris Lattnerd79dc792006-09-09 20:26:32 +00002281 // select has uses other than the div, this allows them to be simplified
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002282 // also. Note that div X, Y is just as good as div X, 0 (undef)
Chris Lattnerd79dc792006-09-09 20:26:32 +00002283 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2284 if (ST->isNullValue()) {
2285 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2286 if (CondI && CondI->getParent() == I.getParent())
Chris Lattner6ab03f62006-09-28 23:35:22 +00002287 UpdateValueUsesWith(CondI, ConstantBool::getFalse());
Chris Lattnerd79dc792006-09-09 20:26:32 +00002288 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2289 I.setOperand(1, SI->getOperand(2));
2290 else
2291 UpdateValueUsesWith(SI, SI->getOperand(2));
2292 return &I;
2293 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002294
Chris Lattnerd79dc792006-09-09 20:26:32 +00002295 // Likewise for: div X, (Cond ? Y : 0) -> div X, Y
2296 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2297 if (ST->isNullValue()) {
2298 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2299 if (CondI && CondI->getParent() == I.getParent())
Chris Lattner6ab03f62006-09-28 23:35:22 +00002300 UpdateValueUsesWith(CondI, ConstantBool::getTrue());
Chris Lattnerd79dc792006-09-09 20:26:32 +00002301 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2302 I.setOperand(1, SI->getOperand(1));
2303 else
2304 UpdateValueUsesWith(SI, SI->getOperand(1));
2305 return &I;
2306 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002307 }
Chris Lattnerd79dc792006-09-09 20:26:32 +00002308
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002309 return 0;
2310}
Misha Brukmanb1c93172005-04-21 23:48:37 +00002311
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002312/// This function implements the transforms common to both integer division
2313/// instructions (udiv and sdiv). It is called by the visitors to those integer
2314/// division instructions.
2315/// @brief Common integer divide transforms
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002316Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002317 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2318
2319 if (Instruction *Common = commonDivTransforms(I))
2320 return Common;
2321
2322 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2323 // div X, 1 == X
2324 if (RHS->equalsInt(1))
2325 return ReplaceInstUsesWith(I, Op0);
2326
2327 // (X / C1) / C2 -> X / (C1*C2)
2328 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2329 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2330 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
2331 return BinaryOperator::create(I.getOpcode(), LHS->getOperand(0),
2332 ConstantExpr::getMul(RHS, LHSRHS));
Chris Lattner42362612005-04-08 04:03:26 +00002333 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002334
2335 if (!RHS->isNullValue()) { // avoid X udiv 0
2336 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2337 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2338 return R;
2339 if (isa<PHINode>(Op0))
2340 if (Instruction *NV = FoldOpIntoPhi(I))
2341 return NV;
2342 }
Chris Lattnerd79dc792006-09-09 20:26:32 +00002343 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002344
Chris Lattner3082c5a2003-02-18 19:28:33 +00002345 // 0 / X == 0, we don't need to preserve faults!
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002346 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattner3082c5a2003-02-18 19:28:33 +00002347 if (LHS->equalsInt(0))
2348 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2349
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002350 return 0;
2351}
2352
2353Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2354 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2355
2356 // Handle the integer div common cases
2357 if (Instruction *Common = commonIDivTransforms(I))
2358 return Common;
2359
2360 // X udiv C^2 -> X >> C
2361 // Check to see if this is an unsigned division with an exact power of 2,
2362 // if so, convert to a right shift.
2363 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
2364 if (uint64_t Val = C->getZExtValue()) // Don't break X / 0
2365 if (isPowerOf2_64(Val)) {
2366 uint64_t ShiftAmt = Log2_64(Val);
Reid Spencerfdff9382006-11-08 06:47:33 +00002367 return new ShiftInst(Instruction::LShr, Op0,
Reid Spencerc635f472006-12-31 05:48:39 +00002368 ConstantInt::get(Type::Int8Ty, ShiftAmt));
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002369 }
2370 }
2371
2372 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
2373 if (ShiftInst *RHSI = dyn_cast<ShiftInst>(I.getOperand(1))) {
2374 if (RHSI->getOpcode() == Instruction::Shl &&
2375 isa<ConstantInt>(RHSI->getOperand(0))) {
2376 uint64_t C1 = cast<ConstantInt>(RHSI->getOperand(0))->getZExtValue();
2377 if (isPowerOf2_64(C1)) {
2378 Value *N = RHSI->getOperand(1);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002379 const Type *NTy = N->getType();
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002380 if (uint64_t C2 = Log2_64(C1)) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002381 Constant *C2V = ConstantInt::get(NTy, C2);
2382 N = InsertNewInstBefore(BinaryOperator::createAdd(N, C2V, "tmp"), I);
Chris Lattner2e90b732006-02-05 07:54:04 +00002383 }
Reid Spencerfdff9382006-11-08 06:47:33 +00002384 return new ShiftInst(Instruction::LShr, Op0, N);
Chris Lattner2e90b732006-02-05 07:54:04 +00002385 }
2386 }
Chris Lattnerdd0c1742005-11-05 07:40:31 +00002387 }
2388
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002389 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
2390 // where C1&C2 are powers of two.
2391 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2392 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2393 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2)))
2394 if (!STO->isNullValue() && !STO->isNullValue()) {
2395 uint64_t TVA = STO->getZExtValue(), FVA = SFO->getZExtValue();
2396 if (isPowerOf2_64(TVA) && isPowerOf2_64(FVA)) {
2397 // Compute the shift amounts
2398 unsigned TSA = Log2_64(TVA), FSA = Log2_64(FVA);
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002399 // Construct the "on true" case of the select
Reid Spencerc635f472006-12-31 05:48:39 +00002400 Constant *TC = ConstantInt::get(Type::Int8Ty, TSA);
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002401 Instruction *TSI =
Reid Spencerfdff9382006-11-08 06:47:33 +00002402 new ShiftInst(Instruction::LShr, Op0, TC, SI->getName()+".t");
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002403 TSI = InsertNewInstBefore(TSI, I);
2404
2405 // Construct the "on false" case of the select
Reid Spencerc635f472006-12-31 05:48:39 +00002406 Constant *FC = ConstantInt::get(Type::Int8Ty, FSA);
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002407 Instruction *FSI =
Reid Spencerfdff9382006-11-08 06:47:33 +00002408 new ShiftInst(Instruction::LShr, Op0, FC, SI->getName()+".f");
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002409 FSI = InsertNewInstBefore(FSI, I);
2410
2411 // construct the select instruction and return it.
Reid Spencerfdff9382006-11-08 06:47:33 +00002412 return new SelectInst(SI->getOperand(0), TSI, FSI, SI->getName());
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002413 }
2414 }
2415 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002416 return 0;
2417}
2418
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002419Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
2420 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2421
2422 // Handle the integer div common cases
2423 if (Instruction *Common = commonIDivTransforms(I))
2424 return Common;
2425
2426 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2427 // sdiv X, -1 == -X
2428 if (RHS->isAllOnesValue())
2429 return BinaryOperator::createNeg(Op0);
2430
2431 // -X/C -> X/-C
2432 if (Value *LHSNeg = dyn_castNegVal(Op0))
2433 return BinaryOperator::createSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
2434 }
2435
2436 // If the sign bits of both operands are zero (i.e. we can prove they are
2437 // unsigned inputs), turn this into a udiv.
2438 if (I.getType()->isInteger()) {
2439 uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
2440 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2441 return BinaryOperator::createUDiv(Op0, Op1, I.getName());
2442 }
2443 }
2444
2445 return 0;
2446}
2447
2448Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
2449 return commonDivTransforms(I);
2450}
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002451
Chris Lattner85dda9a2006-03-02 06:50:58 +00002452/// GetFactor - If we can prove that the specified value is at least a multiple
2453/// of some factor, return that factor.
2454static Constant *GetFactor(Value *V) {
2455 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
2456 return CI;
2457
2458 // Unless we can be tricky, we know this is a multiple of 1.
2459 Constant *Result = ConstantInt::get(V->getType(), 1);
2460
2461 Instruction *I = dyn_cast<Instruction>(V);
2462 if (!I) return Result;
2463
2464 if (I->getOpcode() == Instruction::Mul) {
2465 // Handle multiplies by a constant, etc.
2466 return ConstantExpr::getMul(GetFactor(I->getOperand(0)),
2467 GetFactor(I->getOperand(1)));
2468 } else if (I->getOpcode() == Instruction::Shl) {
2469 // (X<<C) -> X * (1 << C)
2470 if (Constant *ShRHS = dyn_cast<Constant>(I->getOperand(1))) {
2471 ShRHS = ConstantExpr::getShl(Result, ShRHS);
2472 return ConstantExpr::getMul(GetFactor(I->getOperand(0)), ShRHS);
2473 }
2474 } else if (I->getOpcode() == Instruction::And) {
2475 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
2476 // X & 0xFFF0 is known to be a multiple of 16.
2477 unsigned Zeros = CountTrailingZeros_64(RHS->getZExtValue());
2478 if (Zeros != V->getType()->getPrimitiveSizeInBits())
2479 return ConstantExpr::getShl(Result,
Reid Spencerc635f472006-12-31 05:48:39 +00002480 ConstantInt::get(Type::Int8Ty, Zeros));
Chris Lattner85dda9a2006-03-02 06:50:58 +00002481 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002482 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
Chris Lattner85dda9a2006-03-02 06:50:58 +00002483 // Only handle int->int casts.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002484 if (!CI->isIntegerCast())
2485 return Result;
2486 Value *Op = CI->getOperand(0);
2487 return ConstantExpr::getCast(CI->getOpcode(), GetFactor(Op), V->getType());
Chris Lattner85dda9a2006-03-02 06:50:58 +00002488 }
2489 return Result;
2490}
2491
Reid Spencer7eb55b32006-11-02 01:53:59 +00002492/// This function implements the transforms on rem instructions that work
2493/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
2494/// is used by the visitors to those instructions.
2495/// @brief Transforms common to all three rem instructions
2496Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002497 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Reid Spencer7eb55b32006-11-02 01:53:59 +00002498
Chris Lattner0de4a8d2006-02-28 05:30:45 +00002499 // 0 % X == 0, we don't need to preserve faults!
2500 if (Constant *LHS = dyn_cast<Constant>(Op0))
2501 if (LHS->isNullValue())
2502 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2503
2504 if (isa<UndefValue>(Op0)) // undef % X -> 0
2505 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2506 if (isa<UndefValue>(Op1))
2507 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Reid Spencer7eb55b32006-11-02 01:53:59 +00002508
2509 // Handle cases involving: rem X, (select Cond, Y, Z)
2510 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2511 // rem X, (Cond ? 0 : Y) -> rem X, Y. If the rem and the select are in
2512 // the same basic block, then we replace the select with Y, and the
2513 // condition of the select with false (if the cond value is in the same
2514 // BB). If the select has uses other than the div, this allows them to be
2515 // simplified also.
2516 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2517 if (ST->isNullValue()) {
2518 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2519 if (CondI && CondI->getParent() == I.getParent())
2520 UpdateValueUsesWith(CondI, ConstantBool::getFalse());
2521 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2522 I.setOperand(1, SI->getOperand(2));
2523 else
2524 UpdateValueUsesWith(SI, SI->getOperand(2));
Chris Lattner7fd5f072004-07-06 07:01:22 +00002525 return &I;
2526 }
Reid Spencer7eb55b32006-11-02 01:53:59 +00002527 // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
2528 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2529 if (ST->isNullValue()) {
2530 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2531 if (CondI && CondI->getParent() == I.getParent())
2532 UpdateValueUsesWith(CondI, ConstantBool::getTrue());
2533 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2534 I.setOperand(1, SI->getOperand(1));
2535 else
2536 UpdateValueUsesWith(SI, SI->getOperand(1));
2537 return &I;
2538 }
Chris Lattnere9ff0ea2005-11-05 07:28:37 +00002539 }
Chris Lattner7fd5f072004-07-06 07:01:22 +00002540
Reid Spencer7eb55b32006-11-02 01:53:59 +00002541 return 0;
2542}
2543
2544/// This function implements the transforms common to both integer remainder
2545/// instructions (urem and srem). It is called by the visitors to those integer
2546/// remainder instructions.
2547/// @brief Common integer remainder transforms
2548Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
2549 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2550
2551 if (Instruction *common = commonRemTransforms(I))
2552 return common;
2553
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002554 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner0de4a8d2006-02-28 05:30:45 +00002555 // X % 0 == undef, we don't need to preserve faults!
2556 if (RHS->equalsInt(0))
2557 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2558
Chris Lattner3082c5a2003-02-18 19:28:33 +00002559 if (RHS->equalsInt(1)) // X % 1 == 0
2560 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2561
Chris Lattnerb70f1412006-02-28 05:49:21 +00002562 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2563 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2564 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2565 return R;
2566 } else if (isa<PHINode>(Op0I)) {
2567 if (Instruction *NV = FoldOpIntoPhi(I))
2568 return NV;
Chris Lattnerb70f1412006-02-28 05:49:21 +00002569 }
Reid Spencer7eb55b32006-11-02 01:53:59 +00002570 // (X * C1) % C2 --> 0 iff C1 % C2 == 0
2571 if (ConstantExpr::getSRem(GetFactor(Op0I), RHS)->isNullValue())
Chris Lattner85dda9a2006-03-02 06:50:58 +00002572 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerb70f1412006-02-28 05:49:21 +00002573 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00002574 }
2575
Reid Spencer7eb55b32006-11-02 01:53:59 +00002576 return 0;
2577}
2578
2579Instruction *InstCombiner::visitURem(BinaryOperator &I) {
2580 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2581
2582 if (Instruction *common = commonIRemTransforms(I))
2583 return common;
2584
2585 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2586 // X urem C^2 -> X and C
2587 // Check to see if this is an unsigned remainder with an exact power of 2,
2588 // if so, convert to a bitwise and.
2589 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
2590 if (isPowerOf2_64(C->getZExtValue()))
2591 return BinaryOperator::createAnd(Op0, SubOne(C));
2592 }
2593
Chris Lattner2e90b732006-02-05 07:54:04 +00002594 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00002595 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
2596 if (RHSI->getOpcode() == Instruction::Shl &&
2597 isa<ConstantInt>(RHSI->getOperand(0))) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002598 unsigned C1 = cast<ConstantInt>(RHSI->getOperand(0))->getZExtValue();
Chris Lattner2e90b732006-02-05 07:54:04 +00002599 if (isPowerOf2_64(C1)) {
2600 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
2601 Value *Add = InsertNewInstBefore(BinaryOperator::createAdd(RHSI, N1,
2602 "tmp"), I);
2603 return BinaryOperator::createAnd(Op0, Add);
2604 }
2605 }
Reid Spencer7eb55b32006-11-02 01:53:59 +00002606 }
Chris Lattnerd79dc792006-09-09 20:26:32 +00002607
Reid Spencer7eb55b32006-11-02 01:53:59 +00002608 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
2609 // where C1&C2 are powers of two.
2610 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2611 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2612 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
2613 // STO == 0 and SFO == 0 handled above.
2614 if (isPowerOf2_64(STO->getZExtValue()) &&
2615 isPowerOf2_64(SFO->getZExtValue())) {
2616 Value *TrueAnd = InsertNewInstBefore(
2617 BinaryOperator::createAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
2618 Value *FalseAnd = InsertNewInstBefore(
2619 BinaryOperator::createAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
2620 return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
2621 }
2622 }
Chris Lattner2e90b732006-02-05 07:54:04 +00002623 }
2624
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002625 return 0;
2626}
2627
Reid Spencer7eb55b32006-11-02 01:53:59 +00002628Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
2629 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2630
2631 if (Instruction *common = commonIRemTransforms(I))
2632 return common;
2633
2634 if (Value *RHSNeg = dyn_castNegVal(Op1))
2635 if (!isa<ConstantInt>(RHSNeg) ||
2636 cast<ConstantInt>(RHSNeg)->getSExtValue() > 0) {
2637 // X % -Y -> X % Y
2638 AddUsesToWorkList(I);
2639 I.setOperand(1, RHSNeg);
2640 return &I;
2641 }
2642
2643 // If the top bits of both operands are zero (i.e. we can prove they are
2644 // unsigned inputs), turn this into a urem.
2645 uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
2646 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2647 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
2648 return BinaryOperator::createURem(Op0, Op1, I.getName());
2649 }
2650
2651 return 0;
2652}
2653
2654Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00002655 return commonRemTransforms(I);
2656}
2657
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002658// isMaxValueMinusOne - return true if this is Max-1
Reid Spencer266e42b2006-12-23 06:05:41 +00002659static bool isMaxValueMinusOne(const ConstantInt *C, bool isSigned) {
2660 if (isSigned) {
2661 // Calculate 0111111111..11111
2662 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
2663 int64_t Val = INT64_MAX; // All ones
2664 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
2665 return C->getSExtValue() == Val-1;
2666 }
2667 return C->getZExtValue() == C->getType()->getIntegralTypeMask()-1;
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002668}
2669
2670// isMinValuePlusOne - return true if this is Min+1
Reid Spencer266e42b2006-12-23 06:05:41 +00002671static bool isMinValuePlusOne(const ConstantInt *C, bool isSigned) {
2672 if (isSigned) {
2673 // Calculate 1111111111000000000000
2674 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
2675 int64_t Val = -1; // All ones
2676 Val <<= TypeBits-1; // Shift over to the right spot
2677 return C->getSExtValue() == Val+1;
2678 }
2679 return C->getZExtValue() == 1; // unsigned
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002680}
2681
Chris Lattner35167c32004-06-09 07:59:58 +00002682// isOneBitSet - Return true if there is exactly one bit set in the specified
2683// constant.
2684static bool isOneBitSet(const ConstantInt *CI) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002685 uint64_t V = CI->getZExtValue();
Chris Lattner35167c32004-06-09 07:59:58 +00002686 return V && (V & (V-1)) == 0;
2687}
2688
Chris Lattner8fc5af42004-09-23 21:46:38 +00002689#if 0 // Currently unused
2690// isLowOnes - Return true if the constant is of the form 0+1+.
2691static bool isLowOnes(const ConstantInt *CI) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002692 uint64_t V = CI->getZExtValue();
Chris Lattner8fc5af42004-09-23 21:46:38 +00002693
2694 // There won't be bits set in parts that the type doesn't contain.
Reid Spencere0fc4df2006-10-20 07:07:24 +00002695 V &= ConstantInt::getAllOnesValue(CI->getType())->getZExtValue();
Chris Lattner8fc5af42004-09-23 21:46:38 +00002696
2697 uint64_t U = V+1; // If it is low ones, this should be a power of two.
2698 return U && V && (U & V) == 0;
2699}
2700#endif
2701
2702// isHighOnes - Return true if the constant is of the form 1+0+.
2703// This is the same as lowones(~X).
2704static bool isHighOnes(const ConstantInt *CI) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002705 uint64_t V = ~CI->getZExtValue();
Chris Lattner2c14cf72005-08-07 07:03:10 +00002706 if (~V == 0) return false; // 0's does not match "1+"
Chris Lattner8fc5af42004-09-23 21:46:38 +00002707
2708 // There won't be bits set in parts that the type doesn't contain.
Reid Spencere0fc4df2006-10-20 07:07:24 +00002709 V &= ConstantInt::getAllOnesValue(CI->getType())->getZExtValue();
Chris Lattner8fc5af42004-09-23 21:46:38 +00002710
2711 uint64_t U = V+1; // If it is low ones, this should be a power of two.
2712 return U && V && (U & V) == 0;
2713}
2714
Reid Spencer266e42b2006-12-23 06:05:41 +00002715/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
Chris Lattner3ac7c262003-08-13 20:16:26 +00002716/// are carefully arranged to allow folding of expressions such as:
2717///
2718/// (A < B) | (A > B) --> (A != B)
2719///
Reid Spencer266e42b2006-12-23 06:05:41 +00002720/// Note that this is only valid if the first and second predicates have the
2721/// same sign. Is illegal to do: (A u< B) | (A s> B)
Chris Lattner3ac7c262003-08-13 20:16:26 +00002722///
Reid Spencer266e42b2006-12-23 06:05:41 +00002723/// Three bits are used to represent the condition, as follows:
2724/// 0 A > B
2725/// 1 A == B
2726/// 2 A < B
2727///
2728/// <=> Value Definition
2729/// 000 0 Always false
2730/// 001 1 A > B
2731/// 010 2 A == B
2732/// 011 3 A >= B
2733/// 100 4 A < B
2734/// 101 5 A != B
2735/// 110 6 A <= B
2736/// 111 7 Always true
2737///
2738static unsigned getICmpCode(const ICmpInst *ICI) {
2739 switch (ICI->getPredicate()) {
Chris Lattner3ac7c262003-08-13 20:16:26 +00002740 // False -> 0
Reid Spencer266e42b2006-12-23 06:05:41 +00002741 case ICmpInst::ICMP_UGT: return 1; // 001
2742 case ICmpInst::ICMP_SGT: return 1; // 001
2743 case ICmpInst::ICMP_EQ: return 2; // 010
2744 case ICmpInst::ICMP_UGE: return 3; // 011
2745 case ICmpInst::ICMP_SGE: return 3; // 011
2746 case ICmpInst::ICMP_ULT: return 4; // 100
2747 case ICmpInst::ICMP_SLT: return 4; // 100
2748 case ICmpInst::ICMP_NE: return 5; // 101
2749 case ICmpInst::ICMP_ULE: return 6; // 110
2750 case ICmpInst::ICMP_SLE: return 6; // 110
Chris Lattner3ac7c262003-08-13 20:16:26 +00002751 // True -> 7
2752 default:
Reid Spencer266e42b2006-12-23 06:05:41 +00002753 assert(0 && "Invalid ICmp predicate!");
Chris Lattner3ac7c262003-08-13 20:16:26 +00002754 return 0;
2755 }
2756}
2757
Reid Spencer266e42b2006-12-23 06:05:41 +00002758/// getICmpValue - This is the complement of getICmpCode, which turns an
2759/// opcode and two operands into either a constant true or false, or a brand
2760/// new /// ICmp instruction. The sign is passed in to determine which kind
2761/// of predicate to use in new icmp instructions.
2762static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
2763 switch (code) {
2764 default: assert(0 && "Illegal ICmp code!");
2765 case 0: return ConstantBool::getFalse();
2766 case 1:
2767 if (sign)
2768 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
2769 else
2770 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
2771 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
2772 case 3:
2773 if (sign)
2774 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
2775 else
2776 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
2777 case 4:
2778 if (sign)
2779 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
2780 else
2781 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
2782 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
2783 case 6:
2784 if (sign)
2785 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
2786 else
2787 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
2788 case 7: return ConstantBool::getTrue();
Chris Lattner3ac7c262003-08-13 20:16:26 +00002789 }
2790}
2791
Reid Spencer266e42b2006-12-23 06:05:41 +00002792static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
2793 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
2794 (ICmpInst::isSignedPredicate(p1) &&
2795 (p2 == ICmpInst::ICMP_EQ || p2 == ICmpInst::ICMP_NE)) ||
2796 (ICmpInst::isSignedPredicate(p2) &&
2797 (p1 == ICmpInst::ICMP_EQ || p1 == ICmpInst::ICMP_NE));
2798}
2799
2800namespace {
2801// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
2802struct FoldICmpLogical {
Chris Lattner3ac7c262003-08-13 20:16:26 +00002803 InstCombiner &IC;
2804 Value *LHS, *RHS;
Reid Spencer266e42b2006-12-23 06:05:41 +00002805 ICmpInst::Predicate pred;
2806 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
2807 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
2808 pred(ICI->getPredicate()) {}
Chris Lattner3ac7c262003-08-13 20:16:26 +00002809 bool shouldApply(Value *V) const {
Reid Spencer266e42b2006-12-23 06:05:41 +00002810 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
2811 if (PredicatesFoldable(pred, ICI->getPredicate()))
2812 return (ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS ||
2813 ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS);
Chris Lattner3ac7c262003-08-13 20:16:26 +00002814 return false;
2815 }
Reid Spencer266e42b2006-12-23 06:05:41 +00002816 Instruction *apply(Instruction &Log) const {
2817 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
2818 if (ICI->getOperand(0) != LHS) {
2819 assert(ICI->getOperand(1) == LHS);
2820 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
Chris Lattner3ac7c262003-08-13 20:16:26 +00002821 }
2822
Reid Spencer266e42b2006-12-23 06:05:41 +00002823 unsigned LHSCode = getICmpCode(ICI);
2824 unsigned RHSCode = getICmpCode(cast<ICmpInst>(Log.getOperand(1)));
Chris Lattner3ac7c262003-08-13 20:16:26 +00002825 unsigned Code;
2826 switch (Log.getOpcode()) {
2827 case Instruction::And: Code = LHSCode & RHSCode; break;
2828 case Instruction::Or: Code = LHSCode | RHSCode; break;
2829 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner2caaaba2003-09-22 20:33:34 +00002830 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattner3ac7c262003-08-13 20:16:26 +00002831 }
2832
Reid Spencer266e42b2006-12-23 06:05:41 +00002833 Value *RV = getICmpValue(ICmpInst::isSignedPredicate(pred), Code, LHS, RHS);
Chris Lattner3ac7c262003-08-13 20:16:26 +00002834 if (Instruction *I = dyn_cast<Instruction>(RV))
2835 return I;
2836 // Otherwise, it's a constant boolean value...
2837 return IC.ReplaceInstUsesWith(Log, RV);
2838 }
2839};
Chris Lattnere3a63d12006-11-15 04:53:24 +00002840} // end anonymous namespace
Chris Lattner3ac7c262003-08-13 20:16:26 +00002841
Chris Lattnerba1cb382003-09-19 17:17:26 +00002842// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
2843// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
2844// guaranteed to be either a shift instruction or a binary operator.
2845Instruction *InstCombiner::OptAndOp(Instruction *Op,
2846 ConstantIntegral *OpRHS,
2847 ConstantIntegral *AndRHS,
2848 BinaryOperator &TheAnd) {
2849 Value *X = Op->getOperand(0);
Chris Lattnerfcf21a72004-01-12 19:47:05 +00002850 Constant *Together = 0;
2851 if (!isa<ShiftInst>(Op))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002852 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002853
Chris Lattnerba1cb382003-09-19 17:17:26 +00002854 switch (Op->getOpcode()) {
2855 case Instruction::Xor:
Chris Lattner86102b82005-01-01 16:22:27 +00002856 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00002857 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
2858 std::string OpName = Op->getName(); Op->setName("");
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002859 Instruction *And = BinaryOperator::createAnd(X, AndRHS, OpName);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002860 InsertNewInstBefore(And, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002861 return BinaryOperator::createXor(And, Together);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002862 }
2863 break;
2864 case Instruction::Or:
Chris Lattner86102b82005-01-01 16:22:27 +00002865 if (Together == AndRHS) // (X | C) & C --> C
2866 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002867
Chris Lattner86102b82005-01-01 16:22:27 +00002868 if (Op->hasOneUse() && Together != OpRHS) {
2869 // (X | C1) & C2 --> (X | (C1&C2)) & C2
2870 std::string Op0Name = Op->getName(); Op->setName("");
2871 Instruction *Or = BinaryOperator::createOr(X, Together, Op0Name);
2872 InsertNewInstBefore(Or, TheAnd);
2873 return BinaryOperator::createAnd(Or, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002874 }
2875 break;
2876 case Instruction::Add:
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002877 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00002878 // Adding a one to a single bit bit-field should be turned into an XOR
2879 // of the bit. First thing to check is to see if this AND is with a
2880 // single bit constant.
Reid Spencere0fc4df2006-10-20 07:07:24 +00002881 uint64_t AndRHSV = cast<ConstantInt>(AndRHS)->getZExtValue();
Chris Lattnerba1cb382003-09-19 17:17:26 +00002882
2883 // Clear bits that are not part of the constant.
Chris Lattner77defba2006-02-07 07:00:41 +00002884 AndRHSV &= AndRHS->getType()->getIntegralTypeMask();
Chris Lattnerba1cb382003-09-19 17:17:26 +00002885
2886 // If there is only one bit set...
Chris Lattner35167c32004-06-09 07:59:58 +00002887 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00002888 // Ok, at this point, we know that we are masking the result of the
2889 // ADD down to exactly one bit. If the constant we are adding has
2890 // no bits set below this bit, then we can eliminate the ADD.
Reid Spencere0fc4df2006-10-20 07:07:24 +00002891 uint64_t AddRHS = cast<ConstantInt>(OpRHS)->getZExtValue();
Misha Brukmanb1c93172005-04-21 23:48:37 +00002892
Chris Lattnerba1cb382003-09-19 17:17:26 +00002893 // Check to see if any bits below the one bit set in AndRHSV are set.
2894 if ((AddRHS & (AndRHSV-1)) == 0) {
2895 // If not, the only thing that can effect the output of the AND is
2896 // the bit specified by AndRHSV. If that bit is set, the effect of
2897 // the XOR is to toggle the bit. If it is clear, then the ADD has
2898 // no effect.
2899 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
2900 TheAnd.setOperand(0, X);
2901 return &TheAnd;
2902 } else {
2903 std::string Name = Op->getName(); Op->setName("");
2904 // Pull the XOR out of the AND.
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002905 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS, Name);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002906 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002907 return BinaryOperator::createXor(NewAnd, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002908 }
2909 }
2910 }
2911 }
2912 break;
Chris Lattner2da29172003-09-19 19:05:02 +00002913
2914 case Instruction::Shl: {
2915 // We know that the AND will not produce any of the bits shifted in, so if
2916 // the anded constant includes them, clear them now!
2917 //
2918 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner7e794272004-09-24 15:21:34 +00002919 Constant *ShlMask = ConstantExpr::getShl(AllOne, OpRHS);
2920 Constant *CI = ConstantExpr::getAnd(AndRHS, ShlMask);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002921
Chris Lattner7e794272004-09-24 15:21:34 +00002922 if (CI == ShlMask) { // Masking out bits that the shift already masks
2923 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
2924 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner2da29172003-09-19 19:05:02 +00002925 TheAnd.setOperand(1, CI);
2926 return &TheAnd;
2927 }
2928 break;
Misha Brukmanb1c93172005-04-21 23:48:37 +00002929 }
Reid Spencerfdff9382006-11-08 06:47:33 +00002930 case Instruction::LShr:
2931 {
Chris Lattner2da29172003-09-19 19:05:02 +00002932 // We know that the AND will not produce any of the bits shifted in, so if
2933 // the anded constant includes them, clear them now! This only applies to
2934 // unsigned shifts, because a signed shr may bring in set bits!
2935 //
Reid Spencerfdff9382006-11-08 06:47:33 +00002936 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
2937 Constant *ShrMask = ConstantExpr::getLShr(AllOne, OpRHS);
2938 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
Chris Lattner7e794272004-09-24 15:21:34 +00002939
Reid Spencerfdff9382006-11-08 06:47:33 +00002940 if (CI == ShrMask) { // Masking out bits that the shift already masks.
2941 return ReplaceInstUsesWith(TheAnd, Op);
2942 } else if (CI != AndRHS) {
2943 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
2944 return &TheAnd;
2945 }
2946 break;
2947 }
2948 case Instruction::AShr:
2949 // Signed shr.
2950 // See if this is shifting in some sign extension, then masking it out
2951 // with an and.
2952 if (Op->hasOneUse()) {
2953 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
2954 Constant *ShrMask = ConstantExpr::getLShr(AllOne, OpRHS);
Reid Spencer2a499b02006-12-13 17:19:09 +00002955 Constant *C = ConstantExpr::getAnd(AndRHS, ShrMask);
2956 if (C == AndRHS) { // Masking out bits shifted in.
Reid Spencer13bc5d72006-12-12 09:18:51 +00002957 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
Reid Spencerfdff9382006-11-08 06:47:33 +00002958 // Make the argument unsigned.
2959 Value *ShVal = Op->getOperand(0);
Reid Spencer2a499b02006-12-13 17:19:09 +00002960 ShVal = InsertNewInstBefore(new ShiftInst(Instruction::LShr, ShVal,
2961 OpRHS, Op->getName()), TheAnd);
2962 return BinaryOperator::createAnd(ShVal, AndRHS, TheAnd.getName());
Chris Lattner7e794272004-09-24 15:21:34 +00002963 }
Chris Lattner2da29172003-09-19 19:05:02 +00002964 }
2965 break;
Chris Lattnerba1cb382003-09-19 17:17:26 +00002966 }
2967 return 0;
2968}
2969
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002970
Chris Lattner6862fbd2004-09-29 17:40:11 +00002971/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
2972/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
Reid Spencer266e42b2006-12-23 06:05:41 +00002973/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
2974/// whether to treat the V, Lo and HI as signed or not. IB is the location to
Chris Lattner6862fbd2004-09-29 17:40:11 +00002975/// insert new instructions.
2976Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencer266e42b2006-12-23 06:05:41 +00002977 bool isSigned, bool Inside,
2978 Instruction &IB) {
2979 assert(cast<ConstantBool>(ConstantExpr::getICmp((isSigned ?
2980 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getValue() &&
Chris Lattner6862fbd2004-09-29 17:40:11 +00002981 "Lo is not <= Hi in range emission code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00002982
Chris Lattner6862fbd2004-09-29 17:40:11 +00002983 if (Inside) {
2984 if (Lo == Hi) // Trivially false.
Reid Spencer266e42b2006-12-23 06:05:41 +00002985 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002986
Reid Spencer266e42b2006-12-23 06:05:41 +00002987 // V >= Min && V < Hi --> V < Hi
2988 if (cast<ConstantIntegral>(Lo)->isMinValue(isSigned)) {
2989 ICmpInst::Predicate pred = (isSigned ?
2990 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
2991 return new ICmpInst(pred, V, Hi);
2992 }
2993
2994 // Emit V-Lo <u Hi-Lo
2995 Constant *NegLo = ConstantExpr::getNeg(Lo);
2996 Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
Chris Lattner6862fbd2004-09-29 17:40:11 +00002997 InsertNewInstBefore(Add, IB);
Reid Spencer266e42b2006-12-23 06:05:41 +00002998 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
2999 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00003000 }
3001
3002 if (Lo == Hi) // Trivially true.
Reid Spencer266e42b2006-12-23 06:05:41 +00003003 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
Chris Lattner6862fbd2004-09-29 17:40:11 +00003004
Reid Spencer266e42b2006-12-23 06:05:41 +00003005 // V < Min || V >= Hi ->'V > Hi-1'
Chris Lattner6862fbd2004-09-29 17:40:11 +00003006 Hi = SubOne(cast<ConstantInt>(Hi));
Reid Spencer266e42b2006-12-23 06:05:41 +00003007 if (cast<ConstantIntegral>(Lo)->isMinValue(isSigned)) {
3008 ICmpInst::Predicate pred = (isSigned ?
3009 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3010 return new ICmpInst(pred, V, Hi);
3011 }
Reid Spencere0fc4df2006-10-20 07:07:24 +00003012
Reid Spencer266e42b2006-12-23 06:05:41 +00003013 // Emit V-Lo > Hi-1-Lo
3014 Constant *NegLo = ConstantExpr::getNeg(Lo);
3015 Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
Chris Lattner6862fbd2004-09-29 17:40:11 +00003016 InsertNewInstBefore(Add, IB);
Reid Spencer266e42b2006-12-23 06:05:41 +00003017 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3018 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00003019}
3020
Chris Lattnerb4b25302005-09-18 07:22:02 +00003021// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3022// any number of 0s on either side. The 1s are allowed to wrap from LSB to
3023// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3024// not, since all 1s are not contiguous.
3025static bool isRunOfOnes(ConstantIntegral *Val, unsigned &MB, unsigned &ME) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00003026 uint64_t V = Val->getZExtValue();
Chris Lattnerb4b25302005-09-18 07:22:02 +00003027 if (!isShiftedMask_64(V)) return false;
3028
3029 // look for the first zero bit after the run of ones
3030 MB = 64-CountLeadingZeros_64((V - 1) ^ V);
3031 // look for the first non-zero bit
3032 ME = 64-CountLeadingZeros_64(V);
3033 return true;
3034}
3035
3036
3037
3038/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3039/// where isSub determines whether the operator is a sub. If we can fold one of
3040/// the following xforms:
Chris Lattneraf517572005-09-18 04:24:45 +00003041///
3042/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3043/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3044/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3045///
3046/// return (A +/- B).
3047///
3048Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
3049 ConstantIntegral *Mask, bool isSub,
3050 Instruction &I) {
3051 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3052 if (!LHSI || LHSI->getNumOperands() != 2 ||
3053 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3054
3055 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3056
3057 switch (LHSI->getOpcode()) {
3058 default: return 0;
3059 case Instruction::And:
Chris Lattnerb4b25302005-09-18 07:22:02 +00003060 if (ConstantExpr::getAnd(N, Mask) == Mask) {
3061 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Reid Spencere0fc4df2006-10-20 07:07:24 +00003062 if ((Mask->getZExtValue() & Mask->getZExtValue()+1) == 0)
Chris Lattnerb4b25302005-09-18 07:22:02 +00003063 break;
3064
3065 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3066 // part, we don't need any explicit masks to take them out of A. If that
3067 // is all N is, ignore it.
3068 unsigned MB, ME;
3069 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003070 uint64_t Mask = RHS->getType()->getIntegralTypeMask();
3071 Mask >>= 64-MB+1;
3072 if (MaskedValueIsZero(RHS, Mask))
Chris Lattnerb4b25302005-09-18 07:22:02 +00003073 break;
3074 }
3075 }
Chris Lattneraf517572005-09-18 04:24:45 +00003076 return 0;
3077 case Instruction::Or:
3078 case Instruction::Xor:
Chris Lattnerb4b25302005-09-18 07:22:02 +00003079 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Reid Spencere0fc4df2006-10-20 07:07:24 +00003080 if ((Mask->getZExtValue() & Mask->getZExtValue()+1) == 0 &&
Chris Lattnerb4b25302005-09-18 07:22:02 +00003081 ConstantExpr::getAnd(N, Mask)->isNullValue())
Chris Lattneraf517572005-09-18 04:24:45 +00003082 break;
3083 return 0;
3084 }
3085
3086 Instruction *New;
3087 if (isSub)
3088 New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
3089 else
3090 New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
3091 return InsertNewInstBefore(New, I);
3092}
3093
Chris Lattner113f4f42002-06-25 16:13:24 +00003094Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003095 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00003096 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003097
Chris Lattner81a7a232004-10-16 18:11:37 +00003098 if (isa<UndefValue>(Op1)) // X & undef -> 0
3099 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3100
Chris Lattner86102b82005-01-01 16:22:27 +00003101 // and X, X = X
3102 if (Op0 == Op1)
Chris Lattnere6794492002-08-12 21:17:25 +00003103 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003104
Chris Lattner5b2edb12006-02-12 08:02:11 +00003105 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner5997cf92006-02-08 03:25:32 +00003106 // purpose is to compute bits we don't care about.
Chris Lattner0157e7f2006-02-11 09:31:47 +00003107 uint64_t KnownZero, KnownOne;
Chris Lattnerd70d9f52006-03-25 21:58:26 +00003108 if (!isa<PackedType>(I.getType()) &&
3109 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
Chris Lattner0157e7f2006-02-11 09:31:47 +00003110 KnownZero, KnownOne))
Chris Lattner5997cf92006-02-08 03:25:32 +00003111 return &I;
3112
Chris Lattner86102b82005-01-01 16:22:27 +00003113 if (ConstantIntegral *AndRHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00003114 uint64_t AndRHSMask = AndRHS->getZExtValue();
3115 uint64_t TypeMask = Op0->getType()->getIntegralTypeMask();
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00003116 uint64_t NotAndRHS = AndRHSMask^TypeMask;
Chris Lattner86102b82005-01-01 16:22:27 +00003117
Chris Lattnerba1cb382003-09-19 17:17:26 +00003118 // Optimize a variety of ((val OP C1) & C2) combinations...
3119 if (isa<BinaryOperator>(Op0) || isa<ShiftInst>(Op0)) {
3120 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner86102b82005-01-01 16:22:27 +00003121 Value *Op0LHS = Op0I->getOperand(0);
3122 Value *Op0RHS = Op0I->getOperand(1);
3123 switch (Op0I->getOpcode()) {
3124 case Instruction::Xor:
3125 case Instruction::Or:
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00003126 // If the mask is only needed on one incoming arm, push it up.
3127 if (Op0I->hasOneUse()) {
3128 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3129 // Not masking anything out for the LHS, move to RHS.
3130 Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
3131 Op0RHS->getName()+".masked");
3132 InsertNewInstBefore(NewRHS, I);
3133 return BinaryOperator::create(
3134 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003135 }
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003136 if (!isa<Constant>(Op0RHS) &&
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00003137 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3138 // Not masking anything out for the RHS, move to LHS.
3139 Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
3140 Op0LHS->getName()+".masked");
3141 InsertNewInstBefore(NewLHS, I);
3142 return BinaryOperator::create(
3143 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3144 }
3145 }
3146
Chris Lattner86102b82005-01-01 16:22:27 +00003147 break;
Chris Lattneraf517572005-09-18 04:24:45 +00003148 case Instruction::Add:
Chris Lattnerb4b25302005-09-18 07:22:02 +00003149 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3150 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3151 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3152 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
3153 return BinaryOperator::createAnd(V, AndRHS);
3154 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
3155 return BinaryOperator::createAnd(V, AndRHS); // Add commutes
Chris Lattneraf517572005-09-18 04:24:45 +00003156 break;
3157
3158 case Instruction::Sub:
Chris Lattnerb4b25302005-09-18 07:22:02 +00003159 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3160 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3161 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3162 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
3163 return BinaryOperator::createAnd(V, AndRHS);
Chris Lattneraf517572005-09-18 04:24:45 +00003164 break;
Chris Lattner86102b82005-01-01 16:22:27 +00003165 }
3166
Chris Lattner16464b32003-07-23 19:25:52 +00003167 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner86102b82005-01-01 16:22:27 +00003168 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerba1cb382003-09-19 17:17:26 +00003169 return Res;
Chris Lattner86102b82005-01-01 16:22:27 +00003170 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
Chris Lattner2c14cf72005-08-07 07:03:10 +00003171 // If this is an integer truncation or change from signed-to-unsigned, and
3172 // if the source is an and/or with immediate, transform it. This
3173 // frequently occurs for bitfield accesses.
3174 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003175 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
Chris Lattner2c14cf72005-08-07 07:03:10 +00003176 CastOp->getNumOperands() == 2)
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00003177 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1)))
Chris Lattner2c14cf72005-08-07 07:03:10 +00003178 if (CastOp->getOpcode() == Instruction::And) {
3179 // Change: and (cast (and X, C1) to T), C2
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003180 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
3181 // This will fold the two constants together, which may allow
3182 // other simplifications.
Reid Spencerbb65ebf2006-12-12 23:36:14 +00003183 Instruction *NewCast = CastInst::createTruncOrBitCast(
3184 CastOp->getOperand(0), I.getType(),
3185 CastOp->getName()+".shrunk");
Chris Lattner2c14cf72005-08-07 07:03:10 +00003186 NewCast = InsertNewInstBefore(NewCast, I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003187 // trunc_or_bitcast(C1)&C2
Reid Spencerbb65ebf2006-12-12 23:36:14 +00003188 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003189 C3 = ConstantExpr::getAnd(C3, AndRHS);
Chris Lattner2c14cf72005-08-07 07:03:10 +00003190 return BinaryOperator::createAnd(NewCast, C3);
3191 } else if (CastOp->getOpcode() == Instruction::Or) {
3192 // Change: and (cast (or X, C1) to T), C2
3193 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Chris Lattner2dc148e2006-12-12 19:11:20 +00003194 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Chris Lattner2c14cf72005-08-07 07:03:10 +00003195 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
3196 return ReplaceInstUsesWith(I, AndRHS);
3197 }
3198 }
Chris Lattner33217db2003-07-23 19:36:21 +00003199 }
Chris Lattner183b3362004-04-09 19:05:30 +00003200
3201 // Try to fold constant and into select arguments.
3202 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00003203 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00003204 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00003205 if (isa<PHINode>(Op0))
3206 if (Instruction *NV = FoldOpIntoPhi(I))
3207 return NV;
Chris Lattner49b47ae2003-07-23 17:57:01 +00003208 }
3209
Chris Lattnerbb74e222003-03-10 23:06:50 +00003210 Value *Op0NotVal = dyn_castNotVal(Op0);
3211 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00003212
Chris Lattner023a4832004-06-18 06:07:51 +00003213 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
3214 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3215
Misha Brukman9c003d82004-07-30 12:50:08 +00003216 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattnerbb74e222003-03-10 23:06:50 +00003217 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003218 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
3219 I.getName()+".demorgan");
Chris Lattner49b47ae2003-07-23 17:57:01 +00003220 InsertNewInstBefore(Or, I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00003221 return BinaryOperator::createNot(Or);
3222 }
Chris Lattner8b10ab32006-02-13 23:07:23 +00003223
3224 {
3225 Value *A = 0, *B = 0;
Chris Lattner8b10ab32006-02-13 23:07:23 +00003226 if (match(Op0, m_Or(m_Value(A), m_Value(B))))
3227 if (A == Op1 || B == Op1) // (A | ?) & A --> A
3228 return ReplaceInstUsesWith(I, Op1);
3229 if (match(Op1, m_Or(m_Value(A), m_Value(B))))
3230 if (A == Op0 || B == Op0) // A & (A | ?) --> A
3231 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerdcd07922006-04-01 08:03:55 +00003232
3233 if (Op0->hasOneUse() &&
3234 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3235 if (A == Op1) { // (A^B)&A -> A&(A^B)
3236 I.swapOperands(); // Simplify below
3237 std::swap(Op0, Op1);
3238 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
3239 cast<BinaryOperator>(Op0)->swapOperands();
3240 I.swapOperands(); // Simplify below
3241 std::swap(Op0, Op1);
3242 }
3243 }
3244 if (Op1->hasOneUse() &&
3245 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3246 if (B == Op0) { // B&(A^B) -> B&(B^A)
3247 cast<BinaryOperator>(Op1)->swapOperands();
3248 std::swap(A, B);
3249 }
3250 if (A == Op0) { // A&(A^B) -> A & ~B
3251 Instruction *NotB = BinaryOperator::createNot(B, "tmp");
3252 InsertNewInstBefore(NotB, I);
3253 return BinaryOperator::createAnd(A, NotB);
3254 }
3255 }
Chris Lattner8b10ab32006-02-13 23:07:23 +00003256 }
3257
Reid Spencer266e42b2006-12-23 06:05:41 +00003258 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
3259 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3260 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattner3ac7c262003-08-13 20:16:26 +00003261 return R;
3262
Chris Lattner623826c2004-09-28 21:48:02 +00003263 Value *LHSVal, *RHSVal;
3264 ConstantInt *LHSCst, *RHSCst;
Reid Spencer266e42b2006-12-23 06:05:41 +00003265 ICmpInst::Predicate LHSCC, RHSCC;
3266 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3267 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3268 if (LHSVal == RHSVal && // Found (X icmp C1) & (X icmp C2)
3269 // ICMP_[GL]E X, CST is folded to ICMP_[GL]T elsewhere.
3270 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3271 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3272 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
3273 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE) {
Chris Lattner623826c2004-09-28 21:48:02 +00003274 // Ensure that the larger constant is on the RHS.
Reid Spencer266e42b2006-12-23 06:05:41 +00003275 ICmpInst::Predicate GT = ICmpInst::isSignedPredicate(LHSCC) ?
3276 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
3277 Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3278 ICmpInst *LHS = cast<ICmpInst>(Op0);
Chris Lattner623826c2004-09-28 21:48:02 +00003279 if (cast<ConstantBool>(Cmp)->getValue()) {
3280 std::swap(LHS, RHS);
3281 std::swap(LHSCst, RHSCst);
3282 std::swap(LHSCC, RHSCC);
3283 }
3284
Reid Spencer266e42b2006-12-23 06:05:41 +00003285 // At this point, we know we have have two icmp instructions
Chris Lattner623826c2004-09-28 21:48:02 +00003286 // comparing a value against two constants and and'ing the result
3287 // together. Because of the above check, we know that we only have
Reid Spencer266e42b2006-12-23 06:05:41 +00003288 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3289 // (from the FoldICmpLogical check above), that the two constants
3290 // are not equal and that the larger constant is on the RHS
Chris Lattner623826c2004-09-28 21:48:02 +00003291 assert(LHSCst != RHSCst && "Compares not folded above?");
3292
3293 switch (LHSCC) {
3294 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003295 case ICmpInst::ICMP_EQ:
Chris Lattner623826c2004-09-28 21:48:02 +00003296 switch (RHSCC) {
3297 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003298 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
3299 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3300 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
Chris Lattner6ab03f62006-09-28 23:35:22 +00003301 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00003302 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3303 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3304 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
Chris Lattner623826c2004-09-28 21:48:02 +00003305 return ReplaceInstUsesWith(I, LHS);
3306 }
Reid Spencer266e42b2006-12-23 06:05:41 +00003307 case ICmpInst::ICMP_NE:
Chris Lattner623826c2004-09-28 21:48:02 +00003308 switch (RHSCC) {
3309 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003310 case ICmpInst::ICMP_ULT:
3311 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3312 return new ICmpInst(ICmpInst::ICMP_ULT, LHSVal, LHSCst);
3313 break; // (X != 13 & X u< 15) -> no change
3314 case ICmpInst::ICMP_SLT:
3315 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3316 return new ICmpInst(ICmpInst::ICMP_SLT, LHSVal, LHSCst);
3317 break; // (X != 13 & X s< 15) -> no change
3318 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
3319 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
3320 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
Chris Lattner623826c2004-09-28 21:48:02 +00003321 return ReplaceInstUsesWith(I, RHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00003322 case ICmpInst::ICMP_NE:
3323 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
Chris Lattner623826c2004-09-28 21:48:02 +00003324 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3325 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3326 LHSVal->getName()+".off");
3327 InsertNewInstBefore(Add, I);
Reid Spencerc635f472006-12-31 05:48:39 +00003328 return new ICmpInst(ICmpInst::ICMP_UGT, Add, AddCST);
Chris Lattner623826c2004-09-28 21:48:02 +00003329 }
3330 break; // (X != 13 & X != 15) -> no change
3331 }
3332 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00003333 case ICmpInst::ICMP_ULT:
Chris Lattner623826c2004-09-28 21:48:02 +00003334 switch (RHSCC) {
3335 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003336 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
3337 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Chris Lattner6ab03f62006-09-28 23:35:22 +00003338 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00003339 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
3340 break;
3341 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
3342 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
Chris Lattner623826c2004-09-28 21:48:02 +00003343 return ReplaceInstUsesWith(I, LHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00003344 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
3345 break;
Chris Lattner623826c2004-09-28 21:48:02 +00003346 }
Reid Spencer266e42b2006-12-23 06:05:41 +00003347 break;
3348 case ICmpInst::ICMP_SLT:
Chris Lattner623826c2004-09-28 21:48:02 +00003349 switch (RHSCC) {
3350 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003351 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
3352 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
3353 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
3354 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
3355 break;
3356 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
3357 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
Chris Lattner623826c2004-09-28 21:48:02 +00003358 return ReplaceInstUsesWith(I, LHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00003359 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
3360 break;
Chris Lattner623826c2004-09-28 21:48:02 +00003361 }
Reid Spencer266e42b2006-12-23 06:05:41 +00003362 break;
3363 case ICmpInst::ICMP_UGT:
3364 switch (RHSCC) {
3365 default: assert(0 && "Unknown integer condition code!");
3366 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X > 13
3367 return ReplaceInstUsesWith(I, LHS);
3368 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
3369 return ReplaceInstUsesWith(I, RHS);
3370 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
3371 break;
3372 case ICmpInst::ICMP_NE:
3373 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3374 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3375 break; // (X u> 13 & X != 15) -> no change
3376 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) ->(X-14) <u 1
3377 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, false,
3378 true, I);
3379 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
3380 break;
3381 }
3382 break;
3383 case ICmpInst::ICMP_SGT:
3384 switch (RHSCC) {
3385 default: assert(0 && "Unknown integer condition code!");
3386 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X s> 13
3387 return ReplaceInstUsesWith(I, LHS);
3388 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
3389 return ReplaceInstUsesWith(I, RHS);
3390 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
3391 break;
3392 case ICmpInst::ICMP_NE:
3393 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3394 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3395 break; // (X s> 13 & X != 15) -> no change
3396 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) ->(X-14) s< 1
3397 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true,
3398 true, I);
3399 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
3400 break;
3401 }
3402 break;
Chris Lattner623826c2004-09-28 21:48:02 +00003403 }
3404 }
3405 }
3406
Chris Lattner3af10532006-05-05 06:39:07 +00003407 // fold (and (cast A), (cast B)) -> (cast (and A, B))
Reid Spencer799b5bf2006-12-13 08:27:15 +00003408 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
3409 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3410 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
3411 const Type *SrcTy = Op0C->getOperand(0)->getType();
3412 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegral() &&
3413 // Only do this if the casts both really cause code to be generated.
Reid Spencer266e42b2006-12-23 06:05:41 +00003414 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
3415 I.getType(), TD) &&
3416 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
3417 I.getType(), TD)) {
Reid Spencer799b5bf2006-12-13 08:27:15 +00003418 Instruction *NewOp = BinaryOperator::createAnd(Op0C->getOperand(0),
3419 Op1C->getOperand(0),
3420 I.getName());
3421 InsertNewInstBefore(NewOp, I);
3422 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
3423 }
Chris Lattner3af10532006-05-05 06:39:07 +00003424 }
Chris Lattnerf05d69a2006-11-14 07:46:50 +00003425
3426 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
3427 if (ShiftInst *SI1 = dyn_cast<ShiftInst>(Op1)) {
3428 if (ShiftInst *SI0 = dyn_cast<ShiftInst>(Op0))
3429 if (SI0->getOpcode() == SI1->getOpcode() &&
3430 SI0->getOperand(1) == SI1->getOperand(1) &&
3431 (SI0->hasOneUse() || SI1->hasOneUse())) {
3432 Instruction *NewOp =
3433 InsertNewInstBefore(BinaryOperator::createAnd(SI0->getOperand(0),
3434 SI1->getOperand(0),
3435 SI0->getName()), I);
3436 return new ShiftInst(SI1->getOpcode(), NewOp, SI1->getOperand(1));
3437 }
Chris Lattner3af10532006-05-05 06:39:07 +00003438 }
3439
Chris Lattner113f4f42002-06-25 16:13:24 +00003440 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003441}
3442
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003443/// CollectBSwapParts - Look to see if the specified value defines a single byte
3444/// in the result. If it does, and if the specified byte hasn't been filled in
3445/// yet, fill it in and return false.
3446static bool CollectBSwapParts(Value *V, std::vector<Value*> &ByteValues) {
3447 Instruction *I = dyn_cast<Instruction>(V);
3448 if (I == 0) return true;
3449
3450 // If this is an or instruction, it is an inner node of the bswap.
3451 if (I->getOpcode() == Instruction::Or)
3452 return CollectBSwapParts(I->getOperand(0), ByteValues) ||
3453 CollectBSwapParts(I->getOperand(1), ByteValues);
3454
3455 // If this is a shift by a constant int, and it is "24", then its operand
3456 // defines a byte. We only handle unsigned types here.
3457 if (isa<ShiftInst>(I) && isa<ConstantInt>(I->getOperand(1))) {
3458 // Not shifting the entire input by N-1 bytes?
Reid Spencere0fc4df2006-10-20 07:07:24 +00003459 if (cast<ConstantInt>(I->getOperand(1))->getZExtValue() !=
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003460 8*(ByteValues.size()-1))
3461 return true;
3462
3463 unsigned DestNo;
3464 if (I->getOpcode() == Instruction::Shl) {
3465 // X << 24 defines the top byte with the lowest of the input bytes.
3466 DestNo = ByteValues.size()-1;
3467 } else {
3468 // X >>u 24 defines the low byte with the highest of the input bytes.
3469 DestNo = 0;
3470 }
3471
3472 // If the destination byte value is already defined, the values are or'd
3473 // together, which isn't a bswap (unless it's an or of the same bits).
3474 if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
3475 return true;
3476 ByteValues[DestNo] = I->getOperand(0);
3477 return false;
3478 }
3479
3480 // Otherwise, we can only handle and(shift X, imm), imm). Bail out of if we
3481 // don't have this.
3482 Value *Shift = 0, *ShiftLHS = 0;
3483 ConstantInt *AndAmt = 0, *ShiftAmt = 0;
3484 if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
3485 !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
3486 return true;
3487 Instruction *SI = cast<Instruction>(Shift);
3488
3489 // Make sure that the shift amount is by a multiple of 8 and isn't too big.
Reid Spencere0fc4df2006-10-20 07:07:24 +00003490 if (ShiftAmt->getZExtValue() & 7 ||
3491 ShiftAmt->getZExtValue() > 8*ByteValues.size())
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003492 return true;
3493
3494 // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
3495 unsigned DestByte;
3496 for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
Reid Spencere0fc4df2006-10-20 07:07:24 +00003497 if (AndAmt->getZExtValue() == uint64_t(0xFF) << 8*DestByte)
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003498 break;
3499 // Unknown mask for bswap.
3500 if (DestByte == ByteValues.size()) return true;
3501
Reid Spencere0fc4df2006-10-20 07:07:24 +00003502 unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003503 unsigned SrcByte;
3504 if (SI->getOpcode() == Instruction::Shl)
3505 SrcByte = DestByte - ShiftBytes;
3506 else
3507 SrcByte = DestByte + ShiftBytes;
3508
3509 // If the SrcByte isn't a bswapped value from the DestByte, reject it.
3510 if (SrcByte != ByteValues.size()-DestByte-1)
3511 return true;
3512
3513 // If the destination byte value is already defined, the values are or'd
3514 // together, which isn't a bswap (unless it's an or of the same bits).
3515 if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
3516 return true;
3517 ByteValues[DestByte] = SI->getOperand(0);
3518 return false;
3519}
3520
3521/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
3522/// If so, insert the new bswap intrinsic and return it.
3523Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
3524 // We can only handle bswap of unsigned integers, and cannot bswap one byte.
Reid Spencerc635f472006-12-31 05:48:39 +00003525 if (I.getType() == Type::Int8Ty)
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003526 return 0;
3527
3528 /// ByteValues - For each byte of the result, we keep track of which value
3529 /// defines each byte.
3530 std::vector<Value*> ByteValues;
3531 ByteValues.resize(I.getType()->getPrimitiveSize());
3532
3533 // Try to find all the pieces corresponding to the bswap.
3534 if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
3535 CollectBSwapParts(I.getOperand(1), ByteValues))
3536 return 0;
3537
3538 // Check to see if all of the bytes come from the same value.
3539 Value *V = ByteValues[0];
3540 if (V == 0) return 0; // Didn't find a byte? Must be zero.
3541
3542 // Check to make sure that all of the bytes come from the same value.
3543 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
3544 if (ByteValues[i] != V)
3545 return 0;
3546
3547 // If they do then *success* we can turn this into a bswap. Figure out what
3548 // bswap to make it into.
3549 Module *M = I.getParent()->getParent()->getParent();
Chris Lattner091b6ea2006-07-11 18:31:26 +00003550 const char *FnName = 0;
Reid Spencerc635f472006-12-31 05:48:39 +00003551 if (I.getType() == Type::Int16Ty)
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003552 FnName = "llvm.bswap.i16";
Reid Spencerc635f472006-12-31 05:48:39 +00003553 else if (I.getType() == Type::Int32Ty)
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003554 FnName = "llvm.bswap.i32";
Reid Spencerc635f472006-12-31 05:48:39 +00003555 else if (I.getType() == Type::Int64Ty)
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003556 FnName = "llvm.bswap.i64";
3557 else
3558 assert(0 && "Unknown integer type!");
3559 Function *F = M->getOrInsertFunction(FnName, I.getType(), I.getType(), NULL);
3560
3561 return new CallInst(F, V);
3562}
3563
3564
Chris Lattner113f4f42002-06-25 16:13:24 +00003565Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003566 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00003567 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003568
Chris Lattner81a7a232004-10-16 18:11:37 +00003569 if (isa<UndefValue>(Op1))
3570 return ReplaceInstUsesWith(I, // X | undef -> -1
3571 ConstantIntegral::getAllOnesValue(I.getType()));
3572
Chris Lattner5b2edb12006-02-12 08:02:11 +00003573 // or X, X = X
3574 if (Op0 == Op1)
Chris Lattnere6794492002-08-12 21:17:25 +00003575 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003576
Chris Lattner5b2edb12006-02-12 08:02:11 +00003577 // See if we can simplify any instructions used by the instruction whose sole
3578 // purpose is to compute bits we don't care about.
3579 uint64_t KnownZero, KnownOne;
Chris Lattnerd70d9f52006-03-25 21:58:26 +00003580 if (!isa<PackedType>(I.getType()) &&
3581 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
Chris Lattner5b2edb12006-02-12 08:02:11 +00003582 KnownZero, KnownOne))
3583 return &I;
3584
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003585 // or X, -1 == -1
Chris Lattner8f0d1562003-07-23 18:29:44 +00003586 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner330628a2006-01-06 17:59:59 +00003587 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00003588 // (X & C1) | C2 --> (X | C2) & (C1|C2)
3589 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Chris Lattnerb62f5082005-05-09 04:58:36 +00003590 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0->getName());
3591 Op0->setName("");
Chris Lattnerd4252a72004-07-30 07:50:03 +00003592 InsertNewInstBefore(Or, I);
3593 return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, C1));
3594 }
Chris Lattner8f0d1562003-07-23 18:29:44 +00003595
Chris Lattnerd4252a72004-07-30 07:50:03 +00003596 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
3597 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
3598 std::string Op0Name = Op0->getName(); Op0->setName("");
3599 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
3600 InsertNewInstBefore(Or, I);
3601 return BinaryOperator::createXor(Or,
3602 ConstantExpr::getAnd(C1, ConstantExpr::getNot(RHS)));
Chris Lattner8f0d1562003-07-23 18:29:44 +00003603 }
Chris Lattner183b3362004-04-09 19:05:30 +00003604
3605 // Try to fold constant and into select arguments.
3606 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00003607 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00003608 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00003609 if (isa<PHINode>(Op0))
3610 if (Instruction *NV = FoldOpIntoPhi(I))
3611 return NV;
Chris Lattner8f0d1562003-07-23 18:29:44 +00003612 }
3613
Chris Lattner330628a2006-01-06 17:59:59 +00003614 Value *A = 0, *B = 0;
3615 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattner4294cec2005-05-07 23:49:08 +00003616
3617 if (match(Op0, m_And(m_Value(A), m_Value(B))))
3618 if (A == Op1 || B == Op1) // (A & ?) | A --> A
3619 return ReplaceInstUsesWith(I, Op1);
3620 if (match(Op1, m_And(m_Value(A), m_Value(B))))
3621 if (A == Op0 || B == Op0) // A | (A & ?) --> A
3622 return ReplaceInstUsesWith(I, Op0);
3623
Chris Lattnerb7845d62006-07-10 20:25:24 +00003624 // (A | B) | C and A | (B | C) -> bswap if possible.
3625 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003626 if (match(Op0, m_Or(m_Value(), m_Value())) ||
Chris Lattnerb7845d62006-07-10 20:25:24 +00003627 match(Op1, m_Or(m_Value(), m_Value())) ||
3628 (match(Op0, m_Shift(m_Value(), m_Value())) &&
3629 match(Op1, m_Shift(m_Value(), m_Value())))) {
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003630 if (Instruction *BSwap = MatchBSwap(I))
3631 return BSwap;
3632 }
3633
Chris Lattnerb62f5082005-05-09 04:58:36 +00003634 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
3635 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003636 MaskedValueIsZero(Op1, C1->getZExtValue())) {
Chris Lattnerb62f5082005-05-09 04:58:36 +00003637 Instruction *NOr = BinaryOperator::createOr(A, Op1, Op0->getName());
3638 Op0->setName("");
3639 return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
3640 }
3641
3642 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
3643 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003644 MaskedValueIsZero(Op0, C1->getZExtValue())) {
Chris Lattnerb62f5082005-05-09 04:58:36 +00003645 Instruction *NOr = BinaryOperator::createOr(A, Op0, Op1->getName());
3646 Op0->setName("");
3647 return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
3648 }
3649
Chris Lattner15212982005-09-18 03:42:07 +00003650 // (A & C1)|(B & C2)
Chris Lattnerd4252a72004-07-30 07:50:03 +00003651 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattner15212982005-09-18 03:42:07 +00003652 match(Op1, m_And(m_Value(B), m_ConstantInt(C2)))) {
3653
3654 if (A == B) // (A & C1)|(A & C2) == A & (C1|C2)
3655 return BinaryOperator::createAnd(A, ConstantExpr::getOr(C1, C2));
3656
3657
Chris Lattner01f56c62005-09-18 06:02:59 +00003658 // If we have: ((V + N) & C1) | (V & C2)
3659 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
3660 // replace with V+N.
3661 if (C1 == ConstantExpr::getNot(C2)) {
Chris Lattner330628a2006-01-06 17:59:59 +00003662 Value *V1 = 0, *V2 = 0;
Reid Spencere0fc4df2006-10-20 07:07:24 +00003663 if ((C2->getZExtValue() & (C2->getZExtValue()+1)) == 0 && // C2 == 0+1+
Chris Lattner01f56c62005-09-18 06:02:59 +00003664 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
3665 // Add commutes, try both ways.
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003666 if (V1 == B && MaskedValueIsZero(V2, C2->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003667 return ReplaceInstUsesWith(I, A);
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003668 if (V2 == B && MaskedValueIsZero(V1, C2->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003669 return ReplaceInstUsesWith(I, A);
3670 }
3671 // Or commutes, try both ways.
Reid Spencere0fc4df2006-10-20 07:07:24 +00003672 if ((C1->getZExtValue() & (C1->getZExtValue()+1)) == 0 &&
Chris Lattner01f56c62005-09-18 06:02:59 +00003673 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
3674 // Add commutes, try both ways.
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003675 if (V1 == A && MaskedValueIsZero(V2, C1->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003676 return ReplaceInstUsesWith(I, B);
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003677 if (V2 == A && MaskedValueIsZero(V1, C1->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003678 return ReplaceInstUsesWith(I, B);
Chris Lattner15212982005-09-18 03:42:07 +00003679 }
3680 }
3681 }
Chris Lattnerf05d69a2006-11-14 07:46:50 +00003682
3683 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
3684 if (ShiftInst *SI1 = dyn_cast<ShiftInst>(Op1)) {
3685 if (ShiftInst *SI0 = dyn_cast<ShiftInst>(Op0))
3686 if (SI0->getOpcode() == SI1->getOpcode() &&
3687 SI0->getOperand(1) == SI1->getOperand(1) &&
3688 (SI0->hasOneUse() || SI1->hasOneUse())) {
3689 Instruction *NewOp =
3690 InsertNewInstBefore(BinaryOperator::createOr(SI0->getOperand(0),
3691 SI1->getOperand(0),
3692 SI0->getName()), I);
3693 return new ShiftInst(SI1->getOpcode(), NewOp, SI1->getOperand(1));
3694 }
3695 }
Chris Lattner812aab72003-08-12 19:11:07 +00003696
Chris Lattnerd4252a72004-07-30 07:50:03 +00003697 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
3698 if (A == Op1) // ~A | A == -1
Misha Brukmanb1c93172005-04-21 23:48:37 +00003699 return ReplaceInstUsesWith(I,
Chris Lattnerd4252a72004-07-30 07:50:03 +00003700 ConstantIntegral::getAllOnesValue(I.getType()));
3701 } else {
3702 A = 0;
3703 }
Chris Lattner4294cec2005-05-07 23:49:08 +00003704 // Note, A is still live here!
Chris Lattnerd4252a72004-07-30 07:50:03 +00003705 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
3706 if (Op0 == B)
Misha Brukmanb1c93172005-04-21 23:48:37 +00003707 return ReplaceInstUsesWith(I,
Chris Lattnerd4252a72004-07-30 07:50:03 +00003708 ConstantIntegral::getAllOnesValue(I.getType()));
Chris Lattner3e327a42003-03-10 23:13:59 +00003709
Misha Brukman9c003d82004-07-30 12:50:08 +00003710 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattnerd4252a72004-07-30 07:50:03 +00003711 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3712 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
3713 I.getName()+".demorgan"), I);
3714 return BinaryOperator::createNot(And);
3715 }
Chris Lattner3e327a42003-03-10 23:13:59 +00003716 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00003717
Reid Spencer266e42b2006-12-23 06:05:41 +00003718 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
3719 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
3720 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattner3ac7c262003-08-13 20:16:26 +00003721 return R;
3722
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003723 Value *LHSVal, *RHSVal;
3724 ConstantInt *LHSCst, *RHSCst;
Reid Spencer266e42b2006-12-23 06:05:41 +00003725 ICmpInst::Predicate LHSCC, RHSCC;
3726 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3727 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3728 if (LHSVal == RHSVal && // Found (X icmp C1) | (X icmp C2)
3729 // icmp [us][gl]e x, cst is folded to icmp [us][gl]t elsewhere.
3730 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3731 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3732 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
3733 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE) {
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003734 // Ensure that the larger constant is on the RHS.
Reid Spencer266e42b2006-12-23 06:05:41 +00003735 ICmpInst::Predicate GT = ICmpInst::isSignedPredicate(LHSCC) ?
3736 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
3737 Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3738 ICmpInst *LHS = cast<ICmpInst>(Op0);
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003739 if (cast<ConstantBool>(Cmp)->getValue()) {
3740 std::swap(LHS, RHS);
3741 std::swap(LHSCst, RHSCst);
3742 std::swap(LHSCC, RHSCC);
3743 }
3744
Reid Spencer266e42b2006-12-23 06:05:41 +00003745 // At this point, we know we have have two icmp instructions
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003746 // comparing a value against two constants and or'ing the result
3747 // together. Because of the above check, we know that we only have
Reid Spencer266e42b2006-12-23 06:05:41 +00003748 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
3749 // FoldICmpLogical check above), that the two constants are not
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003750 // equal.
3751 assert(LHSCst != RHSCst && "Compares not folded above?");
3752
3753 switch (LHSCC) {
3754 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003755 case ICmpInst::ICMP_EQ:
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003756 switch (RHSCC) {
3757 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003758 case ICmpInst::ICMP_EQ:
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003759 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
3760 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3761 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3762 LHSVal->getName()+".off");
3763 InsertNewInstBefore(Add, I);
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003764 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
Reid Spencer266e42b2006-12-23 06:05:41 +00003765 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003766 }
Reid Spencer266e42b2006-12-23 06:05:41 +00003767 break; // (X == 13 | X == 15) -> no change
3768 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
3769 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
Chris Lattner5c219462005-04-19 06:04:18 +00003770 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00003771 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
3772 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
3773 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003774 return ReplaceInstUsesWith(I, RHS);
3775 }
3776 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00003777 case ICmpInst::ICMP_NE:
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003778 switch (RHSCC) {
3779 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003780 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
3781 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
3782 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003783 return ReplaceInstUsesWith(I, LHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00003784 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
3785 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
3786 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Chris Lattner6ab03f62006-09-28 23:35:22 +00003787 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003788 }
3789 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00003790 case ICmpInst::ICMP_ULT:
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003791 switch (RHSCC) {
3792 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003793 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003794 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00003795 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) ->(X-13) u> 2
3796 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false,
3797 false, I);
3798 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
3799 break;
3800 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
3801 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003802 return ReplaceInstUsesWith(I, RHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00003803 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
3804 break;
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003805 }
3806 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00003807 case ICmpInst::ICMP_SLT:
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003808 switch (RHSCC) {
3809 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003810 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
3811 break;
3812 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) ->(X-13) s> 2
3813 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), true,
3814 false, I);
3815 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
3816 break;
3817 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
3818 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
3819 return ReplaceInstUsesWith(I, RHS);
3820 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
3821 break;
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003822 }
Reid Spencer266e42b2006-12-23 06:05:41 +00003823 break;
3824 case ICmpInst::ICMP_UGT:
3825 switch (RHSCC) {
3826 default: assert(0 && "Unknown integer condition code!");
3827 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
3828 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
3829 return ReplaceInstUsesWith(I, LHS);
3830 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
3831 break;
3832 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
3833 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
3834 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
3835 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
3836 break;
3837 }
3838 break;
3839 case ICmpInst::ICMP_SGT:
3840 switch (RHSCC) {
3841 default: assert(0 && "Unknown integer condition code!");
3842 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
3843 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
3844 return ReplaceInstUsesWith(I, LHS);
3845 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
3846 break;
3847 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
3848 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
3849 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
3850 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
3851 break;
3852 }
3853 break;
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003854 }
3855 }
3856 }
Chris Lattner3af10532006-05-05 06:39:07 +00003857
3858 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Reid Spencer799b5bf2006-12-13 08:27:15 +00003859 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
Chris Lattner3af10532006-05-05 06:39:07 +00003860 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer799b5bf2006-12-13 08:27:15 +00003861 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
3862 const Type *SrcTy = Op0C->getOperand(0)->getType();
3863 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegral() &&
3864 // Only do this if the casts both really cause code to be generated.
Reid Spencer266e42b2006-12-23 06:05:41 +00003865 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
3866 I.getType(), TD) &&
3867 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
3868 I.getType(), TD)) {
Reid Spencer799b5bf2006-12-13 08:27:15 +00003869 Instruction *NewOp = BinaryOperator::createOr(Op0C->getOperand(0),
3870 Op1C->getOperand(0),
3871 I.getName());
3872 InsertNewInstBefore(NewOp, I);
3873 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
3874 }
Chris Lattner3af10532006-05-05 06:39:07 +00003875 }
Chris Lattner3af10532006-05-05 06:39:07 +00003876
Chris Lattner15212982005-09-18 03:42:07 +00003877
Chris Lattner113f4f42002-06-25 16:13:24 +00003878 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003879}
3880
Chris Lattnerc2076352004-02-16 01:20:27 +00003881// XorSelf - Implements: X ^ X --> 0
3882struct XorSelf {
3883 Value *RHS;
3884 XorSelf(Value *rhs) : RHS(rhs) {}
3885 bool shouldApply(Value *LHS) const { return LHS == RHS; }
3886 Instruction *apply(BinaryOperator &Xor) const {
3887 return &Xor;
3888 }
3889};
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003890
3891
Chris Lattner113f4f42002-06-25 16:13:24 +00003892Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003893 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00003894 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003895
Chris Lattner81a7a232004-10-16 18:11:37 +00003896 if (isa<UndefValue>(Op1))
3897 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
3898
Chris Lattnerc2076352004-02-16 01:20:27 +00003899 // xor X, X = 0, even if X is nested in a sequence of Xor's.
3900 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
3901 assert(Result == &I && "AssociativeOpt didn't work?");
Chris Lattnere6794492002-08-12 21:17:25 +00003902 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc2076352004-02-16 01:20:27 +00003903 }
Chris Lattner5b2edb12006-02-12 08:02:11 +00003904
3905 // See if we can simplify any instructions used by the instruction whose sole
3906 // purpose is to compute bits we don't care about.
3907 uint64_t KnownZero, KnownOne;
Chris Lattnerd70d9f52006-03-25 21:58:26 +00003908 if (!isa<PackedType>(I.getType()) &&
3909 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
Chris Lattner5b2edb12006-02-12 08:02:11 +00003910 KnownZero, KnownOne))
3911 return &I;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003912
Chris Lattner97638592003-07-23 21:37:07 +00003913 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00003914 // xor (icmp A, B), true = not (icmp A, B) = !icmp A, B
3915 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
3916 if (RHS == ConstantBool::getTrue() && ICI->hasOneUse())
3917 return new ICmpInst(ICI->getInversePredicate(),
3918 ICI->getOperand(0), ICI->getOperand(1));
Chris Lattnere5806662003-11-04 23:50:51 +00003919
Reid Spencer266e42b2006-12-23 06:05:41 +00003920 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattner8f2f5982003-11-05 01:06:05 +00003921 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003922 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
3923 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003924 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
3925 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003926 ConstantInt::get(I.getType(), 1));
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003927 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003928 }
Chris Lattner023a4832004-06-18 06:07:51 +00003929
3930 // ~(~X & Y) --> (X | ~Y)
3931 if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
3932 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
3933 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
3934 Instruction *NotY =
Misha Brukmanb1c93172005-04-21 23:48:37 +00003935 BinaryOperator::createNot(Op0I->getOperand(1),
Chris Lattner023a4832004-06-18 06:07:51 +00003936 Op0I->getOperand(1)->getName()+".not");
3937 InsertNewInstBefore(NotY, I);
3938 return BinaryOperator::createOr(Op0NotVal, NotY);
3939 }
3940 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003941
Chris Lattner97638592003-07-23 21:37:07 +00003942 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner5b2edb12006-02-12 08:02:11 +00003943 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner0f68fa62003-11-04 23:37:10 +00003944 // ~(X-c) --> (-c-1)-X
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003945 if (RHS->isAllOnesValue()) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003946 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
3947 return BinaryOperator::createSub(
3948 ConstantExpr::getSub(NegOp0CI,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003949 ConstantInt::get(I.getType(), 1)),
Chris Lattner0f68fa62003-11-04 23:37:10 +00003950 Op0I->getOperand(0));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003951 }
Chris Lattnerf78df7c2006-02-26 19:57:54 +00003952 } else if (Op0I->getOpcode() == Instruction::Or) {
3953 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
3954 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getZExtValue())) {
3955 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
3956 // Anything in both C1 and C2 is known to be zero, remove it from
3957 // NewRHS.
3958 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
3959 NewRHS = ConstantExpr::getAnd(NewRHS,
3960 ConstantExpr::getNot(CommonBits));
3961 WorkList.push_back(Op0I);
3962 I.setOperand(0, Op0I->getOperand(0));
3963 I.setOperand(1, NewRHS);
3964 return &I;
3965 }
Chris Lattner97638592003-07-23 21:37:07 +00003966 }
Chris Lattnerb8d6e402002-08-20 18:24:26 +00003967 }
Chris Lattner183b3362004-04-09 19:05:30 +00003968
3969 // Try to fold constant and into select arguments.
3970 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00003971 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00003972 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00003973 if (isa<PHINode>(Op0))
3974 if (Instruction *NV = FoldOpIntoPhi(I))
3975 return NV;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003976 }
3977
Chris Lattnerbb74e222003-03-10 23:06:50 +00003978 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00003979 if (X == Op1)
3980 return ReplaceInstUsesWith(I,
3981 ConstantIntegral::getAllOnesValue(I.getType()));
3982
Chris Lattnerbb74e222003-03-10 23:06:50 +00003983 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00003984 if (X == Op0)
3985 return ReplaceInstUsesWith(I,
3986 ConstantIntegral::getAllOnesValue(I.getType()));
3987
Chris Lattnerdcd07922006-04-01 08:03:55 +00003988 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1))
Chris Lattnerb36d9082004-02-16 03:54:20 +00003989 if (Op1I->getOpcode() == Instruction::Or) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003990 if (Op1I->getOperand(0) == Op0) { // B^(B|A) == (A|B)^B
Chris Lattnerdcd07922006-04-01 08:03:55 +00003991 Op1I->swapOperands();
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003992 I.swapOperands();
3993 std::swap(Op0, Op1);
3994 } else if (Op1I->getOperand(1) == Op0) { // B^(A|B) == (A|B)^B
Chris Lattnerdcd07922006-04-01 08:03:55 +00003995 I.swapOperands(); // Simplified below.
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003996 std::swap(Op0, Op1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003997 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00003998 } else if (Op1I->getOpcode() == Instruction::Xor) {
3999 if (Op0 == Op1I->getOperand(0)) // A^(A^B) == B
4000 return ReplaceInstUsesWith(I, Op1I->getOperand(1));
4001 else if (Op0 == Op1I->getOperand(1)) // A^(B^A) == B
4002 return ReplaceInstUsesWith(I, Op1I->getOperand(0));
Chris Lattnerdcd07922006-04-01 08:03:55 +00004003 } else if (Op1I->getOpcode() == Instruction::And && Op1I->hasOneUse()) {
4004 if (Op1I->getOperand(0) == Op0) // A^(A&B) -> A^(B&A)
4005 Op1I->swapOperands();
4006 if (Op0 == Op1I->getOperand(1)) { // A^(B&A) -> (B&A)^A
4007 I.swapOperands(); // Simplified below.
4008 std::swap(Op0, Op1);
4009 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00004010 }
Chris Lattner1bbb7b62003-03-10 18:24:17 +00004011
Chris Lattnerdcd07922006-04-01 08:03:55 +00004012 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00004013 if (Op0I->getOpcode() == Instruction::Or && Op0I->hasOneUse()) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00004014 if (Op0I->getOperand(0) == Op1) // (B|A)^B == (A|B)^B
Chris Lattnerdcd07922006-04-01 08:03:55 +00004015 Op0I->swapOperands();
Chris Lattnerdcf240a2003-03-10 21:43:22 +00004016 if (Op0I->getOperand(1) == Op1) { // (A|B)^B == A & ~B
Chris Lattnerdcd07922006-04-01 08:03:55 +00004017 Instruction *NotB = BinaryOperator::createNot(Op1, "tmp");
4018 InsertNewInstBefore(NotB, I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004019 return BinaryOperator::createAnd(Op0I->getOperand(0), NotB);
Chris Lattner1bbb7b62003-03-10 18:24:17 +00004020 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00004021 } else if (Op0I->getOpcode() == Instruction::Xor) {
4022 if (Op1 == Op0I->getOperand(0)) // (A^B)^A == B
4023 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
4024 else if (Op1 == Op0I->getOperand(1)) // (B^A)^A == B
4025 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattnerdcd07922006-04-01 08:03:55 +00004026 } else if (Op0I->getOpcode() == Instruction::And && Op0I->hasOneUse()) {
4027 if (Op0I->getOperand(0) == Op1) // (A&B)^A -> (B&A)^A
4028 Op0I->swapOperands();
Chris Lattner6cf49142006-04-01 22:05:01 +00004029 if (Op0I->getOperand(1) == Op1 && // (B&A)^A == ~B & A
4030 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattnerdcd07922006-04-01 08:03:55 +00004031 Instruction *N = BinaryOperator::createNot(Op0I->getOperand(0), "tmp");
4032 InsertNewInstBefore(N, I);
4033 return BinaryOperator::createAnd(N, Op1);
4034 }
Chris Lattner1bbb7b62003-03-10 18:24:17 +00004035 }
4036
Reid Spencer266e42b2006-12-23 06:05:41 +00004037 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
4038 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
4039 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattner3ac7c262003-08-13 20:16:26 +00004040 return R;
4041
Chris Lattner3af10532006-05-05 06:39:07 +00004042 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Reid Spencer799b5bf2006-12-13 08:27:15 +00004043 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
Chris Lattner3af10532006-05-05 06:39:07 +00004044 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer799b5bf2006-12-13 08:27:15 +00004045 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
4046 const Type *SrcTy = Op0C->getOperand(0)->getType();
4047 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegral() &&
4048 // Only do this if the casts both really cause code to be generated.
Reid Spencer266e42b2006-12-23 06:05:41 +00004049 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4050 I.getType(), TD) &&
4051 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4052 I.getType(), TD)) {
Reid Spencer799b5bf2006-12-13 08:27:15 +00004053 Instruction *NewOp = BinaryOperator::createXor(Op0C->getOperand(0),
4054 Op1C->getOperand(0),
4055 I.getName());
4056 InsertNewInstBefore(NewOp, I);
4057 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
4058 }
Chris Lattner3af10532006-05-05 06:39:07 +00004059 }
Chris Lattnerf05d69a2006-11-14 07:46:50 +00004060
4061 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
4062 if (ShiftInst *SI1 = dyn_cast<ShiftInst>(Op1)) {
4063 if (ShiftInst *SI0 = dyn_cast<ShiftInst>(Op0))
4064 if (SI0->getOpcode() == SI1->getOpcode() &&
4065 SI0->getOperand(1) == SI1->getOperand(1) &&
4066 (SI0->hasOneUse() || SI1->hasOneUse())) {
4067 Instruction *NewOp =
4068 InsertNewInstBefore(BinaryOperator::createXor(SI0->getOperand(0),
4069 SI1->getOperand(0),
4070 SI0->getName()), I);
4071 return new ShiftInst(SI1->getOpcode(), NewOp, SI1->getOperand(1));
4072 }
4073 }
Chris Lattner3af10532006-05-05 06:39:07 +00004074
Chris Lattner113f4f42002-06-25 16:13:24 +00004075 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004076}
4077
Chris Lattner6862fbd2004-09-29 17:40:11 +00004078static bool isPositive(ConstantInt *C) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00004079 return C->getSExtValue() >= 0;
Chris Lattner6862fbd2004-09-29 17:40:11 +00004080}
4081
4082/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
4083/// overflowed for this type.
4084static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
4085 ConstantInt *In2) {
4086 Result = cast<ConstantInt>(ConstantExpr::getAdd(In1, In2));
4087
Reid Spencerc635f472006-12-31 05:48:39 +00004088 return cast<ConstantInt>(Result)->getZExtValue() <
4089 cast<ConstantInt>(In1)->getZExtValue();
Chris Lattner6862fbd2004-09-29 17:40:11 +00004090}
4091
Chris Lattner0798af32005-01-13 20:14:25 +00004092/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
4093/// code necessary to compute the offset from the base pointer (without adding
4094/// in the base pointer). Return the result as a signed integer of intptr size.
4095static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
4096 TargetData &TD = IC.getTargetData();
4097 gep_type_iterator GTI = gep_type_begin(GEP);
Reid Spencer266e42b2006-12-23 06:05:41 +00004098 const Type *IntPtrTy = TD.getIntPtrType();
4099 Value *Result = Constant::getNullValue(IntPtrTy);
Chris Lattner0798af32005-01-13 20:14:25 +00004100
4101 // Build a mask for high order bits.
Chris Lattner77defba2006-02-07 07:00:41 +00004102 uint64_t PtrSizeMask = ~0ULL >> (64-TD.getPointerSize()*8);
Chris Lattner0798af32005-01-13 20:14:25 +00004103
Chris Lattner0798af32005-01-13 20:14:25 +00004104 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
4105 Value *Op = GEP->getOperand(i);
Chris Lattnerd35d2102005-01-13 23:26:48 +00004106 uint64_t Size = TD.getTypeSize(GTI.getIndexedType()) & PtrSizeMask;
Reid Spencer266e42b2006-12-23 06:05:41 +00004107 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
Chris Lattner0798af32005-01-13 20:14:25 +00004108 if (Constant *OpC = dyn_cast<Constant>(Op)) {
4109 if (!OpC->isNullValue()) {
Reid Spencer266e42b2006-12-23 06:05:41 +00004110 OpC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
Chris Lattner0798af32005-01-13 20:14:25 +00004111 Scale = ConstantExpr::getMul(OpC, Scale);
4112 if (Constant *RC = dyn_cast<Constant>(Result))
4113 Result = ConstantExpr::getAdd(RC, Scale);
4114 else {
4115 // Emit an add instruction.
4116 Result = IC.InsertNewInstBefore(
4117 BinaryOperator::createAdd(Result, Scale,
4118 GEP->getName()+".offs"), I);
4119 }
4120 }
4121 } else {
Chris Lattner7aa41cf2005-01-14 17:17:59 +00004122 // Convert to correct type.
Reid Spencer266e42b2006-12-23 06:05:41 +00004123 Op = IC.InsertNewInstBefore(CastInst::createSExtOrBitCast(Op, IntPtrTy,
Chris Lattner7aa41cf2005-01-14 17:17:59 +00004124 Op->getName()+".c"), I);
4125 if (Size != 1)
Chris Lattner4cb9fa32005-01-13 20:40:58 +00004126 // We'll let instcombine(mul) convert this to a shl if possible.
4127 Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
4128 GEP->getName()+".idx"), I);
Chris Lattner0798af32005-01-13 20:14:25 +00004129
4130 // Emit an add instruction.
Chris Lattner4cb9fa32005-01-13 20:40:58 +00004131 Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
Chris Lattner0798af32005-01-13 20:14:25 +00004132 GEP->getName()+".offs"), I);
4133 }
4134 }
4135 return Result;
4136}
4137
Reid Spencer266e42b2006-12-23 06:05:41 +00004138/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
Chris Lattner0798af32005-01-13 20:14:25 +00004139/// else. At this point we know that the GEP is on the LHS of the comparison.
Reid Spencer266e42b2006-12-23 06:05:41 +00004140Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
4141 ICmpInst::Predicate Cond,
4142 Instruction &I) {
Chris Lattner0798af32005-01-13 20:14:25 +00004143 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattner81e84172005-01-13 22:25:21 +00004144
4145 if (CastInst *CI = dyn_cast<CastInst>(RHS))
4146 if (isa<PointerType>(CI->getOperand(0)->getType()))
4147 RHS = CI->getOperand(0);
4148
Chris Lattner0798af32005-01-13 20:14:25 +00004149 Value *PtrBase = GEPLHS->getOperand(0);
4150 if (PtrBase == RHS) {
4151 // As an optimization, we don't actually have to compute the actual value of
Reid Spencer266e42b2006-12-23 06:05:41 +00004152 // OFFSET if this is a icmp_eq or icmp_ne comparison, just return whether
4153 // each index is zero or not.
4154 if (Cond == ICmpInst::ICMP_EQ || Cond == ICmpInst::ICMP_NE) {
Chris Lattner81e84172005-01-13 22:25:21 +00004155 Instruction *InVal = 0;
Chris Lattnercd517ff2005-01-28 19:32:01 +00004156 gep_type_iterator GTI = gep_type_begin(GEPLHS);
4157 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i, ++GTI) {
Chris Lattner81e84172005-01-13 22:25:21 +00004158 bool EmitIt = true;
4159 if (Constant *C = dyn_cast<Constant>(GEPLHS->getOperand(i))) {
4160 if (isa<UndefValue>(C)) // undef index -> undef.
4161 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
4162 if (C->isNullValue())
4163 EmitIt = false;
Chris Lattnercd517ff2005-01-28 19:32:01 +00004164 else if (TD->getTypeSize(GTI.getIndexedType()) == 0) {
4165 EmitIt = false; // This is indexing into a zero sized array?
Misha Brukmanb1c93172005-04-21 23:48:37 +00004166 } else if (isa<ConstantInt>(C))
Chris Lattner81e84172005-01-13 22:25:21 +00004167 return ReplaceInstUsesWith(I, // No comparison is needed here.
Reid Spencer266e42b2006-12-23 06:05:41 +00004168 ConstantBool::get(Cond == ICmpInst::ICMP_NE));
Chris Lattner81e84172005-01-13 22:25:21 +00004169 }
4170
4171 if (EmitIt) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00004172 Instruction *Comp =
Reid Spencer266e42b2006-12-23 06:05:41 +00004173 new ICmpInst(Cond, GEPLHS->getOperand(i),
Chris Lattner81e84172005-01-13 22:25:21 +00004174 Constant::getNullValue(GEPLHS->getOperand(i)->getType()));
4175 if (InVal == 0)
4176 InVal = Comp;
4177 else {
4178 InVal = InsertNewInstBefore(InVal, I);
4179 InsertNewInstBefore(Comp, I);
Reid Spencer266e42b2006-12-23 06:05:41 +00004180 if (Cond == ICmpInst::ICMP_NE) // True if any are unequal
Chris Lattner81e84172005-01-13 22:25:21 +00004181 InVal = BinaryOperator::createOr(InVal, Comp);
4182 else // True if all are equal
4183 InVal = BinaryOperator::createAnd(InVal, Comp);
4184 }
4185 }
4186 }
4187
4188 if (InVal)
4189 return InVal;
4190 else
Reid Spencer266e42b2006-12-23 06:05:41 +00004191 // No comparison is needed here, all indexes = 0
4192 ReplaceInstUsesWith(I, ConstantBool::get(Cond == ICmpInst::ICMP_EQ));
Chris Lattner81e84172005-01-13 22:25:21 +00004193 }
Chris Lattner0798af32005-01-13 20:14:25 +00004194
Reid Spencer266e42b2006-12-23 06:05:41 +00004195 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner0798af32005-01-13 20:14:25 +00004196 // the result to fold to a constant!
4197 if (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) {
4198 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
4199 Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
Reid Spencer266e42b2006-12-23 06:05:41 +00004200 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
4201 Constant::getNullValue(Offset->getType()));
Chris Lattner0798af32005-01-13 20:14:25 +00004202 }
4203 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
Chris Lattnera21bf8d2005-04-25 20:17:30 +00004204 // If the base pointers are different, but the indices are the same, just
4205 // compare the base pointer.
4206 if (PtrBase != GEPRHS->getOperand(0)) {
4207 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00004208 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattnerbd43b9d2005-04-26 14:40:41 +00004209 GEPRHS->getOperand(0)->getType();
Chris Lattnera21bf8d2005-04-25 20:17:30 +00004210 if (IndicesTheSame)
4211 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4212 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4213 IndicesTheSame = false;
4214 break;
4215 }
4216
4217 // If all indices are the same, just compare the base pointers.
4218 if (IndicesTheSame)
Reid Spencer266e42b2006-12-23 06:05:41 +00004219 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
4220 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattnera21bf8d2005-04-25 20:17:30 +00004221
4222 // Otherwise, the base pointers are different and the indices are
4223 // different, bail out.
Chris Lattner0798af32005-01-13 20:14:25 +00004224 return 0;
Chris Lattnera21bf8d2005-04-25 20:17:30 +00004225 }
Chris Lattner0798af32005-01-13 20:14:25 +00004226
Chris Lattner81e84172005-01-13 22:25:21 +00004227 // If one of the GEPs has all zero indices, recurse.
4228 bool AllZeros = true;
4229 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4230 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
4231 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
4232 AllZeros = false;
4233 break;
4234 }
4235 if (AllZeros)
Reid Spencer266e42b2006-12-23 06:05:41 +00004236 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
4237 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner4fa89822005-01-14 00:20:05 +00004238
4239 // If the other GEP has all zero indices, recurse.
Chris Lattner81e84172005-01-13 22:25:21 +00004240 AllZeros = true;
4241 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4242 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
4243 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
4244 AllZeros = false;
4245 break;
4246 }
4247 if (AllZeros)
Reid Spencer266e42b2006-12-23 06:05:41 +00004248 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
Chris Lattner81e84172005-01-13 22:25:21 +00004249
Chris Lattner4fa89822005-01-14 00:20:05 +00004250 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
4251 // If the GEPs only differ by one index, compare it.
4252 unsigned NumDifferences = 0; // Keep track of # differences.
4253 unsigned DiffOperand = 0; // The operand that differs.
4254 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4255 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004256 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
4257 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattnerfc4429e2005-01-21 23:06:49 +00004258 // Irreconcilable differences.
Chris Lattner4fa89822005-01-14 00:20:05 +00004259 NumDifferences = 2;
4260 break;
4261 } else {
4262 if (NumDifferences++) break;
4263 DiffOperand = i;
4264 }
4265 }
4266
4267 if (NumDifferences == 0) // SAME GEP?
4268 return ReplaceInstUsesWith(I, // No comparison is needed here.
Reid Spencer266e42b2006-12-23 06:05:41 +00004269 ConstantBool::get(Cond == ICmpInst::ICMP_EQ));
Chris Lattner4fa89822005-01-14 00:20:05 +00004270 else if (NumDifferences == 1) {
Chris Lattnerfc4429e2005-01-21 23:06:49 +00004271 Value *LHSV = GEPLHS->getOperand(DiffOperand);
4272 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Reid Spencer266e42b2006-12-23 06:05:41 +00004273 // Make sure we do a signed comparison here.
4274 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
Chris Lattner4fa89822005-01-14 00:20:05 +00004275 }
4276 }
4277
Reid Spencer266e42b2006-12-23 06:05:41 +00004278 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner0798af32005-01-13 20:14:25 +00004279 // the result to fold to a constant!
4280 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
4281 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
4282 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
4283 Value *L = EmitGEPOffset(GEPLHS, I, *this);
4284 Value *R = EmitGEPOffset(GEPRHS, I, *this);
Reid Spencer266e42b2006-12-23 06:05:41 +00004285 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
Chris Lattner0798af32005-01-13 20:14:25 +00004286 }
4287 }
4288 return 0;
4289}
4290
Reid Spencer266e42b2006-12-23 06:05:41 +00004291Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
4292 bool Changed = SimplifyCompare(I);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004293 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004294
Reid Spencer266e42b2006-12-23 06:05:41 +00004295 // fcmp pred X, X
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004296 if (Op0 == Op1)
4297 return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
Chris Lattner1fc23f32002-05-09 20:11:54 +00004298
Reid Spencer266e42b2006-12-23 06:05:41 +00004299 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
Chris Lattner81a7a232004-10-16 18:11:37 +00004300 return ReplaceInstUsesWith(I, UndefValue::get(Type::BoolTy));
4301
Reid Spencer266e42b2006-12-23 06:05:41 +00004302 // Handle fcmp with constant RHS
4303 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
4304 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4305 switch (LHSI->getOpcode()) {
4306 case Instruction::PHI:
4307 if (Instruction *NV = FoldOpIntoPhi(I))
4308 return NV;
4309 break;
4310 case Instruction::Select:
4311 // If either operand of the select is a constant, we can fold the
4312 // comparison into the select arms, which will cause one to be
4313 // constant folded and the select turned into a bitwise or.
4314 Value *Op1 = 0, *Op2 = 0;
4315 if (LHSI->hasOneUse()) {
4316 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
4317 // Fold the known value into the constant operand.
4318 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
4319 // Insert a new FCmp of the other select operand.
4320 Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
4321 LHSI->getOperand(2), RHSC,
4322 I.getName()), I);
4323 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
4324 // Fold the known value into the constant operand.
4325 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
4326 // Insert a new FCmp of the other select operand.
4327 Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
4328 LHSI->getOperand(1), RHSC,
4329 I.getName()), I);
4330 }
4331 }
4332
4333 if (Op1)
4334 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
4335 break;
4336 }
4337 }
4338
4339 return Changed ? &I : 0;
4340}
4341
4342Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
4343 bool Changed = SimplifyCompare(I);
4344 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4345 const Type *Ty = Op0->getType();
4346
4347 // icmp X, X
4348 if (Op0 == Op1)
4349 return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
4350
4351 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
4352 return ReplaceInstUsesWith(I, UndefValue::get(Type::BoolTy));
4353
4354 // icmp of GlobalValues can never equal each other as long as they aren't
4355 // external weak linkage type.
4356 if (GlobalValue *GV0 = dyn_cast<GlobalValue>(Op0))
4357 if (GlobalValue *GV1 = dyn_cast<GlobalValue>(Op1))
4358 if (!GV0->hasExternalWeakLinkage() || !GV1->hasExternalWeakLinkage())
4359 return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
4360
4361 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
Chris Lattner15ff1e12004-11-14 07:33:16 +00004362 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanb1c93172005-04-21 23:48:37 +00004363 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
4364 isa<ConstantPointerNull>(Op0)) &&
4365 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner15ff1e12004-11-14 07:33:16 +00004366 isa<ConstantPointerNull>(Op1)))
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004367 return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
4368
Reid Spencer266e42b2006-12-23 06:05:41 +00004369 // icmp's with boolean values can always be turned into bitwise operations
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004370 if (Ty == Type::BoolTy) {
Reid Spencer266e42b2006-12-23 06:05:41 +00004371 switch (I.getPredicate()) {
4372 default: assert(0 && "Invalid icmp instruction!");
4373 case ICmpInst::ICMP_EQ: { // icmp eq bool %A, %B -> ~(A^B)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004374 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004375 InsertNewInstBefore(Xor, I);
Chris Lattner16930792003-11-03 04:25:02 +00004376 return BinaryOperator::createNot(Xor);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004377 }
Reid Spencer266e42b2006-12-23 06:05:41 +00004378 case ICmpInst::ICMP_NE: // icmp eq bool %A, %B -> A^B
Chris Lattner4456da62004-08-11 00:50:51 +00004379 return BinaryOperator::createXor(Op0, Op1);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004380
Reid Spencer266e42b2006-12-23 06:05:41 +00004381 case ICmpInst::ICMP_UGT:
4382 case ICmpInst::ICMP_SGT:
4383 std::swap(Op0, Op1); // Change icmp gt -> icmp lt
Chris Lattner4456da62004-08-11 00:50:51 +00004384 // FALL THROUGH
Reid Spencer266e42b2006-12-23 06:05:41 +00004385 case ICmpInst::ICMP_ULT:
4386 case ICmpInst::ICMP_SLT: { // icmp lt bool A, B -> ~X & Y
Chris Lattner4456da62004-08-11 00:50:51 +00004387 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4388 InsertNewInstBefore(Not, I);
4389 return BinaryOperator::createAnd(Not, Op1);
4390 }
Reid Spencer266e42b2006-12-23 06:05:41 +00004391 case ICmpInst::ICMP_UGE:
4392 case ICmpInst::ICMP_SGE:
4393 std::swap(Op0, Op1); // Change icmp ge -> icmp le
Chris Lattner4456da62004-08-11 00:50:51 +00004394 // FALL THROUGH
Reid Spencer266e42b2006-12-23 06:05:41 +00004395 case ICmpInst::ICMP_ULE:
4396 case ICmpInst::ICMP_SLE: { // icmp le bool %A, %B -> ~A | B
Chris Lattner4456da62004-08-11 00:50:51 +00004397 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4398 InsertNewInstBefore(Not, I);
4399 return BinaryOperator::createOr(Not, Op1);
4400 }
4401 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004402 }
4403
Chris Lattner2dd01742004-06-09 04:24:29 +00004404 // See if we are doing a comparison between a constant and an instruction that
4405 // can be folded into the comparison.
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004406 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00004407 switch (I.getPredicate()) {
4408 default: break;
4409 case ICmpInst::ICMP_ULT: // A <u MIN -> FALSE
4410 if (CI->isMinValue(false))
Chris Lattner6ab03f62006-09-28 23:35:22 +00004411 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004412 if (CI->isMaxValue(false)) // A <u MAX -> A != MAX
4413 return new ICmpInst(ICmpInst::ICMP_NE, Op0,Op1);
4414 if (isMinValuePlusOne(CI,false)) // A <u MIN+1 -> A == MIN
4415 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
4416 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00004417
Reid Spencer266e42b2006-12-23 06:05:41 +00004418 case ICmpInst::ICMP_SLT:
4419 if (CI->isMinValue(true)) // A <s MIN -> FALSE
Chris Lattner6ab03f62006-09-28 23:35:22 +00004420 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004421 if (CI->isMaxValue(true)) // A <s MAX -> A != MAX
4422 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4423 if (isMinValuePlusOne(CI,true)) // A <s MIN+1 -> A == MIN
4424 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
4425 break;
4426
4427 case ICmpInst::ICMP_UGT:
4428 if (CI->isMaxValue(false)) // A >u MAX -> FALSE
4429 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4430 if (CI->isMinValue(false)) // A >u MIN -> A != MIN
4431 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4432 if (isMaxValueMinusOne(CI, false)) // A >u MAX-1 -> A == MAX
4433 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
4434 break;
4435
4436 case ICmpInst::ICMP_SGT:
4437 if (CI->isMaxValue(true)) // A >s MAX -> FALSE
4438 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4439 if (CI->isMinValue(true)) // A >s MIN -> A != MIN
4440 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4441 if (isMaxValueMinusOne(CI, true)) // A >s MAX-1 -> A == MAX
4442 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
4443 break;
4444
4445 case ICmpInst::ICMP_ULE:
4446 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
Chris Lattner6ab03f62006-09-28 23:35:22 +00004447 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004448 if (CI->isMinValue(false)) // A <=u MIN -> A == MIN
4449 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4450 if (isMaxValueMinusOne(CI,false)) // A <=u MAX-1 -> A != MAX
4451 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
4452 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00004453
Reid Spencer266e42b2006-12-23 06:05:41 +00004454 case ICmpInst::ICMP_SLE:
4455 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
4456 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4457 if (CI->isMinValue(true)) // A <=s MIN -> A == MIN
4458 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4459 if (isMaxValueMinusOne(CI,true)) // A <=s MAX-1 -> A != MAX
4460 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
4461 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00004462
Reid Spencer266e42b2006-12-23 06:05:41 +00004463 case ICmpInst::ICMP_UGE:
4464 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
4465 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4466 if (CI->isMaxValue(false)) // A >=u MAX -> A == MAX
4467 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4468 if (isMinValuePlusOne(CI,false)) // A >=u MIN-1 -> A != MIN
4469 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
4470 break;
4471
4472 case ICmpInst::ICMP_SGE:
4473 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
4474 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4475 if (CI->isMaxValue(true)) // A >=s MAX -> A == MAX
4476 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4477 if (isMinValuePlusOne(CI,true)) // A >=s MIN-1 -> A != MIN
4478 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
4479 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00004480 }
4481
Reid Spencer266e42b2006-12-23 06:05:41 +00004482 // If we still have a icmp le or icmp ge instruction, turn it into the
4483 // appropriate icmp lt or icmp gt instruction. Since the border cases have
Chris Lattner6862fbd2004-09-29 17:40:11 +00004484 // already been handled above, this requires little checking.
4485 //
Reid Spencer266e42b2006-12-23 06:05:41 +00004486 if (I.getPredicate() == ICmpInst::ICMP_ULE)
4487 return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
4488 if (I.getPredicate() == ICmpInst::ICMP_SLE)
4489 return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
4490 if (I.getPredicate() == ICmpInst::ICMP_UGE)
4491 return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
4492 if (I.getPredicate() == ICmpInst::ICMP_SGE)
4493 return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
Chris Lattneree0f2802006-02-12 02:07:56 +00004494
4495 // See if we can fold the comparison based on bits known to be zero or one
4496 // in the input.
4497 uint64_t KnownZero, KnownOne;
4498 if (SimplifyDemandedBits(Op0, Ty->getIntegralTypeMask(),
4499 KnownZero, KnownOne, 0))
4500 return &I;
4501
4502 // Given the known and unknown bits, compute a range that the LHS could be
4503 // in.
4504 if (KnownOne | KnownZero) {
Reid Spencer266e42b2006-12-23 06:05:41 +00004505 // Compute the Min, Max and RHS values based on the known bits. For the
4506 // EQ and NE we use unsigned values.
Reid Spencer910f23f2006-12-23 19:17:57 +00004507 uint64_t UMin = 0, UMax = 0, URHSVal = 0;
4508 int64_t SMin = 0, SMax = 0, SRHSVal = 0;
Reid Spencer266e42b2006-12-23 06:05:41 +00004509 if (ICmpInst::isSignedPredicate(I.getPredicate())) {
4510 SRHSVal = CI->getSExtValue();
4511 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, SMin,
4512 SMax);
4513 } else {
4514 URHSVal = CI->getZExtValue();
4515 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, UMin,
4516 UMax);
4517 }
4518 switch (I.getPredicate()) { // LE/GE have been folded already.
4519 default: assert(0 && "Unknown icmp opcode!");
4520 case ICmpInst::ICMP_EQ:
4521 if (UMax < URHSVal || UMin > URHSVal)
4522 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4523 break;
4524 case ICmpInst::ICMP_NE:
4525 if (UMax < URHSVal || UMin > URHSVal)
4526 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4527 break;
4528 case ICmpInst::ICMP_ULT:
4529 if (UMax < URHSVal)
4530 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4531 if (UMin > URHSVal)
4532 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4533 break;
4534 case ICmpInst::ICMP_UGT:
4535 if (UMin > URHSVal)
4536 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4537 if (UMax < URHSVal)
4538 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4539 break;
4540 case ICmpInst::ICMP_SLT:
4541 if (SMax < SRHSVal)
4542 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4543 if (SMin > SRHSVal)
4544 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4545 break;
4546 case ICmpInst::ICMP_SGT:
4547 if (SMin > SRHSVal)
4548 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4549 if (SMax < SRHSVal)
4550 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4551 break;
Chris Lattneree0f2802006-02-12 02:07:56 +00004552 }
4553 }
4554
Reid Spencer266e42b2006-12-23 06:05:41 +00004555 // Since the RHS is a ConstantInt (CI), if the left hand side is an
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004556 // instruction, see if that instruction also has constants so that the
Reid Spencer266e42b2006-12-23 06:05:41 +00004557 // instruction can be folded into the icmp
Chris Lattnere1e10e12004-05-25 06:32:08 +00004558 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004559 switch (LHSI->getOpcode()) {
4560 case Instruction::And:
4561 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
4562 LHSI->getOperand(0)->hasOneUse()) {
Chris Lattner4922a0e2006-09-18 05:27:43 +00004563 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
4564
Reid Spencer266e42b2006-12-23 06:05:41 +00004565 // If the LHS is an AND of a truncating cast, we can widen the
Chris Lattner4922a0e2006-09-18 05:27:43 +00004566 // and/compare to be the input width without changing the value
4567 // produced, eliminating a cast.
4568 if (CastInst *Cast = dyn_cast<CastInst>(LHSI->getOperand(0))) {
4569 // We can do this transformation if either the AND constant does not
4570 // have its sign bit set or if it is an equality comparison.
4571 // Extending a relational comparison when we're checking the sign
4572 // bit would not work.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00004573 if (Cast->hasOneUse() && isa<TruncInst>(Cast) &&
Chris Lattner4922a0e2006-09-18 05:27:43 +00004574 (I.isEquality() ||
4575 (AndCST->getZExtValue() == (uint64_t)AndCST->getSExtValue()) &&
4576 (CI->getZExtValue() == (uint64_t)CI->getSExtValue()))) {
4577 ConstantInt *NewCST;
4578 ConstantInt *NewCI;
Reid Spencerc635f472006-12-31 05:48:39 +00004579 NewCST = ConstantInt::get(Cast->getOperand(0)->getType(),
4580 AndCST->getZExtValue());
4581 NewCI = ConstantInt::get(Cast->getOperand(0)->getType(),
4582 CI->getZExtValue());
Chris Lattner4922a0e2006-09-18 05:27:43 +00004583 Instruction *NewAnd =
4584 BinaryOperator::createAnd(Cast->getOperand(0), NewCST,
4585 LHSI->getName());
4586 InsertNewInstBefore(NewAnd, I);
Reid Spencer266e42b2006-12-23 06:05:41 +00004587 return new ICmpInst(I.getPredicate(), NewAnd, NewCI);
Chris Lattner4922a0e2006-09-18 05:27:43 +00004588 }
4589 }
4590
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004591 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
4592 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
4593 // happens a LOT in code produced by the C front-end, for bitfield
4594 // access.
4595 ShiftInst *Shift = dyn_cast<ShiftInst>(LHSI->getOperand(0));
Chris Lattneree0f2802006-02-12 02:07:56 +00004596
4597 // Check to see if there is a noop-cast between the shift and the and.
4598 if (!Shift) {
4599 if (CastInst *CI = dyn_cast<CastInst>(LHSI->getOperand(0)))
Reid Spencer74a528b2006-12-13 18:21:21 +00004600 if (CI->getOpcode() == Instruction::BitCast)
Chris Lattneree0f2802006-02-12 02:07:56 +00004601 Shift = dyn_cast<ShiftInst>(CI->getOperand(0));
4602 }
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004603
Reid Spencere0fc4df2006-10-20 07:07:24 +00004604 ConstantInt *ShAmt;
4605 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
Chris Lattneree0f2802006-02-12 02:07:56 +00004606 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
4607 const Type *AndTy = AndCST->getType(); // Type of the and.
Misha Brukmanb1c93172005-04-21 23:48:37 +00004608
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004609 // We can fold this as long as we can't shift unknown bits
4610 // into the mask. This can only happen with signed shift
4611 // rights, as they sign-extend.
4612 if (ShAmt) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004613 bool CanFold = Shift->isLogicalShift();
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004614 if (!CanFold) {
4615 // To test for the bad case of the signed shr, see if any
4616 // of the bits shifted in could be tested after the mask.
Reid Spencere0fc4df2006-10-20 07:07:24 +00004617 int ShAmtVal = Ty->getPrimitiveSizeInBits()-ShAmt->getZExtValue();
Chris Lattnerc53cb9d2005-06-17 01:29:28 +00004618 if (ShAmtVal < 0) ShAmtVal = 0; // Out of range shift.
4619
Reid Spencerc635f472006-12-31 05:48:39 +00004620 Constant *OShAmt = ConstantInt::get(Type::Int8Ty, ShAmtVal);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004621 Constant *ShVal =
Chris Lattneree0f2802006-02-12 02:07:56 +00004622 ConstantExpr::getShl(ConstantInt::getAllOnesValue(AndTy),
4623 OShAmt);
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004624 if (ConstantExpr::getAnd(ShVal, AndCST)->isNullValue())
4625 CanFold = true;
4626 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004627
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004628 if (CanFold) {
Chris Lattner6afc02f2004-09-28 17:54:07 +00004629 Constant *NewCst;
4630 if (Shift->getOpcode() == Instruction::Shl)
Reid Spencerfdff9382006-11-08 06:47:33 +00004631 NewCst = ConstantExpr::getLShr(CI, ShAmt);
Chris Lattner6afc02f2004-09-28 17:54:07 +00004632 else
4633 NewCst = ConstantExpr::getShl(CI, ShAmt);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004634
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004635 // Check to see if we are shifting out any of the bits being
4636 // compared.
4637 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != CI){
4638 // If we shifted bits out, the fold is not going to work out.
4639 // As a special case, check to see if this means that the
4640 // result is always true or false now.
Reid Spencer266e42b2006-12-23 06:05:41 +00004641 if (I.getPredicate() == ICmpInst::ICMP_EQ)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004642 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004643 if (I.getPredicate() == ICmpInst::ICMP_NE)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004644 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004645 } else {
4646 I.setOperand(1, NewCst);
Chris Lattner6afc02f2004-09-28 17:54:07 +00004647 Constant *NewAndCST;
4648 if (Shift->getOpcode() == Instruction::Shl)
Reid Spencerfdff9382006-11-08 06:47:33 +00004649 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
Chris Lattner6afc02f2004-09-28 17:54:07 +00004650 else
4651 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
4652 LHSI->setOperand(1, NewAndCST);
Reid Spencer6ff3e732007-01-04 05:23:51 +00004653 LHSI->setOperand(0, Shift->getOperand(0));
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004654 WorkList.push_back(Shift); // Shift is dead.
4655 AddUsesToWorkList(I);
4656 return &I;
Chris Lattner1638de42004-07-21 19:50:44 +00004657 }
4658 }
Chris Lattner35167c32004-06-09 07:59:58 +00004659 }
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004660
4661 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
4662 // preferable because it allows the C<<Y expression to be hoisted out
4663 // of a loop if Y is invariant and X is not.
4664 if (Shift && Shift->hasOneUse() && CI->isNullValue() &&
Chris Lattnerde077922006-09-18 18:27:05 +00004665 I.isEquality() && !Shift->isArithmeticShift() &&
4666 isa<Instruction>(Shift->getOperand(0))) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004667 // Compute C << Y.
4668 Value *NS;
Reid Spencerfdff9382006-11-08 06:47:33 +00004669 if (Shift->getOpcode() == Instruction::LShr) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004670 NS = new ShiftInst(Instruction::Shl, AndCST, Shift->getOperand(1),
4671 "tmp");
4672 } else {
Reid Spencer2a499b02006-12-13 17:19:09 +00004673 // Insert a logical shift.
4674 NS = new ShiftInst(Instruction::LShr, AndCST,
Chris Lattner4922a0e2006-09-18 05:27:43 +00004675 Shift->getOperand(1), "tmp");
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004676 }
4677 InsertNewInstBefore(cast<Instruction>(NS), I);
4678
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004679 // Compute X & (C << Y).
Reid Spencer6ff3e732007-01-04 05:23:51 +00004680 Instruction *NewAnd = BinaryOperator::createAnd(
4681 Shift->getOperand(0), NS, LHSI->getName());
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004682 InsertNewInstBefore(NewAnd, I);
4683
4684 I.setOperand(0, NewAnd);
4685 return &I;
4686 }
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004687 }
4688 break;
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004689
Reid Spencer266e42b2006-12-23 06:05:41 +00004690 case Instruction::Shl: // (icmp pred (shl X, ShAmt), CI)
Reid Spencere0fc4df2006-10-20 07:07:24 +00004691 if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004692 if (I.isEquality()) {
Chris Lattner19b57f52005-06-15 20:53:31 +00004693 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
4694
4695 // Check that the shift amount is in range. If not, don't perform
4696 // undefined shifts. When the shift is visited it will be
4697 // simplified.
Reid Spencere0fc4df2006-10-20 07:07:24 +00004698 if (ShAmt->getZExtValue() >= TypeBits)
Chris Lattner19b57f52005-06-15 20:53:31 +00004699 break;
4700
Chris Lattner272d5ca2004-09-28 18:22:15 +00004701 // If we are comparing against bits always shifted out, the
4702 // comparison cannot succeed.
Misha Brukmanb1c93172005-04-21 23:48:37 +00004703 Constant *Comp =
Reid Spencerfdff9382006-11-08 06:47:33 +00004704 ConstantExpr::getShl(ConstantExpr::getLShr(CI, ShAmt), ShAmt);
Chris Lattner272d5ca2004-09-28 18:22:15 +00004705 if (Comp != CI) {// Comparing against a bit that we know is zero.
Reid Spencer266e42b2006-12-23 06:05:41 +00004706 bool IsICMP_NE = I.getPredicate() == ICmpInst::ICMP_NE;
4707 Constant *Cst = ConstantBool::get(IsICMP_NE);
Chris Lattner272d5ca2004-09-28 18:22:15 +00004708 return ReplaceInstUsesWith(I, Cst);
4709 }
4710
4711 if (LHSI->hasOneUse()) {
4712 // Otherwise strength reduce the shift into an and.
Reid Spencere0fc4df2006-10-20 07:07:24 +00004713 unsigned ShAmtVal = (unsigned)ShAmt->getZExtValue();
Chris Lattner272d5ca2004-09-28 18:22:15 +00004714 uint64_t Val = (1ULL << (TypeBits-ShAmtVal))-1;
Reid Spencerc635f472006-12-31 05:48:39 +00004715 Constant *Mask = ConstantInt::get(CI->getType(), Val);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004716
Chris Lattner272d5ca2004-09-28 18:22:15 +00004717 Instruction *AndI =
4718 BinaryOperator::createAnd(LHSI->getOperand(0),
4719 Mask, LHSI->getName()+".mask");
4720 Value *And = InsertNewInstBefore(AndI, I);
Reid Spencer266e42b2006-12-23 06:05:41 +00004721 return new ICmpInst(I.getPredicate(), And,
Reid Spencerfdff9382006-11-08 06:47:33 +00004722 ConstantExpr::getLShr(CI, ShAmt));
Chris Lattner272d5ca2004-09-28 18:22:15 +00004723 }
4724 }
Chris Lattner272d5ca2004-09-28 18:22:15 +00004725 }
4726 break;
4727
Reid Spencer266e42b2006-12-23 06:05:41 +00004728 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
Reid Spencerfdff9382006-11-08 06:47:33 +00004729 case Instruction::AShr:
Reid Spencere0fc4df2006-10-20 07:07:24 +00004730 if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004731 if (I.isEquality()) {
Chris Lattner19b57f52005-06-15 20:53:31 +00004732 // Check that the shift amount is in range. If not, don't perform
4733 // undefined shifts. When the shift is visited it will be
4734 // simplified.
Chris Lattner104002b2005-06-16 01:52:07 +00004735 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
Reid Spencere0fc4df2006-10-20 07:07:24 +00004736 if (ShAmt->getZExtValue() >= TypeBits)
Chris Lattner19b57f52005-06-15 20:53:31 +00004737 break;
4738
Chris Lattner1023b872004-09-27 16:18:50 +00004739 // If we are comparing against bits always shifted out, the
4740 // comparison cannot succeed.
Reid Spencerfdff9382006-11-08 06:47:33 +00004741 Constant *Comp;
Reid Spencerc635f472006-12-31 05:48:39 +00004742 if (LHSI->getOpcode() == Instruction::LShr)
Reid Spencerfdff9382006-11-08 06:47:33 +00004743 Comp = ConstantExpr::getLShr(ConstantExpr::getShl(CI, ShAmt),
4744 ShAmt);
4745 else
4746 Comp = ConstantExpr::getAShr(ConstantExpr::getShl(CI, ShAmt),
4747 ShAmt);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004748
Chris Lattner1023b872004-09-27 16:18:50 +00004749 if (Comp != CI) {// Comparing against a bit that we know is zero.
Reid Spencer266e42b2006-12-23 06:05:41 +00004750 bool IsICMP_NE = I.getPredicate() == ICmpInst::ICMP_NE;
4751 Constant *Cst = ConstantBool::get(IsICMP_NE);
Chris Lattner1023b872004-09-27 16:18:50 +00004752 return ReplaceInstUsesWith(I, Cst);
4753 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004754
Chris Lattner1023b872004-09-27 16:18:50 +00004755 if (LHSI->hasOneUse() || CI->isNullValue()) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00004756 unsigned ShAmtVal = (unsigned)ShAmt->getZExtValue();
Chris Lattner272d5ca2004-09-28 18:22:15 +00004757
Chris Lattner1023b872004-09-27 16:18:50 +00004758 // Otherwise strength reduce the shift into an and.
4759 uint64_t Val = ~0ULL; // All ones.
4760 Val <<= ShAmtVal; // Shift over to the right spot.
Reid Spencerc635f472006-12-31 05:48:39 +00004761 Val &= ~0ULL >> (64-TypeBits);
4762 Constant *Mask = ConstantInt::get(CI->getType(), Val);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004763
Chris Lattner1023b872004-09-27 16:18:50 +00004764 Instruction *AndI =
4765 BinaryOperator::createAnd(LHSI->getOperand(0),
4766 Mask, LHSI->getName()+".mask");
4767 Value *And = InsertNewInstBefore(AndI, I);
Reid Spencer266e42b2006-12-23 06:05:41 +00004768 return new ICmpInst(I.getPredicate(), And,
Chris Lattner1023b872004-09-27 16:18:50 +00004769 ConstantExpr::getShl(CI, ShAmt));
4770 }
Chris Lattner1023b872004-09-27 16:18:50 +00004771 }
4772 }
4773 break;
Chris Lattner7e794272004-09-24 15:21:34 +00004774
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004775 case Instruction::SDiv:
4776 case Instruction::UDiv:
Reid Spencer266e42b2006-12-23 06:05:41 +00004777 // Fold: icmp pred ([us]div X, C1), C2 -> range test
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004778 // Fold this div into the comparison, producing a range check.
4779 // Determine, based on the divide type, what the range is being
4780 // checked. If there is an overflow on the low or high side, remember
4781 // it, otherwise compute the range [low, hi) bounding the new value.
4782 // See: InsertRangeTest above for the kinds of replacements possible.
Chris Lattner6862fbd2004-09-29 17:40:11 +00004783 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004784 // FIXME: If the operand types don't match the type of the divide
4785 // then don't attempt this transform. The code below doesn't have the
4786 // logic to deal with a signed divide and an unsigned compare (and
4787 // vice versa). This is because (x /s C1) <s C2 produces different
4788 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
4789 // (x /u C1) <u C2. Simply casting the operands and result won't
4790 // work. :( The if statement below tests that condition and bails
4791 // if it finds it.
Reid Spencer266e42b2006-12-23 06:05:41 +00004792 bool DivIsSigned = LHSI->getOpcode() == Instruction::SDiv;
4793 if (!I.isEquality() && DivIsSigned != I.isSignedPredicate())
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004794 break;
4795
4796 // Initialize the variables that will indicate the nature of the
4797 // range check.
4798 bool LoOverflow = false, HiOverflow = false;
Chris Lattner6862fbd2004-09-29 17:40:11 +00004799 ConstantInt *LoBound = 0, *HiBound = 0;
4800
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004801 // Compute Prod = CI * DivRHS. We are essentially solving an equation
4802 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
4803 // C2 (CI). By solving for X we can turn this into a range check
4804 // instead of computing a divide.
4805 ConstantInt *Prod =
4806 cast<ConstantInt>(ConstantExpr::getMul(CI, DivRHS));
Chris Lattner6862fbd2004-09-29 17:40:11 +00004807
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004808 // Determine if the product overflows by seeing if the product is
4809 // not equal to the divide. Make sure we do the same kind of divide
4810 // as in the LHS instruction that we're folding.
4811 bool ProdOV = !DivRHS->isNullValue() &&
Reid Spencer266e42b2006-12-23 06:05:41 +00004812 (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004813 ConstantExpr::getUDiv(Prod, DivRHS)) != CI;
4814
Reid Spencer266e42b2006-12-23 06:05:41 +00004815 // Get the ICmp opcode
4816 ICmpInst::Predicate predicate = I.getPredicate();
Chris Lattnera92af962004-10-11 19:40:04 +00004817
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004818 if (DivRHS->isNullValue()) {
4819 // Don't hack on divide by zeros!
Reid Spencer266e42b2006-12-23 06:05:41 +00004820 } else if (!DivIsSigned) { // udiv
Chris Lattner6862fbd2004-09-29 17:40:11 +00004821 LoBound = Prod;
4822 LoOverflow = ProdOV;
4823 HiOverflow = ProdOV || AddWithOverflow(HiBound, LoBound, DivRHS);
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004824 } else if (isPositive(DivRHS)) { // Divisor is > 0.
Chris Lattner6862fbd2004-09-29 17:40:11 +00004825 if (CI->isNullValue()) { // (X / pos) op 0
4826 // Can't overflow.
4827 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
4828 HiBound = DivRHS;
4829 } else if (isPositive(CI)) { // (X / pos) op pos
4830 LoBound = Prod;
4831 LoOverflow = ProdOV;
4832 HiOverflow = ProdOV || AddWithOverflow(HiBound, Prod, DivRHS);
4833 } else { // (X / pos) op neg
4834 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
4835 LoOverflow = AddWithOverflow(LoBound, Prod,
4836 cast<ConstantInt>(DivRHSH));
4837 HiBound = Prod;
4838 HiOverflow = ProdOV;
4839 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004840 } else { // Divisor is < 0.
Chris Lattner6862fbd2004-09-29 17:40:11 +00004841 if (CI->isNullValue()) { // (X / neg) op 0
4842 LoBound = AddOne(DivRHS);
4843 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner73bcba52005-06-17 02:05:55 +00004844 if (HiBound == DivRHS)
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004845 LoBound = 0; // - INTMIN = INTMIN
Chris Lattner6862fbd2004-09-29 17:40:11 +00004846 } else if (isPositive(CI)) { // (X / neg) op pos
4847 HiOverflow = LoOverflow = ProdOV;
4848 if (!LoOverflow)
4849 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS));
4850 HiBound = AddOne(Prod);
4851 } else { // (X / neg) op neg
4852 LoBound = Prod;
4853 LoOverflow = HiOverflow = ProdOV;
4854 HiBound = cast<ConstantInt>(ConstantExpr::getSub(Prod, DivRHS));
4855 }
Chris Lattner0b41e862004-10-08 19:15:44 +00004856
Chris Lattnera92af962004-10-11 19:40:04 +00004857 // Dividing by a negate swaps the condition.
Reid Spencer266e42b2006-12-23 06:05:41 +00004858 predicate = ICmpInst::getSwappedPredicate(predicate);
Chris Lattner6862fbd2004-09-29 17:40:11 +00004859 }
4860
4861 if (LoBound) {
4862 Value *X = LHSI->getOperand(0);
Reid Spencer266e42b2006-12-23 06:05:41 +00004863 switch (predicate) {
4864 default: assert(0 && "Unhandled icmp opcode!");
4865 case ICmpInst::ICMP_EQ:
Chris Lattner6862fbd2004-09-29 17:40:11 +00004866 if (LoOverflow && HiOverflow)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004867 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattner6862fbd2004-09-29 17:40:11 +00004868 else if (HiOverflow)
Reid Spencer266e42b2006-12-23 06:05:41 +00004869 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
4870 ICmpInst::ICMP_UGE, X, LoBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00004871 else if (LoOverflow)
Reid Spencer266e42b2006-12-23 06:05:41 +00004872 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
4873 ICmpInst::ICMP_ULT, X, HiBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00004874 else
Reid Spencer266e42b2006-12-23 06:05:41 +00004875 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned,
4876 true, I);
4877 case ICmpInst::ICMP_NE:
Chris Lattner6862fbd2004-09-29 17:40:11 +00004878 if (LoOverflow && HiOverflow)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004879 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
Chris Lattner6862fbd2004-09-29 17:40:11 +00004880 else if (HiOverflow)
Reid Spencer266e42b2006-12-23 06:05:41 +00004881 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
4882 ICmpInst::ICMP_ULT, X, LoBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00004883 else if (LoOverflow)
Reid Spencer266e42b2006-12-23 06:05:41 +00004884 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
4885 ICmpInst::ICMP_UGE, X, HiBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00004886 else
Reid Spencer266e42b2006-12-23 06:05:41 +00004887 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned,
4888 false, I);
4889 case ICmpInst::ICMP_ULT:
4890 case ICmpInst::ICMP_SLT:
Chris Lattner6862fbd2004-09-29 17:40:11 +00004891 if (LoOverflow)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004892 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004893 return new ICmpInst(predicate, X, LoBound);
4894 case ICmpInst::ICMP_UGT:
4895 case ICmpInst::ICMP_SGT:
Chris Lattner6862fbd2004-09-29 17:40:11 +00004896 if (HiOverflow)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004897 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004898 if (predicate == ICmpInst::ICMP_UGT)
4899 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
4900 else
4901 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00004902 }
4903 }
4904 }
4905 break;
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004906 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004907
Reid Spencer266e42b2006-12-23 06:05:41 +00004908 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004909 if (I.isEquality()) {
Reid Spencer266e42b2006-12-23 06:05:41 +00004910 bool isICMP_NE = I.getPredicate() == ICmpInst::ICMP_NE;
Chris Lattnerd492a0b2003-07-23 17:02:11 +00004911
Reid Spencere0fc4df2006-10-20 07:07:24 +00004912 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
4913 // the second operand is a constant, simplify a bit.
Chris Lattnerc992add2003-08-13 05:33:12 +00004914 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
4915 switch (BO->getOpcode()) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00004916 case Instruction::SRem:
4917 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
4918 if (CI->isNullValue() && isa<ConstantInt>(BO->getOperand(1)) &&
4919 BO->hasOneUse()) {
4920 int64_t V = cast<ConstantInt>(BO->getOperand(1))->getSExtValue();
4921 if (V > 1 && isPowerOf2_64(V)) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00004922 Value *NewRem = InsertNewInstBefore(BinaryOperator::createURem(
4923 BO->getOperand(0), BO->getOperand(1), BO->getName()), I);
Reid Spencer266e42b2006-12-23 06:05:41 +00004924 return new ICmpInst(I.getPredicate(), NewRem,
4925 Constant::getNullValue(BO->getType()));
Chris Lattner23b47b62004-07-06 07:38:18 +00004926 }
Chris Lattner22d00a82005-08-02 19:16:58 +00004927 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004928 break;
Chris Lattnerc992add2003-08-13 05:33:12 +00004929 case Instruction::Add:
Chris Lattner6e079362004-06-27 22:51:36 +00004930 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
4931 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerb121ae12004-09-21 21:35:23 +00004932 if (BO->hasOneUse())
Reid Spencer266e42b2006-12-23 06:05:41 +00004933 return new ICmpInst(I.getPredicate(), BO->getOperand(0),
4934 ConstantExpr::getSub(CI, BOp1C));
Chris Lattner6e079362004-06-27 22:51:36 +00004935 } else if (CI->isNullValue()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00004936 // Replace ((add A, B) != 0) with (A != -B) if A or B is
4937 // efficiently invertible, or if the add has just this one use.
4938 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004939
Chris Lattnerc992add2003-08-13 05:33:12 +00004940 if (Value *NegVal = dyn_castNegVal(BOp1))
Reid Spencer266e42b2006-12-23 06:05:41 +00004941 return new ICmpInst(I.getPredicate(), BOp0, NegVal);
Chris Lattnerc992add2003-08-13 05:33:12 +00004942 else if (Value *NegVal = dyn_castNegVal(BOp0))
Reid Spencer266e42b2006-12-23 06:05:41 +00004943 return new ICmpInst(I.getPredicate(), NegVal, BOp1);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00004944 else if (BO->hasOneUse()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00004945 Instruction *Neg = BinaryOperator::createNeg(BOp1, BO->getName());
4946 BO->setName("");
4947 InsertNewInstBefore(Neg, I);
Reid Spencer266e42b2006-12-23 06:05:41 +00004948 return new ICmpInst(I.getPredicate(), BOp0, Neg);
Chris Lattnerc992add2003-08-13 05:33:12 +00004949 }
4950 }
4951 break;
4952 case Instruction::Xor:
4953 // For the xor case, we can xor two constants together, eliminating
4954 // the explicit xor.
4955 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
Reid Spencer266e42b2006-12-23 06:05:41 +00004956 return new ICmpInst(I.getPredicate(), BO->getOperand(0),
4957 ConstantExpr::getXor(CI, BOC));
Chris Lattnerc992add2003-08-13 05:33:12 +00004958
4959 // FALLTHROUGH
4960 case Instruction::Sub:
4961 // Replace (([sub|xor] A, B) != 0) with (A != B)
4962 if (CI->isNullValue())
Reid Spencer266e42b2006-12-23 06:05:41 +00004963 return new ICmpInst(I.getPredicate(), BO->getOperand(0),
4964 BO->getOperand(1));
Chris Lattnerc992add2003-08-13 05:33:12 +00004965 break;
4966
4967 case Instruction::Or:
4968 // If bits are being or'd in that are not present in the constant we
4969 // are comparing against, then the comparison could never succeed!
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00004970 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Chris Lattnerc8e7e292004-06-10 02:12:35 +00004971 Constant *NotCI = ConstantExpr::getNot(CI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004972 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Reid Spencer266e42b2006-12-23 06:05:41 +00004973 return ReplaceInstUsesWith(I, ConstantBool::get(isICMP_NE));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00004974 }
Chris Lattnerc992add2003-08-13 05:33:12 +00004975 break;
4976
4977 case Instruction::And:
4978 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerd492a0b2003-07-23 17:02:11 +00004979 // If bits are being compared against that are and'd out, then the
4980 // comparison can never succeed!
Chris Lattnerc8e7e292004-06-10 02:12:35 +00004981 if (!ConstantExpr::getAnd(CI,
4982 ConstantExpr::getNot(BOC))->isNullValue())
Reid Spencer266e42b2006-12-23 06:05:41 +00004983 return ReplaceInstUsesWith(I, ConstantBool::get(isICMP_NE));
Chris Lattnerc992add2003-08-13 05:33:12 +00004984
Chris Lattner35167c32004-06-09 07:59:58 +00004985 // If we have ((X & C) == C), turn it into ((X & C) != 0).
Chris Lattneree59d4b2004-06-10 02:33:20 +00004986 if (CI == BOC && isOneBitSet(CI))
Reid Spencer266e42b2006-12-23 06:05:41 +00004987 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
4988 ICmpInst::ICMP_NE, Op0,
4989 Constant::getNullValue(CI->getType()));
Chris Lattner35167c32004-06-09 07:59:58 +00004990
Reid Spencer266e42b2006-12-23 06:05:41 +00004991 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
Chris Lattnerc992add2003-08-13 05:33:12 +00004992 if (isSignBit(BOC)) {
4993 Value *X = BO->getOperand(0);
Reid Spencer266e42b2006-12-23 06:05:41 +00004994 Constant *Zero = Constant::getNullValue(X->getType());
4995 ICmpInst::Predicate pred = isICMP_NE ?
4996 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
4997 return new ICmpInst(pred, X, Zero);
Chris Lattnerc992add2003-08-13 05:33:12 +00004998 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004999
Chris Lattnerbfff18a2004-09-27 19:29:18 +00005000 // ((X & ~7) == 0) --> X < 8
Chris Lattner8fc5af42004-09-23 21:46:38 +00005001 if (CI->isNullValue() && isHighOnes(BOC)) {
5002 Value *X = BO->getOperand(0);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00005003 Constant *NegX = ConstantExpr::getNeg(BOC);
Reid Spencer266e42b2006-12-23 06:05:41 +00005004 ICmpInst::Predicate pred = isICMP_NE ?
5005 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
5006 return new ICmpInst(pred, X, NegX);
Chris Lattner8fc5af42004-09-23 21:46:38 +00005007 }
5008
Chris Lattnerd492a0b2003-07-23 17:02:11 +00005009 }
Chris Lattnerc992add2003-08-13 05:33:12 +00005010 default: break;
5011 }
Chris Lattnera7942b72006-11-29 05:02:16 +00005012 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Op0)) {
5013 // Handle set{eq|ne} <intrinsic>, intcst.
5014 switch (II->getIntrinsicID()) {
5015 default: break;
Reid Spencer266e42b2006-12-23 06:05:41 +00005016 case Intrinsic::bswap_i16:
5017 // icmp eq (bswap(x)), c -> icmp eq (x,bswap(c))
Chris Lattnera7942b72006-11-29 05:02:16 +00005018 WorkList.push_back(II); // Dead?
5019 I.setOperand(0, II->getOperand(1));
Reid Spencerc635f472006-12-31 05:48:39 +00005020 I.setOperand(1, ConstantInt::get(Type::Int16Ty,
Chris Lattnera7942b72006-11-29 05:02:16 +00005021 ByteSwap_16(CI->getZExtValue())));
5022 return &I;
Reid Spencer266e42b2006-12-23 06:05:41 +00005023 case Intrinsic::bswap_i32:
5024 // icmp eq (bswap(x)), c -> icmp eq (x,bswap(c))
Chris Lattnera7942b72006-11-29 05:02:16 +00005025 WorkList.push_back(II); // Dead?
5026 I.setOperand(0, II->getOperand(1));
Reid Spencerc635f472006-12-31 05:48:39 +00005027 I.setOperand(1, ConstantInt::get(Type::Int32Ty,
Chris Lattnera7942b72006-11-29 05:02:16 +00005028 ByteSwap_32(CI->getZExtValue())));
5029 return &I;
Reid Spencer266e42b2006-12-23 06:05:41 +00005030 case Intrinsic::bswap_i64:
5031 // icmp eq (bswap(x)), c -> icmp eq (x,bswap(c))
Chris Lattnera7942b72006-11-29 05:02:16 +00005032 WorkList.push_back(II); // Dead?
5033 I.setOperand(0, II->getOperand(1));
Reid Spencerc635f472006-12-31 05:48:39 +00005034 I.setOperand(1, ConstantInt::get(Type::Int64Ty,
Chris Lattnera7942b72006-11-29 05:02:16 +00005035 ByteSwap_64(CI->getZExtValue())));
5036 return &I;
5037 }
Chris Lattnerc992add2003-08-13 05:33:12 +00005038 }
Reid Spencer266e42b2006-12-23 06:05:41 +00005039 } else { // Not a ICMP_EQ/ICMP_NE
5040 // If the LHS is a cast from an integral value of the same size, then
5041 // since we know the RHS is a constant, try to simlify.
Chris Lattner2b55ea32004-02-23 07:16:20 +00005042 if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
5043 Value *CastOp = Cast->getOperand(0);
5044 const Type *SrcTy = CastOp->getType();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005045 unsigned SrcTySize = SrcTy->getPrimitiveSizeInBits();
Reid Spencer266e42b2006-12-23 06:05:41 +00005046 if (SrcTy->isInteger() &&
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005047 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
Reid Spencer266e42b2006-12-23 06:05:41 +00005048 // If this is an unsigned comparison, try to make the comparison use
5049 // smaller constant values.
5050 switch (I.getPredicate()) {
5051 default: break;
5052 case ICmpInst::ICMP_ULT: { // X u< 128 => X s> -1
5053 ConstantInt *CUI = cast<ConstantInt>(CI);
5054 if (CUI->getZExtValue() == 1ULL << (SrcTySize-1))
5055 return new ICmpInst(ICmpInst::ICMP_SGT, CastOp,
5056 ConstantInt::get(SrcTy, -1));
5057 break;
5058 }
5059 case ICmpInst::ICMP_UGT: { // X u> 127 => X s< 0
5060 ConstantInt *CUI = cast<ConstantInt>(CI);
5061 if (CUI->getZExtValue() == (1ULL << (SrcTySize-1))-1)
5062 return new ICmpInst(ICmpInst::ICMP_SLT, CastOp,
5063 Constant::getNullValue(SrcTy));
5064 break;
5065 }
Chris Lattner2b55ea32004-02-23 07:16:20 +00005066 }
Reid Spencer266e42b2006-12-23 06:05:41 +00005067
Chris Lattner2b55ea32004-02-23 07:16:20 +00005068 }
5069 }
Chris Lattnere967b342003-06-04 05:10:11 +00005070 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005071 }
5072
Reid Spencer266e42b2006-12-23 06:05:41 +00005073 // Handle icmp with constant RHS
Chris Lattner77c32c32005-04-23 15:31:55 +00005074 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5075 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5076 switch (LHSI->getOpcode()) {
Chris Lattnera816eee2005-05-01 04:42:15 +00005077 case Instruction::GetElementPtr:
5078 if (RHSC->isNullValue()) {
Reid Spencer266e42b2006-12-23 06:05:41 +00005079 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
Chris Lattnera816eee2005-05-01 04:42:15 +00005080 bool isAllZeros = true;
5081 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
5082 if (!isa<Constant>(LHSI->getOperand(i)) ||
5083 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
5084 isAllZeros = false;
5085 break;
5086 }
5087 if (isAllZeros)
Reid Spencer266e42b2006-12-23 06:05:41 +00005088 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
Chris Lattnera816eee2005-05-01 04:42:15 +00005089 Constant::getNullValue(LHSI->getOperand(0)->getType()));
5090 }
5091 break;
5092
Chris Lattner77c32c32005-04-23 15:31:55 +00005093 case Instruction::PHI:
5094 if (Instruction *NV = FoldOpIntoPhi(I))
5095 return NV;
5096 break;
5097 case Instruction::Select:
5098 // If either operand of the select is a constant, we can fold the
5099 // comparison into the select arms, which will cause one to be
5100 // constant folded and the select turned into a bitwise or.
5101 Value *Op1 = 0, *Op2 = 0;
5102 if (LHSI->hasOneUse()) {
5103 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5104 // Fold the known value into the constant operand.
Reid Spencer266e42b2006-12-23 06:05:41 +00005105 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5106 // Insert a new ICmp of the other select operand.
5107 Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5108 LHSI->getOperand(2), RHSC,
5109 I.getName()), I);
Chris Lattner77c32c32005-04-23 15:31:55 +00005110 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5111 // Fold the known value into the constant operand.
Reid Spencer266e42b2006-12-23 06:05:41 +00005112 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5113 // Insert a new ICmp of the other select operand.
5114 Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5115 LHSI->getOperand(1), RHSC,
5116 I.getName()), I);
Chris Lattner77c32c32005-04-23 15:31:55 +00005117 }
5118 }
Jeff Cohen82639852005-04-23 21:38:35 +00005119
Chris Lattner77c32c32005-04-23 15:31:55 +00005120 if (Op1)
5121 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
5122 break;
5123 }
5124 }
5125
Reid Spencer266e42b2006-12-23 06:05:41 +00005126 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
Chris Lattner0798af32005-01-13 20:14:25 +00005127 if (User *GEP = dyn_castGetElementPtr(Op0))
Reid Spencer266e42b2006-12-23 06:05:41 +00005128 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
Chris Lattner0798af32005-01-13 20:14:25 +00005129 return NI;
5130 if (User *GEP = dyn_castGetElementPtr(Op1))
Reid Spencer266e42b2006-12-23 06:05:41 +00005131 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
5132 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
Chris Lattner0798af32005-01-13 20:14:25 +00005133 return NI;
5134
Reid Spencer266e42b2006-12-23 06:05:41 +00005135 // Test to see if the operands of the icmp are casted versions of other
Chris Lattner16930792003-11-03 04:25:02 +00005136 // values. If the cast can be stripped off both arguments, we do so now.
Chris Lattner6444c372003-11-03 05:17:03 +00005137 if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
5138 Value *CastOp0 = CI->getOperand(0);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005139 if (CI->isLosslessCast() && I.isEquality() &&
5140 (isa<Constant>(Op1) || isa<CastInst>(Op1))) {
Chris Lattner16930792003-11-03 04:25:02 +00005141 // We keep moving the cast from the left operand over to the right
5142 // operand, where it can often be eliminated completely.
Chris Lattner6444c372003-11-03 05:17:03 +00005143 Op0 = CastOp0;
Misha Brukmanb1c93172005-04-21 23:48:37 +00005144
Chris Lattner16930792003-11-03 04:25:02 +00005145 // If operand #1 is a cast instruction, see if we can eliminate it as
5146 // well.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005147 if (CastInst *CI2 = dyn_cast<CastInst>(Op1)) {
5148 Value *CI2Op0 = CI2->getOperand(0);
5149 if (CI2Op0->getType()->canLosslesslyBitCastTo(Op0->getType()))
5150 Op1 = CI2Op0;
5151 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00005152
Chris Lattner16930792003-11-03 04:25:02 +00005153 // If Op1 is a constant, we can fold the cast into the constant.
5154 if (Op1->getType() != Op0->getType())
5155 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Reid Spencerbb65ebf2006-12-12 23:36:14 +00005156 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
Chris Lattner16930792003-11-03 04:25:02 +00005157 } else {
Reid Spencer266e42b2006-12-23 06:05:41 +00005158 // Otherwise, cast the RHS right before the icmp
Reid Spencer13bc5d72006-12-12 09:18:51 +00005159 Op1 = InsertCastBefore(Instruction::BitCast, Op1, Op0->getType(), I);
Chris Lattner16930792003-11-03 04:25:02 +00005160 }
Reid Spencer266e42b2006-12-23 06:05:41 +00005161 return new ICmpInst(I.getPredicate(), Op0, Op1);
Chris Lattner16930792003-11-03 04:25:02 +00005162 }
5163
Reid Spencer266e42b2006-12-23 06:05:41 +00005164 // Handle the special case of: icmp (cast bool to X), <cst>
Chris Lattner6444c372003-11-03 05:17:03 +00005165 // This comes up when you have code like
5166 // int X = A < B;
5167 // if (X) ...
5168 // For generality, we handle any zero-extension of any operand comparison
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005169 // with a constant or another cast from the same type.
5170 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
Reid Spencer266e42b2006-12-23 06:05:41 +00005171 if (Instruction *R = visitICmpInstWithCastAndCast(I))
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005172 return R;
Chris Lattner6444c372003-11-03 05:17:03 +00005173 }
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00005174
Chris Lattnerb3f24c92006-09-18 04:22:48 +00005175 if (I.isEquality()) {
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00005176 Value *A, *B;
5177 if (match(Op0, m_Xor(m_Value(A), m_Value(B))) &&
5178 (A == Op1 || B == Op1)) {
5179 // (A^B) == A -> B == 0
5180 Value *OtherVal = A == Op1 ? B : A;
Reid Spencer266e42b2006-12-23 06:05:41 +00005181 return new ICmpInst(I.getPredicate(), OtherVal,
5182 Constant::getNullValue(A->getType()));
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00005183 } else if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
5184 (A == Op0 || B == Op0)) {
5185 // A == (A^B) -> B == 0
5186 Value *OtherVal = A == Op0 ? B : A;
Reid Spencer266e42b2006-12-23 06:05:41 +00005187 return new ICmpInst(I.getPredicate(), OtherVal,
5188 Constant::getNullValue(A->getType()));
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00005189 } else if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
5190 // (A-B) == A -> B == 0
Reid Spencer266e42b2006-12-23 06:05:41 +00005191 return new ICmpInst(I.getPredicate(), B,
5192 Constant::getNullValue(B->getType()));
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00005193 } else if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
5194 // A == (A-B) -> B == 0
Reid Spencer266e42b2006-12-23 06:05:41 +00005195 return new ICmpInst(I.getPredicate(), B,
5196 Constant::getNullValue(B->getType()));
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00005197 }
Chris Lattnerd12a4bf2006-11-14 06:06:06 +00005198
5199 Value *C, *D;
5200 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
5201 if (Op0->hasOneUse() && Op1->hasOneUse() &&
5202 match(Op0, m_And(m_Value(A), m_Value(B))) &&
5203 match(Op1, m_And(m_Value(C), m_Value(D)))) {
5204 Value *X = 0, *Y = 0, *Z = 0;
5205
5206 if (A == C) {
5207 X = B; Y = D; Z = A;
5208 } else if (A == D) {
5209 X = B; Y = C; Z = A;
5210 } else if (B == C) {
5211 X = A; Y = D; Z = B;
5212 } else if (B == D) {
5213 X = A; Y = C; Z = B;
5214 }
5215
5216 if (X) { // Build (X^Y) & Z
5217 Op1 = InsertNewInstBefore(BinaryOperator::createXor(X, Y, "tmp"), I);
5218 Op1 = InsertNewInstBefore(BinaryOperator::createAnd(Op1, Z, "tmp"), I);
5219 I.setOperand(0, Op1);
5220 I.setOperand(1, Constant::getNullValue(Op1->getType()));
5221 return &I;
5222 }
5223 }
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00005224 }
Chris Lattner113f4f42002-06-25 16:13:24 +00005225 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005226}
5227
Reid Spencer266e42b2006-12-23 06:05:41 +00005228// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005229// We only handle extending casts so far.
5230//
Reid Spencer266e42b2006-12-23 06:05:41 +00005231Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
5232 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005233 Value *LHSCIOp = LHSCI->getOperand(0);
5234 const Type *SrcTy = LHSCIOp->getType();
Reid Spencer266e42b2006-12-23 06:05:41 +00005235 const Type *DestTy = LHSCI->getType();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005236 Value *RHSCIOp;
5237
Reid Spencer266e42b2006-12-23 06:05:41 +00005238 // We only handle extension cast instructions, so far. Enforce this.
5239 if (LHSCI->getOpcode() != Instruction::ZExt &&
5240 LHSCI->getOpcode() != Instruction::SExt)
Chris Lattner03f06f12005-01-17 03:20:02 +00005241 return 0;
5242
Reid Spencer266e42b2006-12-23 06:05:41 +00005243 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
5244 bool isSignedCmp = ICI.isSignedPredicate();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005245
Reid Spencer266e42b2006-12-23 06:05:41 +00005246 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005247 // Not an extension from the same type?
5248 RHSCIOp = CI->getOperand(0);
Reid Spencer266e42b2006-12-23 06:05:41 +00005249 if (RHSCIOp->getType() != LHSCIOp->getType())
5250 return 0;
5251 else
5252 // Okay, just insert a compare of the reduced operands now!
5253 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
Reid Spencer279fa252004-11-28 21:31:15 +00005254 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005255
Reid Spencer266e42b2006-12-23 06:05:41 +00005256 // If we aren't dealing with a constant on the RHS, exit early
5257 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
5258 if (!CI)
5259 return 0;
5260
5261 // Compute the constant that would happen if we truncated to SrcTy then
5262 // reextended to DestTy.
5263 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
5264 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
5265
5266 // If the re-extended constant didn't change...
5267 if (Res2 == CI) {
5268 // Make sure that sign of the Cmp and the sign of the Cast are the same.
5269 // For example, we might have:
5270 // %A = sext short %X to uint
5271 // %B = icmp ugt uint %A, 1330
5272 // It is incorrect to transform this into
5273 // %B = icmp ugt short %X, 1330
5274 // because %A may have negative value.
5275 //
5276 // However, it is OK if SrcTy is bool (See cast-set.ll testcase)
5277 // OR operation is EQ/NE.
5278 if (isSignedExt == isSignedCmp || SrcTy == Type::BoolTy || ICI.isEquality())
5279 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
5280 else
5281 return 0;
5282 }
5283
5284 // The re-extended constant changed so the constant cannot be represented
5285 // in the shorter type. Consequently, we cannot emit a simple comparison.
5286
5287 // First, handle some easy cases. We know the result cannot be equal at this
5288 // point so handle the ICI.isEquality() cases
5289 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
5290 return ReplaceInstUsesWith(ICI, ConstantBool::getFalse());
5291 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
5292 return ReplaceInstUsesWith(ICI, ConstantBool::getTrue());
5293
5294 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
5295 // should have been folded away previously and not enter in here.
5296 Value *Result;
5297 if (isSignedCmp) {
5298 // We're performing a signed comparison.
5299 if (cast<ConstantInt>(CI)->getSExtValue() < 0)
5300 Result = ConstantBool::getFalse(); // X < (small) --> false
5301 else
5302 Result = ConstantBool::getTrue(); // X < (large) --> true
5303 } else {
5304 // We're performing an unsigned comparison.
5305 if (isSignedExt) {
5306 // We're performing an unsigned comp with a sign extended value.
5307 // This is true if the input is >= 0. [aka >s -1]
5308 Constant *NegOne = ConstantIntegral::getAllOnesValue(SrcTy);
5309 Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
5310 NegOne, ICI.getName()), ICI);
5311 } else {
5312 // Unsigned extend & unsigned compare -> always true.
5313 Result = ConstantBool::getTrue();
5314 }
5315 }
5316
5317 // Finally, return the value computed.
5318 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
5319 ICI.getPredicate() == ICmpInst::ICMP_SLT) {
5320 return ReplaceInstUsesWith(ICI, Result);
5321 } else {
5322 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
5323 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
5324 "ICmp should be folded!");
5325 if (Constant *CI = dyn_cast<Constant>(Result))
5326 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
5327 else
5328 return BinaryOperator::createNot(Result);
5329 }
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005330}
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005331
Chris Lattnere8d6c602003-03-10 19:16:08 +00005332Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
Reid Spencerc635f472006-12-31 05:48:39 +00005333 assert(I.getOperand(1)->getType() == Type::Int8Ty);
Chris Lattner113f4f42002-06-25 16:13:24 +00005334 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005335
5336 // shl X, 0 == X and shr X, 0 == X
5337 // shl 0, X == 0 and shr 0, X == 0
Reid Spencerc635f472006-12-31 05:48:39 +00005338 if (Op1 == Constant::getNullValue(Type::Int8Ty) ||
Chris Lattnere6794492002-08-12 21:17:25 +00005339 Op0 == Constant::getNullValue(Op0->getType()))
5340 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf5b4ef72006-02-12 08:07:37 +00005341
Reid Spencer266e42b2006-12-23 06:05:41 +00005342 if (isa<UndefValue>(Op0)) {
5343 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
Chris Lattner67f05452004-10-16 23:28:04 +00005344 return ReplaceInstUsesWith(I, Op0);
Reid Spencer266e42b2006-12-23 06:05:41 +00005345 else // undef << X -> 0, undef >>u X -> 0
Chris Lattner81a7a232004-10-16 18:11:37 +00005346 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5347 }
5348 if (isa<UndefValue>(Op1)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00005349 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
5350 return ReplaceInstUsesWith(I, Op0);
5351 else // X << undef, X >>u undef -> 0
Chris Lattner81a7a232004-10-16 18:11:37 +00005352 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner81a7a232004-10-16 18:11:37 +00005353 }
5354
Chris Lattnerd4dee402006-11-10 23:38:52 +00005355 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
5356 if (I.getOpcode() == Instruction::AShr)
Reid Spencere0fc4df2006-10-20 07:07:24 +00005357 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Chris Lattnerd4dee402006-11-10 23:38:52 +00005358 if (CSI->isAllOnesValue())
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00005359 return ReplaceInstUsesWith(I, CSI);
5360
Chris Lattner183b3362004-04-09 19:05:30 +00005361 // Try to fold constant and into select arguments.
5362 if (isa<Constant>(Op0))
5363 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner86102b82005-01-01 16:22:27 +00005364 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00005365 return R;
5366
Chris Lattnerb18dbbf2005-05-08 17:34:56 +00005367 // See if we can turn a signed shr into an unsigned shr.
Chris Lattnerb3f24c92006-09-18 04:22:48 +00005368 if (I.isArithmeticShift()) {
Chris Lattnerc3ebf402006-02-07 07:27:52 +00005369 if (MaskedValueIsZero(Op0,
5370 1ULL << (I.getType()->getPrimitiveSizeInBits()-1))) {
Reid Spencerfdff9382006-11-08 06:47:33 +00005371 return new ShiftInst(Instruction::LShr, Op0, Op1, I.getName());
Chris Lattnerb18dbbf2005-05-08 17:34:56 +00005372 }
5373 }
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00005374
Reid Spencere0fc4df2006-10-20 07:07:24 +00005375 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
Reid Spencerc635f472006-12-31 05:48:39 +00005376 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
5377 return Res;
Chris Lattner14553932006-01-06 07:12:35 +00005378 return 0;
5379}
5380
Reid Spencere0fc4df2006-10-20 07:07:24 +00005381Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Chris Lattner14553932006-01-06 07:12:35 +00005382 ShiftInst &I) {
Reid Spencer266e42b2006-12-23 06:05:41 +00005383 bool isLeftShift = I.getOpcode() == Instruction::Shl;
5384 bool isSignedShift = I.getOpcode() == Instruction::AShr;
Chris Lattnerb3309392006-01-06 07:22:22 +00005385 bool isUnsignedShift = !isSignedShift;
Chris Lattner14553932006-01-06 07:12:35 +00005386
Chris Lattnerf5b4ef72006-02-12 08:07:37 +00005387 // See if we can simplify any instructions used by the instruction whose sole
5388 // purpose is to compute bits we don't care about.
5389 uint64_t KnownZero, KnownOne;
5390 if (SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
5391 KnownZero, KnownOne))
5392 return &I;
5393
Chris Lattner14553932006-01-06 07:12:35 +00005394 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
5395 // of a signed value.
5396 //
5397 unsigned TypeBits = Op0->getType()->getPrimitiveSizeInBits();
Reid Spencere0fc4df2006-10-20 07:07:24 +00005398 if (Op1->getZExtValue() >= TypeBits) {
Chris Lattnerb3309392006-01-06 07:22:22 +00005399 if (isUnsignedShift || isLeftShift)
Chris Lattner14553932006-01-06 07:12:35 +00005400 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
5401 else {
Reid Spencerc635f472006-12-31 05:48:39 +00005402 I.setOperand(1, ConstantInt::get(Type::Int8Ty, TypeBits-1));
Chris Lattner14553932006-01-06 07:12:35 +00005403 return &I;
Chris Lattnerf5ce2542004-02-23 20:30:06 +00005404 }
Chris Lattner14553932006-01-06 07:12:35 +00005405 }
5406
5407 // ((X*C1) << C2) == (X * (C1 << C2))
5408 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
5409 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
5410 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
5411 return BinaryOperator::createMul(BO->getOperand(0),
5412 ConstantExpr::getShl(BOOp, Op1));
5413
5414 // Try to fold constant and into select arguments.
5415 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5416 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5417 return R;
5418 if (isa<PHINode>(Op0))
5419 if (Instruction *NV = FoldOpIntoPhi(I))
5420 return NV;
5421
5422 if (Op0->hasOneUse()) {
Chris Lattner14553932006-01-06 07:12:35 +00005423 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
5424 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
5425 Value *V1, *V2;
5426 ConstantInt *CC;
5427 switch (Op0BO->getOpcode()) {
Chris Lattner27cb9db2005-09-18 05:12:10 +00005428 default: break;
5429 case Instruction::Add:
5430 case Instruction::And:
5431 case Instruction::Or:
5432 case Instruction::Xor:
5433 // These operators commute.
5434 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner797dee72005-09-18 06:30:59 +00005435 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
5436 match(Op0BO->getOperand(1),
Chris Lattner14553932006-01-06 07:12:35 +00005437 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Chris Lattner797dee72005-09-18 06:30:59 +00005438 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00005439 Op0BO->getOperand(0), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00005440 Op0BO->getName());
5441 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005442 Instruction *X =
5443 BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
5444 Op0BO->getOperand(1)->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00005445 InsertNewInstBefore(X, I); // (X + (Y << C))
5446 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
Chris Lattner14553932006-01-06 07:12:35 +00005447 C2 = ConstantExpr::getShl(C2, Op1);
Chris Lattner797dee72005-09-18 06:30:59 +00005448 return BinaryOperator::createAnd(X, C2);
5449 }
Chris Lattner14553932006-01-06 07:12:35 +00005450
Chris Lattner797dee72005-09-18 06:30:59 +00005451 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
5452 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
5453 match(Op0BO->getOperand(1),
5454 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner14553932006-01-06 07:12:35 +00005455 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005456 cast<BinaryOperator>(Op0BO->getOperand(1))->getOperand(0)->hasOneUse()) {
Chris Lattner797dee72005-09-18 06:30:59 +00005457 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00005458 Op0BO->getOperand(0), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00005459 Op0BO->getName());
5460 InsertNewInstBefore(YS, I); // (Y << C)
5461 Instruction *XM =
Chris Lattner14553932006-01-06 07:12:35 +00005462 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner797dee72005-09-18 06:30:59 +00005463 V1->getName()+".mask");
5464 InsertNewInstBefore(XM, I); // X & (CC << C)
5465
5466 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
5467 }
Chris Lattner14553932006-01-06 07:12:35 +00005468
Chris Lattner797dee72005-09-18 06:30:59 +00005469 // FALL THROUGH.
Chris Lattner27cb9db2005-09-18 05:12:10 +00005470 case Instruction::Sub:
5471 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner797dee72005-09-18 06:30:59 +00005472 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
5473 match(Op0BO->getOperand(0),
Chris Lattner14553932006-01-06 07:12:35 +00005474 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Chris Lattner797dee72005-09-18 06:30:59 +00005475 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00005476 Op0BO->getOperand(1), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00005477 Op0BO->getName());
5478 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005479 Instruction *X =
Chris Lattner1df0e982006-05-31 21:14:00 +00005480 BinaryOperator::create(Op0BO->getOpcode(), V1, YS,
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005481 Op0BO->getOperand(0)->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00005482 InsertNewInstBefore(X, I); // (X + (Y << C))
5483 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
Chris Lattner14553932006-01-06 07:12:35 +00005484 C2 = ConstantExpr::getShl(C2, Op1);
Chris Lattner797dee72005-09-18 06:30:59 +00005485 return BinaryOperator::createAnd(X, C2);
5486 }
Chris Lattner14553932006-01-06 07:12:35 +00005487
Chris Lattner1df0e982006-05-31 21:14:00 +00005488 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner797dee72005-09-18 06:30:59 +00005489 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
5490 match(Op0BO->getOperand(0),
5491 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner14553932006-01-06 07:12:35 +00005492 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005493 cast<BinaryOperator>(Op0BO->getOperand(0))
5494 ->getOperand(0)->hasOneUse()) {
Chris Lattner797dee72005-09-18 06:30:59 +00005495 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00005496 Op0BO->getOperand(1), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00005497 Op0BO->getName());
5498 InsertNewInstBefore(YS, I); // (Y << C)
5499 Instruction *XM =
Chris Lattner14553932006-01-06 07:12:35 +00005500 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner797dee72005-09-18 06:30:59 +00005501 V1->getName()+".mask");
5502 InsertNewInstBefore(XM, I); // X & (CC << C)
5503
Chris Lattner1df0e982006-05-31 21:14:00 +00005504 return BinaryOperator::create(Op0BO->getOpcode(), XM, YS);
Chris Lattner797dee72005-09-18 06:30:59 +00005505 }
Chris Lattner14553932006-01-06 07:12:35 +00005506
Chris Lattner27cb9db2005-09-18 05:12:10 +00005507 break;
Chris Lattner14553932006-01-06 07:12:35 +00005508 }
5509
5510
5511 // If the operand is an bitwise operator with a constant RHS, and the
5512 // shift is the only use, we can pull it out of the shift.
5513 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
5514 bool isValid = true; // Valid only for And, Or, Xor
5515 bool highBitSet = false; // Transform if high bit of constant set?
5516
5517 switch (Op0BO->getOpcode()) {
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00005518 default: isValid = false; break; // Do not perform transform!
Chris Lattner44bd3922004-10-08 03:46:20 +00005519 case Instruction::Add:
5520 isValid = isLeftShift;
5521 break;
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00005522 case Instruction::Or:
5523 case Instruction::Xor:
5524 highBitSet = false;
5525 break;
5526 case Instruction::And:
5527 highBitSet = true;
5528 break;
Chris Lattner14553932006-01-06 07:12:35 +00005529 }
5530
5531 // If this is a signed shift right, and the high bit is modified
5532 // by the logical operation, do not perform the transformation.
5533 // The highBitSet boolean indicates the value of the high bit of
5534 // the constant which would cause it to be modified for this
5535 // operation.
5536 //
Chris Lattnerb3309392006-01-06 07:22:22 +00005537 if (isValid && !isLeftShift && isSignedShift) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00005538 uint64_t Val = Op0C->getZExtValue();
Chris Lattner14553932006-01-06 07:12:35 +00005539 isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
5540 }
5541
5542 if (isValid) {
5543 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
5544
5545 Instruction *NewShift =
5546 new ShiftInst(I.getOpcode(), Op0BO->getOperand(0), Op1,
5547 Op0BO->getName());
5548 Op0BO->setName("");
5549 InsertNewInstBefore(NewShift, I);
5550
5551 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
5552 NewRHS);
5553 }
5554 }
5555 }
5556 }
5557
Chris Lattnereb372a02006-01-06 07:52:12 +00005558 // Find out if this is a shift of a shift by a constant.
5559 ShiftInst *ShiftOp = 0;
Chris Lattner14553932006-01-06 07:12:35 +00005560 if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0))
Chris Lattnereb372a02006-01-06 07:52:12 +00005561 ShiftOp = Op0SI;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005562 else if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
5563 // If this is a noop-integer cast of a shift instruction, use the shift.
5564 if (isa<ShiftInst>(CI->getOperand(0))) {
Chris Lattnereb372a02006-01-06 07:52:12 +00005565 ShiftOp = cast<ShiftInst>(CI->getOperand(0));
5566 }
5567 }
5568
Reid Spencere0fc4df2006-10-20 07:07:24 +00005569 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Chris Lattnereb372a02006-01-06 07:52:12 +00005570 // Find the operands and properties of the input shift. Note that the
5571 // signedness of the input shift may differ from the current shift if there
5572 // is a noop cast between the two.
Reid Spencer266e42b2006-12-23 06:05:41 +00005573 bool isShiftOfLeftShift = ShiftOp->getOpcode() == Instruction::Shl;
5574 bool isShiftOfSignedShift = ShiftOp->getOpcode() == Instruction::AShr;
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005575 bool isShiftOfUnsignedShift = !isShiftOfSignedShift;
Chris Lattnereb372a02006-01-06 07:52:12 +00005576
Reid Spencere0fc4df2006-10-20 07:07:24 +00005577 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Chris Lattnereb372a02006-01-06 07:52:12 +00005578
Reid Spencere0fc4df2006-10-20 07:07:24 +00005579 unsigned ShiftAmt1 = (unsigned)ShiftAmt1C->getZExtValue();
5580 unsigned ShiftAmt2 = (unsigned)Op1->getZExtValue();
Chris Lattnereb372a02006-01-06 07:52:12 +00005581
5582 // Check for (A << c1) << c2 and (A >> c1) >> c2.
5583 if (isLeftShift == isShiftOfLeftShift) {
5584 // Do not fold these shifts if the first one is signed and the second one
5585 // is unsigned and this is a right shift. Further, don't do any folding
5586 // on them.
5587 if (isShiftOfSignedShift && isUnsignedShift && !isLeftShift)
5588 return 0;
Chris Lattner14553932006-01-06 07:12:35 +00005589
Chris Lattnereb372a02006-01-06 07:52:12 +00005590 unsigned Amt = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
5591 if (Amt > Op0->getType()->getPrimitiveSizeInBits())
5592 Amt = Op0->getType()->getPrimitiveSizeInBits();
Chris Lattner14553932006-01-06 07:12:35 +00005593
Chris Lattnereb372a02006-01-06 07:52:12 +00005594 Value *Op = ShiftOp->getOperand(0);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005595 ShiftInst *ShiftResult = new ShiftInst(I.getOpcode(), Op,
Reid Spencerc635f472006-12-31 05:48:39 +00005596 ConstantInt::get(Type::Int8Ty, Amt));
Reid Spencerfdff9382006-11-08 06:47:33 +00005597 if (I.getType() == ShiftResult->getType())
5598 return ShiftResult;
5599 InsertNewInstBefore(ShiftResult, I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005600 return CastInst::create(Instruction::BitCast, ShiftResult, I.getType());
Chris Lattnereb372a02006-01-06 07:52:12 +00005601 }
5602
5603 // Check for (A << c1) >> c2 or (A >> c1) << c2. If we are dealing with
5604 // signed types, we can only support the (A >> c1) << c2 configuration,
5605 // because it can not turn an arbitrary bit of A into a sign bit.
5606 if (isUnsignedShift || isLeftShift) {
5607 // Calculate bitmask for what gets shifted off the edge.
5608 Constant *C = ConstantIntegral::getAllOnesValue(I.getType());
5609 if (isLeftShift)
5610 C = ConstantExpr::getShl(C, ShiftAmt1C);
5611 else
Reid Spencerfdff9382006-11-08 06:47:33 +00005612 C = ConstantExpr::getLShr(C, ShiftAmt1C);
Chris Lattnereb372a02006-01-06 07:52:12 +00005613
5614 Value *Op = ShiftOp->getOperand(0);
Chris Lattnereb372a02006-01-06 07:52:12 +00005615
5616 Instruction *Mask =
5617 BinaryOperator::createAnd(Op, C, Op->getName()+".mask");
5618 InsertNewInstBefore(Mask, I);
5619
5620 // Figure out what flavor of shift we should use...
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005621 if (ShiftAmt1 == ShiftAmt2) {
Chris Lattnereb372a02006-01-06 07:52:12 +00005622 return ReplaceInstUsesWith(I, Mask); // (A << c) >> c === A & c2
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005623 } else if (ShiftAmt1 < ShiftAmt2) {
Chris Lattnereb372a02006-01-06 07:52:12 +00005624 return new ShiftInst(I.getOpcode(), Mask,
Reid Spencerc635f472006-12-31 05:48:39 +00005625 ConstantInt::get(Type::Int8Ty, ShiftAmt2-ShiftAmt1));
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005626 } else if (isShiftOfUnsignedShift || isShiftOfLeftShift) {
5627 if (isShiftOfUnsignedShift && !isShiftOfLeftShift && isSignedShift) {
Reid Spencerfdff9382006-11-08 06:47:33 +00005628 return new ShiftInst(Instruction::LShr, Mask,
Reid Spencerc635f472006-12-31 05:48:39 +00005629 ConstantInt::get(Type::Int8Ty, ShiftAmt1-ShiftAmt2));
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005630 } else {
5631 return new ShiftInst(ShiftOp->getOpcode(), Mask,
Reid Spencerc635f472006-12-31 05:48:39 +00005632 ConstantInt::get(Type::Int8Ty, ShiftAmt1-ShiftAmt2));
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005633 }
5634 } else {
5635 // (X >>s C1) << C2 where C1 > C2 === (X >>s (C1-C2)) & mask
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005636 Instruction *Shift =
Reid Spencer2a499b02006-12-13 17:19:09 +00005637 new ShiftInst(ShiftOp->getOpcode(), Mask,
Reid Spencerc635f472006-12-31 05:48:39 +00005638 ConstantInt::get(Type::Int8Ty, ShiftAmt1-ShiftAmt2));
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005639 InsertNewInstBefore(Shift, I);
5640
5641 C = ConstantIntegral::getAllOnesValue(Shift->getType());
5642 C = ConstantExpr::getShl(C, Op1);
Reid Spencer2a499b02006-12-13 17:19:09 +00005643 return BinaryOperator::createAnd(Shift, C, Op->getName()+".mask");
Chris Lattnereb372a02006-01-06 07:52:12 +00005644 }
5645 } else {
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005646 // We can handle signed (X << C1) >>s C2 if it's a sign extend. In
Chris Lattnereb372a02006-01-06 07:52:12 +00005647 // this case, C1 == C2 and C1 is 8, 16, or 32.
5648 if (ShiftAmt1 == ShiftAmt2) {
5649 const Type *SExtType = 0;
Chris Lattner655d08f2006-04-28 22:21:41 +00005650 switch (Op0->getType()->getPrimitiveSizeInBits() - ShiftAmt1) {
Reid Spencerc635f472006-12-31 05:48:39 +00005651 case 8 : SExtType = Type::Int8Ty; break;
5652 case 16: SExtType = Type::Int16Ty; break;
5653 case 32: SExtType = Type::Int32Ty; break;
Chris Lattnereb372a02006-01-06 07:52:12 +00005654 }
5655
5656 if (SExtType) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005657 Instruction *NewTrunc =
5658 new TruncInst(ShiftOp->getOperand(0), SExtType, "sext");
Chris Lattnereb372a02006-01-06 07:52:12 +00005659 InsertNewInstBefore(NewTrunc, I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005660 return new SExtInst(NewTrunc, I.getType());
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00005661 }
Chris Lattner27cb9db2005-09-18 05:12:10 +00005662 }
Chris Lattner86102b82005-01-01 16:22:27 +00005663 }
Chris Lattnereb372a02006-01-06 07:52:12 +00005664 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005665 return 0;
5666}
5667
Chris Lattner48a44f72002-05-02 17:06:02 +00005668
Chris Lattner8f663e82005-10-29 04:36:15 +00005669/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
5670/// expression. If so, decompose it, returning some value X, such that Val is
5671/// X*Scale+Offset.
5672///
5673static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
5674 unsigned &Offset) {
Reid Spencerc635f472006-12-31 05:48:39 +00005675 assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
Reid Spencere0fc4df2006-10-20 07:07:24 +00005676 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
Reid Spencerc635f472006-12-31 05:48:39 +00005677 Offset = CI->getZExtValue();
5678 Scale = 1;
5679 return ConstantInt::get(Type::Int32Ty, 0);
Chris Lattner8f663e82005-10-29 04:36:15 +00005680 } else if (Instruction *I = dyn_cast<Instruction>(Val)) {
5681 if (I->getNumOperands() == 2) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00005682 if (ConstantInt *CUI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Reid Spencerc635f472006-12-31 05:48:39 +00005683 if (I->getOpcode() == Instruction::Shl) {
5684 // This is a value scaled by '1 << the shift amt'.
5685 Scale = 1U << CUI->getZExtValue();
5686 Offset = 0;
5687 return I->getOperand(0);
5688 } else if (I->getOpcode() == Instruction::Mul) {
5689 // This value is scaled by 'CUI'.
5690 Scale = CUI->getZExtValue();
5691 Offset = 0;
5692 return I->getOperand(0);
5693 } else if (I->getOpcode() == Instruction::Add) {
5694 // We have X+C. Check to see if we really have (X*C2)+C1,
5695 // where C1 is divisible by C2.
5696 unsigned SubScale;
5697 Value *SubVal =
5698 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
5699 Offset += CUI->getZExtValue();
5700 if (SubScale > 1 && (Offset % SubScale == 0)) {
5701 Scale = SubScale;
5702 return SubVal;
Chris Lattner8f663e82005-10-29 04:36:15 +00005703 }
5704 }
5705 }
5706 }
5707 }
5708
5709 // Otherwise, we can't look past this.
5710 Scale = 1;
5711 Offset = 0;
5712 return Val;
5713}
5714
5715
Chris Lattner216be912005-10-24 06:03:58 +00005716/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
5717/// try to eliminate the cast by moving the type information into the alloc.
5718Instruction *InstCombiner::PromoteCastOfAllocation(CastInst &CI,
5719 AllocationInst &AI) {
5720 const PointerType *PTy = dyn_cast<PointerType>(CI.getType());
Chris Lattnerbb171802005-10-27 05:53:56 +00005721 if (!PTy) return 0; // Not casting the allocation to a pointer type.
Chris Lattner216be912005-10-24 06:03:58 +00005722
Chris Lattnerac87beb2005-10-24 06:22:12 +00005723 // Remove any uses of AI that are dead.
5724 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
5725 std::vector<Instruction*> DeadUsers;
5726 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
5727 Instruction *User = cast<Instruction>(*UI++);
5728 if (isInstructionTriviallyDead(User)) {
5729 while (UI != E && *UI == User)
5730 ++UI; // If this instruction uses AI more than once, don't break UI.
5731
5732 // Add operands to the worklist.
5733 AddUsesToWorkList(*User);
5734 ++NumDeadInst;
Bill Wendling5dbf43c2006-11-26 09:46:52 +00005735 DOUT << "IC: DCE: " << *User;
Chris Lattnerac87beb2005-10-24 06:22:12 +00005736
5737 User->eraseFromParent();
5738 removeFromWorkList(User);
5739 }
5740 }
5741
Chris Lattner216be912005-10-24 06:03:58 +00005742 // Get the type really allocated and the type casted to.
5743 const Type *AllocElTy = AI.getAllocatedType();
5744 const Type *CastElTy = PTy->getElementType();
5745 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner355ecc02005-10-24 06:26:18 +00005746
Chris Lattner7d190672006-10-01 19:40:58 +00005747 unsigned AllocElTyAlign = TD->getTypeAlignment(AllocElTy);
5748 unsigned CastElTyAlign = TD->getTypeAlignment(CastElTy);
Chris Lattner355ecc02005-10-24 06:26:18 +00005749 if (CastElTyAlign < AllocElTyAlign) return 0;
5750
Chris Lattner46705b22005-10-24 06:35:18 +00005751 // If the allocation has multiple uses, only promote it if we are strictly
5752 // increasing the alignment of the resultant allocation. If we keep it the
5753 // same, we open the door to infinite loops of various kinds.
5754 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
5755
Chris Lattner216be912005-10-24 06:03:58 +00005756 uint64_t AllocElTySize = TD->getTypeSize(AllocElTy);
5757 uint64_t CastElTySize = TD->getTypeSize(CastElTy);
Chris Lattnerbb171802005-10-27 05:53:56 +00005758 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner355ecc02005-10-24 06:26:18 +00005759
Chris Lattner8270c332005-10-29 03:19:53 +00005760 // See if we can satisfy the modulus by pulling a scale out of the array
5761 // size argument.
Chris Lattner8f663e82005-10-29 04:36:15 +00005762 unsigned ArraySizeScale, ArrayOffset;
5763 Value *NumElements = // See if the array size is a decomposable linear expr.
5764 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
5765
Chris Lattner8270c332005-10-29 03:19:53 +00005766 // If we can now satisfy the modulus, by using a non-1 scale, we really can
5767 // do the xform.
Chris Lattner8f663e82005-10-29 04:36:15 +00005768 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
5769 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattnerb3ecf962005-10-27 06:12:00 +00005770
Chris Lattner8270c332005-10-29 03:19:53 +00005771 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
5772 Value *Amt = 0;
5773 if (Scale == 1) {
5774 Amt = NumElements;
5775 } else {
Reid Spencere0fc4df2006-10-20 07:07:24 +00005776 // If the allocation size is constant, form a constant mul expression
Reid Spencerc635f472006-12-31 05:48:39 +00005777 Amt = ConstantInt::get(Type::Int32Ty, Scale);
5778 if (isa<ConstantInt>(NumElements))
Reid Spencere0fc4df2006-10-20 07:07:24 +00005779 Amt = ConstantExpr::getMul(
5780 cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
5781 // otherwise multiply the amount and the number of elements
Chris Lattner8270c332005-10-29 03:19:53 +00005782 else if (Scale != 1) {
5783 Instruction *Tmp = BinaryOperator::createMul(Amt, NumElements, "tmp");
5784 Amt = InsertNewInstBefore(Tmp, AI);
Chris Lattnerb3ecf962005-10-27 06:12:00 +00005785 }
Chris Lattnerbb171802005-10-27 05:53:56 +00005786 }
5787
Chris Lattner8f663e82005-10-29 04:36:15 +00005788 if (unsigned Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
Reid Spencerc635f472006-12-31 05:48:39 +00005789 Value *Off = ConstantInt::get(Type::Int32Ty, Offset);
Chris Lattner8f663e82005-10-29 04:36:15 +00005790 Instruction *Tmp = BinaryOperator::createAdd(Amt, Off, "tmp");
5791 Amt = InsertNewInstBefore(Tmp, AI);
5792 }
5793
Chris Lattner216be912005-10-24 06:03:58 +00005794 std::string Name = AI.getName(); AI.setName("");
5795 AllocationInst *New;
5796 if (isa<MallocInst>(AI))
Nate Begeman848622f2005-11-05 09:21:28 +00005797 New = new MallocInst(CastElTy, Amt, AI.getAlignment(), Name);
Chris Lattner216be912005-10-24 06:03:58 +00005798 else
Nate Begeman848622f2005-11-05 09:21:28 +00005799 New = new AllocaInst(CastElTy, Amt, AI.getAlignment(), Name);
Chris Lattner216be912005-10-24 06:03:58 +00005800 InsertNewInstBefore(New, AI);
Chris Lattner46705b22005-10-24 06:35:18 +00005801
5802 // If the allocation has multiple uses, insert a cast and change all things
5803 // that used it to use the new cast. This will also hack on CI, but it will
5804 // die soon.
5805 if (!AI.hasOneUse()) {
5806 AddUsesToWorkList(AI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005807 // New is the allocation instruction, pointer typed. AI is the original
5808 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
5809 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
Chris Lattner46705b22005-10-24 06:35:18 +00005810 InsertNewInstBefore(NewCast, AI);
5811 AI.replaceAllUsesWith(NewCast);
5812 }
Chris Lattner216be912005-10-24 06:03:58 +00005813 return ReplaceInstUsesWith(CI, New);
5814}
5815
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005816/// CanEvaluateInDifferentType - Return true if we can take the specified value
5817/// and return it without inserting any new casts. This is used by code that
5818/// tries to decide whether promoting or shrinking integer operations to wider
5819/// or smaller types will allow us to eliminate a truncate or extend.
5820static bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
5821 int &NumCastsRemoved) {
5822 if (isa<Constant>(V)) return true;
5823
5824 Instruction *I = dyn_cast<Instruction>(V);
5825 if (!I || !I->hasOneUse()) return false;
5826
5827 switch (I->getOpcode()) {
5828 case Instruction::And:
5829 case Instruction::Or:
5830 case Instruction::Xor:
5831 // These operators can all arbitrarily be extended or truncated.
5832 return CanEvaluateInDifferentType(I->getOperand(0), Ty, NumCastsRemoved) &&
5833 CanEvaluateInDifferentType(I->getOperand(1), Ty, NumCastsRemoved);
Chris Lattner960acb02006-11-29 07:18:39 +00005834 case Instruction::AShr:
5835 case Instruction::LShr:
5836 case Instruction::Shl:
5837 // If this is just a bitcast changing the sign of the operation, we can
5838 // convert if the operand can be converted.
5839 if (V->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
5840 return CanEvaluateInDifferentType(I->getOperand(0), Ty, NumCastsRemoved);
5841 break;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005842 case Instruction::Trunc:
5843 case Instruction::ZExt:
5844 case Instruction::SExt:
5845 case Instruction::BitCast:
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005846 // If this is a cast from the destination type, we can trivially eliminate
5847 // it, and this will remove a cast overall.
5848 if (I->getOperand(0)->getType() == Ty) {
Chris Lattner3fda3862006-06-28 17:34:50 +00005849 // If the first operand is itself a cast, and is eliminable, do not count
5850 // this as an eliminable cast. We would prefer to eliminate those two
5851 // casts first.
Reid Spencerde46e482006-11-02 20:25:50 +00005852 if (isa<CastInst>(I->getOperand(0)))
Chris Lattner3fda3862006-06-28 17:34:50 +00005853 return true;
5854
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005855 ++NumCastsRemoved;
5856 return true;
5857 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005858 break;
5859 default:
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005860 // TODO: Can handle more cases here.
5861 break;
5862 }
5863
5864 return false;
5865}
5866
5867/// EvaluateInDifferentType - Given an expression that
5868/// CanEvaluateInDifferentType returns true for, actually insert the code to
5869/// evaluate the expression.
Reid Spencer74a528b2006-12-13 18:21:21 +00005870Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
5871 bool isSigned ) {
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005872 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencer74a528b2006-12-13 18:21:21 +00005873 return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005874
5875 // Otherwise, it must be an instruction.
5876 Instruction *I = cast<Instruction>(V);
Chris Lattnerd0622b62006-05-20 23:14:03 +00005877 Instruction *Res = 0;
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005878 switch (I->getOpcode()) {
5879 case Instruction::And:
5880 case Instruction::Or:
5881 case Instruction::Xor: {
Reid Spencer74a528b2006-12-13 18:21:21 +00005882 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
5883 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005884 Res = BinaryOperator::create((Instruction::BinaryOps)I->getOpcode(),
5885 LHS, RHS, I->getName());
5886 break;
5887 }
Chris Lattner960acb02006-11-29 07:18:39 +00005888 case Instruction::AShr:
5889 case Instruction::LShr:
5890 case Instruction::Shl: {
Reid Spencer74a528b2006-12-13 18:21:21 +00005891 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
Chris Lattner960acb02006-11-29 07:18:39 +00005892 Res = new ShiftInst((Instruction::OtherOps)I->getOpcode(), LHS,
5893 I->getOperand(1), I->getName());
5894 break;
5895 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005896 case Instruction::Trunc:
5897 case Instruction::ZExt:
5898 case Instruction::SExt:
5899 case Instruction::BitCast:
5900 // If the source type of the cast is the type we're trying for then we can
5901 // just return the source. There's no need to insert it because its not new.
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005902 if (I->getOperand(0)->getType() == Ty)
5903 return I->getOperand(0);
5904
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005905 // Some other kind of cast, which shouldn't happen, so just ..
5906 // FALL THROUGH
5907 default:
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005908 // TODO: Can handle more cases here.
5909 assert(0 && "Unreachable!");
5910 break;
5911 }
5912
5913 return InsertNewInstBefore(Res, *I);
5914}
5915
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005916/// @brief Implement the transforms common to all CastInst visitors.
5917Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
Chris Lattner55d4bda2003-06-23 21:59:52 +00005918 Value *Src = CI.getOperand(0);
5919
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005920 // Casting undef to anything results in undef so might as just replace it and
5921 // get rid of the cast.
Chris Lattner81a7a232004-10-16 18:11:37 +00005922 if (isa<UndefValue>(Src)) // cast undef -> undef
5923 return ReplaceInstUsesWith(CI, UndefValue::get(CI.getType()));
5924
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005925 // Many cases of "cast of a cast" are eliminable. If its eliminable we just
5926 // eliminate it now.
Chris Lattner86102b82005-01-01 16:22:27 +00005927 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005928 if (Instruction::CastOps opc =
5929 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
5930 // The first cast (CSrc) is eliminable so we need to fix up or replace
5931 // the second cast (CI). CSrc will then have a good chance of being dead.
5932 return CastInst::create(opc, CSrc->getOperand(0), CI.getType());
Chris Lattner650b6da2002-08-02 20:00:25 +00005933 }
5934 }
Chris Lattner03841652004-05-25 04:29:21 +00005935
Chris Lattnerd0d51602003-06-21 23:12:02 +00005936 // If casting the result of a getelementptr instruction with no offset, turn
5937 // this into a cast of the original pointer!
5938 //
Chris Lattner55d4bda2003-06-23 21:59:52 +00005939 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattnerd0d51602003-06-21 23:12:02 +00005940 bool AllZeroOperands = true;
5941 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
5942 if (!isa<Constant>(GEP->getOperand(i)) ||
5943 !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
5944 AllZeroOperands = false;
5945 break;
5946 }
5947 if (AllZeroOperands) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005948 // Changing the cast operand is usually not a good idea but it is safe
5949 // here because the pointer operand is being replaced with another
5950 // pointer operand so the opcode doesn't need to change.
Chris Lattnerd0d51602003-06-21 23:12:02 +00005951 CI.setOperand(0, GEP->getOperand(0));
5952 return &CI;
5953 }
5954 }
Chris Lattnerec45a4c2006-11-21 17:05:13 +00005955
Chris Lattnerf4ad1652003-11-02 05:57:39 +00005956 // If we are casting a malloc or alloca to a pointer to a type of the same
5957 // size, rewrite the allocation instruction to allocate the "right" type.
Chris Lattnerf4ad1652003-11-02 05:57:39 +00005958 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
Chris Lattner216be912005-10-24 06:03:58 +00005959 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
5960 return V;
Chris Lattnerf4ad1652003-11-02 05:57:39 +00005961
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005962 // If we are casting a select then fold the cast into the select
Chris Lattner86102b82005-01-01 16:22:27 +00005963 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
5964 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
5965 return NV;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005966
5967 // If we are casting a PHI then fold the cast into the PHI
Chris Lattner6a4adcd2004-09-29 05:07:12 +00005968 if (isa<PHINode>(Src))
5969 if (Instruction *NV = FoldOpIntoPhi(CI))
5970 return NV;
Chris Lattnerb19a5c62006-04-12 18:09:35 +00005971
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005972 return 0;
5973}
5974
5975/// Only the TRUNC, ZEXT, SEXT, and BITCONVERT can have both operands as
5976/// integers. This function implements the common transforms for all those
5977/// cases.
5978/// @brief Implement the transforms common to CastInst with integer operands
5979Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
5980 if (Instruction *Result = commonCastTransforms(CI))
5981 return Result;
5982
5983 Value *Src = CI.getOperand(0);
5984 const Type *SrcTy = Src->getType();
5985 const Type *DestTy = CI.getType();
5986 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
5987 unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
5988
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005989 // See if we can simplify any instructions used by the LHS whose sole
5990 // purpose is to compute bits we don't care about.
5991 uint64_t KnownZero = 0, KnownOne = 0;
5992 if (SimplifyDemandedBits(&CI, DestTy->getIntegralTypeMask(),
5993 KnownZero, KnownOne))
5994 return &CI;
5995
5996 // If the source isn't an instruction or has more than one use then we
5997 // can't do anything more.
Reid Spencer266e42b2006-12-23 06:05:41 +00005998 Instruction *SrcI = dyn_cast<Instruction>(Src);
5999 if (!SrcI || !Src->hasOneUse())
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006000 return 0;
6001
6002 // Attempt to propagate the cast into the instruction.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006003 int NumCastsRemoved = 0;
6004 if (CanEvaluateInDifferentType(SrcI, DestTy, NumCastsRemoved)) {
6005 // If this cast is a truncate, evaluting in a different type always
6006 // eliminates the cast, so it is always a win. If this is a noop-cast
6007 // this just removes a noop cast which isn't pointful, but simplifies
6008 // the code. If this is a zero-extension, we need to do an AND to
6009 // maintain the clear top-part of the computation, so we require that
6010 // the input have eliminated at least one cast. If this is a sign
6011 // extension, we insert two new casts (to do the extension) so we
6012 // require that two casts have been eliminated.
6013 bool DoXForm = CI.isNoopCast(TD->getIntPtrType());
6014 if (!DoXForm) {
6015 switch (CI.getOpcode()) {
6016 case Instruction::Trunc:
6017 DoXForm = true;
6018 break;
6019 case Instruction::ZExt:
6020 DoXForm = NumCastsRemoved >= 1;
6021 break;
6022 case Instruction::SExt:
6023 DoXForm = NumCastsRemoved >= 2;
6024 break;
6025 case Instruction::BitCast:
6026 DoXForm = false;
6027 break;
6028 default:
6029 // All the others use floating point so we shouldn't actually
6030 // get here because of the check above.
6031 assert(!"Unknown cast type .. unreachable");
6032 break;
6033 }
6034 }
6035
6036 if (DoXForm) {
Reid Spencer74a528b2006-12-13 18:21:21 +00006037 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
6038 CI.getOpcode() == Instruction::SExt);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006039 assert(Res->getType() == DestTy);
6040 switch (CI.getOpcode()) {
6041 default: assert(0 && "Unknown cast type!");
6042 case Instruction::Trunc:
6043 case Instruction::BitCast:
6044 // Just replace this cast with the result.
6045 return ReplaceInstUsesWith(CI, Res);
6046 case Instruction::ZExt: {
6047 // We need to emit an AND to clear the high bits.
6048 assert(SrcBitSize < DestBitSize && "Not a zext?");
6049 Constant *C =
Reid Spencerc635f472006-12-31 05:48:39 +00006050 ConstantInt::get(Type::Int64Ty, (1ULL << SrcBitSize)-1);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006051 if (DestBitSize < 64)
6052 C = ConstantExpr::getTrunc(C, DestTy);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006053 return BinaryOperator::createAnd(Res, C);
6054 }
6055 case Instruction::SExt:
6056 // We need to emit a cast to truncate, then a cast to sext.
6057 return CastInst::create(Instruction::SExt,
Reid Spencer13bc5d72006-12-12 09:18:51 +00006058 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
6059 CI), DestTy);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006060 }
6061 }
6062 }
6063
6064 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
6065 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
6066
6067 switch (SrcI->getOpcode()) {
6068 case Instruction::Add:
6069 case Instruction::Mul:
6070 case Instruction::And:
6071 case Instruction::Or:
6072 case Instruction::Xor:
6073 // If we are discarding information, or just changing the sign,
6074 // rewrite.
6075 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
6076 // Don't insert two casts if they cannot be eliminated. We allow
6077 // two casts to be inserted if the sizes are the same. This could
6078 // only be converting signedness, which is a noop.
6079 if (DestBitSize == SrcBitSize ||
Reid Spencer266e42b2006-12-23 06:05:41 +00006080 !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
6081 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer2a499b02006-12-13 17:19:09 +00006082 Instruction::CastOps opcode = CI.getOpcode();
Reid Spencer13bc5d72006-12-12 09:18:51 +00006083 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
6084 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
6085 return BinaryOperator::create(
6086 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006087 }
6088 }
6089
6090 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
6091 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
6092 SrcI->getOpcode() == Instruction::Xor &&
6093 Op1 == ConstantBool::getTrue() &&
Reid Spencer266e42b2006-12-23 06:05:41 +00006094 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00006095 Value *New = InsertOperandCastBefore(Instruction::ZExt, Op0, DestTy, &CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006096 return BinaryOperator::createXor(New, ConstantInt::get(CI.getType(), 1));
6097 }
6098 break;
6099 case Instruction::SDiv:
6100 case Instruction::UDiv:
6101 case Instruction::SRem:
6102 case Instruction::URem:
6103 // If we are just changing the sign, rewrite.
6104 if (DestBitSize == SrcBitSize) {
6105 // Don't insert two casts if they cannot be eliminated. We allow
6106 // two casts to be inserted if the sizes are the same. This could
6107 // only be converting signedness, which is a noop.
Reid Spencer266e42b2006-12-23 06:05:41 +00006108 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
6109 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00006110 Value *Op0c = InsertOperandCastBefore(Instruction::BitCast,
6111 Op0, DestTy, SrcI);
6112 Value *Op1c = InsertOperandCastBefore(Instruction::BitCast,
6113 Op1, DestTy, SrcI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006114 return BinaryOperator::create(
6115 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
6116 }
6117 }
6118 break;
6119
6120 case Instruction::Shl:
6121 // Allow changing the sign of the source operand. Do not allow
6122 // changing the size of the shift, UNLESS the shift amount is a
6123 // constant. We must not change variable sized shifts to a smaller
6124 // size, because it is undefined to shift more bits out than exist
6125 // in the value.
6126 if (DestBitSize == SrcBitSize ||
6127 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00006128 Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
6129 Instruction::BitCast : Instruction::Trunc);
6130 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006131 return new ShiftInst(Instruction::Shl, Op0c, Op1);
6132 }
6133 break;
6134 case Instruction::AShr:
6135 // If this is a signed shr, and if all bits shifted in are about to be
6136 // truncated off, turn it into an unsigned shr to allow greater
6137 // simplifications.
6138 if (DestBitSize < SrcBitSize &&
6139 isa<ConstantInt>(Op1)) {
6140 unsigned ShiftAmt = cast<ConstantInt>(Op1)->getZExtValue();
6141 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
6142 // Insert the new logical shift right.
6143 return new ShiftInst(Instruction::LShr, Op0, Op1);
6144 }
6145 }
6146 break;
6147
Reid Spencer266e42b2006-12-23 06:05:41 +00006148 case Instruction::ICmp:
6149 // If we are just checking for a icmp eq of a single bit and casting it
6150 // to an integer, then shift the bit to the appropriate place and then
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006151 // cast to integer to avoid the comparison.
6152 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
6153 uint64_t Op1CV = Op1C->getZExtValue();
6154 // cast (X == 0) to int --> X^1 iff X has only the low bit set.
6155 // cast (X == 0) to int --> (X>>1)^1 iff X has only the 2nd bit set.
6156 // cast (X == 1) to int --> X iff X has only the low bit set.
6157 // cast (X == 2) to int --> X>>1 iff X has only the 2nd bit set.
6158 // cast (X != 0) to int --> X iff X has only the low bit set.
6159 // cast (X != 0) to int --> X>>1 iff X has only the 2nd bit set.
6160 // cast (X != 1) to int --> X^1 iff X has only the low bit set.
6161 // cast (X != 2) to int --> (X>>1)^1 iff X has only the 2nd bit set.
6162 if (Op1CV == 0 || isPowerOf2_64(Op1CV)) {
6163 // If Op1C some other power of two, convert:
6164 uint64_t KnownZero, KnownOne;
6165 uint64_t TypeMask = Op1->getType()->getIntegralTypeMask();
6166 ComputeMaskedBits(Op0, TypeMask, KnownZero, KnownOne);
Reid Spencer266e42b2006-12-23 06:05:41 +00006167
6168 // This only works for EQ and NE
6169 ICmpInst::Predicate pred = cast<ICmpInst>(SrcI)->getPredicate();
6170 if (pred != ICmpInst::ICMP_NE && pred != ICmpInst::ICMP_EQ)
6171 break;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006172
6173 if (isPowerOf2_64(KnownZero^TypeMask)) { // Exactly 1 possible 1?
Reid Spencer266e42b2006-12-23 06:05:41 +00006174 bool isNE = pred == ICmpInst::ICMP_NE;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006175 if (Op1CV && (Op1CV != (KnownZero^TypeMask))) {
6176 // (X&4) == 2 --> false
6177 // (X&4) != 2 --> true
Reid Spencer266e42b2006-12-23 06:05:41 +00006178 Constant *Res = ConstantBool::get(isNE);
Reid Spencerbb65ebf2006-12-12 23:36:14 +00006179 Res = ConstantExpr::getZExt(Res, CI.getType());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006180 return ReplaceInstUsesWith(CI, Res);
6181 }
6182
6183 unsigned ShiftAmt = Log2_64(KnownZero^TypeMask);
6184 Value *In = Op0;
6185 if (ShiftAmt) {
6186 // Perform a logical shr by shiftamt.
6187 // Insert the shift to put the result in the low bit.
6188 In = InsertNewInstBefore(
6189 new ShiftInst(Instruction::LShr, In,
Reid Spencerc635f472006-12-31 05:48:39 +00006190 ConstantInt::get(Type::Int8Ty, ShiftAmt),
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006191 In->getName()+".lobit"), CI);
6192 }
6193
Reid Spencer266e42b2006-12-23 06:05:41 +00006194 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006195 Constant *One = ConstantInt::get(In->getType(), 1);
6196 In = BinaryOperator::createXor(In, One, "tmp");
6197 InsertNewInstBefore(cast<Instruction>(In), CI);
6198 }
6199
6200 if (CI.getType() == In->getType())
6201 return ReplaceInstUsesWith(CI, In);
6202 else
Reid Spencerbb65ebf2006-12-12 23:36:14 +00006203 return CastInst::createIntegerCast(In, CI.getType(), false/*ZExt*/);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006204 }
6205 }
6206 }
6207 break;
6208 }
6209 return 0;
6210}
6211
6212Instruction *InstCombiner::visitTrunc(CastInst &CI) {
Chris Lattnerd747f012006-11-29 07:04:07 +00006213 if (Instruction *Result = commonIntCastTransforms(CI))
6214 return Result;
6215
6216 Value *Src = CI.getOperand(0);
6217 const Type *Ty = CI.getType();
6218 unsigned DestBitWidth = Ty->getPrimitiveSizeInBits();
6219
6220 if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
6221 switch (SrcI->getOpcode()) {
6222 default: break;
6223 case Instruction::LShr:
6224 // We can shrink lshr to something smaller if we know the bits shifted in
6225 // are already zeros.
6226 if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
6227 unsigned ShAmt = ShAmtV->getZExtValue();
6228
6229 // Get a mask for the bits shifting in.
6230 uint64_t Mask = (~0ULL >> (64-ShAmt)) << DestBitWidth;
Reid Spencer13bc5d72006-12-12 09:18:51 +00006231 Value* SrcIOp0 = SrcI->getOperand(0);
6232 if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
Chris Lattnerd747f012006-11-29 07:04:07 +00006233 if (ShAmt >= DestBitWidth) // All zeros.
6234 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
6235
6236 // Okay, we can shrink this. Truncate the input, then return a new
6237 // shift.
Reid Spencer2a499b02006-12-13 17:19:09 +00006238 Value *V = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
Chris Lattnerd747f012006-11-29 07:04:07 +00006239 return new ShiftInst(Instruction::LShr, V, SrcI->getOperand(1));
6240 }
Chris Lattnerc209b582006-12-05 01:26:29 +00006241 } else { // This is a variable shr.
6242
6243 // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'. This is
6244 // more LLVM instructions, but allows '1 << Y' to be hoisted if
6245 // loop-invariant and CSE'd.
6246 if (CI.getType() == Type::BoolTy && SrcI->hasOneUse()) {
6247 Value *One = ConstantInt::get(SrcI->getType(), 1);
6248
6249 Value *V = InsertNewInstBefore(new ShiftInst(Instruction::Shl, One,
6250 SrcI->getOperand(1),
6251 "tmp"), CI);
6252 V = InsertNewInstBefore(BinaryOperator::createAnd(V,
6253 SrcI->getOperand(0),
6254 "tmp"), CI);
6255 Value *Zero = Constant::getNullValue(V->getType());
Reid Spencer266e42b2006-12-23 06:05:41 +00006256 return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
Chris Lattnerc209b582006-12-05 01:26:29 +00006257 }
Chris Lattnerd747f012006-11-29 07:04:07 +00006258 }
6259 break;
6260 }
6261 }
6262
6263 return 0;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006264}
6265
6266Instruction *InstCombiner::visitZExt(CastInst &CI) {
6267 // If one of the common conversion will work ..
6268 if (Instruction *Result = commonIntCastTransforms(CI))
6269 return Result;
6270
6271 Value *Src = CI.getOperand(0);
6272
6273 // If this is a cast of a cast
6274 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006275 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
6276 // types and if the sizes are just right we can convert this into a logical
6277 // 'and' which will be much cheaper than the pair of casts.
6278 if (isa<TruncInst>(CSrc)) {
6279 // Get the sizes of the types involved
6280 Value *A = CSrc->getOperand(0);
6281 unsigned SrcSize = A->getType()->getPrimitiveSizeInBits();
6282 unsigned MidSize = CSrc->getType()->getPrimitiveSizeInBits();
6283 unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
6284 // If we're actually extending zero bits and the trunc is a no-op
6285 if (MidSize < DstSize && SrcSize == DstSize) {
6286 // Replace both of the casts with an And of the type mask.
6287 uint64_t AndValue = CSrc->getType()->getIntegralTypeMask();
6288 Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
6289 Instruction *And =
6290 BinaryOperator::createAnd(CSrc->getOperand(0), AndConst);
6291 // Unfortunately, if the type changed, we need to cast it back.
6292 if (And->getType() != CI.getType()) {
6293 And->setName(CSrc->getName()+".mask");
6294 InsertNewInstBefore(And, CI);
Reid Spencerbb65ebf2006-12-12 23:36:14 +00006295 And = CastInst::createIntegerCast(And, CI.getType(), false/*ZExt*/);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006296 }
6297 return And;
6298 }
6299 }
6300 }
6301
6302 return 0;
6303}
6304
6305Instruction *InstCombiner::visitSExt(CastInst &CI) {
6306 return commonIntCastTransforms(CI);
6307}
6308
6309Instruction *InstCombiner::visitFPTrunc(CastInst &CI) {
6310 return commonCastTransforms(CI);
6311}
6312
6313Instruction *InstCombiner::visitFPExt(CastInst &CI) {
6314 return commonCastTransforms(CI);
6315}
6316
6317Instruction *InstCombiner::visitFPToUI(CastInst &CI) {
Reid Spencerad05ee92006-11-30 23:13:36 +00006318 return commonCastTransforms(CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006319}
6320
6321Instruction *InstCombiner::visitFPToSI(CastInst &CI) {
Reid Spencerad05ee92006-11-30 23:13:36 +00006322 return commonCastTransforms(CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006323}
6324
6325Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
6326 return commonCastTransforms(CI);
6327}
6328
6329Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
6330 return commonCastTransforms(CI);
6331}
6332
6333Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
Reid Spencerad05ee92006-11-30 23:13:36 +00006334 return commonCastTransforms(CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006335}
6336
6337Instruction *InstCombiner::visitIntToPtr(CastInst &CI) {
6338 return commonCastTransforms(CI);
6339}
6340
6341Instruction *InstCombiner::visitBitCast(CastInst &CI) {
6342
6343 // If the operands are integer typed then apply the integer transforms,
6344 // otherwise just apply the common ones.
6345 Value *Src = CI.getOperand(0);
6346 const Type *SrcTy = Src->getType();
6347 const Type *DestTy = CI.getType();
6348
6349 if (SrcTy->isInteger() && DestTy->isInteger()) {
6350 if (Instruction *Result = commonIntCastTransforms(CI))
6351 return Result;
6352 } else {
6353 if (Instruction *Result = commonCastTransforms(CI))
6354 return Result;
6355 }
6356
6357
6358 // Get rid of casts from one type to the same type. These are useless and can
6359 // be replaced by the operand.
6360 if (DestTy == Src->getType())
6361 return ReplaceInstUsesWith(CI, Src);
6362
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006363 // If the source and destination are pointers, and this cast is equivalent to
6364 // a getelementptr X, 0, 0, 0... turn it into the appropriate getelementptr.
6365 // This can enhance SROA and other transforms that want type-safe pointers.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006366 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
6367 if (const PointerType *SrcPTy = dyn_cast<PointerType>(SrcTy)) {
6368 const Type *DstElTy = DstPTy->getElementType();
6369 const Type *SrcElTy = SrcPTy->getElementType();
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006370
Reid Spencerc635f472006-12-31 05:48:39 +00006371 Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006372 unsigned NumZeros = 0;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006373 while (SrcElTy != DstElTy &&
6374 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
6375 SrcElTy->getNumContainedTypes() /* not "{}" */) {
6376 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006377 ++NumZeros;
6378 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00006379
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006380 // If we found a path from the src to dest, create the getelementptr now.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006381 if (SrcElTy == DstElTy) {
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006382 std::vector<Value*> Idxs(NumZeros+1, ZeroUInt);
6383 return new GetElementPtrInst(Src, Idxs);
6384 }
6385 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006386 }
Chris Lattnerdfae8be2003-07-24 17:35:25 +00006387
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006388 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
6389 if (SVI->hasOneUse()) {
6390 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
6391 // a bitconvert to a vector with the same # elts.
6392 if (isa<PackedType>(DestTy) &&
6393 cast<PackedType>(DestTy)->getNumElements() ==
6394 SVI->getType()->getNumElements()) {
6395 CastInst *Tmp;
6396 // If either of the operands is a cast from CI.getType(), then
6397 // evaluating the shuffle in the casted destination's type will allow
6398 // us to eliminate at least one cast.
6399 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
6400 Tmp->getOperand(0)->getType() == DestTy) ||
6401 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
6402 Tmp->getOperand(0)->getType() == DestTy)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00006403 Value *LHS = InsertOperandCastBefore(Instruction::BitCast,
6404 SVI->getOperand(0), DestTy, &CI);
6405 Value *RHS = InsertOperandCastBefore(Instruction::BitCast,
6406 SVI->getOperand(1), DestTy, &CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006407 // Return a new shuffle vector. Use the same element ID's, as we
6408 // know the vector types match #elts.
6409 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner99155be2006-05-25 23:24:33 +00006410 }
6411 }
6412 }
6413 }
Chris Lattner260ab202002-04-18 17:39:14 +00006414 return 0;
Chris Lattnerca081252001-12-14 16:52:21 +00006415}
6416
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006417/// GetSelectFoldableOperands - We want to turn code that looks like this:
6418/// %C = or %A, %B
6419/// %D = select %cond, %C, %A
6420/// into:
6421/// %C = select %cond, %B, 0
6422/// %D = or %A, %C
6423///
6424/// Assuming that the specified instruction is an operand to the select, return
6425/// a bitmask indicating which operands of this instruction are foldable if they
6426/// equal the other incoming value of the select.
6427///
6428static unsigned GetSelectFoldableOperands(Instruction *I) {
6429 switch (I->getOpcode()) {
6430 case Instruction::Add:
6431 case Instruction::Mul:
6432 case Instruction::And:
6433 case Instruction::Or:
6434 case Instruction::Xor:
6435 return 3; // Can fold through either operand.
6436 case Instruction::Sub: // Can only fold on the amount subtracted.
6437 case Instruction::Shl: // Can only fold on the shift amount.
Reid Spencerfdff9382006-11-08 06:47:33 +00006438 case Instruction::LShr:
6439 case Instruction::AShr:
Misha Brukmanb1c93172005-04-21 23:48:37 +00006440 return 1;
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006441 default:
6442 return 0; // Cannot fold
6443 }
6444}
6445
6446/// GetSelectFoldableConstant - For the same transformation as the previous
6447/// function, return the identity constant that goes into the select.
6448static Constant *GetSelectFoldableConstant(Instruction *I) {
6449 switch (I->getOpcode()) {
6450 default: assert(0 && "This cannot happen!"); abort();
6451 case Instruction::Add:
6452 case Instruction::Sub:
6453 case Instruction::Or:
6454 case Instruction::Xor:
6455 return Constant::getNullValue(I->getType());
6456 case Instruction::Shl:
Reid Spencerfdff9382006-11-08 06:47:33 +00006457 case Instruction::LShr:
6458 case Instruction::AShr:
Reid Spencerc635f472006-12-31 05:48:39 +00006459 return Constant::getNullValue(Type::Int8Ty);
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006460 case Instruction::And:
6461 return ConstantInt::getAllOnesValue(I->getType());
6462 case Instruction::Mul:
6463 return ConstantInt::get(I->getType(), 1);
6464 }
6465}
6466
Chris Lattner411336f2005-01-19 21:50:18 +00006467/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
6468/// have the same opcode and only one use each. Try to simplify this.
6469Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
6470 Instruction *FI) {
6471 if (TI->getNumOperands() == 1) {
6472 // If this is a non-volatile load or a cast from the same type,
6473 // merge.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006474 if (TI->isCast()) {
Chris Lattner411336f2005-01-19 21:50:18 +00006475 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
6476 return 0;
6477 } else {
6478 return 0; // unknown unary op.
6479 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00006480
Chris Lattner411336f2005-01-19 21:50:18 +00006481 // Fold this by inserting a select from the input values.
6482 SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
6483 FI->getOperand(0), SI.getName()+".v");
6484 InsertNewInstBefore(NewSI, SI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006485 return CastInst::create(Instruction::CastOps(TI->getOpcode()), NewSI,
6486 TI->getType());
Chris Lattner411336f2005-01-19 21:50:18 +00006487 }
6488
Reid Spencer266e42b2006-12-23 06:05:41 +00006489 // Only handle binary, compare and shift operators here.
Reid Spencer43c77d52006-12-23 18:58:04 +00006490 if (!isa<ShiftInst>(TI) && !isa<BinaryOperator>(TI))
Chris Lattner411336f2005-01-19 21:50:18 +00006491 return 0;
6492
6493 // Figure out if the operations have any operands in common.
6494 Value *MatchOp, *OtherOpT, *OtherOpF;
6495 bool MatchIsOpZero;
6496 if (TI->getOperand(0) == FI->getOperand(0)) {
6497 MatchOp = TI->getOperand(0);
6498 OtherOpT = TI->getOperand(1);
6499 OtherOpF = FI->getOperand(1);
6500 MatchIsOpZero = true;
6501 } else if (TI->getOperand(1) == FI->getOperand(1)) {
6502 MatchOp = TI->getOperand(1);
6503 OtherOpT = TI->getOperand(0);
6504 OtherOpF = FI->getOperand(0);
6505 MatchIsOpZero = false;
6506 } else if (!TI->isCommutative()) {
6507 return 0;
6508 } else if (TI->getOperand(0) == FI->getOperand(1)) {
6509 MatchOp = TI->getOperand(0);
6510 OtherOpT = TI->getOperand(1);
6511 OtherOpF = FI->getOperand(0);
6512 MatchIsOpZero = true;
6513 } else if (TI->getOperand(1) == FI->getOperand(0)) {
6514 MatchOp = TI->getOperand(1);
6515 OtherOpT = TI->getOperand(0);
6516 OtherOpF = FI->getOperand(1);
6517 MatchIsOpZero = true;
6518 } else {
6519 return 0;
6520 }
6521
6522 // If we reach here, they do have operations in common.
6523 SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
6524 OtherOpF, SI.getName()+".v");
6525 InsertNewInstBefore(NewSI, SI);
6526
6527 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
6528 if (MatchIsOpZero)
6529 return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
6530 else
6531 return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
Chris Lattner411336f2005-01-19 21:50:18 +00006532 }
Reid Spencer43c77d52006-12-23 18:58:04 +00006533
6534 assert(isa<ShiftInst>(TI) && "Should only have Shift here");
6535 if (MatchIsOpZero)
6536 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), MatchOp, NewSI);
6537 else
6538 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), NewSI, MatchOp);
Chris Lattner411336f2005-01-19 21:50:18 +00006539}
6540
Chris Lattnerb909e8b2004-03-12 05:52:32 +00006541Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattner533bc492004-03-30 19:37:13 +00006542 Value *CondVal = SI.getCondition();
6543 Value *TrueVal = SI.getTrueValue();
6544 Value *FalseVal = SI.getFalseValue();
6545
6546 // select true, X, Y -> X
6547 // select false, X, Y -> Y
6548 if (ConstantBool *C = dyn_cast<ConstantBool>(CondVal))
Chris Lattner6ab03f62006-09-28 23:35:22 +00006549 return ReplaceInstUsesWith(SI, C->getValue() ? TrueVal : FalseVal);
Chris Lattner533bc492004-03-30 19:37:13 +00006550
6551 // select C, X, X -> X
6552 if (TrueVal == FalseVal)
6553 return ReplaceInstUsesWith(SI, TrueVal);
6554
Chris Lattner81a7a232004-10-16 18:11:37 +00006555 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
6556 return ReplaceInstUsesWith(SI, FalseVal);
6557 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
6558 return ReplaceInstUsesWith(SI, TrueVal);
6559 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
6560 if (isa<Constant>(TrueVal))
6561 return ReplaceInstUsesWith(SI, TrueVal);
6562 else
6563 return ReplaceInstUsesWith(SI, FalseVal);
6564 }
6565
Chris Lattner1c631e82004-04-08 04:43:23 +00006566 if (SI.getType() == Type::BoolTy)
6567 if (ConstantBool *C = dyn_cast<ConstantBool>(TrueVal)) {
Chris Lattner6ab03f62006-09-28 23:35:22 +00006568 if (C->getValue()) {
Chris Lattner1c631e82004-04-08 04:43:23 +00006569 // Change: A = select B, true, C --> A = or B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00006570 return BinaryOperator::createOr(CondVal, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00006571 } else {
6572 // Change: A = select B, false, C --> A = and !B, C
6573 Value *NotCond =
6574 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
6575 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00006576 return BinaryOperator::createAnd(NotCond, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00006577 }
6578 } else if (ConstantBool *C = dyn_cast<ConstantBool>(FalseVal)) {
Chris Lattner6ab03f62006-09-28 23:35:22 +00006579 if (C->getValue() == false) {
Chris Lattner1c631e82004-04-08 04:43:23 +00006580 // Change: A = select B, C, false --> A = and B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00006581 return BinaryOperator::createAnd(CondVal, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00006582 } else {
6583 // Change: A = select B, C, true --> A = or !B, C
6584 Value *NotCond =
6585 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
6586 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00006587 return BinaryOperator::createOr(NotCond, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00006588 }
6589 }
6590
Chris Lattner183b3362004-04-09 19:05:30 +00006591 // Selecting between two integer constants?
6592 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
6593 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
6594 // select C, 1, 0 -> cast C to int
Reid Spencere0fc4df2006-10-20 07:07:24 +00006595 if (FalseValC->isNullValue() && TrueValC->getZExtValue() == 1) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006596 return CastInst::create(Instruction::ZExt, CondVal, SI.getType());
Reid Spencere0fc4df2006-10-20 07:07:24 +00006597 } else if (TrueValC->isNullValue() && FalseValC->getZExtValue() == 1) {
Chris Lattner183b3362004-04-09 19:05:30 +00006598 // select C, 0, 1 -> cast !C to int
6599 Value *NotCond =
6600 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
Chris Lattnercf7baf32004-04-09 18:19:44 +00006601 "not."+CondVal->getName()), SI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006602 return CastInst::create(Instruction::ZExt, NotCond, SI.getType());
Chris Lattnercf7baf32004-04-09 18:19:44 +00006603 }
Chris Lattner35167c32004-06-09 07:59:58 +00006604
Reid Spencer266e42b2006-12-23 06:05:41 +00006605 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Chris Lattner380c7e92006-09-20 04:44:59 +00006606
Reid Spencer266e42b2006-12-23 06:05:41 +00006607 // (x <s 0) ? -1 : 0 -> ashr x, 31
6608 // (x >u 2147483647) ? -1 : 0 -> ashr x, 31
Chris Lattner380c7e92006-09-20 04:44:59 +00006609 if (TrueValC->isAllOnesValue() && FalseValC->isNullValue())
6610 if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
6611 bool CanXForm = false;
Reid Spencer266e42b2006-12-23 06:05:41 +00006612 if (IC->isSignedPredicate())
Chris Lattner380c7e92006-09-20 04:44:59 +00006613 CanXForm = CmpCst->isNullValue() &&
Reid Spencer266e42b2006-12-23 06:05:41 +00006614 IC->getPredicate() == ICmpInst::ICMP_SLT;
Chris Lattner380c7e92006-09-20 04:44:59 +00006615 else {
6616 unsigned Bits = CmpCst->getType()->getPrimitiveSizeInBits();
Reid Spencere0fc4df2006-10-20 07:07:24 +00006617 CanXForm = (CmpCst->getZExtValue() == ~0ULL >> (64-Bits+1)) &&
Reid Spencer266e42b2006-12-23 06:05:41 +00006618 IC->getPredicate() == ICmpInst::ICMP_UGT;
Chris Lattner380c7e92006-09-20 04:44:59 +00006619 }
6620
6621 if (CanXForm) {
6622 // The comparison constant and the result are not neccessarily the
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006623 // same width. Make an all-ones value by inserting a AShr.
Chris Lattner380c7e92006-09-20 04:44:59 +00006624 Value *X = IC->getOperand(0);
Chris Lattner380c7e92006-09-20 04:44:59 +00006625 unsigned Bits = X->getType()->getPrimitiveSizeInBits();
Reid Spencerc635f472006-12-31 05:48:39 +00006626 Constant *ShAmt = ConstantInt::get(Type::Int8Ty, Bits-1);
Reid Spencerfdff9382006-11-08 06:47:33 +00006627 Instruction *SRA = new ShiftInst(Instruction::AShr, X,
Chris Lattner380c7e92006-09-20 04:44:59 +00006628 ShAmt, "ones");
6629 InsertNewInstBefore(SRA, SI);
6630
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006631 // Finally, convert to the type of the select RHS. We figure out
6632 // if this requires a SExt, Trunc or BitCast based on the sizes.
6633 Instruction::CastOps opc = Instruction::BitCast;
6634 unsigned SRASize = SRA->getType()->getPrimitiveSizeInBits();
6635 unsigned SISize = SI.getType()->getPrimitiveSizeInBits();
6636 if (SRASize < SISize)
6637 opc = Instruction::SExt;
6638 else if (SRASize > SISize)
6639 opc = Instruction::Trunc;
6640 return CastInst::create(opc, SRA, SI.getType());
Chris Lattner380c7e92006-09-20 04:44:59 +00006641 }
6642 }
6643
6644
6645 // If one of the constants is zero (we know they can't both be) and we
Reid Spencer266e42b2006-12-23 06:05:41 +00006646 // have a fcmp instruction with zero, and we have an 'and' with the
Chris Lattner380c7e92006-09-20 04:44:59 +00006647 // non-constant value, eliminate this whole mess. This corresponds to
6648 // cases like this: ((X & 27) ? 27 : 0)
6649 if (TrueValC->isNullValue() || FalseValC->isNullValue())
Chris Lattnerb3f24c92006-09-18 04:22:48 +00006650 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner35167c32004-06-09 07:59:58 +00006651 cast<Constant>(IC->getOperand(1))->isNullValue())
6652 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
6653 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00006654 isa<ConstantInt>(ICA->getOperand(1)) &&
6655 (ICA->getOperand(1) == TrueValC ||
6656 ICA->getOperand(1) == FalseValC) &&
Chris Lattner35167c32004-06-09 07:59:58 +00006657 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
6658 // Okay, now we know that everything is set up, we just don't
Reid Spencer266e42b2006-12-23 06:05:41 +00006659 // know whether we have a icmp_ne or icmp_eq and whether the
6660 // true or false val is the zero.
Chris Lattner35167c32004-06-09 07:59:58 +00006661 bool ShouldNotVal = !TrueValC->isNullValue();
Reid Spencer266e42b2006-12-23 06:05:41 +00006662 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
Chris Lattner35167c32004-06-09 07:59:58 +00006663 Value *V = ICA;
6664 if (ShouldNotVal)
6665 V = InsertNewInstBefore(BinaryOperator::create(
6666 Instruction::Xor, V, ICA->getOperand(1)), SI);
6667 return ReplaceInstUsesWith(SI, V);
6668 }
Chris Lattner380c7e92006-09-20 04:44:59 +00006669 }
Chris Lattner533bc492004-03-30 19:37:13 +00006670 }
Chris Lattner623fba12004-04-10 22:21:27 +00006671
6672 // See if we are selecting two values based on a comparison of the two values.
Reid Spencer266e42b2006-12-23 06:05:41 +00006673 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
6674 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
Chris Lattner623fba12004-04-10 22:21:27 +00006675 // Transform (X == Y) ? X : Y -> Y
Reid Spencer266e42b2006-12-23 06:05:41 +00006676 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ)
Chris Lattner623fba12004-04-10 22:21:27 +00006677 return ReplaceInstUsesWith(SI, FalseVal);
6678 // Transform (X != Y) ? X : Y -> X
Reid Spencer266e42b2006-12-23 06:05:41 +00006679 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
Chris Lattner623fba12004-04-10 22:21:27 +00006680 return ReplaceInstUsesWith(SI, TrueVal);
6681 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6682
Reid Spencer266e42b2006-12-23 06:05:41 +00006683 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
Chris Lattner623fba12004-04-10 22:21:27 +00006684 // Transform (X == Y) ? Y : X -> X
Reid Spencer266e42b2006-12-23 06:05:41 +00006685 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ)
Chris Lattner24cf0202004-04-11 01:39:19 +00006686 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattner623fba12004-04-10 22:21:27 +00006687 // Transform (X != Y) ? Y : X -> Y
Reid Spencer266e42b2006-12-23 06:05:41 +00006688 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
6689 return ReplaceInstUsesWith(SI, TrueVal);
6690 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6691 }
6692 }
6693
6694 // See if we are selecting two values based on a comparison of the two values.
6695 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal)) {
6696 if (ICI->getOperand(0) == TrueVal && ICI->getOperand(1) == FalseVal) {
6697 // Transform (X == Y) ? X : Y -> Y
6698 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
6699 return ReplaceInstUsesWith(SI, FalseVal);
6700 // Transform (X != Y) ? X : Y -> X
6701 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
6702 return ReplaceInstUsesWith(SI, TrueVal);
6703 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6704
6705 } else if (ICI->getOperand(0) == FalseVal && ICI->getOperand(1) == TrueVal){
6706 // Transform (X == Y) ? Y : X -> X
6707 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
6708 return ReplaceInstUsesWith(SI, FalseVal);
6709 // Transform (X != Y) ? Y : X -> Y
6710 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
Chris Lattner24cf0202004-04-11 01:39:19 +00006711 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattner623fba12004-04-10 22:21:27 +00006712 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6713 }
6714 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00006715
Chris Lattnera04c9042005-01-13 22:52:24 +00006716 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
6717 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
6718 if (TI->hasOneUse() && FI->hasOneUse()) {
Chris Lattnera04c9042005-01-13 22:52:24 +00006719 Instruction *AddOp = 0, *SubOp = 0;
6720
Chris Lattner411336f2005-01-19 21:50:18 +00006721 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
6722 if (TI->getOpcode() == FI->getOpcode())
6723 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
6724 return IV;
6725
6726 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
6727 // even legal for FP.
Chris Lattnera04c9042005-01-13 22:52:24 +00006728 if (TI->getOpcode() == Instruction::Sub &&
6729 FI->getOpcode() == Instruction::Add) {
6730 AddOp = FI; SubOp = TI;
6731 } else if (FI->getOpcode() == Instruction::Sub &&
6732 TI->getOpcode() == Instruction::Add) {
6733 AddOp = TI; SubOp = FI;
6734 }
6735
6736 if (AddOp) {
6737 Value *OtherAddOp = 0;
6738 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
6739 OtherAddOp = AddOp->getOperand(1);
6740 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
6741 OtherAddOp = AddOp->getOperand(0);
6742 }
6743
6744 if (OtherAddOp) {
Chris Lattnerb580d262006-02-24 18:05:58 +00006745 // So at this point we know we have (Y -> OtherAddOp):
6746 // select C, (add X, Y), (sub X, Z)
6747 Value *NegVal; // Compute -Z
6748 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
6749 NegVal = ConstantExpr::getNeg(C);
6750 } else {
6751 NegVal = InsertNewInstBefore(
6752 BinaryOperator::createNeg(SubOp->getOperand(1), "tmp"), SI);
Chris Lattnera04c9042005-01-13 22:52:24 +00006753 }
Chris Lattnerb580d262006-02-24 18:05:58 +00006754
6755 Value *NewTrueOp = OtherAddOp;
6756 Value *NewFalseOp = NegVal;
6757 if (AddOp != TI)
6758 std::swap(NewTrueOp, NewFalseOp);
6759 Instruction *NewSel =
6760 new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
6761
6762 NewSel = InsertNewInstBefore(NewSel, SI);
6763 return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
Chris Lattnera04c9042005-01-13 22:52:24 +00006764 }
6765 }
6766 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00006767
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006768 // See if we can fold the select into one of our operands.
6769 if (SI.getType()->isInteger()) {
6770 // See the comment above GetSelectFoldableOperands for a description of the
6771 // transformation we are doing here.
6772 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
6773 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
6774 !isa<Constant>(FalseVal))
6775 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
6776 unsigned OpToFold = 0;
6777 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
6778 OpToFold = 1;
6779 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
6780 OpToFold = 2;
6781 }
6782
6783 if (OpToFold) {
6784 Constant *C = GetSelectFoldableConstant(TVI);
6785 std::string Name = TVI->getName(); TVI->setName("");
6786 Instruction *NewSel =
6787 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C,
6788 Name);
6789 InsertNewInstBefore(NewSel, SI);
6790 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
6791 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
6792 else if (ShiftInst *SI = dyn_cast<ShiftInst>(TVI))
6793 return new ShiftInst(SI->getOpcode(), FalseVal, NewSel);
6794 else {
6795 assert(0 && "Unknown instruction!!");
6796 }
6797 }
6798 }
Chris Lattner6862fbd2004-09-29 17:40:11 +00006799
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006800 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
6801 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
6802 !isa<Constant>(TrueVal))
6803 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
6804 unsigned OpToFold = 0;
6805 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
6806 OpToFold = 1;
6807 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
6808 OpToFold = 2;
6809 }
6810
6811 if (OpToFold) {
6812 Constant *C = GetSelectFoldableConstant(FVI);
6813 std::string Name = FVI->getName(); FVI->setName("");
6814 Instruction *NewSel =
6815 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold),
6816 Name);
6817 InsertNewInstBefore(NewSel, SI);
6818 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
6819 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
6820 else if (ShiftInst *SI = dyn_cast<ShiftInst>(FVI))
6821 return new ShiftInst(SI->getOpcode(), TrueVal, NewSel);
6822 else {
6823 assert(0 && "Unknown instruction!!");
6824 }
6825 }
6826 }
6827 }
Chris Lattnerd6f636a2005-04-24 07:30:14 +00006828
6829 if (BinaryOperator::isNot(CondVal)) {
6830 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
6831 SI.setOperand(1, FalseVal);
6832 SI.setOperand(2, TrueVal);
6833 return &SI;
6834 }
6835
Chris Lattnerb909e8b2004-03-12 05:52:32 +00006836 return 0;
6837}
6838
Chris Lattner82f2ef22006-03-06 20:18:44 +00006839/// GetKnownAlignment - If the specified pointer has an alignment that we can
6840/// determine, return it, otherwise return 0.
6841static unsigned GetKnownAlignment(Value *V, TargetData *TD) {
6842 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
6843 unsigned Align = GV->getAlignment();
6844 if (Align == 0 && TD)
6845 Align = TD->getTypeAlignment(GV->getType()->getElementType());
6846 return Align;
6847 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
6848 unsigned Align = AI->getAlignment();
6849 if (Align == 0 && TD) {
6850 if (isa<AllocaInst>(AI))
6851 Align = TD->getTypeAlignment(AI->getType()->getElementType());
6852 else if (isa<MallocInst>(AI)) {
6853 // Malloc returns maximally aligned memory.
6854 Align = TD->getTypeAlignment(AI->getType()->getElementType());
6855 Align = std::max(Align, (unsigned)TD->getTypeAlignment(Type::DoubleTy));
Reid Spencerc635f472006-12-31 05:48:39 +00006856 Align = std::max(Align, (unsigned)TD->getTypeAlignment(Type::Int64Ty));
Chris Lattner82f2ef22006-03-06 20:18:44 +00006857 }
6858 }
6859 return Align;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006860 } else if (isa<BitCastInst>(V) ||
Chris Lattner53ef5a02006-03-07 01:28:57 +00006861 (isa<ConstantExpr>(V) &&
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006862 cast<ConstantExpr>(V)->getOpcode() == Instruction::BitCast)) {
Chris Lattner53ef5a02006-03-07 01:28:57 +00006863 User *CI = cast<User>(V);
Chris Lattner82f2ef22006-03-06 20:18:44 +00006864 if (isa<PointerType>(CI->getOperand(0)->getType()))
6865 return GetKnownAlignment(CI->getOperand(0), TD);
6866 return 0;
Chris Lattner53ef5a02006-03-07 01:28:57 +00006867 } else if (isa<GetElementPtrInst>(V) ||
6868 (isa<ConstantExpr>(V) &&
6869 cast<ConstantExpr>(V)->getOpcode()==Instruction::GetElementPtr)) {
6870 User *GEPI = cast<User>(V);
Chris Lattner82f2ef22006-03-06 20:18:44 +00006871 unsigned BaseAlignment = GetKnownAlignment(GEPI->getOperand(0), TD);
6872 if (BaseAlignment == 0) return 0;
6873
6874 // If all indexes are zero, it is just the alignment of the base pointer.
6875 bool AllZeroOperands = true;
6876 for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
6877 if (!isa<Constant>(GEPI->getOperand(i)) ||
6878 !cast<Constant>(GEPI->getOperand(i))->isNullValue()) {
6879 AllZeroOperands = false;
6880 break;
6881 }
6882 if (AllZeroOperands)
6883 return BaseAlignment;
6884
6885 // Otherwise, if the base alignment is >= the alignment we expect for the
6886 // base pointer type, then we know that the resultant pointer is aligned at
6887 // least as much as its type requires.
6888 if (!TD) return 0;
6889
6890 const Type *BasePtrTy = GEPI->getOperand(0)->getType();
6891 if (TD->getTypeAlignment(cast<PointerType>(BasePtrTy)->getElementType())
Chris Lattner53ef5a02006-03-07 01:28:57 +00006892 <= BaseAlignment) {
6893 const Type *GEPTy = GEPI->getType();
6894 return TD->getTypeAlignment(cast<PointerType>(GEPTy)->getElementType());
6895 }
Chris Lattner82f2ef22006-03-06 20:18:44 +00006896 return 0;
6897 }
6898 return 0;
6899}
6900
Chris Lattnerb909e8b2004-03-12 05:52:32 +00006901
Chris Lattnerc66b2232006-01-13 20:11:04 +00006902/// visitCallInst - CallInst simplification. This mostly only handles folding
6903/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
6904/// the heavy lifting.
6905///
Chris Lattner970c33a2003-06-19 17:00:31 +00006906Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattnerc66b2232006-01-13 20:11:04 +00006907 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
6908 if (!II) return visitCallSite(&CI);
6909
Chris Lattner51ea1272004-02-28 05:22:00 +00006910 // Intrinsics cannot occur in an invoke, so handle them here instead of in
6911 // visitCallSite.
Chris Lattnerc66b2232006-01-13 20:11:04 +00006912 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner00648e12004-10-12 04:52:52 +00006913 bool Changed = false;
6914
6915 // memmove/cpy/set of zero bytes is a noop.
6916 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
6917 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
6918
Chris Lattner00648e12004-10-12 04:52:52 +00006919 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencere0fc4df2006-10-20 07:07:24 +00006920 if (CI->getZExtValue() == 1) {
Chris Lattner00648e12004-10-12 04:52:52 +00006921 // Replace the instruction with just byte operations. We would
6922 // transform other cases to loads/stores, but we don't know if
6923 // alignment is sufficient.
6924 }
Chris Lattner51ea1272004-02-28 05:22:00 +00006925 }
6926
Chris Lattner00648e12004-10-12 04:52:52 +00006927 // If we have a memmove and the source operation is a constant global,
6928 // then the source and dest pointers can't alias, so we can change this
6929 // into a call to memcpy.
Chris Lattner82f2ef22006-03-06 20:18:44 +00006930 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(II)) {
Chris Lattner00648e12004-10-12 04:52:52 +00006931 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
6932 if (GVSrc->isConstant()) {
6933 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner681ef2f2006-03-03 01:34:17 +00006934 const char *Name;
Andrew Lenharth0ebb0b02006-11-03 22:45:50 +00006935 if (CI.getCalledFunction()->getFunctionType()->getParamType(2) ==
Reid Spencerc635f472006-12-31 05:48:39 +00006936 Type::Int32Ty)
Chris Lattner681ef2f2006-03-03 01:34:17 +00006937 Name = "llvm.memcpy.i32";
6938 else
6939 Name = "llvm.memcpy.i64";
6940 Function *MemCpy = M->getOrInsertFunction(Name,
Chris Lattner00648e12004-10-12 04:52:52 +00006941 CI.getCalledFunction()->getFunctionType());
6942 CI.setOperand(0, MemCpy);
6943 Changed = true;
6944 }
Chris Lattner82f2ef22006-03-06 20:18:44 +00006945 }
Chris Lattner00648e12004-10-12 04:52:52 +00006946
Chris Lattner82f2ef22006-03-06 20:18:44 +00006947 // If we can determine a pointer alignment that is bigger than currently
6948 // set, update the alignment.
6949 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
6950 unsigned Alignment1 = GetKnownAlignment(MI->getOperand(1), TD);
6951 unsigned Alignment2 = GetKnownAlignment(MI->getOperand(2), TD);
6952 unsigned Align = std::min(Alignment1, Alignment2);
Reid Spencere0fc4df2006-10-20 07:07:24 +00006953 if (MI->getAlignment()->getZExtValue() < Align) {
Reid Spencerc635f472006-12-31 05:48:39 +00006954 MI->setAlignment(ConstantInt::get(Type::Int32Ty, Align));
Chris Lattner82f2ef22006-03-06 20:18:44 +00006955 Changed = true;
6956 }
6957 } else if (isa<MemSetInst>(MI)) {
6958 unsigned Alignment = GetKnownAlignment(MI->getDest(), TD);
Reid Spencere0fc4df2006-10-20 07:07:24 +00006959 if (MI->getAlignment()->getZExtValue() < Alignment) {
Reid Spencerc635f472006-12-31 05:48:39 +00006960 MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
Chris Lattner82f2ef22006-03-06 20:18:44 +00006961 Changed = true;
6962 }
6963 }
6964
Chris Lattnerc66b2232006-01-13 20:11:04 +00006965 if (Changed) return II;
Chris Lattner503221f2006-01-13 21:28:09 +00006966 } else {
6967 switch (II->getIntrinsicID()) {
6968 default: break;
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00006969 case Intrinsic::ppc_altivec_lvx:
6970 case Intrinsic::ppc_altivec_lvxl:
Chris Lattner36dd7c92006-04-17 22:26:56 +00006971 case Intrinsic::x86_sse_loadu_ps:
6972 case Intrinsic::x86_sse2_loadu_pd:
6973 case Intrinsic::x86_sse2_loadu_dq:
6974 // Turn PPC lvx -> load if the pointer is known aligned.
6975 // Turn X86 loadups -> load if the pointer is known aligned.
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00006976 if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00006977 Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(1),
Chris Lattnere79d2492006-04-06 19:19:17 +00006978 PointerType::get(II->getType()), CI);
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00006979 return new LoadInst(Ptr);
6980 }
6981 break;
6982 case Intrinsic::ppc_altivec_stvx:
6983 case Intrinsic::ppc_altivec_stvxl:
6984 // Turn stvx -> store if the pointer is known aligned.
6985 if (GetKnownAlignment(II->getOperand(2), TD) >= 16) {
Chris Lattnere79d2492006-04-06 19:19:17 +00006986 const Type *OpPtrTy = PointerType::get(II->getOperand(1)->getType());
Reid Spencer13bc5d72006-12-12 09:18:51 +00006987 Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(2),
6988 OpPtrTy, CI);
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00006989 return new StoreInst(II->getOperand(1), Ptr);
6990 }
6991 break;
Chris Lattner36dd7c92006-04-17 22:26:56 +00006992 case Intrinsic::x86_sse_storeu_ps:
6993 case Intrinsic::x86_sse2_storeu_pd:
6994 case Intrinsic::x86_sse2_storeu_dq:
6995 case Intrinsic::x86_sse2_storel_dq:
6996 // Turn X86 storeu -> store if the pointer is known aligned.
6997 if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
6998 const Type *OpPtrTy = PointerType::get(II->getOperand(2)->getType());
Reid Spencer13bc5d72006-12-12 09:18:51 +00006999 Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(1),
7000 OpPtrTy, CI);
Chris Lattner36dd7c92006-04-17 22:26:56 +00007001 return new StoreInst(II->getOperand(2), Ptr);
7002 }
7003 break;
Chris Lattner2deeaea2006-10-05 06:55:50 +00007004
7005 case Intrinsic::x86_sse_cvttss2si: {
7006 // These intrinsics only demands the 0th element of its input vector. If
7007 // we can simplify the input based on that, do so now.
7008 uint64_t UndefElts;
7009 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1,
7010 UndefElts)) {
7011 II->setOperand(1, V);
7012 return II;
7013 }
7014 break;
7015 }
7016
Chris Lattnere79d2492006-04-06 19:19:17 +00007017 case Intrinsic::ppc_altivec_vperm:
7018 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
7019 if (ConstantPacked *Mask = dyn_cast<ConstantPacked>(II->getOperand(3))) {
7020 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
7021
7022 // Check that all of the elements are integer constants or undefs.
7023 bool AllEltsOk = true;
7024 for (unsigned i = 0; i != 16; ++i) {
7025 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
7026 !isa<UndefValue>(Mask->getOperand(i))) {
7027 AllEltsOk = false;
7028 break;
7029 }
7030 }
7031
7032 if (AllEltsOk) {
7033 // Cast the input vectors to byte vectors.
Reid Spencer13bc5d72006-12-12 09:18:51 +00007034 Value *Op0 = InsertCastBefore(Instruction::BitCast,
7035 II->getOperand(1), Mask->getType(), CI);
7036 Value *Op1 = InsertCastBefore(Instruction::BitCast,
7037 II->getOperand(2), Mask->getType(), CI);
Chris Lattnere79d2492006-04-06 19:19:17 +00007038 Value *Result = UndefValue::get(Op0->getType());
7039
7040 // Only extract each element once.
7041 Value *ExtractedElts[32];
7042 memset(ExtractedElts, 0, sizeof(ExtractedElts));
7043
7044 for (unsigned i = 0; i != 16; ++i) {
7045 if (isa<UndefValue>(Mask->getOperand(i)))
7046 continue;
Reid Spencere0fc4df2006-10-20 07:07:24 +00007047 unsigned Idx =cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
Chris Lattnere79d2492006-04-06 19:19:17 +00007048 Idx &= 31; // Match the hardware behavior.
7049
7050 if (ExtractedElts[Idx] == 0) {
7051 Instruction *Elt =
Chris Lattner2deeaea2006-10-05 06:55:50 +00007052 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
Chris Lattnere79d2492006-04-06 19:19:17 +00007053 InsertNewInstBefore(Elt, CI);
7054 ExtractedElts[Idx] = Elt;
7055 }
7056
7057 // Insert this value into the result vector.
Chris Lattner2deeaea2006-10-05 06:55:50 +00007058 Result = new InsertElementInst(Result, ExtractedElts[Idx], i,"tmp");
Chris Lattnere79d2492006-04-06 19:19:17 +00007059 InsertNewInstBefore(cast<Instruction>(Result), CI);
7060 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007061 return CastInst::create(Instruction::BitCast, Result, CI.getType());
Chris Lattnere79d2492006-04-06 19:19:17 +00007062 }
7063 }
7064 break;
7065
Chris Lattner503221f2006-01-13 21:28:09 +00007066 case Intrinsic::stackrestore: {
7067 // If the save is right next to the restore, remove the restore. This can
7068 // happen when variable allocas are DCE'd.
7069 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
7070 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
7071 BasicBlock::iterator BI = SS;
7072 if (&*++BI == II)
7073 return EraseInstFromFunction(CI);
7074 }
7075 }
7076
7077 // If the stack restore is in a return/unwind block and if there are no
7078 // allocas or calls between the restore and the return, nuke the restore.
7079 TerminatorInst *TI = II->getParent()->getTerminator();
7080 if (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)) {
7081 BasicBlock::iterator BI = II;
7082 bool CannotRemove = false;
7083 for (++BI; &*BI != TI; ++BI) {
7084 if (isa<AllocaInst>(BI) ||
7085 (isa<CallInst>(BI) && !isa<IntrinsicInst>(BI))) {
7086 CannotRemove = true;
7087 break;
7088 }
7089 }
7090 if (!CannotRemove)
7091 return EraseInstFromFunction(CI);
7092 }
7093 break;
7094 }
7095 }
Chris Lattner00648e12004-10-12 04:52:52 +00007096 }
7097
Chris Lattnerc66b2232006-01-13 20:11:04 +00007098 return visitCallSite(II);
Chris Lattner970c33a2003-06-19 17:00:31 +00007099}
7100
7101// InvokeInst simplification
7102//
7103Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattneraec3d942003-10-07 22:32:43 +00007104 return visitCallSite(&II);
Chris Lattner970c33a2003-06-19 17:00:31 +00007105}
7106
Chris Lattneraec3d942003-10-07 22:32:43 +00007107// visitCallSite - Improvements for call and invoke instructions.
7108//
7109Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner75b4d1d2003-10-07 22:54:13 +00007110 bool Changed = false;
7111
7112 // If the callee is a constexpr cast of a function, attempt to move the cast
7113 // to the arguments of the call/invoke.
Chris Lattneraec3d942003-10-07 22:32:43 +00007114 if (transformConstExprCastCall(CS)) return 0;
7115
Chris Lattner75b4d1d2003-10-07 22:54:13 +00007116 Value *Callee = CS.getCalledValue();
Chris Lattner81a7a232004-10-16 18:11:37 +00007117
Chris Lattner61d9d812005-05-13 07:09:09 +00007118 if (Function *CalleeF = dyn_cast<Function>(Callee))
7119 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
7120 Instruction *OldCall = CS.getInstruction();
7121 // If the call and callee calling conventions don't match, this call must
7122 // be unreachable, as the call is undefined.
Chris Lattner6ab03f62006-09-28 23:35:22 +00007123 new StoreInst(ConstantBool::getTrue(),
Chris Lattner61d9d812005-05-13 07:09:09 +00007124 UndefValue::get(PointerType::get(Type::BoolTy)), OldCall);
7125 if (!OldCall->use_empty())
7126 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
7127 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
7128 return EraseInstFromFunction(*OldCall);
7129 return 0;
7130 }
7131
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007132 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
7133 // This instruction is not reachable, just remove it. We insert a store to
7134 // undef so that we know that this code is not reachable, despite the fact
7135 // that we can't modify the CFG here.
Chris Lattner6ab03f62006-09-28 23:35:22 +00007136 new StoreInst(ConstantBool::getTrue(),
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007137 UndefValue::get(PointerType::get(Type::BoolTy)),
7138 CS.getInstruction());
7139
7140 if (!CS.getInstruction()->use_empty())
7141 CS.getInstruction()->
7142 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
7143
7144 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
7145 // Don't break the CFG, insert a dummy cond branch.
7146 new BranchInst(II->getNormalDest(), II->getUnwindDest(),
Chris Lattner6ab03f62006-09-28 23:35:22 +00007147 ConstantBool::getTrue(), II);
Chris Lattner81a7a232004-10-16 18:11:37 +00007148 }
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007149 return EraseInstFromFunction(*CS.getInstruction());
7150 }
Chris Lattner81a7a232004-10-16 18:11:37 +00007151
Chris Lattner75b4d1d2003-10-07 22:54:13 +00007152 const PointerType *PTy = cast<PointerType>(Callee->getType());
7153 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
7154 if (FTy->isVarArg()) {
7155 // See if we can optimize any arguments passed through the varargs area of
7156 // the call.
7157 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
7158 E = CS.arg_end(); I != E; ++I)
7159 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
7160 // If this cast does not effect the value passed through the varargs
7161 // area, we can eliminate the use of the cast.
7162 Value *Op = CI->getOperand(0);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007163 if (CI->isLosslessCast()) {
Chris Lattner75b4d1d2003-10-07 22:54:13 +00007164 *I = Op;
7165 Changed = true;
7166 }
7167 }
7168 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00007169
Chris Lattner75b4d1d2003-10-07 22:54:13 +00007170 return Changed ? CS.getInstruction() : 0;
Chris Lattneraec3d942003-10-07 22:32:43 +00007171}
7172
Chris Lattner970c33a2003-06-19 17:00:31 +00007173// transformConstExprCastCall - If the callee is a constexpr cast of a function,
7174// attempt to move the cast to the arguments of the call/invoke.
7175//
7176bool InstCombiner::transformConstExprCastCall(CallSite CS) {
7177 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
7178 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007179 if (CE->getOpcode() != Instruction::BitCast ||
7180 !isa<Function>(CE->getOperand(0)))
Chris Lattner970c33a2003-06-19 17:00:31 +00007181 return false;
Reid Spencer87436872004-07-18 00:38:32 +00007182 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner970c33a2003-06-19 17:00:31 +00007183 Instruction *Caller = CS.getInstruction();
7184
7185 // Okay, this is a cast from a function to a different type. Unless doing so
7186 // would cause a type conversion of one of our arguments, change this call to
7187 // be a direct call with arguments casted to the appropriate types.
7188 //
7189 const FunctionType *FT = Callee->getFunctionType();
7190 const Type *OldRetTy = Caller->getType();
7191
Chris Lattner1f7942f2004-01-14 06:06:08 +00007192 // Check to see if we are changing the return type...
7193 if (OldRetTy != FT->getReturnType()) {
7194 if (Callee->isExternal() &&
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007195 !Caller->use_empty() &&
7196 !(OldRetTy->canLosslesslyBitCastTo(FT->getReturnType()) ||
Andrew Lenharth61eae292006-04-20 14:56:47 +00007197 (isa<PointerType>(FT->getReturnType()) &&
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007198 TD->getIntPtrType()->canLosslesslyBitCastTo(OldRetTy)))
7199 )
Chris Lattner1f7942f2004-01-14 06:06:08 +00007200 return false; // Cannot transform this return value...
7201
7202 // If the callsite is an invoke instruction, and the return value is used by
7203 // a PHI node in a successor, we cannot change the return type of the call
7204 // because there is no place to put the cast instruction (without breaking
7205 // the critical edge). Bail out in this case.
7206 if (!Caller->use_empty())
7207 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
7208 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
7209 UI != E; ++UI)
7210 if (PHINode *PN = dyn_cast<PHINode>(*UI))
7211 if (PN->getParent() == II->getNormalDest() ||
Chris Lattnerfae8ab32004-02-08 21:44:31 +00007212 PN->getParent() == II->getUnwindDest())
Chris Lattner1f7942f2004-01-14 06:06:08 +00007213 return false;
7214 }
Chris Lattner970c33a2003-06-19 17:00:31 +00007215
7216 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
7217 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanb1c93172005-04-21 23:48:37 +00007218
Chris Lattner970c33a2003-06-19 17:00:31 +00007219 CallSite::arg_iterator AI = CS.arg_begin();
7220 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
7221 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthebfa24e2006-06-28 01:01:52 +00007222 const Type *ActTy = (*AI)->getType();
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007223 ConstantInt *c = dyn_cast<ConstantInt>(*AI);
Andrew Lenharthebfa24e2006-06-28 01:01:52 +00007224 //Either we can cast directly, or we can upconvert the argument
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007225 bool isConvertible = ActTy->canLosslesslyBitCastTo(ParamTy) ||
Andrew Lenharthebfa24e2006-06-28 01:01:52 +00007226 (ParamTy->isIntegral() && ActTy->isIntegral() &&
Andrew Lenharthebfa24e2006-06-28 01:01:52 +00007227 ParamTy->getPrimitiveSize() >= ActTy->getPrimitiveSize()) ||
7228 (c && ParamTy->getPrimitiveSize() >= ActTy->getPrimitiveSize() &&
Reid Spencere0fc4df2006-10-20 07:07:24 +00007229 c->getSExtValue() > 0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00007230 if (Callee->isExternal() && !isConvertible) return false;
Chris Lattner970c33a2003-06-19 17:00:31 +00007231 }
7232
7233 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
7234 Callee->isExternal())
7235 return false; // Do not delete arguments unless we have a function body...
7236
7237 // Okay, we decided that this is a safe thing to do: go ahead and start
7238 // inserting cast instructions as necessary...
7239 std::vector<Value*> Args;
7240 Args.reserve(NumActualArgs);
7241
7242 AI = CS.arg_begin();
7243 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
7244 const Type *ParamTy = FT->getParamType(i);
7245 if ((*AI)->getType() == ParamTy) {
7246 Args.push_back(*AI);
7247 } else {
Reid Spencer668d90f2006-12-18 08:47:13 +00007248 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
Reid Spencerc635f472006-12-31 05:48:39 +00007249 false, ParamTy, false);
Reid Spencer668d90f2006-12-18 08:47:13 +00007250 CastInst *NewCast = CastInst::create(opcode, *AI, ParamTy, "tmp");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007251 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
Chris Lattner970c33a2003-06-19 17:00:31 +00007252 }
7253 }
7254
7255 // If the function takes more arguments than the call was taking, add them
7256 // now...
7257 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
7258 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
7259
7260 // If we are removing arguments to the function, emit an obnoxious warning...
7261 if (FT->getNumParams() < NumActualArgs)
7262 if (!FT->isVarArg()) {
Bill Wendlingf3baad32006-12-07 01:30:32 +00007263 cerr << "WARNING: While resolving call to function '"
7264 << Callee->getName() << "' arguments were dropped!\n";
Chris Lattner970c33a2003-06-19 17:00:31 +00007265 } else {
7266 // Add all of the arguments in their promoted form to the arg list...
7267 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
7268 const Type *PTy = getPromotedType((*AI)->getType());
7269 if (PTy != (*AI)->getType()) {
7270 // Must promote to pass through va_arg area!
Reid Spencerc635f472006-12-31 05:48:39 +00007271 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false,
7272 PTy, false);
Reid Spencer668d90f2006-12-18 08:47:13 +00007273 Instruction *Cast = CastInst::create(opcode, *AI, PTy, "tmp");
Chris Lattner970c33a2003-06-19 17:00:31 +00007274 InsertNewInstBefore(Cast, *Caller);
7275 Args.push_back(Cast);
7276 } else {
7277 Args.push_back(*AI);
7278 }
7279 }
7280 }
7281
7282 if (FT->getReturnType() == Type::VoidTy)
7283 Caller->setName(""); // Void type should not have a name...
7284
7285 Instruction *NC;
7286 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Chris Lattnerfae8ab32004-02-08 21:44:31 +00007287 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
Chris Lattner970c33a2003-06-19 17:00:31 +00007288 Args, Caller->getName(), Caller);
Chris Lattner05c703e2005-05-14 12:25:32 +00007289 cast<InvokeInst>(II)->setCallingConv(II->getCallingConv());
Chris Lattner970c33a2003-06-19 17:00:31 +00007290 } else {
7291 NC = new CallInst(Callee, Args, Caller->getName(), Caller);
Chris Lattner6aacb0f2005-05-06 06:48:21 +00007292 if (cast<CallInst>(Caller)->isTailCall())
7293 cast<CallInst>(NC)->setTailCall();
Chris Lattner05c703e2005-05-14 12:25:32 +00007294 cast<CallInst>(NC)->setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Chris Lattner970c33a2003-06-19 17:00:31 +00007295 }
7296
7297 // Insert a cast of the return type as necessary...
7298 Value *NV = NC;
7299 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
7300 if (NV->getType() != Type::VoidTy) {
Reid Spencer668d90f2006-12-18 08:47:13 +00007301 const Type *CallerTy = Caller->getType();
Reid Spencerc635f472006-12-31 05:48:39 +00007302 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
7303 CallerTy, false);
Reid Spencer668d90f2006-12-18 08:47:13 +00007304 NV = NC = CastInst::create(opcode, NC, CallerTy, "tmp");
Chris Lattner686767f2003-10-30 00:46:41 +00007305
7306 // If this is an invoke instruction, we should insert it after the first
7307 // non-phi, instruction in the normal successor block.
7308 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
7309 BasicBlock::iterator I = II->getNormalDest()->begin();
7310 while (isa<PHINode>(I)) ++I;
7311 InsertNewInstBefore(NC, *I);
7312 } else {
7313 // Otherwise, it's a call, just insert cast right after the call instr
7314 InsertNewInstBefore(NC, *Caller);
7315 }
Chris Lattner51ea1272004-02-28 05:22:00 +00007316 AddUsersToWorkList(*Caller);
Chris Lattner970c33a2003-06-19 17:00:31 +00007317 } else {
Chris Lattnere29d6342004-10-17 21:22:38 +00007318 NV = UndefValue::get(Caller->getType());
Chris Lattner970c33a2003-06-19 17:00:31 +00007319 }
7320 }
7321
7322 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
7323 Caller->replaceAllUsesWith(NV);
7324 Caller->getParent()->getInstList().erase(Caller);
7325 removeFromWorkList(Caller);
7326 return true;
7327}
7328
Chris Lattnercadac0c2006-11-01 04:51:18 +00007329/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
7330/// and if a/b/c/d and the add's all have a single use, turn this into two phi's
7331/// and a single binop.
7332Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
7333 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Chris Lattnereebea432006-11-01 07:43:41 +00007334 assert(isa<BinaryOperator>(FirstInst) || isa<ShiftInst>(FirstInst) ||
Reid Spencer266e42b2006-12-23 06:05:41 +00007335 isa<GetElementPtrInst>(FirstInst) || isa<CmpInst>(FirstInst));
Chris Lattnercadac0c2006-11-01 04:51:18 +00007336 unsigned Opc = FirstInst->getOpcode();
Chris Lattnercd62f112006-11-08 19:29:23 +00007337 Value *LHSVal = FirstInst->getOperand(0);
7338 Value *RHSVal = FirstInst->getOperand(1);
7339
7340 const Type *LHSType = LHSVal->getType();
7341 const Type *RHSType = RHSVal->getType();
Chris Lattnercadac0c2006-11-01 04:51:18 +00007342
7343 // Scan to see if all operands are the same opcode, all have one use, and all
7344 // kill their operands (i.e. the operands have one use).
Chris Lattnerdc826fc2006-11-01 04:55:47 +00007345 for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
Chris Lattnercadac0c2006-11-01 04:51:18 +00007346 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Chris Lattnerdc826fc2006-11-01 04:55:47 +00007347 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
Reid Spencer266e42b2006-12-23 06:05:41 +00007348 // Verify type of the LHS matches so we don't fold cmp's of different
Chris Lattnereebea432006-11-01 07:43:41 +00007349 // types or GEP's with different index types.
7350 I->getOperand(0)->getType() != LHSType ||
7351 I->getOperand(1)->getType() != RHSType)
Chris Lattnercadac0c2006-11-01 04:51:18 +00007352 return 0;
Reid Spencer266e42b2006-12-23 06:05:41 +00007353
7354 // If they are CmpInst instructions, check their predicates
7355 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
7356 if (cast<CmpInst>(I)->getPredicate() !=
7357 cast<CmpInst>(FirstInst)->getPredicate())
7358 return 0;
Chris Lattnercd62f112006-11-08 19:29:23 +00007359
7360 // Keep track of which operand needs a phi node.
7361 if (I->getOperand(0) != LHSVal) LHSVal = 0;
7362 if (I->getOperand(1) != RHSVal) RHSVal = 0;
Chris Lattnercadac0c2006-11-01 04:51:18 +00007363 }
7364
Chris Lattner4f218d52006-11-08 19:42:28 +00007365 // Otherwise, this is safe to transform, determine if it is profitable.
7366
7367 // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
7368 // Indexes are often folded into load/store instructions, so we don't want to
7369 // hide them behind a phi.
7370 if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
7371 return 0;
7372
Chris Lattnercadac0c2006-11-01 04:51:18 +00007373 Value *InLHS = FirstInst->getOperand(0);
Chris Lattnercadac0c2006-11-01 04:51:18 +00007374 Value *InRHS = FirstInst->getOperand(1);
Chris Lattner4f218d52006-11-08 19:42:28 +00007375 PHINode *NewLHS = 0, *NewRHS = 0;
Chris Lattnercd62f112006-11-08 19:29:23 +00007376 if (LHSVal == 0) {
7377 NewLHS = new PHINode(LHSType, FirstInst->getOperand(0)->getName()+".pn");
7378 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
7379 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
Chris Lattnereebea432006-11-01 07:43:41 +00007380 InsertNewInstBefore(NewLHS, PN);
7381 LHSVal = NewLHS;
7382 }
Chris Lattnercd62f112006-11-08 19:29:23 +00007383
7384 if (RHSVal == 0) {
7385 NewRHS = new PHINode(RHSType, FirstInst->getOperand(1)->getName()+".pn");
7386 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
7387 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
Chris Lattnereebea432006-11-01 07:43:41 +00007388 InsertNewInstBefore(NewRHS, PN);
7389 RHSVal = NewRHS;
7390 }
7391
Chris Lattnercd62f112006-11-08 19:29:23 +00007392 // Add all operands to the new PHIs.
7393 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7394 if (NewLHS) {
7395 Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
7396 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
7397 }
7398 if (NewRHS) {
7399 Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
7400 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
7401 }
7402 }
7403
Chris Lattnercadac0c2006-11-01 04:51:18 +00007404 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattnereebea432006-11-01 07:43:41 +00007405 return BinaryOperator::create(BinOp->getOpcode(), LHSVal, RHSVal);
Reid Spencer266e42b2006-12-23 06:05:41 +00007406 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
7407 return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal,
7408 RHSVal);
Chris Lattnereebea432006-11-01 07:43:41 +00007409 else if (ShiftInst *SI = dyn_cast<ShiftInst>(FirstInst))
7410 return new ShiftInst(SI->getOpcode(), LHSVal, RHSVal);
7411 else {
7412 assert(isa<GetElementPtrInst>(FirstInst));
7413 return new GetElementPtrInst(LHSVal, RHSVal);
7414 }
Chris Lattnercadac0c2006-11-01 04:51:18 +00007415}
7416
Chris Lattner14f82c72006-11-01 07:13:54 +00007417/// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
7418/// of the block that defines it. This means that it must be obvious the value
7419/// of the load is not changed from the point of the load to the end of the
7420/// block it is in.
7421static bool isSafeToSinkLoad(LoadInst *L) {
7422 BasicBlock::iterator BBI = L, E = L->getParent()->end();
7423
7424 for (++BBI; BBI != E; ++BBI)
7425 if (BBI->mayWriteToMemory())
7426 return false;
7427 return true;
7428}
7429
Chris Lattner970c33a2003-06-19 17:00:31 +00007430
Chris Lattner7515cab2004-11-14 19:13:23 +00007431// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
7432// operator and they all are only used by the PHI, PHI together their
7433// inputs, and do the operation once, to the result of the PHI.
7434Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
7435 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
7436
7437 // Scan the instruction, looking for input operations that can be folded away.
7438 // If all input operands to the phi are the same instruction (e.g. a cast from
7439 // the same type or "+42") we can pull the operation through the PHI, reducing
7440 // code size and simplifying code.
7441 Constant *ConstantOp = 0;
7442 const Type *CastSrcTy = 0;
Chris Lattner14f82c72006-11-01 07:13:54 +00007443 bool isVolatile = false;
Chris Lattner7515cab2004-11-14 19:13:23 +00007444 if (isa<CastInst>(FirstInst)) {
7445 CastSrcTy = FirstInst->getOperand(0)->getType();
Reid Spencer266e42b2006-12-23 06:05:41 +00007446 } else if (isa<BinaryOperator>(FirstInst) || isa<ShiftInst>(FirstInst) ||
7447 isa<CmpInst>(FirstInst)) {
7448 // Can fold binop, compare or shift here if the RHS is a constant,
7449 // otherwise call FoldPHIArgBinOpIntoPHI.
Chris Lattner7515cab2004-11-14 19:13:23 +00007450 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Chris Lattnercadac0c2006-11-01 04:51:18 +00007451 if (ConstantOp == 0)
7452 return FoldPHIArgBinOpIntoPHI(PN);
Chris Lattner14f82c72006-11-01 07:13:54 +00007453 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
7454 isVolatile = LI->isVolatile();
7455 // We can't sink the load if the loaded value could be modified between the
7456 // load and the PHI.
7457 if (LI->getParent() != PN.getIncomingBlock(0) ||
7458 !isSafeToSinkLoad(LI))
7459 return 0;
Chris Lattnereebea432006-11-01 07:43:41 +00007460 } else if (isa<GetElementPtrInst>(FirstInst)) {
Chris Lattner4f218d52006-11-08 19:42:28 +00007461 if (FirstInst->getNumOperands() == 2)
Chris Lattnereebea432006-11-01 07:43:41 +00007462 return FoldPHIArgBinOpIntoPHI(PN);
7463 // Can't handle general GEPs yet.
7464 return 0;
Chris Lattner7515cab2004-11-14 19:13:23 +00007465 } else {
7466 return 0; // Cannot fold this operation.
7467 }
7468
7469 // Check to see if all arguments are the same operation.
7470 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7471 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
7472 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
Reid Spencer266e42b2006-12-23 06:05:41 +00007473 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
Chris Lattner7515cab2004-11-14 19:13:23 +00007474 return 0;
7475 if (CastSrcTy) {
7476 if (I->getOperand(0)->getType() != CastSrcTy)
7477 return 0; // Cast operation must match.
Chris Lattner14f82c72006-11-01 07:13:54 +00007478 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00007479 // We can't sink the load if the loaded value could be modified between
7480 // the load and the PHI.
Chris Lattner14f82c72006-11-01 07:13:54 +00007481 if (LI->isVolatile() != isVolatile ||
7482 LI->getParent() != PN.getIncomingBlock(i) ||
7483 !isSafeToSinkLoad(LI))
7484 return 0;
Chris Lattner7515cab2004-11-14 19:13:23 +00007485 } else if (I->getOperand(1) != ConstantOp) {
7486 return 0;
7487 }
7488 }
7489
7490 // Okay, they are all the same operation. Create a new PHI node of the
7491 // correct type, and PHI together all of the LHS's of the instructions.
7492 PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
7493 PN.getName()+".in");
Chris Lattnerd8e20182005-01-29 00:39:08 +00007494 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattner46dd5a62004-11-14 19:29:34 +00007495
7496 Value *InVal = FirstInst->getOperand(0);
7497 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattner7515cab2004-11-14 19:13:23 +00007498
7499 // Add all operands to the new PHI.
Chris Lattner46dd5a62004-11-14 19:29:34 +00007500 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7501 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
7502 if (NewInVal != InVal)
7503 InVal = 0;
7504 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
7505 }
7506
7507 Value *PhiVal;
7508 if (InVal) {
7509 // The new PHI unions all of the same values together. This is really
7510 // common, so we handle it intelligently here for compile-time speed.
7511 PhiVal = InVal;
7512 delete NewPN;
7513 } else {
7514 InsertNewInstBefore(NewPN, PN);
7515 PhiVal = NewPN;
7516 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00007517
Chris Lattner7515cab2004-11-14 19:13:23 +00007518 // Insert and return the new operation.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007519 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
7520 return CastInst::create(FirstCI->getOpcode(), PhiVal, PN.getType());
Reid Spencerde46e482006-11-02 20:25:50 +00007521 else if (isa<LoadInst>(FirstInst))
Chris Lattner14f82c72006-11-01 07:13:54 +00007522 return new LoadInst(PhiVal, "", isVolatile);
Chris Lattner7515cab2004-11-14 19:13:23 +00007523 else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattner46dd5a62004-11-14 19:29:34 +00007524 return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
Reid Spencer266e42b2006-12-23 06:05:41 +00007525 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
7526 return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(),
7527 PhiVal, ConstantOp);
Chris Lattner7515cab2004-11-14 19:13:23 +00007528 else
7529 return new ShiftInst(cast<ShiftInst>(FirstInst)->getOpcode(),
Chris Lattner46dd5a62004-11-14 19:29:34 +00007530 PhiVal, ConstantOp);
Chris Lattner7515cab2004-11-14 19:13:23 +00007531}
Chris Lattner48a44f72002-05-02 17:06:02 +00007532
Chris Lattner71536432005-01-17 05:10:15 +00007533/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
7534/// that is dead.
7535static bool DeadPHICycle(PHINode *PN, std::set<PHINode*> &PotentiallyDeadPHIs) {
7536 if (PN->use_empty()) return true;
7537 if (!PN->hasOneUse()) return false;
7538
7539 // Remember this node, and if we find the cycle, return.
7540 if (!PotentiallyDeadPHIs.insert(PN).second)
7541 return true;
7542
7543 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
7544 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanb1c93172005-04-21 23:48:37 +00007545
Chris Lattner71536432005-01-17 05:10:15 +00007546 return false;
7547}
7548
Chris Lattnerbbbdd852002-05-06 18:06:38 +00007549// PHINode simplification
7550//
Chris Lattner113f4f42002-06-25 16:13:24 +00007551Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonbbf89902006-07-10 22:15:25 +00007552 // If LCSSA is around, don't mess with Phi nodes
7553 if (mustPreserveAnalysisID(LCSSAID)) return 0;
Owen Andersona6968f82006-07-10 19:03:49 +00007554
Owen Andersonae8aa642006-07-10 22:03:18 +00007555 if (Value *V = PN.hasConstantValue())
7556 return ReplaceInstUsesWith(PN, V);
7557
Owen Andersonae8aa642006-07-10 22:03:18 +00007558 // If all PHI operands are the same operation, pull them through the PHI,
7559 // reducing code size.
7560 if (isa<Instruction>(PN.getIncomingValue(0)) &&
7561 PN.getIncomingValue(0)->hasOneUse())
7562 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
7563 return Result;
7564
7565 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
7566 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
7567 // PHI)... break the cycle.
7568 if (PN.hasOneUse())
7569 if (PHINode *PU = dyn_cast<PHINode>(PN.use_back())) {
7570 std::set<PHINode*> PotentiallyDeadPHIs;
7571 PotentiallyDeadPHIs.insert(&PN);
7572 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
7573 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
7574 }
7575
Chris Lattner91daeb52003-12-19 05:58:40 +00007576 return 0;
Chris Lattnerbbbdd852002-05-06 18:06:38 +00007577}
7578
Reid Spencer13bc5d72006-12-12 09:18:51 +00007579static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
7580 Instruction *InsertPoint,
7581 InstCombiner *IC) {
Reid Spencer2a499b02006-12-13 17:19:09 +00007582 unsigned PtrSize = DTy->getPrimitiveSize();
Reid Spencer13bc5d72006-12-12 09:18:51 +00007583 unsigned VTySize = V->getType()->getPrimitiveSize();
7584 // We must cast correctly to the pointer type. Ensure that we
7585 // sign extend the integer value if it is smaller as this is
7586 // used for address computation.
7587 Instruction::CastOps opcode =
7588 (VTySize < PtrSize ? Instruction::SExt :
7589 (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
7590 return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
Chris Lattner69193f92004-04-05 01:30:19 +00007591}
7592
Chris Lattner48a44f72002-05-02 17:06:02 +00007593
Chris Lattner113f4f42002-06-25 16:13:24 +00007594Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner5f667a62004-05-07 22:09:22 +00007595 Value *PtrOp = GEP.getOperand(0);
Chris Lattner471bd762003-05-22 19:07:21 +00007596 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
Chris Lattner113f4f42002-06-25 16:13:24 +00007597 // If so, eliminate the noop.
Chris Lattner8d0bacb2004-02-22 05:25:17 +00007598 if (GEP.getNumOperands() == 1)
Chris Lattner5f667a62004-05-07 22:09:22 +00007599 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner8d0bacb2004-02-22 05:25:17 +00007600
Chris Lattner81a7a232004-10-16 18:11:37 +00007601 if (isa<UndefValue>(GEP.getOperand(0)))
7602 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
7603
Chris Lattner8d0bacb2004-02-22 05:25:17 +00007604 bool HasZeroPointerIndex = false;
7605 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
7606 HasZeroPointerIndex = C->isNullValue();
7607
7608 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner5f667a62004-05-07 22:09:22 +00007609 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner48a44f72002-05-02 17:06:02 +00007610
Chris Lattner69193f92004-04-05 01:30:19 +00007611 // Eliminate unneeded casts for indices.
7612 bool MadeChange = false;
Chris Lattner2b2412d2004-04-07 18:38:20 +00007613 gep_type_iterator GTI = gep_type_begin(GEP);
7614 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI)
7615 if (isa<SequentialType>(*GTI)) {
7616 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
7617 Value *Src = CI->getOperand(0);
7618 const Type *SrcTy = Src->getType();
7619 const Type *DestTy = CI->getType();
7620 if (Src->getType()->isInteger()) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00007621 if (SrcTy->getPrimitiveSizeInBits() ==
7622 DestTy->getPrimitiveSizeInBits()) {
Chris Lattner2b2412d2004-04-07 18:38:20 +00007623 // We can always eliminate a cast from ulong or long to the other.
7624 // We can always eliminate a cast from uint to int or the other on
7625 // 32-bit pointer platforms.
Chris Lattnerd1f46d32005-04-24 06:59:08 +00007626 if (DestTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()){
Chris Lattner2b2412d2004-04-07 18:38:20 +00007627 MadeChange = true;
7628 GEP.setOperand(i, Src);
7629 }
7630 } else if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
7631 SrcTy->getPrimitiveSize() == 4) {
Reid Spencer266e42b2006-12-23 06:05:41 +00007632 // We can eliminate a cast from [u]int to [u]long iff the target
7633 // is a 32-bit pointer target.
7634 if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
Chris Lattner2b2412d2004-04-07 18:38:20 +00007635 MadeChange = true;
7636 GEP.setOperand(i, Src);
7637 }
Chris Lattner69193f92004-04-05 01:30:19 +00007638 }
7639 }
7640 }
Chris Lattner2b2412d2004-04-07 18:38:20 +00007641 // If we are using a wider index than needed for this platform, shrink it
7642 // to what we need. If the incoming value needs a cast instruction,
7643 // insert it. This explicit cast can make subsequent optimizations more
7644 // obvious.
7645 Value *Op = GEP.getOperand(i);
7646 if (Op->getType()->getPrimitiveSize() > TD->getPointerSize())
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00007647 if (Constant *C = dyn_cast<Constant>(Op)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00007648 GEP.setOperand(i, ConstantExpr::getTrunc(C, TD->getIntPtrType()));
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00007649 MadeChange = true;
7650 } else {
Reid Spencer13bc5d72006-12-12 09:18:51 +00007651 Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
7652 GEP);
Chris Lattner2b2412d2004-04-07 18:38:20 +00007653 GEP.setOperand(i, Op);
7654 MadeChange = true;
7655 }
Chris Lattner69193f92004-04-05 01:30:19 +00007656 }
7657 if (MadeChange) return &GEP;
7658
Chris Lattnerae7a0d32002-08-02 19:29:35 +00007659 // Combine Indices - If the source pointer to this getelementptr instruction
7660 // is a getelementptr instruction, combine the indices of the two
7661 // getelementptr instructions into a single instruction.
7662 //
Chris Lattner57c67b02004-03-25 22:59:29 +00007663 std::vector<Value*> SrcGEPOperands;
Chris Lattner0798af32005-01-13 20:14:25 +00007664 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattner57c67b02004-03-25 22:59:29 +00007665 SrcGEPOperands.assign(Src->op_begin(), Src->op_end());
Chris Lattner57c67b02004-03-25 22:59:29 +00007666
7667 if (!SrcGEPOperands.empty()) {
Chris Lattner5f667a62004-05-07 22:09:22 +00007668 // Note that if our source is a gep chain itself that we wait for that
7669 // chain to be resolved before we perform this transformation. This
7670 // avoids us creating a TON of code in some cases.
7671 //
7672 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
7673 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
7674 return 0; // Wait until our source is folded to completion.
7675
Chris Lattnerae7a0d32002-08-02 19:29:35 +00007676 std::vector<Value *> Indices;
Chris Lattner5f667a62004-05-07 22:09:22 +00007677
7678 // Find out whether the last index in the source GEP is a sequential idx.
7679 bool EndsWithSequential = false;
7680 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
7681 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattner8ec5f882004-05-08 22:41:42 +00007682 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00007683
Chris Lattnerae7a0d32002-08-02 19:29:35 +00007684 // Can we combine the two pointer arithmetics offsets?
Chris Lattner5f667a62004-05-07 22:09:22 +00007685 if (EndsWithSequential) {
Chris Lattner235af562003-03-05 22:33:14 +00007686 // Replace: gep (gep %P, long B), long A, ...
7687 // With: T = long A+B; gep %P, T, ...
7688 //
Chris Lattner5f667a62004-05-07 22:09:22 +00007689 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner69193f92004-04-05 01:30:19 +00007690 if (SO1 == Constant::getNullValue(SO1->getType())) {
7691 Sum = GO1;
7692 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
7693 Sum = SO1;
7694 } else {
7695 // If they aren't the same type, convert both to an integer of the
7696 // target's pointer size.
7697 if (SO1->getType() != GO1->getType()) {
7698 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00007699 SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
Chris Lattner69193f92004-04-05 01:30:19 +00007700 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00007701 GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
Chris Lattner69193f92004-04-05 01:30:19 +00007702 } else {
7703 unsigned PS = TD->getPointerSize();
Chris Lattner69193f92004-04-05 01:30:19 +00007704 if (SO1->getType()->getPrimitiveSize() == PS) {
7705 // Convert GO1 to SO1's type.
Reid Spencer13bc5d72006-12-12 09:18:51 +00007706 GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
Chris Lattner69193f92004-04-05 01:30:19 +00007707
7708 } else if (GO1->getType()->getPrimitiveSize() == PS) {
7709 // Convert SO1 to GO1's type.
Reid Spencer13bc5d72006-12-12 09:18:51 +00007710 SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
Chris Lattner69193f92004-04-05 01:30:19 +00007711 } else {
7712 const Type *PT = TD->getIntPtrType();
Reid Spencer13bc5d72006-12-12 09:18:51 +00007713 SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
7714 GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
Chris Lattner69193f92004-04-05 01:30:19 +00007715 }
7716 }
7717 }
Chris Lattner5f667a62004-05-07 22:09:22 +00007718 if (isa<Constant>(SO1) && isa<Constant>(GO1))
7719 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
7720 else {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00007721 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
7722 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner5f667a62004-05-07 22:09:22 +00007723 }
Chris Lattner69193f92004-04-05 01:30:19 +00007724 }
Chris Lattner5f667a62004-05-07 22:09:22 +00007725
7726 // Recycle the GEP we already have if possible.
7727 if (SrcGEPOperands.size() == 2) {
7728 GEP.setOperand(0, SrcGEPOperands[0]);
7729 GEP.setOperand(1, Sum);
7730 return &GEP;
7731 } else {
7732 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
7733 SrcGEPOperands.end()-1);
7734 Indices.push_back(Sum);
7735 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
7736 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00007737 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner69193f92004-04-05 01:30:19 +00007738 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00007739 SrcGEPOperands.size() != 1) {
Chris Lattnerae7a0d32002-08-02 19:29:35 +00007740 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattner57c67b02004-03-25 22:59:29 +00007741 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
7742 SrcGEPOperands.end());
Chris Lattnerae7a0d32002-08-02 19:29:35 +00007743 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
7744 }
7745
7746 if (!Indices.empty())
Chris Lattner57c67b02004-03-25 22:59:29 +00007747 return new GetElementPtrInst(SrcGEPOperands[0], Indices, GEP.getName());
Chris Lattnerc59af1d2002-08-17 22:21:59 +00007748
Chris Lattner5f667a62004-05-07 22:09:22 +00007749 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattnerc59af1d2002-08-17 22:21:59 +00007750 // GEP of global variable. If all of the indices for this GEP are
7751 // constants, we can promote this to a constexpr instead of an instruction.
7752
7753 // Scan for nonconstants...
7754 std::vector<Constant*> Indices;
7755 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
7756 for (; I != E && isa<Constant>(*I); ++I)
7757 Indices.push_back(cast<Constant>(*I));
7758
7759 if (I == E) { // If they are all constants...
Chris Lattnerf3edc492004-07-18 18:59:44 +00007760 Constant *CE = ConstantExpr::getGetElementPtr(GV, Indices);
Chris Lattnerc59af1d2002-08-17 22:21:59 +00007761
7762 // Replace all uses of the GEP with the new constexpr...
7763 return ReplaceInstUsesWith(GEP, CE);
7764 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007765 } else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast?
Chris Lattner567b81f2005-09-13 00:40:14 +00007766 if (!isa<PointerType>(X->getType())) {
7767 // Not interesting. Source pointer must be a cast from pointer.
7768 } else if (HasZeroPointerIndex) {
7769 // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
7770 // into : GEP [10 x ubyte]* X, long 0, ...
7771 //
7772 // This occurs when the program declares an array extern like "int X[];"
7773 //
7774 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
7775 const PointerType *XTy = cast<PointerType>(X->getType());
7776 if (const ArrayType *XATy =
7777 dyn_cast<ArrayType>(XTy->getElementType()))
7778 if (const ArrayType *CATy =
7779 dyn_cast<ArrayType>(CPTy->getElementType()))
7780 if (CATy->getElementType() == XATy->getElementType()) {
7781 // At this point, we know that the cast source type is a pointer
7782 // to an array of the same type as the destination pointer
7783 // array. Because the array type is never stepped over (there
7784 // is a leading zero) we can fold the cast into this GEP.
7785 GEP.setOperand(0, X);
7786 return &GEP;
7787 }
7788 } else if (GEP.getNumOperands() == 2) {
7789 // Transform things like:
Chris Lattner2a893292005-09-13 18:36:04 +00007790 // %t = getelementptr ubyte* cast ([2 x int]* %str to uint*), uint %V
7791 // into: %t1 = getelementptr [2 x int*]* %str, int 0, uint %V; cast
Chris Lattner567b81f2005-09-13 00:40:14 +00007792 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
7793 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
7794 if (isa<ArrayType>(SrcElTy) &&
7795 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
7796 TD->getTypeSize(ResElTy)) {
7797 Value *V = InsertNewInstBefore(
Reid Spencerc635f472006-12-31 05:48:39 +00007798 new GetElementPtrInst(X, Constant::getNullValue(Type::Int32Ty),
Chris Lattner567b81f2005-09-13 00:40:14 +00007799 GEP.getOperand(1), GEP.getName()), GEP);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007800 // V and GEP are both pointer types --> BitCast
7801 return new BitCastInst(V, GEP.getType());
Chris Lattner8d0bacb2004-02-22 05:25:17 +00007802 }
Chris Lattner2a893292005-09-13 18:36:04 +00007803
7804 // Transform things like:
7805 // getelementptr sbyte* cast ([100 x double]* X to sbyte*), int %tmp
7806 // (where tmp = 8*tmp2) into:
7807 // getelementptr [100 x double]* %arr, int 0, int %tmp.2
7808
7809 if (isa<ArrayType>(SrcElTy) &&
Reid Spencerc635f472006-12-31 05:48:39 +00007810 (ResElTy == Type::Int8Ty || ResElTy == Type::Int8Ty)) {
Chris Lattner2a893292005-09-13 18:36:04 +00007811 uint64_t ArrayEltSize =
7812 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType());
7813
7814 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
7815 // allow either a mul, shift, or constant here.
7816 Value *NewIdx = 0;
7817 ConstantInt *Scale = 0;
7818 if (ArrayEltSize == 1) {
7819 NewIdx = GEP.getOperand(1);
7820 Scale = ConstantInt::get(NewIdx->getType(), 1);
7821 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Chris Lattnera393e4d2005-09-14 17:32:56 +00007822 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner2a893292005-09-13 18:36:04 +00007823 Scale = CI;
7824 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
7825 if (Inst->getOpcode() == Instruction::Shl &&
7826 isa<ConstantInt>(Inst->getOperand(1))) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00007827 unsigned ShAmt =
7828 cast<ConstantInt>(Inst->getOperand(1))->getZExtValue();
Reid Spencer266e42b2006-12-23 06:05:41 +00007829 Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmt);
Chris Lattner2a893292005-09-13 18:36:04 +00007830 NewIdx = Inst->getOperand(0);
7831 } else if (Inst->getOpcode() == Instruction::Mul &&
7832 isa<ConstantInt>(Inst->getOperand(1))) {
7833 Scale = cast<ConstantInt>(Inst->getOperand(1));
7834 NewIdx = Inst->getOperand(0);
7835 }
7836 }
7837
7838 // If the index will be to exactly the right offset with the scale taken
7839 // out, perform the transformation.
Reid Spencere0fc4df2006-10-20 07:07:24 +00007840 if (Scale && Scale->getZExtValue() % ArrayEltSize == 0) {
Reid Spencerde46e482006-11-02 20:25:50 +00007841 if (isa<ConstantInt>(Scale))
Reid Spencere0fc4df2006-10-20 07:07:24 +00007842 Scale = ConstantInt::get(Scale->getType(),
7843 Scale->getZExtValue() / ArrayEltSize);
7844 if (Scale->getZExtValue() != 1) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00007845 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
7846 true /*SExt*/);
Chris Lattner2a893292005-09-13 18:36:04 +00007847 Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
7848 NewIdx = InsertNewInstBefore(Sc, GEP);
7849 }
7850
7851 // Insert the new GEP instruction.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007852 Instruction *NewGEP =
Reid Spencerc635f472006-12-31 05:48:39 +00007853 new GetElementPtrInst(X, Constant::getNullValue(Type::Int32Ty),
Chris Lattner2a893292005-09-13 18:36:04 +00007854 NewIdx, GEP.getName());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007855 NewGEP = InsertNewInstBefore(NewGEP, GEP);
7856 // The NewGEP must be pointer typed, so must the old one -> BitCast
7857 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner2a893292005-09-13 18:36:04 +00007858 }
7859 }
Chris Lattner8d0bacb2004-02-22 05:25:17 +00007860 }
Chris Lattnerca081252001-12-14 16:52:21 +00007861 }
7862
Chris Lattnerca081252001-12-14 16:52:21 +00007863 return 0;
7864}
7865
Chris Lattner1085bdf2002-11-04 16:18:53 +00007866Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
7867 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
7868 if (AI.isArrayAllocation()) // Check C != 1
Reid Spencere0fc4df2006-10-20 07:07:24 +00007869 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
7870 const Type *NewTy =
7871 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Chris Lattnera2620ac2002-11-09 00:49:43 +00007872 AllocationInst *New = 0;
Chris Lattner1085bdf2002-11-04 16:18:53 +00007873
7874 // Create and insert the replacement instruction...
7875 if (isa<MallocInst>(AI))
Nate Begeman848622f2005-11-05 09:21:28 +00007876 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00007877 else {
7878 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Nate Begeman848622f2005-11-05 09:21:28 +00007879 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00007880 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00007881
7882 InsertNewInstBefore(New, AI);
Misha Brukmanb1c93172005-04-21 23:48:37 +00007883
Chris Lattner1085bdf2002-11-04 16:18:53 +00007884 // Scan to the end of the allocation instructions, to skip over a block of
7885 // allocas if possible...
7886 //
7887 BasicBlock::iterator It = New;
7888 while (isa<AllocationInst>(*It)) ++It;
7889
7890 // Now that I is pointing to the first non-allocation-inst in the block,
7891 // insert our getelementptr instruction...
7892 //
Reid Spencerc635f472006-12-31 05:48:39 +00007893 Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
Chris Lattner809dfac2005-05-04 19:10:26 +00007894 Value *V = new GetElementPtrInst(New, NullIdx, NullIdx,
7895 New->getName()+".sub", It);
Chris Lattner1085bdf2002-11-04 16:18:53 +00007896
7897 // Now make everything use the getelementptr instead of the original
7898 // allocation.
Chris Lattnerabb77c92004-03-19 06:08:10 +00007899 return ReplaceInstUsesWith(AI, V);
Chris Lattner81a7a232004-10-16 18:11:37 +00007900 } else if (isa<UndefValue>(AI.getArraySize())) {
7901 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner1085bdf2002-11-04 16:18:53 +00007902 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00007903
7904 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
7905 // Note that we only do this for alloca's, because malloc should allocate and
7906 // return a unique pointer, even for a zero byte allocation.
Misha Brukmanb1c93172005-04-21 23:48:37 +00007907 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
Chris Lattner49df6ce2004-07-02 22:55:47 +00007908 TD->getTypeSize(AI.getAllocatedType()) == 0)
Chris Lattnerabb77c92004-03-19 06:08:10 +00007909 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
7910
Chris Lattner1085bdf2002-11-04 16:18:53 +00007911 return 0;
7912}
7913
Chris Lattner8427bff2003-12-07 01:24:23 +00007914Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
7915 Value *Op = FI.getOperand(0);
7916
7917 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
7918 if (CastInst *CI = dyn_cast<CastInst>(Op))
7919 if (isa<PointerType>(CI->getOperand(0)->getType())) {
7920 FI.setOperand(0, CI->getOperand(0));
7921 return &FI;
7922 }
7923
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007924 // free undef -> unreachable.
7925 if (isa<UndefValue>(Op)) {
7926 // Insert a new store to null because we cannot modify the CFG here.
Chris Lattner6ab03f62006-09-28 23:35:22 +00007927 new StoreInst(ConstantBool::getTrue(),
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007928 UndefValue::get(PointerType::get(Type::BoolTy)), &FI);
7929 return EraseInstFromFunction(FI);
7930 }
7931
Chris Lattnerf3a36602004-02-28 04:57:37 +00007932 // If we have 'free null' delete the instruction. This can happen in stl code
7933 // when lots of inlining happens.
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007934 if (isa<ConstantPointerNull>(Op))
Chris Lattner51ea1272004-02-28 05:22:00 +00007935 return EraseInstFromFunction(FI);
Chris Lattnerf3a36602004-02-28 04:57:37 +00007936
Chris Lattner8427bff2003-12-07 01:24:23 +00007937 return 0;
7938}
7939
7940
Chris Lattner72684fe2005-01-31 05:51:45 +00007941/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Chris Lattner35e24772004-07-13 01:49:43 +00007942static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
7943 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00007944 Value *CastOp = CI->getOperand(0);
Chris Lattner35e24772004-07-13 01:49:43 +00007945
7946 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00007947 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Chris Lattner35e24772004-07-13 01:49:43 +00007948 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00007949
Chris Lattnerebca4762006-04-02 05:37:12 +00007950 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
7951 isa<PackedType>(DestPTy)) {
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00007952 // If the source is an array, the code below will not succeed. Check to
7953 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
7954 // constants.
7955 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
7956 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
7957 if (ASrcTy->getNumElements() != 0) {
Reid Spencerc635f472006-12-31 05:48:39 +00007958 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::Int32Ty));
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00007959 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
7960 SrcTy = cast<PointerType>(CastOp->getType());
7961 SrcPTy = SrcTy->getElementType();
7962 }
7963
Chris Lattnerebca4762006-04-02 05:37:12 +00007964 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
7965 isa<PackedType>(SrcPTy)) &&
Chris Lattnerecfa9b52005-03-29 06:37:47 +00007966 // Do not allow turning this into a load of an integer, which is then
7967 // casted to a pointer, this pessimizes pointer analysis a lot.
7968 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00007969 IC.getTargetData().getTypeSize(SrcPTy) ==
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00007970 IC.getTargetData().getTypeSize(DestPTy)) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00007971
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00007972 // Okay, we are casting from one integer or pointer type to another of
7973 // the same size. Instead of casting the pointer before the load, cast
7974 // the result of the loaded value.
7975 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
7976 CI->getName(),
7977 LI.isVolatile()),LI);
7978 // Now cast the result of the load.
Reid Spencerbb65ebf2006-12-12 23:36:14 +00007979 return new BitCastInst(NewLoad, LI.getType());
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00007980 }
Chris Lattner35e24772004-07-13 01:49:43 +00007981 }
7982 }
7983 return 0;
7984}
7985
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00007986/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattnere6f13092004-09-19 19:18:10 +00007987/// from this value cannot trap. If it is not obviously safe to load from the
7988/// specified pointer, we do a quick local scan of the basic block containing
7989/// ScanFrom, to determine if the address is already accessed.
7990static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
7991 // If it is an alloca or global variable, it is always safe to load from.
7992 if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
7993
7994 // Otherwise, be a little bit agressive by scanning the local block where we
7995 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00007996 // from/to. If so, the previous load or store would have already trapped,
7997 // so there is no harm doing an extra load (also, CSE will later eliminate
7998 // the load entirely).
Chris Lattnere6f13092004-09-19 19:18:10 +00007999 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
8000
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00008001 while (BBI != E) {
Chris Lattnere6f13092004-09-19 19:18:10 +00008002 --BBI;
8003
8004 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
8005 if (LI->getOperand(0) == V) return true;
8006 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
8007 if (SI->getOperand(1) == V) return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +00008008
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00008009 }
Chris Lattnere6f13092004-09-19 19:18:10 +00008010 return false;
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008011}
8012
Chris Lattner0f1d8a32003-06-26 05:06:25 +00008013Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
8014 Value *Op = LI.getOperand(0);
Chris Lattner7e8af382004-01-12 04:13:56 +00008015
Chris Lattnera9d84e32005-05-01 04:24:53 +00008016 // load (cast X) --> cast (load X) iff safe
Reid Spencerde46e482006-11-02 20:25:50 +00008017 if (isa<CastInst>(Op))
Chris Lattnera9d84e32005-05-01 04:24:53 +00008018 if (Instruction *Res = InstCombineLoadCast(*this, LI))
8019 return Res;
8020
8021 // None of the following transforms are legal for volatile loads.
8022 if (LI.isVolatile()) return 0;
Chris Lattnerb990f7d2005-09-12 22:00:15 +00008023
Chris Lattnerb990f7d2005-09-12 22:00:15 +00008024 if (&LI.getParent()->front() != &LI) {
8025 BasicBlock::iterator BBI = &LI; --BBI;
Chris Lattnere0bfdf12005-09-12 22:21:03 +00008026 // If the instruction immediately before this is a store to the same
8027 // address, do a simple form of store->load forwarding.
Chris Lattnerb990f7d2005-09-12 22:00:15 +00008028 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
8029 if (SI->getOperand(1) == LI.getOperand(0))
8030 return ReplaceInstUsesWith(LI, SI->getOperand(0));
Chris Lattnere0bfdf12005-09-12 22:21:03 +00008031 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
8032 if (LIB->getOperand(0) == LI.getOperand(0))
8033 return ReplaceInstUsesWith(LI, LIB);
Chris Lattnerb990f7d2005-09-12 22:00:15 +00008034 }
Chris Lattnera9d84e32005-05-01 04:24:53 +00008035
8036 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op))
8037 if (isa<ConstantPointerNull>(GEPI->getOperand(0)) ||
8038 isa<UndefValue>(GEPI->getOperand(0))) {
8039 // Insert a new store to null instruction before the load to indicate
8040 // that this code is not reachable. We do this instead of inserting
8041 // an unreachable instruction directly because we cannot modify the
8042 // CFG.
8043 new StoreInst(UndefValue::get(LI.getType()),
8044 Constant::getNullValue(Op->getType()), &LI);
8045 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
8046 }
8047
Chris Lattner81a7a232004-10-16 18:11:37 +00008048 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattnera9d84e32005-05-01 04:24:53 +00008049 // load null/undef -> undef
8050 if ((C->isNullValue() || isa<UndefValue>(C))) {
Chris Lattner8ba9ec92004-10-18 02:59:09 +00008051 // Insert a new store to null instruction before the load to indicate that
8052 // this code is not reachable. We do this instead of inserting an
8053 // unreachable instruction directly because we cannot modify the CFG.
Chris Lattnera9d84e32005-05-01 04:24:53 +00008054 new StoreInst(UndefValue::get(LI.getType()),
8055 Constant::getNullValue(Op->getType()), &LI);
Chris Lattner81a7a232004-10-16 18:11:37 +00008056 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner8ba9ec92004-10-18 02:59:09 +00008057 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00008058
Chris Lattner81a7a232004-10-16 18:11:37 +00008059 // Instcombine load (constant global) into the value loaded.
8060 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
8061 if (GV->isConstant() && !GV->isExternal())
8062 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanb1c93172005-04-21 23:48:37 +00008063
Chris Lattner81a7a232004-10-16 18:11:37 +00008064 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
8065 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
8066 if (CE->getOpcode() == Instruction::GetElementPtr) {
8067 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
8068 if (GV->isConstant() && !GV->isExternal())
Chris Lattner0b011ec2005-09-26 05:28:06 +00008069 if (Constant *V =
8070 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
Chris Lattner81a7a232004-10-16 18:11:37 +00008071 return ReplaceInstUsesWith(LI, V);
Chris Lattnera9d84e32005-05-01 04:24:53 +00008072 if (CE->getOperand(0)->isNullValue()) {
8073 // Insert a new store to null instruction before the load to indicate
8074 // that this code is not reachable. We do this instead of inserting
8075 // an unreachable instruction directly because we cannot modify the
8076 // CFG.
8077 new StoreInst(UndefValue::get(LI.getType()),
8078 Constant::getNullValue(Op->getType()), &LI);
8079 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
8080 }
8081
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008082 } else if (CE->isCast()) {
Chris Lattner81a7a232004-10-16 18:11:37 +00008083 if (Instruction *Res = InstCombineLoadCast(*this, LI))
8084 return Res;
8085 }
8086 }
Chris Lattnere228ee52004-04-08 20:39:49 +00008087
Chris Lattnera9d84e32005-05-01 04:24:53 +00008088 if (Op->hasOneUse()) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008089 // Change select and PHI nodes to select values instead of addresses: this
8090 // helps alias analysis out a lot, allows many others simplifications, and
8091 // exposes redundancy in the code.
8092 //
8093 // Note that we cannot do the transformation unless we know that the
8094 // introduced loads cannot trap! Something like this is valid as long as
8095 // the condition is always false: load (select bool %C, int* null, int* %G),
8096 // but it would not be valid if we transformed it to load from null
8097 // unconditionally.
8098 //
8099 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
8100 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattnere6f13092004-09-19 19:18:10 +00008101 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
8102 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008103 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner42618552004-09-20 10:15:10 +00008104 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008105 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner42618552004-09-20 10:15:10 +00008106 SI->getOperand(2)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008107 return new SelectInst(SI->getCondition(), V1, V2);
8108 }
8109
Chris Lattnerbdcf41a2004-09-23 15:46:00 +00008110 // load (select (cond, null, P)) -> load P
8111 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
8112 if (C->isNullValue()) {
8113 LI.setOperand(0, SI->getOperand(2));
8114 return &LI;
8115 }
8116
8117 // load (select (cond, P, null)) -> load P
8118 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
8119 if (C->isNullValue()) {
8120 LI.setOperand(0, SI->getOperand(1));
8121 return &LI;
8122 }
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008123 }
8124 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00008125 return 0;
8126}
8127
Chris Lattner72684fe2005-01-31 05:51:45 +00008128/// InstCombineStoreToCast - Fold 'store V, (cast P)' -> store (cast V), P'
8129/// when possible.
8130static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
8131 User *CI = cast<User>(SI.getOperand(1));
8132 Value *CastOp = CI->getOperand(0);
8133
8134 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
8135 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
8136 const Type *SrcPTy = SrcTy->getElementType();
8137
8138 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
8139 // If the source is an array, the code below will not succeed. Check to
8140 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
8141 // constants.
8142 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
8143 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
8144 if (ASrcTy->getNumElements() != 0) {
Reid Spencerc635f472006-12-31 05:48:39 +00008145 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::Int32Ty));
Chris Lattner72684fe2005-01-31 05:51:45 +00008146 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
8147 SrcTy = cast<PointerType>(CastOp->getType());
8148 SrcPTy = SrcTy->getElementType();
8149 }
8150
8151 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00008152 IC.getTargetData().getTypeSize(SrcPTy) ==
Chris Lattner72684fe2005-01-31 05:51:45 +00008153 IC.getTargetData().getTypeSize(DestPTy)) {
8154
8155 // Okay, we are casting from one integer or pointer type to another of
8156 // the same size. Instead of casting the pointer before the store, cast
8157 // the value to be stored.
8158 Value *NewCast;
Reid Spencerbb65ebf2006-12-12 23:36:14 +00008159 Instruction::CastOps opcode = Instruction::BitCast;
8160 Value *SIOp0 = SI.getOperand(0);
Reid Spencer74a528b2006-12-13 18:21:21 +00008161 if (isa<PointerType>(SrcPTy)) {
Reid Spencerbb65ebf2006-12-12 23:36:14 +00008162 if (SIOp0->getType()->isIntegral())
8163 opcode = Instruction::IntToPtr;
8164 } else if (SrcPTy->isIntegral()) {
Reid Spencer74a528b2006-12-13 18:21:21 +00008165 if (isa<PointerType>(SIOp0->getType()))
Reid Spencerbb65ebf2006-12-12 23:36:14 +00008166 opcode = Instruction::PtrToInt;
8167 }
8168 if (Constant *C = dyn_cast<Constant>(SIOp0))
8169 NewCast = ConstantExpr::getCast(opcode, C, SrcPTy);
Chris Lattner72684fe2005-01-31 05:51:45 +00008170 else
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008171 NewCast = IC.InsertNewInstBefore(
Reid Spencerbb65ebf2006-12-12 23:36:14 +00008172 CastInst::create(opcode, SIOp0, SrcPTy, SIOp0->getName()+".c"), SI);
Chris Lattner72684fe2005-01-31 05:51:45 +00008173 return new StoreInst(NewCast, CastOp);
8174 }
8175 }
8176 }
8177 return 0;
8178}
8179
Chris Lattner31f486c2005-01-31 05:36:43 +00008180Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
8181 Value *Val = SI.getOperand(0);
8182 Value *Ptr = SI.getOperand(1);
8183
8184 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner5997cf92006-02-08 03:25:32 +00008185 EraseInstFromFunction(SI);
Chris Lattner31f486c2005-01-31 05:36:43 +00008186 ++NumCombined;
8187 return 0;
8188 }
8189
Chris Lattner5997cf92006-02-08 03:25:32 +00008190 // Do really simple DSE, to catch cases where there are several consequtive
8191 // stores to the same location, separated by a few arithmetic operations. This
8192 // situation often occurs with bitfield accesses.
8193 BasicBlock::iterator BBI = &SI;
8194 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
8195 --ScanInsts) {
8196 --BBI;
8197
8198 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
8199 // Prev store isn't volatile, and stores to the same location?
8200 if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
8201 ++NumDeadStore;
8202 ++BBI;
8203 EraseInstFromFunction(*PrevSI);
8204 continue;
8205 }
8206 break;
8207 }
8208
Chris Lattnerdab43b22006-05-26 19:19:20 +00008209 // If this is a load, we have to stop. However, if the loaded value is from
8210 // the pointer we're loading and is producing the pointer we're storing,
8211 // then *this* store is dead (X = load P; store X -> P).
8212 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
8213 if (LI == Val && LI->getOperand(0) == Ptr) {
8214 EraseInstFromFunction(SI);
8215 ++NumCombined;
8216 return 0;
8217 }
8218 // Otherwise, this is a load from some other location. Stores before it
8219 // may not be dead.
8220 break;
8221 }
8222
Chris Lattner5997cf92006-02-08 03:25:32 +00008223 // Don't skip over loads or things that can modify memory.
Chris Lattnerdab43b22006-05-26 19:19:20 +00008224 if (BBI->mayWriteToMemory())
Chris Lattner5997cf92006-02-08 03:25:32 +00008225 break;
8226 }
8227
8228
8229 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner31f486c2005-01-31 05:36:43 +00008230
8231 // store X, null -> turns into 'unreachable' in SimplifyCFG
8232 if (isa<ConstantPointerNull>(Ptr)) {
8233 if (!isa<UndefValue>(Val)) {
8234 SI.setOperand(0, UndefValue::get(Val->getType()));
8235 if (Instruction *U = dyn_cast<Instruction>(Val))
8236 WorkList.push_back(U); // Dropped a use.
8237 ++NumCombined;
8238 }
8239 return 0; // Do not modify these!
8240 }
8241
8242 // store undef, Ptr -> noop
8243 if (isa<UndefValue>(Val)) {
Chris Lattner5997cf92006-02-08 03:25:32 +00008244 EraseInstFromFunction(SI);
Chris Lattner31f486c2005-01-31 05:36:43 +00008245 ++NumCombined;
8246 return 0;
8247 }
8248
Chris Lattner72684fe2005-01-31 05:51:45 +00008249 // If the pointer destination is a cast, see if we can fold the cast into the
8250 // source instead.
Reid Spencerde46e482006-11-02 20:25:50 +00008251 if (isa<CastInst>(Ptr))
Chris Lattner72684fe2005-01-31 05:51:45 +00008252 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
8253 return Res;
8254 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008255 if (CE->isCast())
Chris Lattner72684fe2005-01-31 05:51:45 +00008256 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
8257 return Res;
8258
Chris Lattner219175c2005-09-12 23:23:25 +00008259
8260 // If this store is the last instruction in the basic block, and if the block
8261 // ends with an unconditional branch, try to move it to the successor block.
Chris Lattner5997cf92006-02-08 03:25:32 +00008262 BBI = &SI; ++BBI;
Chris Lattner219175c2005-09-12 23:23:25 +00008263 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
8264 if (BI->isUnconditional()) {
8265 // Check to see if the successor block has exactly two incoming edges. If
8266 // so, see if the other predecessor contains a store to the same location.
8267 // if so, insert a PHI node (if needed) and move the stores down.
8268 BasicBlock *Dest = BI->getSuccessor(0);
8269
8270 pred_iterator PI = pred_begin(Dest);
8271 BasicBlock *Other = 0;
8272 if (*PI != BI->getParent())
8273 Other = *PI;
8274 ++PI;
8275 if (PI != pred_end(Dest)) {
8276 if (*PI != BI->getParent())
8277 if (Other)
8278 Other = 0;
8279 else
8280 Other = *PI;
8281 if (++PI != pred_end(Dest))
8282 Other = 0;
8283 }
8284 if (Other) { // If only one other pred...
8285 BBI = Other->getTerminator();
8286 // Make sure this other block ends in an unconditional branch and that
8287 // there is an instruction before the branch.
8288 if (isa<BranchInst>(BBI) && cast<BranchInst>(BBI)->isUnconditional() &&
8289 BBI != Other->begin()) {
8290 --BBI;
8291 StoreInst *OtherStore = dyn_cast<StoreInst>(BBI);
8292
8293 // If this instruction is a store to the same location.
8294 if (OtherStore && OtherStore->getOperand(1) == SI.getOperand(1)) {
8295 // Okay, we know we can perform this transformation. Insert a PHI
8296 // node now if we need it.
8297 Value *MergedVal = OtherStore->getOperand(0);
8298 if (MergedVal != SI.getOperand(0)) {
8299 PHINode *PN = new PHINode(MergedVal->getType(), "storemerge");
8300 PN->reserveOperandSpace(2);
8301 PN->addIncoming(SI.getOperand(0), SI.getParent());
8302 PN->addIncoming(OtherStore->getOperand(0), Other);
8303 MergedVal = InsertNewInstBefore(PN, Dest->front());
8304 }
8305
8306 // Advance to a place where it is safe to insert the new store and
8307 // insert it.
8308 BBI = Dest->begin();
8309 while (isa<PHINode>(BBI)) ++BBI;
8310 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
8311 OtherStore->isVolatile()), *BBI);
8312
8313 // Nuke the old stores.
Chris Lattner5997cf92006-02-08 03:25:32 +00008314 EraseInstFromFunction(SI);
8315 EraseInstFromFunction(*OtherStore);
Chris Lattner219175c2005-09-12 23:23:25 +00008316 ++NumCombined;
8317 return 0;
8318 }
8319 }
8320 }
8321 }
8322
Chris Lattner31f486c2005-01-31 05:36:43 +00008323 return 0;
8324}
8325
8326
Chris Lattner9eef8a72003-06-04 04:46:00 +00008327Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
8328 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4fdd96c2005-06-18 17:37:34 +00008329 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00008330 BasicBlock *TrueDest;
8331 BasicBlock *FalseDest;
8332 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
8333 !isa<Constant>(X)) {
8334 // Swap Destinations and condition...
8335 BI.setCondition(X);
8336 BI.setSuccessor(0, FalseDest);
8337 BI.setSuccessor(1, TrueDest);
8338 return &BI;
8339 }
8340
Reid Spencer266e42b2006-12-23 06:05:41 +00008341 // Cannonicalize fcmp_one -> fcmp_oeq
8342 FCmpInst::Predicate FPred; Value *Y;
8343 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
8344 TrueDest, FalseDest)))
8345 if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
8346 FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
8347 FCmpInst *I = cast<FCmpInst>(BI.getCondition());
Chris Lattnerd4252a72004-07-30 07:50:03 +00008348 std::string Name = I->getName(); I->setName("");
Reid Spencer266e42b2006-12-23 06:05:41 +00008349 FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
8350 Value *NewSCC = new FCmpInst(NewPred, X, Y, Name, I);
8351 // Swap Destinations and condition...
8352 BI.setCondition(NewSCC);
8353 BI.setSuccessor(0, FalseDest);
8354 BI.setSuccessor(1, TrueDest);
8355 removeFromWorkList(I);
8356 I->getParent()->getInstList().erase(I);
8357 WorkList.push_back(cast<Instruction>(NewSCC));
8358 return &BI;
8359 }
8360
8361 // Cannonicalize icmp_ne -> icmp_eq
8362 ICmpInst::Predicate IPred;
8363 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
8364 TrueDest, FalseDest)))
8365 if ((IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
8366 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
8367 IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
8368 ICmpInst *I = cast<ICmpInst>(BI.getCondition());
8369 std::string Name = I->getName(); I->setName("");
8370 ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
8371 Value *NewSCC = new ICmpInst(NewPred, X, Y, Name, I);
Chris Lattnere967b342003-06-04 05:10:11 +00008372 // Swap Destinations and condition...
Chris Lattnerd4252a72004-07-30 07:50:03 +00008373 BI.setCondition(NewSCC);
Chris Lattnere967b342003-06-04 05:10:11 +00008374 BI.setSuccessor(0, FalseDest);
8375 BI.setSuccessor(1, TrueDest);
Chris Lattnerd4252a72004-07-30 07:50:03 +00008376 removeFromWorkList(I);
8377 I->getParent()->getInstList().erase(I);
8378 WorkList.push_back(cast<Instruction>(NewSCC));
Chris Lattnere967b342003-06-04 05:10:11 +00008379 return &BI;
8380 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00008381
Chris Lattner9eef8a72003-06-04 04:46:00 +00008382 return 0;
8383}
Chris Lattner1085bdf2002-11-04 16:18:53 +00008384
Chris Lattner4c9c20a2004-07-03 00:26:11 +00008385Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
8386 Value *Cond = SI.getCondition();
8387 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
8388 if (I->getOpcode() == Instruction::Add)
8389 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
8390 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
8391 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattner81a7a232004-10-16 18:11:37 +00008392 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner4c9c20a2004-07-03 00:26:11 +00008393 AddRHS));
8394 SI.setOperand(0, I->getOperand(0));
8395 WorkList.push_back(I);
8396 return &SI;
8397 }
8398 }
8399 return 0;
8400}
8401
Chris Lattner6bc98652006-03-05 00:22:33 +00008402/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
8403/// is to leave as a vector operation.
8404static bool CheapToScalarize(Value *V, bool isConstant) {
8405 if (isa<ConstantAggregateZero>(V))
8406 return true;
8407 if (ConstantPacked *C = dyn_cast<ConstantPacked>(V)) {
8408 if (isConstant) return true;
8409 // If all elts are the same, we can extract.
8410 Constant *Op0 = C->getOperand(0);
8411 for (unsigned i = 1; i < C->getNumOperands(); ++i)
8412 if (C->getOperand(i) != Op0)
8413 return false;
8414 return true;
8415 }
8416 Instruction *I = dyn_cast<Instruction>(V);
8417 if (!I) return false;
8418
8419 // Insert element gets simplified to the inserted element or is deleted if
8420 // this is constant idx extract element and its a constant idx insertelt.
8421 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
8422 isa<ConstantInt>(I->getOperand(2)))
8423 return true;
8424 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
8425 return true;
8426 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
8427 if (BO->hasOneUse() &&
8428 (CheapToScalarize(BO->getOperand(0), isConstant) ||
8429 CheapToScalarize(BO->getOperand(1), isConstant)))
8430 return true;
Reid Spencer266e42b2006-12-23 06:05:41 +00008431 if (CmpInst *CI = dyn_cast<CmpInst>(I))
8432 if (CI->hasOneUse() &&
8433 (CheapToScalarize(CI->getOperand(0), isConstant) ||
8434 CheapToScalarize(CI->getOperand(1), isConstant)))
8435 return true;
Chris Lattner6bc98652006-03-05 00:22:33 +00008436
8437 return false;
8438}
8439
Chris Lattner12249be2006-05-25 23:48:38 +00008440/// getShuffleMask - Read and decode a shufflevector mask. It turns undef
8441/// elements into values that are larger than the #elts in the input.
8442static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
8443 unsigned NElts = SVI->getType()->getNumElements();
8444 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
8445 return std::vector<unsigned>(NElts, 0);
8446 if (isa<UndefValue>(SVI->getOperand(2)))
8447 return std::vector<unsigned>(NElts, 2*NElts);
8448
8449 std::vector<unsigned> Result;
8450 const ConstantPacked *CP = cast<ConstantPacked>(SVI->getOperand(2));
8451 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
8452 if (isa<UndefValue>(CP->getOperand(i)))
8453 Result.push_back(NElts*2); // undef -> 8
8454 else
Reid Spencere0fc4df2006-10-20 07:07:24 +00008455 Result.push_back(cast<ConstantInt>(CP->getOperand(i))->getZExtValue());
Chris Lattner12249be2006-05-25 23:48:38 +00008456 return Result;
8457}
8458
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008459/// FindScalarElement - Given a vector and an element number, see if the scalar
8460/// value is already around as a register, for example if it were inserted then
8461/// extracted from the vector.
8462static Value *FindScalarElement(Value *V, unsigned EltNo) {
8463 assert(isa<PackedType>(V->getType()) && "Not looking at a vector?");
8464 const PackedType *PTy = cast<PackedType>(V->getType());
Chris Lattner2d37f922006-04-10 23:06:36 +00008465 unsigned Width = PTy->getNumElements();
8466 if (EltNo >= Width) // Out of range access.
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008467 return UndefValue::get(PTy->getElementType());
8468
8469 if (isa<UndefValue>(V))
8470 return UndefValue::get(PTy->getElementType());
8471 else if (isa<ConstantAggregateZero>(V))
8472 return Constant::getNullValue(PTy->getElementType());
8473 else if (ConstantPacked *CP = dyn_cast<ConstantPacked>(V))
8474 return CP->getOperand(EltNo);
8475 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
8476 // If this is an insert to a variable element, we don't know what it is.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008477 if (!isa<ConstantInt>(III->getOperand(2)))
8478 return 0;
8479 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008480
8481 // If this is an insert to the element we are looking for, return the
8482 // inserted value.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008483 if (EltNo == IIElt)
8484 return III->getOperand(1);
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008485
8486 // Otherwise, the insertelement doesn't modify the value, recurse on its
8487 // vector input.
8488 return FindScalarElement(III->getOperand(0), EltNo);
Chris Lattner2d37f922006-04-10 23:06:36 +00008489 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Chris Lattner12249be2006-05-25 23:48:38 +00008490 unsigned InEl = getShuffleMask(SVI)[EltNo];
8491 if (InEl < Width)
8492 return FindScalarElement(SVI->getOperand(0), InEl);
8493 else if (InEl < Width*2)
8494 return FindScalarElement(SVI->getOperand(1), InEl - Width);
8495 else
8496 return UndefValue::get(PTy->getElementType());
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008497 }
8498
8499 // Otherwise, we don't know.
8500 return 0;
8501}
8502
Robert Bocchinoa8352962006-01-13 22:48:06 +00008503Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008504
Chris Lattner92346c32006-03-31 18:25:14 +00008505 // If packed val is undef, replace extract with scalar undef.
8506 if (isa<UndefValue>(EI.getOperand(0)))
8507 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
8508
8509 // If packed val is constant 0, replace extract with scalar 0.
8510 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
8511 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
8512
Robert Bocchinoa8352962006-01-13 22:48:06 +00008513 if (ConstantPacked *C = dyn_cast<ConstantPacked>(EI.getOperand(0))) {
8514 // If packed val is constant with uniform operands, replace EI
8515 // with that operand
Chris Lattner6bc98652006-03-05 00:22:33 +00008516 Constant *op0 = C->getOperand(0);
Robert Bocchinoa8352962006-01-13 22:48:06 +00008517 for (unsigned i = 1; i < C->getNumOperands(); ++i)
Chris Lattner6bc98652006-03-05 00:22:33 +00008518 if (C->getOperand(i) != op0) {
8519 op0 = 0;
8520 break;
8521 }
8522 if (op0)
8523 return ReplaceInstUsesWith(EI, op0);
Robert Bocchinoa8352962006-01-13 22:48:06 +00008524 }
Chris Lattner6bc98652006-03-05 00:22:33 +00008525
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008526 // If extracting a specified index from the vector, see if we can recursively
8527 // find a previously computed scalar that was inserted into the vector.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008528 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Chris Lattner2deeaea2006-10-05 06:55:50 +00008529 // This instruction only demands the single element from the input vector.
8530 // If the input vector has a single use, simplify it based on this use
8531 // property.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008532 uint64_t IndexVal = IdxC->getZExtValue();
Chris Lattner2deeaea2006-10-05 06:55:50 +00008533 if (EI.getOperand(0)->hasOneUse()) {
8534 uint64_t UndefElts;
8535 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Reid Spencere0fc4df2006-10-20 07:07:24 +00008536 1 << IndexVal,
Chris Lattner2deeaea2006-10-05 06:55:50 +00008537 UndefElts)) {
8538 EI.setOperand(0, V);
8539 return &EI;
8540 }
8541 }
8542
Reid Spencere0fc4df2006-10-20 07:07:24 +00008543 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008544 return ReplaceInstUsesWith(EI, Elt);
Chris Lattner2d37f922006-04-10 23:06:36 +00008545 }
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008546
Chris Lattner83f65782006-05-25 22:53:38 +00008547 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Robert Bocchinoa8352962006-01-13 22:48:06 +00008548 if (I->hasOneUse()) {
8549 // Push extractelement into predecessor operation if legal and
8550 // profitable to do so
8551 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Chris Lattner6bc98652006-03-05 00:22:33 +00008552 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
8553 if (CheapToScalarize(BO, isConstantElt)) {
8554 ExtractElementInst *newEI0 =
8555 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
8556 EI.getName()+".lhs");
8557 ExtractElementInst *newEI1 =
8558 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
8559 EI.getName()+".rhs");
8560 InsertNewInstBefore(newEI0, EI);
8561 InsertNewInstBefore(newEI1, EI);
8562 return BinaryOperator::create(BO->getOpcode(), newEI0, newEI1);
8563 }
Reid Spencerde46e482006-11-02 20:25:50 +00008564 } else if (isa<LoadInst>(I)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00008565 Value *Ptr = InsertCastBefore(Instruction::BitCast, I->getOperand(0),
Robert Bocchinoa8352962006-01-13 22:48:06 +00008566 PointerType::get(EI.getType()), EI);
8567 GetElementPtrInst *GEP =
Reid Spencera736fdf2006-11-29 01:11:01 +00008568 new GetElementPtrInst(Ptr, EI.getOperand(1), I->getName() + ".gep");
Robert Bocchinoa8352962006-01-13 22:48:06 +00008569 InsertNewInstBefore(GEP, EI);
8570 return new LoadInst(GEP);
Chris Lattner83f65782006-05-25 22:53:38 +00008571 }
8572 }
8573 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
8574 // Extracting the inserted element?
8575 if (IE->getOperand(2) == EI.getOperand(1))
8576 return ReplaceInstUsesWith(EI, IE->getOperand(1));
8577 // If the inserted and extracted elements are constants, they must not
8578 // be the same value, extract from the pre-inserted value instead.
8579 if (isa<Constant>(IE->getOperand(2)) &&
8580 isa<Constant>(EI.getOperand(1))) {
8581 AddUsesToWorkList(EI);
8582 EI.setOperand(0, IE->getOperand(0));
8583 return &EI;
8584 }
8585 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
8586 // If this is extracting an element from a shufflevector, figure out where
8587 // it came from and extract from the appropriate input element instead.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008588 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
8589 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
Chris Lattner12249be2006-05-25 23:48:38 +00008590 Value *Src;
8591 if (SrcIdx < SVI->getType()->getNumElements())
8592 Src = SVI->getOperand(0);
8593 else if (SrcIdx < SVI->getType()->getNumElements()*2) {
8594 SrcIdx -= SVI->getType()->getNumElements();
8595 Src = SVI->getOperand(1);
8596 } else {
8597 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattner612fa8e2006-03-30 22:02:40 +00008598 }
Chris Lattner2deeaea2006-10-05 06:55:50 +00008599 return new ExtractElementInst(Src, SrcIdx);
Robert Bocchinoa8352962006-01-13 22:48:06 +00008600 }
8601 }
Chris Lattner83f65782006-05-25 22:53:38 +00008602 }
Robert Bocchinoa8352962006-01-13 22:48:06 +00008603 return 0;
8604}
8605
Chris Lattner90951862006-04-16 00:51:47 +00008606/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
8607/// elements from either LHS or RHS, return the shuffle mask and true.
8608/// Otherwise, return false.
8609static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
8610 std::vector<Constant*> &Mask) {
8611 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
8612 "Invalid CollectSingleShuffleElements");
8613 unsigned NumElts = cast<PackedType>(V->getType())->getNumElements();
8614
8615 if (isa<UndefValue>(V)) {
Reid Spencerc635f472006-12-31 05:48:39 +00008616 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattner90951862006-04-16 00:51:47 +00008617 return true;
8618 } else if (V == LHS) {
8619 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc635f472006-12-31 05:48:39 +00008620 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattner90951862006-04-16 00:51:47 +00008621 return true;
8622 } else if (V == RHS) {
8623 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc635f472006-12-31 05:48:39 +00008624 Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
Chris Lattner90951862006-04-16 00:51:47 +00008625 return true;
8626 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
8627 // If this is an insert of an extract from some other vector, include it.
8628 Value *VecOp = IEI->getOperand(0);
8629 Value *ScalarOp = IEI->getOperand(1);
8630 Value *IdxOp = IEI->getOperand(2);
8631
Chris Lattnerb6cb64b2006-04-27 21:14:21 +00008632 if (!isa<ConstantInt>(IdxOp))
8633 return false;
Reid Spencere0fc4df2006-10-20 07:07:24 +00008634 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerb6cb64b2006-04-27 21:14:21 +00008635
8636 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
8637 // Okay, we can handle this if the vector we are insertinting into is
8638 // transitively ok.
8639 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
8640 // If so, update the mask to reflect the inserted undef.
Reid Spencerc635f472006-12-31 05:48:39 +00008641 Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
Chris Lattnerb6cb64b2006-04-27 21:14:21 +00008642 return true;
8643 }
8644 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
8645 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner90951862006-04-16 00:51:47 +00008646 EI->getOperand(0)->getType() == V->getType()) {
8647 unsigned ExtractedIdx =
Reid Spencere0fc4df2006-10-20 07:07:24 +00008648 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattner90951862006-04-16 00:51:47 +00008649
8650 // This must be extracting from either LHS or RHS.
8651 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
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 value.
8656 if (EI->getOperand(0) == LHS) {
8657 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc635f472006-12-31 05:48:39 +00008658 ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattner90951862006-04-16 00:51:47 +00008659 } else {
8660 assert(EI->getOperand(0) == RHS);
8661 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc635f472006-12-31 05:48:39 +00008662 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
Chris Lattner90951862006-04-16 00:51:47 +00008663
8664 }
8665 return true;
8666 }
8667 }
8668 }
8669 }
8670 }
8671 // TODO: Handle shufflevector here!
8672
8673 return false;
8674}
8675
8676/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
8677/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
8678/// that computes V and the LHS value of the shuffle.
Chris Lattner39fac442006-04-15 01:39:45 +00008679static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Chris Lattner90951862006-04-16 00:51:47 +00008680 Value *&RHS) {
8681 assert(isa<PackedType>(V->getType()) &&
8682 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattner39fac442006-04-15 01:39:45 +00008683 "Invalid shuffle!");
8684 unsigned NumElts = cast<PackedType>(V->getType())->getNumElements();
8685
8686 if (isa<UndefValue>(V)) {
Reid Spencerc635f472006-12-31 05:48:39 +00008687 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattner39fac442006-04-15 01:39:45 +00008688 return V;
8689 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencerc635f472006-12-31 05:48:39 +00008690 Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
Chris Lattner39fac442006-04-15 01:39:45 +00008691 return V;
8692 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
8693 // If this is an insert of an extract from some other vector, include it.
8694 Value *VecOp = IEI->getOperand(0);
8695 Value *ScalarOp = IEI->getOperand(1);
8696 Value *IdxOp = IEI->getOperand(2);
8697
8698 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
8699 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
8700 EI->getOperand(0)->getType() == V->getType()) {
8701 unsigned ExtractedIdx =
Reid Spencere0fc4df2006-10-20 07:07:24 +00008702 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
8703 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattner39fac442006-04-15 01:39:45 +00008704
8705 // Either the extracted from or inserted into vector must be RHSVec,
8706 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner90951862006-04-16 00:51:47 +00008707 if (EI->getOperand(0) == RHS || RHS == 0) {
8708 RHS = EI->getOperand(0);
8709 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
Chris Lattner39fac442006-04-15 01:39:45 +00008710 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc635f472006-12-31 05:48:39 +00008711 ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
Chris Lattner39fac442006-04-15 01:39:45 +00008712 return V;
8713 }
8714
Chris Lattner90951862006-04-16 00:51:47 +00008715 if (VecOp == RHS) {
8716 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
Chris Lattner39fac442006-04-15 01:39:45 +00008717 // Everything but the extracted element is replaced with the RHS.
8718 for (unsigned i = 0; i != NumElts; ++i) {
8719 if (i != InsertedIdx)
Reid Spencerc635f472006-12-31 05:48:39 +00008720 Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
Chris Lattner39fac442006-04-15 01:39:45 +00008721 }
8722 return V;
8723 }
Chris Lattner90951862006-04-16 00:51:47 +00008724
8725 // If this insertelement is a chain that comes from exactly these two
8726 // vectors, return the vector and the effective shuffle.
8727 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
8728 return EI->getOperand(0);
8729
Chris Lattner39fac442006-04-15 01:39:45 +00008730 }
8731 }
8732 }
Chris Lattner90951862006-04-16 00:51:47 +00008733 // TODO: Handle shufflevector here!
Chris Lattner39fac442006-04-15 01:39:45 +00008734
8735 // Otherwise, can't do anything fancy. Return an identity vector.
8736 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc635f472006-12-31 05:48:39 +00008737 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattner39fac442006-04-15 01:39:45 +00008738 return V;
8739}
8740
8741Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
8742 Value *VecOp = IE.getOperand(0);
8743 Value *ScalarOp = IE.getOperand(1);
8744 Value *IdxOp = IE.getOperand(2);
8745
8746 // If the inserted element was extracted from some other vector, and if the
8747 // indexes are constant, try to turn this into a shufflevector operation.
8748 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
8749 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
8750 EI->getOperand(0)->getType() == IE.getType()) {
8751 unsigned NumVectorElts = IE.getType()->getNumElements();
Reid Spencere0fc4df2006-10-20 07:07:24 +00008752 unsigned ExtractedIdx=cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
8753 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattner39fac442006-04-15 01:39:45 +00008754
8755 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
8756 return ReplaceInstUsesWith(IE, VecOp);
8757
8758 if (InsertedIdx >= NumVectorElts) // Out of range insert.
8759 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
8760
8761 // If we are extracting a value from a vector, then inserting it right
8762 // back into the same place, just use the input vector.
8763 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
8764 return ReplaceInstUsesWith(IE, VecOp);
8765
8766 // We could theoretically do this for ANY input. However, doing so could
8767 // turn chains of insertelement instructions into a chain of shufflevector
8768 // instructions, and right now we do not merge shufflevectors. As such,
8769 // only do this in a situation where it is clear that there is benefit.
8770 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
8771 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
8772 // the values of VecOp, except then one read from EIOp0.
8773 // Build a new shuffle mask.
8774 std::vector<Constant*> Mask;
8775 if (isa<UndefValue>(VecOp))
Reid Spencerc635f472006-12-31 05:48:39 +00008776 Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
Chris Lattner39fac442006-04-15 01:39:45 +00008777 else {
8778 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
Reid Spencerc635f472006-12-31 05:48:39 +00008779 Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
Chris Lattner39fac442006-04-15 01:39:45 +00008780 NumVectorElts));
8781 }
Reid Spencerc635f472006-12-31 05:48:39 +00008782 Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattner39fac442006-04-15 01:39:45 +00008783 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
8784 ConstantPacked::get(Mask));
8785 }
8786
8787 // If this insertelement isn't used by some other insertelement, turn it
8788 // (and any insertelements it points to), into one big shuffle.
8789 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
8790 std::vector<Constant*> Mask;
Chris Lattner90951862006-04-16 00:51:47 +00008791 Value *RHS = 0;
8792 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
8793 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
8794 // We now have a shuffle of LHS, RHS, Mask.
8795 return new ShuffleVectorInst(LHS, RHS, ConstantPacked::get(Mask));
Chris Lattner39fac442006-04-15 01:39:45 +00008796 }
8797 }
8798 }
8799
8800 return 0;
8801}
8802
8803
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008804Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
8805 Value *LHS = SVI.getOperand(0);
8806 Value *RHS = SVI.getOperand(1);
Chris Lattner12249be2006-05-25 23:48:38 +00008807 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008808
8809 bool MadeChange = false;
8810
Chris Lattner2deeaea2006-10-05 06:55:50 +00008811 // Undefined shuffle mask -> undefined value.
Chris Lattner12249be2006-05-25 23:48:38 +00008812 if (isa<UndefValue>(SVI.getOperand(2)))
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008813 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
8814
Chris Lattner39fac442006-04-15 01:39:45 +00008815 // TODO: If we have shuffle(x, undef, mask) and any elements of mask refer to
8816 // the undef, change them to undefs.
8817
Chris Lattner12249be2006-05-25 23:48:38 +00008818 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
8819 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
8820 if (LHS == RHS || isa<UndefValue>(LHS)) {
8821 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008822 // shuffle(undef,undef,mask) -> undef.
8823 return ReplaceInstUsesWith(SVI, LHS);
8824 }
8825
Chris Lattner12249be2006-05-25 23:48:38 +00008826 // Remap any references to RHS to use LHS.
8827 std::vector<Constant*> Elts;
8828 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner0e477162006-05-26 00:29:06 +00008829 if (Mask[i] >= 2*e)
Reid Spencerc635f472006-12-31 05:48:39 +00008830 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner0e477162006-05-26 00:29:06 +00008831 else {
8832 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
8833 (Mask[i] < e && isa<UndefValue>(LHS)))
8834 Mask[i] = 2*e; // Turn into undef.
8835 else
8836 Mask[i] &= (e-1); // Force to LHS.
Reid Spencerc635f472006-12-31 05:48:39 +00008837 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
Chris Lattner0e477162006-05-26 00:29:06 +00008838 }
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008839 }
Chris Lattner12249be2006-05-25 23:48:38 +00008840 SVI.setOperand(0, SVI.getOperand(1));
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008841 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Chris Lattner12249be2006-05-25 23:48:38 +00008842 SVI.setOperand(2, ConstantPacked::get(Elts));
Chris Lattner0e477162006-05-26 00:29:06 +00008843 LHS = SVI.getOperand(0);
8844 RHS = SVI.getOperand(1);
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008845 MadeChange = true;
8846 }
8847
Chris Lattner0e477162006-05-26 00:29:06 +00008848 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner12249be2006-05-25 23:48:38 +00008849 bool isLHSID = true, isRHSID = true;
Chris Lattner34cebe72006-04-16 00:03:56 +00008850
Chris Lattner12249be2006-05-25 23:48:38 +00008851 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
8852 if (Mask[i] >= e*2) continue; // Ignore undef values.
8853 // Is this an identity shuffle of the LHS value?
8854 isLHSID &= (Mask[i] == i);
8855
8856 // Is this an identity shuffle of the RHS value?
8857 isRHSID &= (Mask[i]-e == i);
Chris Lattner34cebe72006-04-16 00:03:56 +00008858 }
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008859
Chris Lattner12249be2006-05-25 23:48:38 +00008860 // Eliminate identity shuffles.
8861 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
8862 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008863
Chris Lattner0e477162006-05-26 00:29:06 +00008864 // If the LHS is a shufflevector itself, see if we can combine it with this
8865 // one without producing an unusual shuffle. Here we are really conservative:
8866 // we are absolutely afraid of producing a shuffle mask not in the input
8867 // program, because the code gen may not be smart enough to turn a merged
8868 // shuffle into two specific shuffles: it may produce worse code. As such,
8869 // we only merge two shuffles if the result is one of the two input shuffle
8870 // masks. In this case, merging the shuffles just removes one instruction,
8871 // which we know is safe. This is good for things like turning:
8872 // (splat(splat)) -> splat.
8873 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
8874 if (isa<UndefValue>(RHS)) {
8875 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
8876
8877 std::vector<unsigned> NewMask;
8878 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
8879 if (Mask[i] >= 2*e)
8880 NewMask.push_back(2*e);
8881 else
8882 NewMask.push_back(LHSMask[Mask[i]]);
8883
8884 // If the result mask is equal to the src shuffle or this shuffle mask, do
8885 // the replacement.
8886 if (NewMask == LHSMask || NewMask == Mask) {
8887 std::vector<Constant*> Elts;
8888 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
8889 if (NewMask[i] >= e*2) {
Reid Spencerc635f472006-12-31 05:48:39 +00008890 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner0e477162006-05-26 00:29:06 +00008891 } else {
Reid Spencerc635f472006-12-31 05:48:39 +00008892 Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
Chris Lattner0e477162006-05-26 00:29:06 +00008893 }
8894 }
8895 return new ShuffleVectorInst(LHSSVI->getOperand(0),
8896 LHSSVI->getOperand(1),
8897 ConstantPacked::get(Elts));
8898 }
8899 }
8900 }
8901
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008902 return MadeChange ? &SVI : 0;
8903}
8904
8905
Robert Bocchinoa8352962006-01-13 22:48:06 +00008906
Chris Lattner99f48c62002-09-02 04:59:56 +00008907void InstCombiner::removeFromWorkList(Instruction *I) {
8908 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
8909 WorkList.end());
8910}
8911
Chris Lattner39c98bb2004-12-08 23:43:58 +00008912
8913/// TryToSinkInstruction - Try to move the specified instruction from its
8914/// current block into the beginning of DestBlock, which can only happen if it's
8915/// safe to move the instruction past all of the instructions between it and the
8916/// end of its block.
8917static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
8918 assert(I->hasOneUse() && "Invariants didn't hold!");
8919
Chris Lattnerc4f67e62005-10-27 17:13:11 +00008920 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
8921 if (isa<PHINode>(I) || I->mayWriteToMemory()) return false;
Misha Brukmanb1c93172005-04-21 23:48:37 +00008922
Chris Lattner39c98bb2004-12-08 23:43:58 +00008923 // Do not sink alloca instructions out of the entry block.
8924 if (isa<AllocaInst>(I) && I->getParent() == &DestBlock->getParent()->front())
8925 return false;
8926
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00008927 // We can only sink load instructions if there is nothing between the load and
8928 // the end of block that could change the value.
8929 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00008930 for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
8931 Scan != E; ++Scan)
8932 if (Scan->mayWriteToMemory())
8933 return false;
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00008934 }
Chris Lattner39c98bb2004-12-08 23:43:58 +00008935
8936 BasicBlock::iterator InsertPos = DestBlock->begin();
8937 while (isa<PHINode>(InsertPos)) ++InsertPos;
8938
Chris Lattner9f269e42005-08-08 19:11:57 +00008939 I->moveBefore(InsertPos);
Chris Lattner39c98bb2004-12-08 23:43:58 +00008940 ++NumSunkInst;
8941 return true;
8942}
8943
Chris Lattner1443bc52006-05-11 17:11:52 +00008944/// OptimizeConstantExpr - Given a constant expression and target data layout
Reid Spencer13bc5d72006-12-12 09:18:51 +00008945/// information, symbolically evaluate the constant expr to something simpler
Chris Lattner1443bc52006-05-11 17:11:52 +00008946/// if possible.
8947static Constant *OptimizeConstantExpr(ConstantExpr *CE, const TargetData *TD) {
8948 if (!TD) return CE;
8949
8950 Constant *Ptr = CE->getOperand(0);
8951 if (CE->getOpcode() == Instruction::GetElementPtr && Ptr->isNullValue() &&
8952 cast<PointerType>(Ptr->getType())->getElementType()->isSized()) {
8953 // If this is a constant expr gep that is effectively computing an
8954 // "offsetof", fold it into 'cast int Size to T*' instead of 'gep 0, 0, 12'
8955 bool isFoldableGEP = true;
8956 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
8957 if (!isa<ConstantInt>(CE->getOperand(i)))
8958 isFoldableGEP = false;
8959 if (isFoldableGEP) {
8960 std::vector<Value*> Ops(CE->op_begin()+1, CE->op_end());
8961 uint64_t Offset = TD->getIndexedOffset(Ptr->getType(), Ops);
Reid Spencer2a499b02006-12-13 17:19:09 +00008962 Constant *C = ConstantInt::get(TD->getIntPtrType(), Offset);
Reid Spencer13bc5d72006-12-12 09:18:51 +00008963 return ConstantExpr::getIntToPtr(C, CE->getType());
Chris Lattner1443bc52006-05-11 17:11:52 +00008964 }
8965 }
8966
8967 return CE;
8968}
8969
Chris Lattnera36ee4e2006-05-10 19:00:36 +00008970
8971/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
8972/// all reachable code to the worklist.
8973///
8974/// This has a couple of tricks to make the code faster and more powerful. In
8975/// particular, we constant fold and DCE instructions as we go, to avoid adding
8976/// them to the worklist (this significantly speeds up instcombine on code where
8977/// many instructions are dead or constant). Additionally, if we find a branch
8978/// whose condition is a known constant, we only visit the reachable successors.
8979///
8980static void AddReachableCodeToWorklist(BasicBlock *BB,
8981 std::set<BasicBlock*> &Visited,
Chris Lattner1443bc52006-05-11 17:11:52 +00008982 std::vector<Instruction*> &WorkList,
8983 const TargetData *TD) {
Chris Lattnera36ee4e2006-05-10 19:00:36 +00008984 // We have now visited this block! If we've already been here, bail out.
8985 if (!Visited.insert(BB).second) return;
8986
8987 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
8988 Instruction *Inst = BBI++;
8989
8990 // DCE instruction if trivially dead.
8991 if (isInstructionTriviallyDead(Inst)) {
8992 ++NumDeadInst;
Bill Wendling5dbf43c2006-11-26 09:46:52 +00008993 DOUT << "IC: DCE: " << *Inst;
Chris Lattnera36ee4e2006-05-10 19:00:36 +00008994 Inst->eraseFromParent();
8995 continue;
8996 }
8997
8998 // ConstantProp instruction if trivially constant.
8999 if (Constant *C = ConstantFoldInstruction(Inst)) {
Chris Lattner1443bc52006-05-11 17:11:52 +00009000 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
9001 C = OptimizeConstantExpr(CE, TD);
Bill Wendling5dbf43c2006-11-26 09:46:52 +00009002 DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009003 Inst->replaceAllUsesWith(C);
9004 ++NumConstProp;
9005 Inst->eraseFromParent();
9006 continue;
9007 }
9008
9009 WorkList.push_back(Inst);
9010 }
9011
9012 // Recursively visit successors. If this is a branch or switch on a constant,
9013 // only visit the reachable successor.
9014 TerminatorInst *TI = BB->getTerminator();
9015 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
9016 if (BI->isConditional() && isa<ConstantBool>(BI->getCondition())) {
9017 bool CondVal = cast<ConstantBool>(BI->getCondition())->getValue();
Chris Lattner1443bc52006-05-11 17:11:52 +00009018 AddReachableCodeToWorklist(BI->getSuccessor(!CondVal), Visited, WorkList,
9019 TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009020 return;
9021 }
9022 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
9023 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
9024 // See if this is an explicit destination.
9025 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
9026 if (SI->getCaseValue(i) == Cond) {
Chris Lattner1443bc52006-05-11 17:11:52 +00009027 AddReachableCodeToWorklist(SI->getSuccessor(i), Visited, WorkList,TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009028 return;
9029 }
9030
9031 // Otherwise it is the default destination.
Chris Lattner1443bc52006-05-11 17:11:52 +00009032 AddReachableCodeToWorklist(SI->getSuccessor(0), Visited, WorkList, TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009033 return;
9034 }
9035 }
9036
9037 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
Chris Lattner1443bc52006-05-11 17:11:52 +00009038 AddReachableCodeToWorklist(TI->getSuccessor(i), Visited, WorkList, TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009039}
9040
Chris Lattner113f4f42002-06-25 16:13:24 +00009041bool InstCombiner::runOnFunction(Function &F) {
Chris Lattner260ab202002-04-18 17:39:14 +00009042 bool Changed = false;
Chris Lattnerf4ad1652003-11-02 05:57:39 +00009043 TD = &getAnalysis<TargetData>();
Chris Lattnerca081252001-12-14 16:52:21 +00009044
Chris Lattner4ed40f72005-07-07 20:40:38 +00009045 {
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009046 // Do a depth-first traversal of the function, populate the worklist with
9047 // the reachable instructions. Ignore blocks that are not reachable. Keep
9048 // track of which blocks we visit.
Chris Lattner4ed40f72005-07-07 20:40:38 +00009049 std::set<BasicBlock*> Visited;
Chris Lattner1443bc52006-05-11 17:11:52 +00009050 AddReachableCodeToWorklist(F.begin(), Visited, WorkList, TD);
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00009051
Chris Lattner4ed40f72005-07-07 20:40:38 +00009052 // Do a quick scan over the function. If we find any blocks that are
9053 // unreachable, remove any instructions inside of them. This prevents
9054 // the instcombine code from having to deal with some bad special cases.
9055 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
9056 if (!Visited.count(BB)) {
9057 Instruction *Term = BB->getTerminator();
9058 while (Term != BB->begin()) { // Remove instrs bottom-up
9059 BasicBlock::iterator I = Term; --I;
Chris Lattner2d3a7a62004-04-27 15:13:33 +00009060
Bill Wendling5dbf43c2006-11-26 09:46:52 +00009061 DOUT << "IC: DCE: " << *I;
Chris Lattner4ed40f72005-07-07 20:40:38 +00009062 ++NumDeadInst;
9063
9064 if (!I->use_empty())
9065 I->replaceAllUsesWith(UndefValue::get(I->getType()));
9066 I->eraseFromParent();
9067 }
9068 }
9069 }
Chris Lattnerca081252001-12-14 16:52:21 +00009070
9071 while (!WorkList.empty()) {
9072 Instruction *I = WorkList.back(); // Get an instruction from the worklist
9073 WorkList.pop_back();
9074
Chris Lattner1443bc52006-05-11 17:11:52 +00009075 // Check to see if we can DCE the instruction.
Chris Lattner99f48c62002-09-02 04:59:56 +00009076 if (isInstructionTriviallyDead(I)) {
Chris Lattner1443bc52006-05-11 17:11:52 +00009077 // Add operands to the worklist.
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009078 if (I->getNumOperands() < 4)
Chris Lattner51ea1272004-02-28 05:22:00 +00009079 AddUsesToWorkList(*I);
Chris Lattner99f48c62002-09-02 04:59:56 +00009080 ++NumDeadInst;
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009081
Bill Wendling5dbf43c2006-11-26 09:46:52 +00009082 DOUT << "IC: DCE: " << *I;
Chris Lattnercd517ff2005-01-28 19:32:01 +00009083
9084 I->eraseFromParent();
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009085 removeFromWorkList(I);
9086 continue;
9087 }
Chris Lattner99f48c62002-09-02 04:59:56 +00009088
Chris Lattner1443bc52006-05-11 17:11:52 +00009089 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattner99f48c62002-09-02 04:59:56 +00009090 if (Constant *C = ConstantFoldInstruction(I)) {
Chris Lattner1443bc52006-05-11 17:11:52 +00009091 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
9092 C = OptimizeConstantExpr(CE, TD);
Bill Wendling5dbf43c2006-11-26 09:46:52 +00009093 DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
Chris Lattnercd517ff2005-01-28 19:32:01 +00009094
Chris Lattner1443bc52006-05-11 17:11:52 +00009095 // Add operands to the worklist.
Chris Lattner51ea1272004-02-28 05:22:00 +00009096 AddUsesToWorkList(*I);
Chris Lattnerc6509f42002-12-05 22:41:53 +00009097 ReplaceInstUsesWith(*I, C);
9098
Chris Lattner99f48c62002-09-02 04:59:56 +00009099 ++NumConstProp;
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009100 I->eraseFromParent();
Chris Lattner800aaaf2003-10-07 15:17:02 +00009101 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009102 continue;
Chris Lattner99f48c62002-09-02 04:59:56 +00009103 }
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009104
Chris Lattner39c98bb2004-12-08 23:43:58 +00009105 // See if we can trivially sink this instruction to a successor basic block.
9106 if (I->hasOneUse()) {
9107 BasicBlock *BB = I->getParent();
9108 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
9109 if (UserParent != BB) {
9110 bool UserIsSuccessor = false;
9111 // See if the user is one of our successors.
9112 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
9113 if (*SI == UserParent) {
9114 UserIsSuccessor = true;
9115 break;
9116 }
9117
9118 // If the user is one of our immediate successors, and if that successor
9119 // only has us as a predecessors (we'd have to split the critical edge
9120 // otherwise), we can keep going.
9121 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
9122 next(pred_begin(UserParent)) == pred_end(UserParent))
9123 // Okay, the CFG is simple enough, try to sink this instruction.
9124 Changed |= TryToSinkInstruction(I, UserParent);
9125 }
9126 }
9127
Chris Lattnerca081252001-12-14 16:52:21 +00009128 // Now that we have an instruction, try combining it to simplify it...
Chris Lattnerae7a0d32002-08-02 19:29:35 +00009129 if (Instruction *Result = visit(*I)) {
Chris Lattner0b18c1d2002-05-10 15:38:35 +00009130 ++NumCombined;
Chris Lattner260ab202002-04-18 17:39:14 +00009131 // Should we replace the old instruction with a new one?
Chris Lattner053c0932002-05-14 15:24:07 +00009132 if (Result != I) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +00009133 DOUT << "IC: Old = " << *I
9134 << " New = " << *Result;
Chris Lattner7d2a5392004-03-13 23:54:27 +00009135
Chris Lattner396dbfe2004-06-09 05:08:07 +00009136 // Everything uses the new instruction now.
9137 I->replaceAllUsesWith(Result);
9138
9139 // Push the new instruction and any users onto the worklist.
9140 WorkList.push_back(Result);
9141 AddUsersToWorkList(*Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009142
9143 // Move the name to the new instruction first...
9144 std::string OldName = I->getName(); I->setName("");
Chris Lattner950fc782003-10-07 22:58:41 +00009145 Result->setName(OldName);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009146
9147 // Insert the new instruction into the basic block...
9148 BasicBlock *InstParent = I->getParent();
Chris Lattner7515cab2004-11-14 19:13:23 +00009149 BasicBlock::iterator InsertPos = I;
9150
9151 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
9152 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
9153 ++InsertPos;
9154
9155 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009156
Chris Lattner63d75af2004-05-01 23:27:23 +00009157 // Make sure that we reprocess all operands now that we reduced their
9158 // use counts.
Chris Lattnerb643a9e2004-05-01 23:19:52 +00009159 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
9160 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
9161 WorkList.push_back(OpI);
9162
Chris Lattner396dbfe2004-06-09 05:08:07 +00009163 // Instructions can end up on the worklist more than once. Make sure
9164 // we do not process an instruction that has been deleted.
9165 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009166
9167 // Erase the old instruction.
9168 InstParent->getInstList().erase(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00009169 } else {
Bill Wendling5dbf43c2006-11-26 09:46:52 +00009170 DOUT << "IC: MOD = " << *I;
Chris Lattner7d2a5392004-03-13 23:54:27 +00009171
Chris Lattnerae7a0d32002-08-02 19:29:35 +00009172 // If the instruction was modified, it's possible that it is now dead.
9173 // if so, remove it.
Chris Lattner63d75af2004-05-01 23:27:23 +00009174 if (isInstructionTriviallyDead(I)) {
9175 // Make sure we process all operands now that we are reducing their
9176 // use counts.
9177 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
9178 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
9179 WorkList.push_back(OpI);
Misha Brukmanb1c93172005-04-21 23:48:37 +00009180
Chris Lattner63d75af2004-05-01 23:27:23 +00009181 // Instructions may end up in the worklist more than once. Erase all
Robert Bocchinoa8352962006-01-13 22:48:06 +00009182 // occurrences of this instruction.
Chris Lattner99f48c62002-09-02 04:59:56 +00009183 removeFromWorkList(I);
Chris Lattner31f486c2005-01-31 05:36:43 +00009184 I->eraseFromParent();
Chris Lattner396dbfe2004-06-09 05:08:07 +00009185 } else {
9186 WorkList.push_back(Result);
9187 AddUsersToWorkList(*Result);
Chris Lattnerae7a0d32002-08-02 19:29:35 +00009188 }
Chris Lattner053c0932002-05-14 15:24:07 +00009189 }
Chris Lattner260ab202002-04-18 17:39:14 +00009190 Changed = true;
Chris Lattnerca081252001-12-14 16:52:21 +00009191 }
9192 }
9193
Chris Lattner260ab202002-04-18 17:39:14 +00009194 return Changed;
Chris Lattner04805fa2002-02-26 21:46:54 +00009195}
9196
Brian Gaeke38b79e82004-07-27 17:43:21 +00009197FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattner260ab202002-04-18 17:39:14 +00009198 return new InstCombiner();
Chris Lattner04805fa2002-02-26 21:46:54 +00009199}
Brian Gaeke960707c2003-11-11 22:41:34 +00009200