blob: c039b3999a3bdd3ec69a9bfcc11a6a84b40222fb [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
Zhou Sheng75b871f2007-01-11 12:24:14 +0000305 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
306 ConstantInt *AndRHS, BinaryOperator &TheAnd);
Chris Lattneraf517572005-09-18 04:24:45 +0000307
Zhou Sheng75b871f2007-01-11 12:24:14 +0000308 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
Chris Lattneraf517572005-09-18 04:24:45 +0000309 bool isSub, Instruction &I);
Chris Lattner6862fbd2004-09-29 17:40:11 +0000310 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencer266e42b2006-12-23 06:05:41 +0000311 bool isSigned, bool Inside, Instruction &IB);
Chris Lattner216be912005-10-24 06:03:58 +0000312 Instruction *PromoteCastOfAllocation(CastInst &CI, AllocationInst &AI);
Chris Lattnerc482a9e2006-06-15 19:07:26 +0000313 Instruction *MatchBSwap(BinaryOperator &I);
314
Reid Spencer74a528b2006-12-13 18:21:21 +0000315 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
Chris Lattner260ab202002-04-18 17:39:14 +0000316 };
Chris Lattnerb28b6802002-07-23 18:06:35 +0000317
Chris Lattnerc2d3d312006-08-27 22:42:52 +0000318 RegisterPass<InstCombiner> X("instcombine", "Combine redundant instructions");
Chris Lattner260ab202002-04-18 17:39:14 +0000319}
320
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000321// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattner81a7a232004-10-16 18:11:37 +0000322// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000323static unsigned getComplexity(Value *V) {
324 if (isa<Instruction>(V)) {
325 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
Chris Lattner81a7a232004-10-16 18:11:37 +0000326 return 3;
327 return 4;
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000328 }
Chris Lattner81a7a232004-10-16 18:11:37 +0000329 if (isa<Argument>(V)) return 3;
330 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000331}
Chris Lattner260ab202002-04-18 17:39:14 +0000332
Chris Lattner7fb29e12003-03-11 00:12:48 +0000333// isOnlyUse - Return true if this instruction will be deleted if we stop using
334// it.
335static bool isOnlyUse(Value *V) {
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000336 return V->hasOneUse() || isa<Constant>(V);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000337}
338
Chris Lattnere79e8542004-02-23 06:38:22 +0000339// getPromotedType - Return the specified type promoted as it would be to pass
340// though a va_arg area...
341static const Type *getPromotedType(const Type *Ty) {
Chris Lattner97bfcea2004-06-17 18:16:02 +0000342 switch (Ty->getTypeID()) {
Reid Spencerc635f472006-12-31 05:48:39 +0000343 case Type::Int8TyID:
344 case Type::Int16TyID: return Type::Int32Ty;
Chris Lattnere79e8542004-02-23 06:38:22 +0000345 case Type::FloatTyID: return Type::DoubleTy;
346 default: return Ty;
347 }
348}
349
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000350/// getBitCastOperand - If the specified operand is a CastInst or a constant
351/// expression bitcast, return the operand value, otherwise return null.
352static Value *getBitCastOperand(Value *V) {
353 if (BitCastInst *I = dyn_cast<BitCastInst>(V))
Chris Lattner567b81f2005-09-13 00:40:14 +0000354 return I->getOperand(0);
355 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000356 if (CE->getOpcode() == Instruction::BitCast)
Chris Lattner567b81f2005-09-13 00:40:14 +0000357 return CE->getOperand(0);
358 return 0;
359}
360
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000361/// This function is a wrapper around CastInst::isEliminableCastPair. It
362/// simply extracts arguments and returns what that function returns.
363/// @Determine if it is valid to eliminate a Convert pair
364static Instruction::CastOps
365isEliminableCastPair(
366 const CastInst *CI, ///< The first cast instruction
367 unsigned opcode, ///< The opcode of the second cast instruction
368 const Type *DstTy, ///< The target type for the second cast instruction
369 TargetData *TD ///< The target data for pointer size
370) {
371
372 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
373 const Type *MidTy = CI->getType(); // B from above
Chris Lattner1d441ad2006-05-06 09:00:16 +0000374
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000375 // Get the opcodes of the two Cast instructions
376 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
377 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
Chris Lattner1d441ad2006-05-06 09:00:16 +0000378
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000379 return Instruction::CastOps(
380 CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
381 DstTy, TD->getIntPtrType()));
Chris Lattner1d441ad2006-05-06 09:00:16 +0000382}
383
384/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
385/// in any code being generated. It does not require codegen if V is simple
386/// enough or if the cast can be folded into other casts.
Reid Spencer266e42b2006-12-23 06:05:41 +0000387static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
388 const Type *Ty, TargetData *TD) {
Chris Lattner1d441ad2006-05-06 09:00:16 +0000389 if (V->getType() == Ty || isa<Constant>(V)) return false;
390
Chris Lattner99155be2006-05-25 23:24:33 +0000391 // If this is another cast that can be eliminated, it isn't codegen either.
Chris Lattner1d441ad2006-05-06 09:00:16 +0000392 if (const CastInst *CI = dyn_cast<CastInst>(V))
Reid Spencer266e42b2006-12-23 06:05:41 +0000393 if (isEliminableCastPair(CI, opcode, Ty, TD))
Chris Lattner1d441ad2006-05-06 09:00:16 +0000394 return false;
395 return true;
396}
397
398/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
399/// InsertBefore instruction. This is specialized a bit to avoid inserting
400/// casts that are known to not do anything...
401///
Reid Spencer13bc5d72006-12-12 09:18:51 +0000402Value *InstCombiner::InsertOperandCastBefore(Instruction::CastOps opcode,
403 Value *V, const Type *DestTy,
Chris Lattner1d441ad2006-05-06 09:00:16 +0000404 Instruction *InsertBefore) {
405 if (V->getType() == DestTy) return V;
406 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencer13bc5d72006-12-12 09:18:51 +0000407 return ConstantExpr::getCast(opcode, C, DestTy);
Chris Lattner1d441ad2006-05-06 09:00:16 +0000408
Reid Spencer13bc5d72006-12-12 09:18:51 +0000409 return InsertCastBefore(opcode, V, DestTy, *InsertBefore);
Chris Lattner1d441ad2006-05-06 09:00:16 +0000410}
411
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000412// SimplifyCommutative - This performs a few simplifications for commutative
413// operators:
Chris Lattner260ab202002-04-18 17:39:14 +0000414//
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000415// 1. Order operands such that they are listed from right (least complex) to
416// left (most complex). This puts constants before unary operators before
417// binary operators.
418//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000419// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
420// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000421//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000422bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000423 bool Changed = false;
424 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
425 Changed = !I.swapOperands();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000426
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000427 if (!I.isAssociative()) return Changed;
428 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattner7fb29e12003-03-11 00:12:48 +0000429 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
430 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
431 if (isa<Constant>(I.getOperand(1))) {
Chris Lattner34428442003-05-27 16:40:51 +0000432 Constant *Folded = ConstantExpr::get(I.getOpcode(),
433 cast<Constant>(I.getOperand(1)),
434 cast<Constant>(Op->getOperand(1)));
Chris Lattner7fb29e12003-03-11 00:12:48 +0000435 I.setOperand(0, Op->getOperand(0));
436 I.setOperand(1, Folded);
437 return true;
438 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
439 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
440 isOnlyUse(Op) && isOnlyUse(Op1)) {
441 Constant *C1 = cast<Constant>(Op->getOperand(1));
442 Constant *C2 = cast<Constant>(Op1->getOperand(1));
443
444 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner34428442003-05-27 16:40:51 +0000445 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000446 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
447 Op1->getOperand(0),
448 Op1->getName(), &I);
449 WorkList.push_back(New);
450 I.setOperand(0, New);
451 I.setOperand(1, Folded);
452 return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000453 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000454 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000455 return Changed;
Chris Lattner260ab202002-04-18 17:39:14 +0000456}
Chris Lattnerca081252001-12-14 16:52:21 +0000457
Reid Spencer266e42b2006-12-23 06:05:41 +0000458/// SimplifyCompare - For a CmpInst this function just orders the operands
459/// so that theyare listed from right (least complex) to left (most complex).
460/// This puts constants before unary operators before binary operators.
461bool InstCombiner::SimplifyCompare(CmpInst &I) {
462 if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
463 return false;
464 I.swapOperands();
465 // Compare instructions are not associative so there's nothing else we can do.
466 return true;
467}
468
Chris Lattnerbb74e222003-03-10 23:06:50 +0000469// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
470// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattner9fa53de2002-05-06 16:49:18 +0000471//
Chris Lattnerbb74e222003-03-10 23:06:50 +0000472static inline Value *dyn_castNegVal(Value *V) {
473 if (BinaryOperator::isNeg(V))
Chris Lattnerd6f636a2005-04-24 07:30:14 +0000474 return BinaryOperator::getNegArgument(V);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000475
Chris Lattner9ad0d552004-12-14 20:08:06 +0000476 // Constants can be considered to be negated values if they can be folded.
477 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
478 return ConstantExpr::getNeg(C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000479 return 0;
Chris Lattner9fa53de2002-05-06 16:49:18 +0000480}
481
Chris Lattnerbb74e222003-03-10 23:06:50 +0000482static inline Value *dyn_castNotVal(Value *V) {
483 if (BinaryOperator::isNot(V))
Chris Lattnerd6f636a2005-04-24 07:30:14 +0000484 return BinaryOperator::getNotArgument(V);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000485
486 // Constants can be considered to be not'ed values...
Zhou Sheng75b871f2007-01-11 12:24:14 +0000487 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Chris Lattnerc8e7e292004-06-10 02:12:35 +0000488 return ConstantExpr::getNot(C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000489 return 0;
490}
491
Chris Lattner7fb29e12003-03-11 00:12:48 +0000492// dyn_castFoldableMul - If this value is a multiply that can be folded into
493// other computations (because it has a constant operand), return the
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000494// non-constant operand of the multiply, and set CST to point to the multiplier.
495// Otherwise, return null.
Chris Lattner7fb29e12003-03-11 00:12:48 +0000496//
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000497static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000498 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000499 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattner7fb29e12003-03-11 00:12:48 +0000500 if (I->getOpcode() == Instruction::Mul)
Chris Lattner970136362004-11-15 05:54:07 +0000501 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattner7fb29e12003-03-11 00:12:48 +0000502 return I->getOperand(0);
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000503 if (I->getOpcode() == Instruction::Shl)
Chris Lattner970136362004-11-15 05:54:07 +0000504 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000505 // The multiplier is really 1 << CST.
506 Constant *One = ConstantInt::get(V->getType(), 1);
507 CST = cast<ConstantInt>(ConstantExpr::getShl(One, CST));
508 return I->getOperand(0);
509 }
510 }
Chris Lattner7fb29e12003-03-11 00:12:48 +0000511 return 0;
Chris Lattner3082c5a2003-02-18 19:28:33 +0000512}
Chris Lattner31ae8632002-08-14 17:51:49 +0000513
Chris Lattner0798af32005-01-13 20:14:25 +0000514/// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
515/// expression, return it.
516static User *dyn_castGetElementPtr(Value *V) {
517 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
518 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
519 if (CE->getOpcode() == Instruction::GetElementPtr)
520 return cast<User>(V);
521 return false;
522}
523
Chris Lattner623826c2004-09-28 21:48:02 +0000524// AddOne, SubOne - Add or subtract a constant one from an integer constant...
Chris Lattner6862fbd2004-09-29 17:40:11 +0000525static ConstantInt *AddOne(ConstantInt *C) {
526 return cast<ConstantInt>(ConstantExpr::getAdd(C,
527 ConstantInt::get(C->getType(), 1)));
Chris Lattner623826c2004-09-28 21:48:02 +0000528}
Chris Lattner6862fbd2004-09-29 17:40:11 +0000529static ConstantInt *SubOne(ConstantInt *C) {
530 return cast<ConstantInt>(ConstantExpr::getSub(C,
531 ConstantInt::get(C->getType(), 1)));
Chris Lattner623826c2004-09-28 21:48:02 +0000532}
533
Chris Lattner0157e7f2006-02-11 09:31:47 +0000534
Chris Lattner4534dd592006-02-09 07:38:58 +0000535/// ComputeMaskedBits - Determine which of the bits specified in Mask are
536/// known to be either zero or one and return them in the KnownZero/KnownOne
537/// bitsets. This code only analyzes bits in Mask, in order to short-circuit
538/// processing.
539static void ComputeMaskedBits(Value *V, uint64_t Mask, uint64_t &KnownZero,
540 uint64_t &KnownOne, unsigned Depth = 0) {
Chris Lattner0b3557f2005-09-24 23:43:33 +0000541 // Note, we cannot consider 'undef' to be "IsZero" here. The problem is that
542 // we cannot optimize based on the assumption that it is zero without changing
Chris Lattnerc3ebf402006-02-07 07:27:52 +0000543 // it to be an explicit zero. If we don't change it to zero, other code could
Chris Lattner0b3557f2005-09-24 23:43:33 +0000544 // optimized based on the contradictory assumption that it is non-zero.
545 // Because instcombine aggressively folds operations with undef args anyway,
546 // this won't lose us code quality.
Zhou Sheng75b871f2007-01-11 12:24:14 +0000547 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
Chris Lattner4534dd592006-02-09 07:38:58 +0000548 // We know all of the bits for a constant!
Chris Lattner0157e7f2006-02-11 09:31:47 +0000549 KnownOne = CI->getZExtValue() & Mask;
Chris Lattner4534dd592006-02-09 07:38:58 +0000550 KnownZero = ~KnownOne & Mask;
551 return;
552 }
553
554 KnownZero = KnownOne = 0; // Don't know anything.
Chris Lattner92a68652006-02-07 08:05:22 +0000555 if (Depth == 6 || Mask == 0)
Chris Lattner4534dd592006-02-09 07:38:58 +0000556 return; // Limit search depth.
557
558 uint64_t KnownZero2, KnownOne2;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000559 Instruction *I = dyn_cast<Instruction>(V);
560 if (!I) return;
561
Chris Lattnerfb296922006-05-04 17:33:35 +0000562 Mask &= V->getType()->getIntegralTypeMask();
563
Chris Lattner0157e7f2006-02-11 09:31:47 +0000564 switch (I->getOpcode()) {
565 case Instruction::And:
566 // If either the LHS or the RHS are Zero, the result is zero.
567 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
568 Mask &= ~KnownZero;
569 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
570 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
571 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
572
573 // Output known-1 bits are only known if set in both the LHS & RHS.
574 KnownOne &= KnownOne2;
575 // Output known-0 are known to be clear if zero in either the LHS | RHS.
576 KnownZero |= KnownZero2;
577 return;
578 case Instruction::Or:
579 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
580 Mask &= ~KnownOne;
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-0 bits are only known if clear in both the LHS & RHS.
586 KnownZero &= KnownZero2;
587 // Output known-1 are known to be set if set in either the LHS | RHS.
588 KnownOne |= KnownOne2;
589 return;
590 case Instruction::Xor: {
591 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
592 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
593 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
594 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
595
596 // Output known-0 bits are known if clear or set in both the LHS & RHS.
597 uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
598 // Output known-1 are known to be set if set in only one of the LHS, RHS.
599 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
600 KnownZero = KnownZeroOut;
601 return;
602 }
603 case Instruction::Select:
604 ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
605 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
606 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
607 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
608
609 // Only known if known in both the LHS and RHS.
610 KnownOne &= KnownOne2;
611 KnownZero &= KnownZero2;
612 return;
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000613 case Instruction::FPTrunc:
614 case Instruction::FPExt:
615 case Instruction::FPToUI:
616 case Instruction::FPToSI:
617 case Instruction::SIToFP:
618 case Instruction::PtrToInt:
619 case Instruction::UIToFP:
620 case Instruction::IntToPtr:
621 return; // Can't work with floating point or pointers
622 case Instruction::Trunc:
623 // All these have integer operands
624 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
625 return;
626 case Instruction::BitCast: {
Chris Lattner0157e7f2006-02-11 09:31:47 +0000627 const Type *SrcTy = I->getOperand(0)->getType();
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000628 if (SrcTy->isIntegral()) {
Chris Lattner0157e7f2006-02-11 09:31:47 +0000629 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
Chris Lattner4534dd592006-02-09 07:38:58 +0000630 return;
631 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000632 break;
633 }
634 case Instruction::ZExt: {
635 // Compute the bits in the result that are not present in the input.
636 const Type *SrcTy = I->getOperand(0)->getType();
Chris Lattner0157e7f2006-02-11 09:31:47 +0000637 uint64_t NotIn = ~SrcTy->getIntegralTypeMask();
638 uint64_t NewBits = I->getType()->getIntegralTypeMask() & NotIn;
Chris Lattner62010c42005-10-09 06:36:35 +0000639
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000640 Mask &= SrcTy->getIntegralTypeMask();
641 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
642 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
643 // The top bits are known to be zero.
644 KnownZero |= NewBits;
645 return;
646 }
647 case Instruction::SExt: {
648 // Compute the bits in the result that are not present in the input.
649 const Type *SrcTy = I->getOperand(0)->getType();
650 uint64_t NotIn = ~SrcTy->getIntegralTypeMask();
651 uint64_t NewBits = I->getType()->getIntegralTypeMask() & NotIn;
652
653 Mask &= SrcTy->getIntegralTypeMask();
654 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
655 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattner92a68652006-02-07 08:05:22 +0000656
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000657 // If the sign bit of the input is known set or clear, then we know the
658 // top bits of the result.
659 uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
660 if (KnownZero & InSignBit) { // Input sign bit known zero
661 KnownZero |= NewBits;
662 KnownOne &= ~NewBits;
663 } else if (KnownOne & InSignBit) { // Input sign bit known set
664 KnownOne |= NewBits;
665 KnownZero &= ~NewBits;
666 } else { // Input sign bit unknown
667 KnownZero &= ~NewBits;
668 KnownOne &= ~NewBits;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000669 }
670 return;
671 }
672 case Instruction::Shl:
673 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
Reid Spencere0fc4df2006-10-20 07:07:24 +0000674 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
675 uint64_t ShiftAmt = SA->getZExtValue();
676 Mask >>= ShiftAmt;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000677 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
678 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Reid Spencere0fc4df2006-10-20 07:07:24 +0000679 KnownZero <<= ShiftAmt;
680 KnownOne <<= ShiftAmt;
681 KnownZero |= (1ULL << ShiftAmt)-1; // low bits known zero.
Chris Lattner0157e7f2006-02-11 09:31:47 +0000682 return;
683 }
684 break;
Reid Spencerfdff9382006-11-08 06:47:33 +0000685 case Instruction::LShr:
Chris Lattner0157e7f2006-02-11 09:31:47 +0000686 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
Reid Spencere0fc4df2006-10-20 07:07:24 +0000687 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Chris Lattner0157e7f2006-02-11 09:31:47 +0000688 // Compute the new bits that are at the top now.
Reid Spencere0fc4df2006-10-20 07:07:24 +0000689 uint64_t ShiftAmt = SA->getZExtValue();
690 uint64_t HighBits = (1ULL << ShiftAmt)-1;
691 HighBits <<= I->getType()->getPrimitiveSizeInBits()-ShiftAmt;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000692
Reid Spencerfdff9382006-11-08 06:47:33 +0000693 // Unsigned shift right.
694 Mask <<= ShiftAmt;
695 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
696 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
697 KnownZero >>= ShiftAmt;
698 KnownOne >>= ShiftAmt;
699 KnownZero |= HighBits; // high bits known zero.
700 return;
701 }
702 break;
703 case Instruction::AShr:
704 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
705 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
706 // Compute the new bits that are at the top now.
707 uint64_t ShiftAmt = SA->getZExtValue();
708 uint64_t HighBits = (1ULL << ShiftAmt)-1;
709 HighBits <<= I->getType()->getPrimitiveSizeInBits()-ShiftAmt;
710
711 // Signed shift right.
712 Mask <<= ShiftAmt;
713 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
714 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
715 KnownZero >>= ShiftAmt;
716 KnownOne >>= ShiftAmt;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000717
Reid Spencerfdff9382006-11-08 06:47:33 +0000718 // Handle the sign bits.
719 uint64_t SignBit = 1ULL << (I->getType()->getPrimitiveSizeInBits()-1);
720 SignBit >>= ShiftAmt; // Adjust to where it is now in the mask.
Chris Lattner0157e7f2006-02-11 09:31:47 +0000721
Reid Spencerfdff9382006-11-08 06:47:33 +0000722 if (KnownZero & SignBit) { // New bits are known zero.
723 KnownZero |= HighBits;
724 } else if (KnownOne & SignBit) { // New bits are known one.
725 KnownOne |= HighBits;
Chris Lattner4534dd592006-02-09 07:38:58 +0000726 }
727 return;
Chris Lattner62010c42005-10-09 06:36:35 +0000728 }
Chris Lattner0157e7f2006-02-11 09:31:47 +0000729 break;
Chris Lattner0b3557f2005-09-24 23:43:33 +0000730 }
Chris Lattner92a68652006-02-07 08:05:22 +0000731}
732
733/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
734/// this predicate to simplify operations downstream. Mask is known to be zero
735/// for bits that V cannot have.
736static bool MaskedValueIsZero(Value *V, uint64_t Mask, unsigned Depth = 0) {
Chris Lattner4534dd592006-02-09 07:38:58 +0000737 uint64_t KnownZero, KnownOne;
738 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
739 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
740 return (KnownZero & Mask) == Mask;
Chris Lattner0b3557f2005-09-24 23:43:33 +0000741}
742
Chris Lattner0157e7f2006-02-11 09:31:47 +0000743/// ShrinkDemandedConstant - Check to see if the specified operand of the
744/// specified instruction is a constant integer. If so, check to see if there
745/// are any bits set in the constant that are not demanded. If so, shrink the
746/// constant and return true.
747static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
748 uint64_t Demanded) {
749 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
750 if (!OpC) return false;
751
752 // If there are no bits set that aren't demanded, nothing to do.
753 if ((~Demanded & OpC->getZExtValue()) == 0)
754 return false;
755
756 // This is producing any bits that are not needed, shrink the RHS.
757 uint64_t Val = Demanded & OpC->getZExtValue();
Zhou Sheng75b871f2007-01-11 12:24:14 +0000758 I->setOperand(OpNo, ConstantInt::get(OpC->getType(), Val));
Chris Lattner0157e7f2006-02-11 09:31:47 +0000759 return true;
760}
761
Chris Lattneree0f2802006-02-12 02:07:56 +0000762// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
763// set of known zero and one bits, compute the maximum and minimum values that
764// could have the specified known zero and known one bits, returning them in
765// min/max.
766static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
767 uint64_t KnownZero,
768 uint64_t KnownOne,
769 int64_t &Min, int64_t &Max) {
770 uint64_t TypeBits = Ty->getIntegralTypeMask();
771 uint64_t UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
772
773 uint64_t SignBit = 1ULL << (Ty->getPrimitiveSizeInBits()-1);
774
775 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
776 // bit if it is unknown.
777 Min = KnownOne;
778 Max = KnownOne|UnknownBits;
779
780 if (SignBit & UnknownBits) { // Sign bit is unknown
781 Min |= SignBit;
782 Max &= ~SignBit;
783 }
784
785 // Sign extend the min/max values.
786 int ShAmt = 64-Ty->getPrimitiveSizeInBits();
787 Min = (Min << ShAmt) >> ShAmt;
788 Max = (Max << ShAmt) >> ShAmt;
789}
790
791// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
792// a set of known zero and one bits, compute the maximum and minimum values that
793// could have the specified known zero and known one bits, returning them in
794// min/max.
795static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
796 uint64_t KnownZero,
797 uint64_t KnownOne,
798 uint64_t &Min,
799 uint64_t &Max) {
800 uint64_t TypeBits = Ty->getIntegralTypeMask();
801 uint64_t UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
802
803 // The minimum value is when the unknown bits are all zeros.
804 Min = KnownOne;
805 // The maximum value is when the unknown bits are all ones.
806 Max = KnownOne|UnknownBits;
807}
Chris Lattner0157e7f2006-02-11 09:31:47 +0000808
809
810/// SimplifyDemandedBits - Look at V. At this point, we know that only the
811/// DemandedMask bits of the result of V are ever used downstream. If we can
812/// use this information to simplify V, do so and return true. Otherwise,
813/// analyze the expression and return a mask of KnownOne and KnownZero bits for
814/// the expression (used to simplify the caller). The KnownZero/One bits may
815/// only be accurate for those bits in the DemandedMask.
816bool InstCombiner::SimplifyDemandedBits(Value *V, uint64_t DemandedMask,
817 uint64_t &KnownZero, uint64_t &KnownOne,
Chris Lattner2590e512006-02-07 06:56:34 +0000818 unsigned Depth) {
Zhou Sheng75b871f2007-01-11 12:24:14 +0000819 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
Chris Lattner0157e7f2006-02-11 09:31:47 +0000820 // We know all of the bits for a constant!
821 KnownOne = CI->getZExtValue() & DemandedMask;
822 KnownZero = ~KnownOne & DemandedMask;
823 return false;
824 }
825
826 KnownZero = KnownOne = 0;
Chris Lattner2590e512006-02-07 06:56:34 +0000827 if (!V->hasOneUse()) { // Other users may use these bits.
Chris Lattner0157e7f2006-02-11 09:31:47 +0000828 if (Depth != 0) { // Not at the root.
829 // Just compute the KnownZero/KnownOne bits to simplify things downstream.
830 ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
Chris Lattner2590e512006-02-07 06:56:34 +0000831 return false;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000832 }
Chris Lattner2590e512006-02-07 06:56:34 +0000833 // If this is the root being simplified, allow it to have multiple uses,
Chris Lattner0157e7f2006-02-11 09:31:47 +0000834 // just set the DemandedMask to all bits.
835 DemandedMask = V->getType()->getIntegralTypeMask();
836 } else if (DemandedMask == 0) { // Not demanding any bits from V.
Chris Lattner92a68652006-02-07 08:05:22 +0000837 if (V != UndefValue::get(V->getType()))
838 return UpdateValueUsesWith(V, UndefValue::get(V->getType()));
839 return false;
Chris Lattner2590e512006-02-07 06:56:34 +0000840 } else if (Depth == 6) { // Limit search depth.
841 return false;
842 }
843
844 Instruction *I = dyn_cast<Instruction>(V);
845 if (!I) return false; // Only analyze instructions.
846
Chris Lattnerfb296922006-05-04 17:33:35 +0000847 DemandedMask &= V->getType()->getIntegralTypeMask();
848
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000849 uint64_t KnownZero2 = 0, KnownOne2 = 0;
Chris Lattner2590e512006-02-07 06:56:34 +0000850 switch (I->getOpcode()) {
851 default: break;
852 case Instruction::And:
Chris Lattner0157e7f2006-02-11 09:31:47 +0000853 // If either the LHS or the RHS are Zero, the result is zero.
854 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
855 KnownZero, KnownOne, Depth+1))
856 return true;
857 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
858
859 // If something is known zero on the RHS, the bits aren't demanded on the
860 // LHS.
861 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownZero,
862 KnownZero2, KnownOne2, Depth+1))
863 return true;
864 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
865
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000866 // If all of the demanded bits are known 1 on one side, return the other.
Chris Lattner0157e7f2006-02-11 09:31:47 +0000867 // These bits cannot contribute to the result of the 'and'.
868 if ((DemandedMask & ~KnownZero2 & KnownOne) == (DemandedMask & ~KnownZero2))
869 return UpdateValueUsesWith(I, I->getOperand(0));
870 if ((DemandedMask & ~KnownZero & KnownOne2) == (DemandedMask & ~KnownZero))
871 return UpdateValueUsesWith(I, I->getOperand(1));
Chris Lattner5b2edb12006-02-12 08:02:11 +0000872
873 // If all of the demanded bits in the inputs are known zeros, return zero.
874 if ((DemandedMask & (KnownZero|KnownZero2)) == DemandedMask)
875 return UpdateValueUsesWith(I, Constant::getNullValue(I->getType()));
876
Chris Lattner0157e7f2006-02-11 09:31:47 +0000877 // If the RHS is a constant, see if we can simplify it.
Chris Lattner5b2edb12006-02-12 08:02:11 +0000878 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~KnownZero2))
Chris Lattner0157e7f2006-02-11 09:31:47 +0000879 return UpdateValueUsesWith(I, I);
880
881 // Output known-1 bits are only known if set in both the LHS & RHS.
882 KnownOne &= KnownOne2;
883 // Output known-0 are known to be clear if zero in either the LHS | RHS.
884 KnownZero |= KnownZero2;
885 break;
886 case Instruction::Or:
887 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
888 KnownZero, KnownOne, Depth+1))
889 return true;
890 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
891 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownOne,
892 KnownZero2, KnownOne2, Depth+1))
893 return true;
894 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
895
896 // If all of the demanded bits are known zero on one side, return the other.
897 // These bits cannot contribute to the result of the 'or'.
Jeff Cohen0add83e2006-02-18 03:20:33 +0000898 if ((DemandedMask & ~KnownOne2 & KnownZero) == (DemandedMask & ~KnownOne2))
Chris Lattner0157e7f2006-02-11 09:31:47 +0000899 return UpdateValueUsesWith(I, I->getOperand(0));
Jeff Cohen0add83e2006-02-18 03:20:33 +0000900 if ((DemandedMask & ~KnownOne & KnownZero2) == (DemandedMask & ~KnownOne))
Chris Lattner0157e7f2006-02-11 09:31:47 +0000901 return UpdateValueUsesWith(I, I->getOperand(1));
Chris Lattner5b2edb12006-02-12 08:02:11 +0000902
903 // If all of the potentially set bits on one side are known to be set on
904 // the other side, just use the 'other' side.
905 if ((DemandedMask & (~KnownZero) & KnownOne2) ==
906 (DemandedMask & (~KnownZero)))
907 return UpdateValueUsesWith(I, I->getOperand(0));
Nate Begeman8a77efe2006-02-16 21:11:51 +0000908 if ((DemandedMask & (~KnownZero2) & KnownOne) ==
909 (DemandedMask & (~KnownZero2)))
910 return UpdateValueUsesWith(I, I->getOperand(1));
Chris Lattner0157e7f2006-02-11 09:31:47 +0000911
912 // If the RHS is a constant, see if we can simplify it.
913 if (ShrinkDemandedConstant(I, 1, DemandedMask))
914 return UpdateValueUsesWith(I, I);
915
916 // Output known-0 bits are only known if clear in both the LHS & RHS.
917 KnownZero &= KnownZero2;
918 // Output known-1 are known to be set if set in either the LHS | RHS.
919 KnownOne |= KnownOne2;
920 break;
921 case Instruction::Xor: {
922 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
923 KnownZero, KnownOne, Depth+1))
924 return true;
925 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
926 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
927 KnownZero2, KnownOne2, Depth+1))
928 return true;
929 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
930
931 // If all of the demanded bits are known zero on one side, return the other.
932 // These bits cannot contribute to the result of the 'xor'.
933 if ((DemandedMask & KnownZero) == DemandedMask)
934 return UpdateValueUsesWith(I, I->getOperand(0));
935 if ((DemandedMask & KnownZero2) == DemandedMask)
936 return UpdateValueUsesWith(I, I->getOperand(1));
937
938 // Output known-0 bits are known if clear or set in both the LHS & RHS.
939 uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
940 // Output known-1 are known to be set if set in only one of the LHS, RHS.
941 uint64_t KnownOneOut = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
942
Chris Lattner8e9a7b72006-11-27 19:55:07 +0000943 // If all of the demanded bits are known to be zero on one side or the
944 // other, turn this into an *inclusive* or.
Chris Lattner5b2edb12006-02-12 08:02:11 +0000945 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattner8e9a7b72006-11-27 19:55:07 +0000946 if ((DemandedMask & ~KnownZero & ~KnownZero2) == 0) {
947 Instruction *Or =
948 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
949 I->getName());
950 InsertNewInstBefore(Or, *I);
951 return UpdateValueUsesWith(I, Or);
Chris Lattner2590e512006-02-07 06:56:34 +0000952 }
Chris Lattner0157e7f2006-02-11 09:31:47 +0000953
Chris Lattner5b2edb12006-02-12 08:02:11 +0000954 // If all of the demanded bits on one side are known, and all of the set
955 // bits on that side are also known to be set on the other side, turn this
956 // into an AND, as we know the bits will be cleared.
957 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
958 if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask) { // all known
959 if ((KnownOne & KnownOne2) == KnownOne) {
Zhou Sheng75b871f2007-01-11 12:24:14 +0000960 Constant *AndC = ConstantInt::get(I->getType(),
961 ~KnownOne & DemandedMask);
Chris Lattner5b2edb12006-02-12 08:02:11 +0000962 Instruction *And =
963 BinaryOperator::createAnd(I->getOperand(0), AndC, "tmp");
964 InsertNewInstBefore(And, *I);
965 return UpdateValueUsesWith(I, And);
966 }
967 }
968
Chris Lattner0157e7f2006-02-11 09:31:47 +0000969 // If the RHS is a constant, see if we can simplify it.
970 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
971 if (ShrinkDemandedConstant(I, 1, DemandedMask))
972 return UpdateValueUsesWith(I, I);
973
974 KnownZero = KnownZeroOut;
975 KnownOne = KnownOneOut;
976 break;
977 }
978 case Instruction::Select:
979 if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
980 KnownZero, KnownOne, Depth+1))
981 return true;
982 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
983 KnownZero2, KnownOne2, Depth+1))
984 return true;
985 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
986 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
987
988 // If the operands are constants, see if we can simplify them.
989 if (ShrinkDemandedConstant(I, 1, DemandedMask))
990 return UpdateValueUsesWith(I, I);
991 if (ShrinkDemandedConstant(I, 2, DemandedMask))
992 return UpdateValueUsesWith(I, I);
993
994 // Only known if known in both the LHS and RHS.
995 KnownOne &= KnownOne2;
996 KnownZero &= KnownZero2;
997 break;
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000998 case Instruction::Trunc:
999 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1000 KnownZero, KnownOne, Depth+1))
1001 return true;
1002 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1003 break;
1004 case Instruction::BitCast:
1005 if (!I->getOperand(0)->getType()->isIntegral())
1006 return false;
Chris Lattner850465d2006-09-16 03:14:10 +00001007
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001008 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1009 KnownZero, KnownOne, Depth+1))
1010 return true;
1011 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1012 break;
1013 case Instruction::ZExt: {
1014 // Compute the bits in the result that are not present in the input.
1015 const Type *SrcTy = I->getOperand(0)->getType();
Chris Lattner0157e7f2006-02-11 09:31:47 +00001016 uint64_t NotIn = ~SrcTy->getIntegralTypeMask();
1017 uint64_t NewBits = I->getType()->getIntegralTypeMask() & NotIn;
1018
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001019 DemandedMask &= SrcTy->getIntegralTypeMask();
1020 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 // The top bits are known to be zero.
1025 KnownZero |= NewBits;
1026 break;
1027 }
1028 case Instruction::SExt: {
1029 // Compute the bits in the result that are not present in the input.
1030 const Type *SrcTy = I->getOperand(0)->getType();
1031 uint64_t NotIn = ~SrcTy->getIntegralTypeMask();
1032 uint64_t NewBits = I->getType()->getIntegralTypeMask() & NotIn;
1033
1034 // Get the sign bit for the source type
1035 uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
1036 int64_t InputDemandedBits = DemandedMask & SrcTy->getIntegralTypeMask();
Chris Lattner7d852282006-02-13 22:41:07 +00001037
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001038 // If any of the sign extended bits are demanded, we know that the sign
1039 // bit is demanded.
1040 if (NewBits & DemandedMask)
1041 InputDemandedBits |= InSignBit;
Chris Lattner7d852282006-02-13 22:41:07 +00001042
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001043 if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
1044 KnownZero, KnownOne, Depth+1))
1045 return true;
1046 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattner0157e7f2006-02-11 09:31:47 +00001047
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001048 // If the sign bit of the input is known set or clear, then we know the
1049 // top bits of the result.
Chris Lattner2590e512006-02-07 06:56:34 +00001050
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001051 // If the input sign bit is known zero, or if the NewBits are not demanded
1052 // convert this into a zero extension.
1053 if ((KnownZero & InSignBit) || (NewBits & ~DemandedMask) == NewBits) {
1054 // Convert to ZExt cast
1055 CastInst *NewCast = CastInst::create(
1056 Instruction::ZExt, I->getOperand(0), I->getType(), I->getName(), I);
1057 return UpdateValueUsesWith(I, NewCast);
1058 } else if (KnownOne & InSignBit) { // Input sign bit known set
1059 KnownOne |= NewBits;
1060 KnownZero &= ~NewBits;
1061 } else { // Input sign bit unknown
1062 KnownZero &= ~NewBits;
1063 KnownOne &= ~NewBits;
Chris Lattner2590e512006-02-07 06:56:34 +00001064 }
Chris Lattner0157e7f2006-02-11 09:31:47 +00001065 break;
Chris Lattner2590e512006-02-07 06:56:34 +00001066 }
Chris Lattner6e2c15c2006-11-09 05:12:27 +00001067 case Instruction::Add:
1068 // If there is a constant on the RHS, there are a variety of xformations
1069 // we can do.
1070 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1071 // If null, this should be simplified elsewhere. Some of the xforms here
1072 // won't work if the RHS is zero.
1073 if (RHS->isNullValue())
1074 break;
1075
1076 // Figure out what the input bits are. If the top bits of the and result
1077 // are not demanded, then the add doesn't demand them from its input
1078 // either.
1079
1080 // Shift the demanded mask up so that it's at the top of the uint64_t.
1081 unsigned BitWidth = I->getType()->getPrimitiveSizeInBits();
1082 unsigned NLZ = CountLeadingZeros_64(DemandedMask << (64-BitWidth));
1083
1084 // If the top bit of the output is demanded, demand everything from the
1085 // input. Otherwise, we demand all the input bits except NLZ top bits.
Jeff Cohen223004c2007-01-08 20:17:17 +00001086 uint64_t InDemandedBits = ~0ULL >> (64-BitWidth+NLZ);
Chris Lattner6e2c15c2006-11-09 05:12:27 +00001087
1088 // Find information about known zero/one bits in the input.
1089 if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits,
1090 KnownZero2, KnownOne2, Depth+1))
1091 return true;
1092
1093 // If the RHS of the add has bits set that can't affect the input, reduce
1094 // the constant.
1095 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1096 return UpdateValueUsesWith(I, I);
1097
1098 // Avoid excess work.
1099 if (KnownZero2 == 0 && KnownOne2 == 0)
1100 break;
1101
1102 // Turn it into OR if input bits are zero.
1103 if ((KnownZero2 & RHS->getZExtValue()) == RHS->getZExtValue()) {
1104 Instruction *Or =
1105 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1106 I->getName());
1107 InsertNewInstBefore(Or, *I);
1108 return UpdateValueUsesWith(I, Or);
1109 }
1110
1111 // We can say something about the output known-zero and known-one bits,
1112 // depending on potential carries from the input constant and the
1113 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1114 // bits set and the RHS constant is 0x01001, then we know we have a known
1115 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1116
1117 // To compute this, we first compute the potential carry bits. These are
1118 // the bits which may be modified. I'm not aware of a better way to do
1119 // this scan.
1120 uint64_t RHSVal = RHS->getZExtValue();
1121
1122 bool CarryIn = false;
1123 uint64_t CarryBits = 0;
1124 uint64_t CurBit = 1;
1125 for (unsigned i = 0; i != BitWidth; ++i, CurBit <<= 1) {
1126 // Record the current carry in.
1127 if (CarryIn) CarryBits |= CurBit;
1128
1129 bool CarryOut;
1130
1131 // This bit has a carry out unless it is "zero + zero" or
1132 // "zero + anything" with no carry in.
1133 if ((KnownZero2 & CurBit) && ((RHSVal & CurBit) == 0)) {
1134 CarryOut = false; // 0 + 0 has no carry out, even with carry in.
1135 } else if (!CarryIn &&
1136 ((KnownZero2 & CurBit) || ((RHSVal & CurBit) == 0))) {
1137 CarryOut = false; // 0 + anything has no carry out if no carry in.
1138 } else {
1139 // Otherwise, we have to assume we have a carry out.
1140 CarryOut = true;
1141 }
1142
1143 // This stage's carry out becomes the next stage's carry-in.
1144 CarryIn = CarryOut;
1145 }
1146
1147 // Now that we know which bits have carries, compute the known-1/0 sets.
1148
1149 // Bits are known one if they are known zero in one operand and one in the
1150 // other, and there is no input carry.
1151 KnownOne = ((KnownZero2 & RHSVal) | (KnownOne2 & ~RHSVal)) & ~CarryBits;
1152
1153 // Bits are known zero if they are known zero in both operands and there
1154 // is no input carry.
1155 KnownZero = KnownZero2 & ~RHSVal & ~CarryBits;
1156 }
1157 break;
Chris Lattner2590e512006-02-07 06:56:34 +00001158 case Instruction::Shl:
Reid Spencere0fc4df2006-10-20 07:07:24 +00001159 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1160 uint64_t ShiftAmt = SA->getZExtValue();
1161 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask >> ShiftAmt,
Chris Lattner0157e7f2006-02-11 09:31:47 +00001162 KnownZero, KnownOne, Depth+1))
1163 return true;
1164 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Reid Spencere0fc4df2006-10-20 07:07:24 +00001165 KnownZero <<= ShiftAmt;
1166 KnownOne <<= ShiftAmt;
1167 KnownZero |= (1ULL << ShiftAmt) - 1; // low bits known zero.
Chris Lattner0157e7f2006-02-11 09:31:47 +00001168 }
Chris Lattner2590e512006-02-07 06:56:34 +00001169 break;
Reid Spencerfdff9382006-11-08 06:47:33 +00001170 case Instruction::LShr:
1171 // For a logical shift right
1172 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1173 unsigned ShiftAmt = SA->getZExtValue();
1174
1175 // Compute the new bits that are at the top now.
1176 uint64_t HighBits = (1ULL << ShiftAmt)-1;
1177 HighBits <<= I->getType()->getPrimitiveSizeInBits() - ShiftAmt;
1178 uint64_t TypeMask = I->getType()->getIntegralTypeMask();
1179 // Unsigned shift right.
1180 if (SimplifyDemandedBits(I->getOperand(0),
1181 (DemandedMask << ShiftAmt) & TypeMask,
1182 KnownZero, KnownOne, Depth+1))
1183 return true;
1184 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1185 KnownZero &= TypeMask;
1186 KnownOne &= TypeMask;
1187 KnownZero >>= ShiftAmt;
1188 KnownOne >>= ShiftAmt;
1189 KnownZero |= HighBits; // high bits known zero.
1190 }
1191 break;
1192 case Instruction::AShr:
Chris Lattner420c4bc2006-09-18 04:31:40 +00001193 // If this is an arithmetic shift right and only the low-bit is set, we can
1194 // always convert this into a logical shr, even if the shift amount is
1195 // variable. The low bit of the shift cannot be an input sign bit unless
1196 // the shift amount is >= the size of the datatype, which is undefined.
Reid Spencerfdff9382006-11-08 06:47:33 +00001197 if (DemandedMask == 1) {
1198 // Perform the logical shift right.
1199 Value *NewVal = new ShiftInst(Instruction::LShr, I->getOperand(0),
1200 I->getOperand(1), I->getName());
Reid Spencer00c482b2006-10-26 19:19:06 +00001201 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
Chris Lattner420c4bc2006-09-18 04:31:40 +00001202 return UpdateValueUsesWith(I, NewVal);
1203 }
1204
Reid Spencere0fc4df2006-10-20 07:07:24 +00001205 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1206 unsigned ShiftAmt = SA->getZExtValue();
Chris Lattner0157e7f2006-02-11 09:31:47 +00001207
1208 // Compute the new bits that are at the top now.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001209 uint64_t HighBits = (1ULL << ShiftAmt)-1;
1210 HighBits <<= I->getType()->getPrimitiveSizeInBits() - ShiftAmt;
Chris Lattner68e74752006-02-13 06:09:08 +00001211 uint64_t TypeMask = I->getType()->getIntegralTypeMask();
Reid Spencerfdff9382006-11-08 06:47:33 +00001212 // Signed shift right.
1213 if (SimplifyDemandedBits(I->getOperand(0),
1214 (DemandedMask << ShiftAmt) & TypeMask,
1215 KnownZero, KnownOne, Depth+1))
1216 return true;
1217 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1218 KnownZero &= TypeMask;
1219 KnownOne &= TypeMask;
1220 KnownZero >>= ShiftAmt;
1221 KnownOne >>= ShiftAmt;
Chris Lattner0157e7f2006-02-11 09:31:47 +00001222
Reid Spencerfdff9382006-11-08 06:47:33 +00001223 // Handle the sign bits.
1224 uint64_t SignBit = 1ULL << (I->getType()->getPrimitiveSizeInBits()-1);
1225 SignBit >>= ShiftAmt; // Adjust to where it is now in the mask.
Chris Lattner0157e7f2006-02-11 09:31:47 +00001226
Reid Spencerfdff9382006-11-08 06:47:33 +00001227 // If the input sign bit is known to be zero, or if none of the top bits
1228 // are demanded, turn this into an unsigned shift right.
1229 if ((KnownZero & SignBit) || (HighBits & ~DemandedMask) == HighBits) {
1230 // Perform the logical shift right.
1231 Value *NewVal = new ShiftInst(Instruction::LShr, I->getOperand(0),
1232 SA, I->getName());
1233 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1234 return UpdateValueUsesWith(I, NewVal);
1235 } else if (KnownOne & SignBit) { // New bits are known one.
1236 KnownOne |= HighBits;
Chris Lattner2590e512006-02-07 06:56:34 +00001237 }
Chris Lattner0157e7f2006-02-11 09:31:47 +00001238 }
Chris Lattner2590e512006-02-07 06:56:34 +00001239 break;
1240 }
Chris Lattner0157e7f2006-02-11 09:31:47 +00001241
1242 // If the client is only demanding bits that we know, return the known
1243 // constant.
1244 if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask)
Zhou Sheng75b871f2007-01-11 12:24:14 +00001245 return UpdateValueUsesWith(I, ConstantInt::get(I->getType(), KnownOne));
Chris Lattner2590e512006-02-07 06:56:34 +00001246 return false;
1247}
1248
Chris Lattner2deeaea2006-10-05 06:55:50 +00001249
1250/// SimplifyDemandedVectorElts - The specified value producecs a vector with
1251/// 64 or fewer elements. DemandedElts contains the set of elements that are
1252/// actually used by the caller. This method analyzes which elements of the
1253/// operand are undef and returns that information in UndefElts.
1254///
1255/// If the information about demanded elements can be used to simplify the
1256/// operation, the operation is simplified, then the resultant value is
1257/// returned. This returns null if no change was made.
1258Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1259 uint64_t &UndefElts,
1260 unsigned Depth) {
1261 unsigned VWidth = cast<PackedType>(V->getType())->getNumElements();
1262 assert(VWidth <= 64 && "Vector too wide to analyze!");
1263 uint64_t EltMask = ~0ULL >> (64-VWidth);
1264 assert(DemandedElts != EltMask && (DemandedElts & ~EltMask) == 0 &&
1265 "Invalid DemandedElts!");
1266
1267 if (isa<UndefValue>(V)) {
1268 // If the entire vector is undefined, just return this info.
1269 UndefElts = EltMask;
1270 return 0;
1271 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1272 UndefElts = EltMask;
1273 return UndefValue::get(V->getType());
1274 }
1275
1276 UndefElts = 0;
1277 if (ConstantPacked *CP = dyn_cast<ConstantPacked>(V)) {
1278 const Type *EltTy = cast<PackedType>(V->getType())->getElementType();
1279 Constant *Undef = UndefValue::get(EltTy);
1280
1281 std::vector<Constant*> Elts;
1282 for (unsigned i = 0; i != VWidth; ++i)
1283 if (!(DemandedElts & (1ULL << i))) { // If not demanded, set to undef.
1284 Elts.push_back(Undef);
1285 UndefElts |= (1ULL << i);
1286 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1287 Elts.push_back(Undef);
1288 UndefElts |= (1ULL << i);
1289 } else { // Otherwise, defined.
1290 Elts.push_back(CP->getOperand(i));
1291 }
1292
1293 // If we changed the constant, return it.
1294 Constant *NewCP = ConstantPacked::get(Elts);
1295 return NewCP != CP ? NewCP : 0;
1296 } else if (isa<ConstantAggregateZero>(V)) {
1297 // Simplify the CAZ to a ConstantPacked where the non-demanded elements are
1298 // set to undef.
1299 const Type *EltTy = cast<PackedType>(V->getType())->getElementType();
1300 Constant *Zero = Constant::getNullValue(EltTy);
1301 Constant *Undef = UndefValue::get(EltTy);
1302 std::vector<Constant*> Elts;
1303 for (unsigned i = 0; i != VWidth; ++i)
1304 Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1305 UndefElts = DemandedElts ^ EltMask;
1306 return ConstantPacked::get(Elts);
1307 }
1308
1309 if (!V->hasOneUse()) { // Other users may use these bits.
1310 if (Depth != 0) { // Not at the root.
1311 // TODO: Just compute the UndefElts information recursively.
1312 return false;
1313 }
1314 return false;
1315 } else if (Depth == 10) { // Limit search depth.
1316 return false;
1317 }
1318
1319 Instruction *I = dyn_cast<Instruction>(V);
1320 if (!I) return false; // Only analyze instructions.
1321
1322 bool MadeChange = false;
1323 uint64_t UndefElts2;
1324 Value *TmpV;
1325 switch (I->getOpcode()) {
1326 default: break;
1327
1328 case Instruction::InsertElement: {
1329 // If this is a variable index, we don't know which element it overwrites.
1330 // demand exactly the same input as we produce.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001331 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
Chris Lattner2deeaea2006-10-05 06:55:50 +00001332 if (Idx == 0) {
1333 // Note that we can't propagate undef elt info, because we don't know
1334 // which elt is getting updated.
1335 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1336 UndefElts2, Depth+1);
1337 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1338 break;
1339 }
1340
1341 // If this is inserting an element that isn't demanded, remove this
1342 // insertelement.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001343 unsigned IdxNo = Idx->getZExtValue();
Chris Lattner2deeaea2006-10-05 06:55:50 +00001344 if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1345 return AddSoonDeadInstToWorklist(*I, 0);
1346
1347 // Otherwise, the element inserted overwrites whatever was there, so the
1348 // input demanded set is simpler than the output set.
1349 TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1350 DemandedElts & ~(1ULL << IdxNo),
1351 UndefElts, Depth+1);
1352 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1353
1354 // The inserted element is defined.
1355 UndefElts |= 1ULL << IdxNo;
1356 break;
1357 }
1358
1359 case Instruction::And:
1360 case Instruction::Or:
1361 case Instruction::Xor:
1362 case Instruction::Add:
1363 case Instruction::Sub:
1364 case Instruction::Mul:
1365 // div/rem demand all inputs, because they don't want divide by zero.
1366 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1367 UndefElts, Depth+1);
1368 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1369 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1370 UndefElts2, Depth+1);
1371 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1372
1373 // Output elements are undefined if both are undefined. Consider things
1374 // like undef&0. The result is known zero, not undef.
1375 UndefElts &= UndefElts2;
1376 break;
1377
1378 case Instruction::Call: {
1379 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1380 if (!II) break;
1381 switch (II->getIntrinsicID()) {
1382 default: break;
1383
1384 // Binary vector operations that work column-wise. A dest element is a
1385 // function of the corresponding input elements from the two inputs.
1386 case Intrinsic::x86_sse_sub_ss:
1387 case Intrinsic::x86_sse_mul_ss:
1388 case Intrinsic::x86_sse_min_ss:
1389 case Intrinsic::x86_sse_max_ss:
1390 case Intrinsic::x86_sse2_sub_sd:
1391 case Intrinsic::x86_sse2_mul_sd:
1392 case Intrinsic::x86_sse2_min_sd:
1393 case Intrinsic::x86_sse2_max_sd:
1394 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1395 UndefElts, Depth+1);
1396 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1397 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1398 UndefElts2, Depth+1);
1399 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1400
1401 // If only the low elt is demanded and this is a scalarizable intrinsic,
1402 // scalarize it now.
1403 if (DemandedElts == 1) {
1404 switch (II->getIntrinsicID()) {
1405 default: break;
1406 case Intrinsic::x86_sse_sub_ss:
1407 case Intrinsic::x86_sse_mul_ss:
1408 case Intrinsic::x86_sse2_sub_sd:
1409 case Intrinsic::x86_sse2_mul_sd:
1410 // TODO: Lower MIN/MAX/ABS/etc
1411 Value *LHS = II->getOperand(1);
1412 Value *RHS = II->getOperand(2);
1413 // Extract the element as scalars.
1414 LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1415 RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1416
1417 switch (II->getIntrinsicID()) {
1418 default: assert(0 && "Case stmts out of sync!");
1419 case Intrinsic::x86_sse_sub_ss:
1420 case Intrinsic::x86_sse2_sub_sd:
1421 TmpV = InsertNewInstBefore(BinaryOperator::createSub(LHS, RHS,
1422 II->getName()), *II);
1423 break;
1424 case Intrinsic::x86_sse_mul_ss:
1425 case Intrinsic::x86_sse2_mul_sd:
1426 TmpV = InsertNewInstBefore(BinaryOperator::createMul(LHS, RHS,
1427 II->getName()), *II);
1428 break;
1429 }
1430
1431 Instruction *New =
1432 new InsertElementInst(UndefValue::get(II->getType()), TmpV, 0U,
1433 II->getName());
1434 InsertNewInstBefore(New, *II);
1435 AddSoonDeadInstToWorklist(*II, 0);
1436 return New;
1437 }
1438 }
1439
1440 // Output elements are undefined if both are undefined. Consider things
1441 // like undef&0. The result is known zero, not undef.
1442 UndefElts &= UndefElts2;
1443 break;
1444 }
1445 break;
1446 }
1447 }
1448 return MadeChange ? I : 0;
1449}
1450
Reid Spencer266e42b2006-12-23 06:05:41 +00001451/// @returns true if the specified compare instruction is
1452/// true when both operands are equal...
1453/// @brief Determine if the ICmpInst returns true if both operands are equal
1454static bool isTrueWhenEqual(ICmpInst &ICI) {
1455 ICmpInst::Predicate pred = ICI.getPredicate();
1456 return pred == ICmpInst::ICMP_EQ || pred == ICmpInst::ICMP_UGE ||
1457 pred == ICmpInst::ICMP_SGE || pred == ICmpInst::ICMP_ULE ||
1458 pred == ICmpInst::ICMP_SLE;
1459}
1460
1461/// @returns true if the specified compare instruction is
1462/// true when both operands are equal...
1463/// @brief Determine if the FCmpInst returns true if both operands are equal
1464static bool isTrueWhenEqual(FCmpInst &FCI) {
1465 FCmpInst::Predicate pred = FCI.getPredicate();
1466 return pred == FCmpInst::FCMP_OEQ || pred == FCmpInst::FCMP_UEQ ||
1467 pred == FCmpInst::FCMP_OGE || pred == FCmpInst::FCMP_UGE ||
1468 pred == FCmpInst::FCMP_OLE || pred == FCmpInst::FCMP_ULE;
Chris Lattner623826c2004-09-28 21:48:02 +00001469}
Chris Lattnerb8b97502003-08-13 19:01:45 +00001470
1471/// AssociativeOpt - Perform an optimization on an associative operator. This
1472/// function is designed to check a chain of associative operators for a
1473/// potential to apply a certain optimization. Since the optimization may be
1474/// applicable if the expression was reassociated, this checks the chain, then
1475/// reassociates the expression as necessary to expose the optimization
1476/// opportunity. This makes use of a special Functor, which must define
1477/// 'shouldApply' and 'apply' methods.
1478///
1479template<typename Functor>
1480Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1481 unsigned Opcode = Root.getOpcode();
1482 Value *LHS = Root.getOperand(0);
1483
1484 // Quick check, see if the immediate LHS matches...
1485 if (F.shouldApply(LHS))
1486 return F.apply(Root);
1487
1488 // Otherwise, if the LHS is not of the same opcode as the root, return.
1489 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001490 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattnerb8b97502003-08-13 19:01:45 +00001491 // Should we apply this transform to the RHS?
1492 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1493
1494 // If not to the RHS, check to see if we should apply to the LHS...
1495 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1496 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1497 ShouldApply = true;
1498 }
1499
1500 // If the functor wants to apply the optimization to the RHS of LHSI,
1501 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1502 if (ShouldApply) {
1503 BasicBlock *BB = Root.getParent();
Misha Brukmanb1c93172005-04-21 23:48:37 +00001504
Chris Lattnerb8b97502003-08-13 19:01:45 +00001505 // Now all of the instructions are in the current basic block, go ahead
1506 // and perform the reassociation.
1507 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1508
1509 // First move the selected RHS to the LHS of the root...
1510 Root.setOperand(0, LHSI->getOperand(1));
1511
1512 // Make what used to be the LHS of the root be the user of the root...
1513 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner284d3b02004-04-16 18:08:07 +00001514 if (&Root == TmpLHSI) {
Chris Lattner8953b902004-04-05 02:10:19 +00001515 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1516 return 0;
1517 }
Chris Lattner284d3b02004-04-16 18:08:07 +00001518 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattnerb8b97502003-08-13 19:01:45 +00001519 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner284d3b02004-04-16 18:08:07 +00001520 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
1521 BasicBlock::iterator ARI = &Root; ++ARI;
1522 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
1523 ARI = Root;
Chris Lattnerb8b97502003-08-13 19:01:45 +00001524
1525 // Now propagate the ExtraOperand down the chain of instructions until we
1526 // get to LHSI.
1527 while (TmpLHSI != LHSI) {
1528 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner284d3b02004-04-16 18:08:07 +00001529 // Move the instruction to immediately before the chain we are
1530 // constructing to avoid breaking dominance properties.
1531 NextLHSI->getParent()->getInstList().remove(NextLHSI);
1532 BB->getInstList().insert(ARI, NextLHSI);
1533 ARI = NextLHSI;
1534
Chris Lattnerb8b97502003-08-13 19:01:45 +00001535 Value *NextOp = NextLHSI->getOperand(1);
1536 NextLHSI->setOperand(1, ExtraOperand);
1537 TmpLHSI = NextLHSI;
1538 ExtraOperand = NextOp;
1539 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001540
Chris Lattnerb8b97502003-08-13 19:01:45 +00001541 // Now that the instructions are reassociated, have the functor perform
1542 // the transformation...
1543 return F.apply(Root);
1544 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001545
Chris Lattnerb8b97502003-08-13 19:01:45 +00001546 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1547 }
1548 return 0;
1549}
1550
1551
1552// AddRHS - Implements: X + X --> X << 1
1553struct AddRHS {
1554 Value *RHS;
1555 AddRHS(Value *rhs) : RHS(rhs) {}
1556 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1557 Instruction *apply(BinaryOperator &Add) const {
1558 return new ShiftInst(Instruction::Shl, Add.getOperand(0),
Reid Spencerc635f472006-12-31 05:48:39 +00001559 ConstantInt::get(Type::Int8Ty, 1));
Chris Lattnerb8b97502003-08-13 19:01:45 +00001560 }
1561};
1562
1563// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1564// iff C1&C2 == 0
1565struct AddMaskingAnd {
1566 Constant *C2;
1567 AddMaskingAnd(Constant *c) : C2(c) {}
1568 bool shouldApply(Value *LHS) const {
Chris Lattnerd4252a72004-07-30 07:50:03 +00001569 ConstantInt *C1;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001570 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Chris Lattnerd4252a72004-07-30 07:50:03 +00001571 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattnerb8b97502003-08-13 19:01:45 +00001572 }
1573 Instruction *apply(BinaryOperator &Add) const {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001574 return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattnerb8b97502003-08-13 19:01:45 +00001575 }
1576};
1577
Chris Lattner86102b82005-01-01 16:22:27 +00001578static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner183b3362004-04-09 19:05:30 +00001579 InstCombiner *IC) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001580 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
Chris Lattner86102b82005-01-01 16:22:27 +00001581 if (Constant *SOC = dyn_cast<Constant>(SO))
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001582 return ConstantExpr::getCast(CI->getOpcode(), SOC, I.getType());
Misha Brukmanb1c93172005-04-21 23:48:37 +00001583
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001584 return IC->InsertNewInstBefore(CastInst::create(
1585 CI->getOpcode(), SO, I.getType(), SO->getName() + ".cast"), I);
Chris Lattner86102b82005-01-01 16:22:27 +00001586 }
1587
Chris Lattner183b3362004-04-09 19:05:30 +00001588 // Figure out if the constant is the left or the right argument.
Chris Lattner86102b82005-01-01 16:22:27 +00001589 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1590 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattnerb8b97502003-08-13 19:01:45 +00001591
Chris Lattner183b3362004-04-09 19:05:30 +00001592 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1593 if (ConstIsRHS)
Chris Lattner86102b82005-01-01 16:22:27 +00001594 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1595 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner183b3362004-04-09 19:05:30 +00001596 }
1597
1598 Value *Op0 = SO, *Op1 = ConstOperand;
1599 if (!ConstIsRHS)
1600 std::swap(Op0, Op1);
1601 Instruction *New;
Chris Lattner86102b82005-01-01 16:22:27 +00001602 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1603 New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
Reid Spencer266e42b2006-12-23 06:05:41 +00001604 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1605 New = CmpInst::create(CI->getOpcode(), CI->getPredicate(), Op0, Op1,
1606 SO->getName()+".cmp");
Chris Lattner86102b82005-01-01 16:22:27 +00001607 else if (ShiftInst *SI = dyn_cast<ShiftInst>(&I))
1608 New = new ShiftInst(SI->getOpcode(), Op0, Op1, SO->getName()+".sh");
Chris Lattnerf9d96652004-04-10 19:15:56 +00001609 else {
Chris Lattner183b3362004-04-09 19:05:30 +00001610 assert(0 && "Unknown binary instruction type!");
Chris Lattnerf9d96652004-04-10 19:15:56 +00001611 abort();
1612 }
Chris Lattner86102b82005-01-01 16:22:27 +00001613 return IC->InsertNewInstBefore(New, I);
1614}
1615
1616// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1617// constant as the other operand, try to fold the binary operator into the
1618// select arguments. This also works for Cast instructions, which obviously do
1619// not have a second operand.
1620static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1621 InstCombiner *IC) {
1622 // Don't modify shared select instructions
1623 if (!SI->hasOneUse()) return 0;
1624 Value *TV = SI->getOperand(1);
1625 Value *FV = SI->getOperand(2);
1626
1627 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner374e6592005-04-21 05:43:13 +00001628 // Bool selects with constant operands can be folded to logical ops.
Reid Spencer542964f2007-01-11 18:21:29 +00001629 if (SI->getType() == Type::Int1Ty) return 0;
Chris Lattner374e6592005-04-21 05:43:13 +00001630
Chris Lattner86102b82005-01-01 16:22:27 +00001631 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1632 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1633
1634 return new SelectInst(SI->getCondition(), SelectTrueVal,
1635 SelectFalseVal);
1636 }
1637 return 0;
Chris Lattner183b3362004-04-09 19:05:30 +00001638}
1639
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001640
1641/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1642/// node as operand #0, see if we can fold the instruction into the PHI (which
1643/// is only possible if all operands to the PHI are constants).
1644Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1645 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattner7515cab2004-11-14 19:13:23 +00001646 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner04689872006-09-09 22:02:56 +00001647 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001648
Chris Lattner04689872006-09-09 22:02:56 +00001649 // Check to see if all of the operands of the PHI are constants. If there is
1650 // one non-constant value, remember the BB it is. If there is more than one
1651 // bail out.
1652 BasicBlock *NonConstBB = 0;
1653 for (unsigned i = 0; i != NumPHIValues; ++i)
1654 if (!isa<Constant>(PN->getIncomingValue(i))) {
1655 if (NonConstBB) return 0; // More than one non-const value.
1656 NonConstBB = PN->getIncomingBlock(i);
1657
1658 // If the incoming non-constant value is in I's block, we have an infinite
1659 // loop.
1660 if (NonConstBB == I.getParent())
1661 return 0;
1662 }
1663
1664 // If there is exactly one non-constant value, we can insert a copy of the
1665 // operation in that block. However, if this is a critical edge, we would be
1666 // inserting the computation one some other paths (e.g. inside a loop). Only
1667 // do this if the pred block is unconditionally branching into the phi block.
1668 if (NonConstBB) {
1669 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1670 if (!BI || !BI->isUnconditional()) return 0;
1671 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001672
1673 // Okay, we can do the transformation: create the new PHI node.
1674 PHINode *NewPN = new PHINode(I.getType(), I.getName());
1675 I.setName("");
Chris Lattnerd8e20182005-01-29 00:39:08 +00001676 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001677 InsertNewInstBefore(NewPN, *PN);
1678
1679 // Next, add all of the operands to the PHI.
1680 if (I.getNumOperands() == 2) {
1681 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattner7515cab2004-11-14 19:13:23 +00001682 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner04689872006-09-09 22:02:56 +00001683 Value *InV;
1684 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencer266e42b2006-12-23 06:05:41 +00001685 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1686 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
1687 else
1688 InV = ConstantExpr::get(I.getOpcode(), InC, C);
Chris Lattner04689872006-09-09 22:02:56 +00001689 } else {
1690 assert(PN->getIncomingBlock(i) == NonConstBB);
1691 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1692 InV = BinaryOperator::create(BO->getOpcode(),
1693 PN->getIncomingValue(i), C, "phitmp",
1694 NonConstBB->getTerminator());
Reid Spencer266e42b2006-12-23 06:05:41 +00001695 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1696 InV = CmpInst::create(CI->getOpcode(),
1697 CI->getPredicate(),
1698 PN->getIncomingValue(i), C, "phitmp",
1699 NonConstBB->getTerminator());
Chris Lattner04689872006-09-09 22:02:56 +00001700 else if (ShiftInst *SI = dyn_cast<ShiftInst>(&I))
1701 InV = new ShiftInst(SI->getOpcode(),
1702 PN->getIncomingValue(i), C, "phitmp",
1703 NonConstBB->getTerminator());
1704 else
1705 assert(0 && "Unknown binop!");
1706
1707 WorkList.push_back(cast<Instruction>(InV));
1708 }
1709 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001710 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001711 } else {
1712 CastInst *CI = cast<CastInst>(&I);
1713 const Type *RetTy = CI->getType();
Chris Lattner7515cab2004-11-14 19:13:23 +00001714 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner04689872006-09-09 22:02:56 +00001715 Value *InV;
1716 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001717 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Chris Lattner04689872006-09-09 22:02:56 +00001718 } else {
1719 assert(PN->getIncomingBlock(i) == NonConstBB);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001720 InV = CastInst::create(CI->getOpcode(), PN->getIncomingValue(i),
1721 I.getType(), "phitmp",
1722 NonConstBB->getTerminator());
Chris Lattner04689872006-09-09 22:02:56 +00001723 WorkList.push_back(cast<Instruction>(InV));
1724 }
1725 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001726 }
1727 }
1728 return ReplaceInstUsesWith(I, NewPN);
1729}
1730
Chris Lattner113f4f42002-06-25 16:13:24 +00001731Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001732 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00001733 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattner9fa53de2002-05-06 16:49:18 +00001734
Chris Lattnercf4a9962004-04-10 22:01:55 +00001735 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattner81a7a232004-10-16 18:11:37 +00001736 // X + undef -> undef
1737 if (isa<UndefValue>(RHS))
1738 return ReplaceInstUsesWith(I, RHS);
1739
Chris Lattnercf4a9962004-04-10 22:01:55 +00001740 // X + 0 --> X
Chris Lattner7a002fe2006-12-02 00:13:08 +00001741 if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
Chris Lattner7fde91e2005-10-17 17:56:38 +00001742 if (RHSC->isNullValue())
1743 return ReplaceInstUsesWith(I, LHS);
Chris Lattnerda1b1522005-10-17 20:18:38 +00001744 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
1745 if (CFP->isExactlyValue(-0.0))
1746 return ReplaceInstUsesWith(I, LHS);
Chris Lattner7fde91e2005-10-17 17:56:38 +00001747 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001748
Chris Lattnercf4a9962004-04-10 22:01:55 +00001749 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattner6e2c15c2006-11-09 05:12:27 +00001750 // X + (signbit) --> X ^ signbit
Chris Lattner92a68652006-02-07 08:05:22 +00001751 uint64_t Val = CI->getZExtValue();
Chris Lattner77defba2006-02-07 07:00:41 +00001752 if (Val == (1ULL << (CI->getType()->getPrimitiveSizeInBits()-1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001753 return BinaryOperator::createXor(LHS, RHS);
Chris Lattner6e2c15c2006-11-09 05:12:27 +00001754
1755 // See if SimplifyDemandedBits can simplify this. This handles stuff like
1756 // (X & 254)+1 -> (X&254)|1
1757 uint64_t KnownZero, KnownOne;
1758 if (!isa<PackedType>(I.getType()) &&
1759 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
1760 KnownZero, KnownOne))
1761 return &I;
Chris Lattnercf4a9962004-04-10 22:01:55 +00001762 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001763
1764 if (isa<PHINode>(LHS))
1765 if (Instruction *NV = FoldOpIntoPhi(I))
1766 return NV;
Chris Lattner0b3557f2005-09-24 23:43:33 +00001767
Chris Lattner330628a2006-01-06 17:59:59 +00001768 ConstantInt *XorRHS = 0;
1769 Value *XorLHS = 0;
Chris Lattner0b3557f2005-09-24 23:43:33 +00001770 if (match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
1771 unsigned TySizeBits = I.getType()->getPrimitiveSizeInBits();
1772 int64_t RHSSExt = cast<ConstantInt>(RHSC)->getSExtValue();
1773 uint64_t RHSZExt = cast<ConstantInt>(RHSC)->getZExtValue();
1774
1775 uint64_t C0080Val = 1ULL << 31;
1776 int64_t CFF80Val = -C0080Val;
1777 unsigned Size = 32;
1778 do {
1779 if (TySizeBits > Size) {
1780 bool Found = false;
1781 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
1782 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
1783 if (RHSSExt == CFF80Val) {
1784 if (XorRHS->getZExtValue() == C0080Val)
1785 Found = true;
1786 } else if (RHSZExt == C0080Val) {
1787 if (XorRHS->getSExtValue() == CFF80Val)
1788 Found = true;
1789 }
1790 if (Found) {
1791 // This is a sign extend if the top bits are known zero.
Chris Lattner4534dd592006-02-09 07:38:58 +00001792 uint64_t Mask = ~0ULL;
Chris Lattnerc3ebf402006-02-07 07:27:52 +00001793 Mask <<= 64-(TySizeBits-Size);
Chris Lattner4534dd592006-02-09 07:38:58 +00001794 Mask &= XorLHS->getType()->getIntegralTypeMask();
Chris Lattnerc3ebf402006-02-07 07:27:52 +00001795 if (!MaskedValueIsZero(XorLHS, Mask))
Chris Lattner0b3557f2005-09-24 23:43:33 +00001796 Size = 0; // Not a sign ext, but can't be any others either.
1797 goto FoundSExt;
1798 }
1799 }
1800 Size >>= 1;
1801 C0080Val >>= Size;
1802 CFF80Val >>= Size;
1803 } while (Size >= 8);
1804
1805FoundSExt:
1806 const Type *MiddleType = 0;
1807 switch (Size) {
1808 default: break;
Reid Spencerc635f472006-12-31 05:48:39 +00001809 case 32: MiddleType = Type::Int32Ty; break;
1810 case 16: MiddleType = Type::Int16Ty; break;
1811 case 8: MiddleType = Type::Int8Ty; break;
Chris Lattner0b3557f2005-09-24 23:43:33 +00001812 }
1813 if (MiddleType) {
Reid Spencerbb65ebf2006-12-12 23:36:14 +00001814 Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
Chris Lattner0b3557f2005-09-24 23:43:33 +00001815 InsertNewInstBefore(NewTrunc, I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001816 return new SExtInst(NewTrunc, I.getType());
Chris Lattner0b3557f2005-09-24 23:43:33 +00001817 }
1818 }
Chris Lattnercf4a9962004-04-10 22:01:55 +00001819 }
Chris Lattner9fa53de2002-05-06 16:49:18 +00001820
Chris Lattnerb8b97502003-08-13 19:01:45 +00001821 // X + X --> X << 1
Robert Bocchino7b5b86c2004-07-27 21:02:21 +00001822 if (I.getType()->isInteger()) {
Chris Lattnerb8b97502003-08-13 19:01:45 +00001823 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Chris Lattner47060462005-04-07 17:14:51 +00001824
1825 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
1826 if (RHSI->getOpcode() == Instruction::Sub)
1827 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
1828 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
1829 }
1830 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
1831 if (LHSI->getOpcode() == Instruction::Sub)
1832 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
1833 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
1834 }
Robert Bocchino7b5b86c2004-07-27 21:02:21 +00001835 }
Chris Lattnerede3fe02003-08-13 04:18:28 +00001836
Chris Lattner147e9752002-05-08 22:46:53 +00001837 // -A + B --> B - A
Chris Lattnerbb74e222003-03-10 23:06:50 +00001838 if (Value *V = dyn_castNegVal(LHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001839 return BinaryOperator::createSub(RHS, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +00001840
1841 // A + -B --> A - B
Chris Lattnerbb74e222003-03-10 23:06:50 +00001842 if (!isa<Constant>(RHS))
1843 if (Value *V = dyn_castNegVal(RHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001844 return BinaryOperator::createSub(LHS, V);
Chris Lattner260ab202002-04-18 17:39:14 +00001845
Misha Brukmanb1c93172005-04-21 23:48:37 +00001846
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001847 ConstantInt *C2;
1848 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
1849 if (X == RHS) // X*C + X --> X * (C+1)
1850 return BinaryOperator::createMul(RHS, AddOne(C2));
1851
1852 // X*C1 + X*C2 --> X * (C1+C2)
1853 ConstantInt *C1;
1854 if (X == dyn_castFoldableMul(RHS, C1))
1855 return BinaryOperator::createMul(X, ConstantExpr::getAdd(C1, C2));
Chris Lattner57c8d992003-02-18 19:57:07 +00001856 }
1857
1858 // X + X*C --> X * (C+1)
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001859 if (dyn_castFoldableMul(RHS, C2) == LHS)
1860 return BinaryOperator::createMul(LHS, AddOne(C2));
1861
Chris Lattner23eb8ec2007-01-05 02:17:46 +00001862 // X + ~X --> -1 since ~X = -X-1
1863 if (dyn_castNotVal(LHS) == RHS ||
1864 dyn_castNotVal(RHS) == LHS)
1865 return ReplaceInstUsesWith(I, ConstantInt::getAllOnesValue(I.getType()));
1866
Chris Lattner57c8d992003-02-18 19:57:07 +00001867
Chris Lattnerb8b97502003-08-13 19:01:45 +00001868 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattnerd4252a72004-07-30 07:50:03 +00001869 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattner23eb8ec2007-01-05 02:17:46 +00001870 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
1871 return R;
Chris Lattner7fb29e12003-03-11 00:12:48 +00001872
Chris Lattnerb9cde762003-10-02 15:11:26 +00001873 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner330628a2006-01-06 17:59:59 +00001874 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00001875 if (match(LHS, m_Not(m_Value(X)))) { // ~X + C --> (C-1) - X
1876 Constant *C= ConstantExpr::getSub(CRHS, ConstantInt::get(I.getType(), 1));
1877 return BinaryOperator::createSub(C, X);
Chris Lattnerb9cde762003-10-02 15:11:26 +00001878 }
Chris Lattnerd4252a72004-07-30 07:50:03 +00001879
Chris Lattnerbff91d92004-10-08 05:07:56 +00001880 // (X & FF00) + xx00 -> (X+xx00) & FF00
1881 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
1882 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
1883 if (Anded == CRHS) {
1884 // See if all bits from the first bit set in the Add RHS up are included
1885 // in the mask. First, get the rightmost bit.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001886 uint64_t AddRHSV = CRHS->getZExtValue();
Chris Lattnerbff91d92004-10-08 05:07:56 +00001887
1888 // Form a mask of all bits from the lowest bit added through the top.
1889 uint64_t AddRHSHighBits = ~((AddRHSV & -AddRHSV)-1);
Chris Lattner77defba2006-02-07 07:00:41 +00001890 AddRHSHighBits &= C2->getType()->getIntegralTypeMask();
Chris Lattnerbff91d92004-10-08 05:07:56 +00001891
1892 // See if the and mask includes all of these bits.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001893 uint64_t AddRHSHighBitsAnd = AddRHSHighBits & C2->getZExtValue();
Misha Brukmanb1c93172005-04-21 23:48:37 +00001894
Chris Lattnerbff91d92004-10-08 05:07:56 +00001895 if (AddRHSHighBits == AddRHSHighBitsAnd) {
1896 // Okay, the xform is safe. Insert the new add pronto.
1897 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
1898 LHS->getName()), I);
1899 return BinaryOperator::createAnd(NewAdd, C2);
1900 }
1901 }
1902 }
1903
Chris Lattnerd4252a72004-07-30 07:50:03 +00001904 // Try to fold constant add into select arguments.
1905 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner86102b82005-01-01 16:22:27 +00001906 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattnerd4252a72004-07-30 07:50:03 +00001907 return R;
Chris Lattnerb9cde762003-10-02 15:11:26 +00001908 }
1909
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001910 // add (cast *A to intptrtype) B ->
1911 // cast (GEP (cast *A to sbyte*) B) ->
1912 // intptrtype
Andrew Lenharth4f339be2006-09-19 18:24:51 +00001913 {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001914 CastInst *CI = dyn_cast<CastInst>(LHS);
1915 Value *Other = RHS;
Andrew Lenharth4f339be2006-09-19 18:24:51 +00001916 if (!CI) {
1917 CI = dyn_cast<CastInst>(RHS);
1918 Other = LHS;
1919 }
Andrew Lenharth44cb67a2006-09-20 15:37:57 +00001920 if (CI && CI->getType()->isSized() &&
Reid Spencer8f166b02007-01-08 16:32:00 +00001921 (CI->getType()->getPrimitiveSizeInBits() ==
1922 TD->getIntPtrType()->getPrimitiveSizeInBits())
Andrew Lenharth44cb67a2006-09-20 15:37:57 +00001923 && isa<PointerType>(CI->getOperand(0)->getType())) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00001924 Value *I2 = InsertCastBefore(Instruction::BitCast, CI->getOperand(0),
Reid Spencerc635f472006-12-31 05:48:39 +00001925 PointerType::get(Type::Int8Ty), I);
Andrew Lenharth44cb67a2006-09-20 15:37:57 +00001926 I2 = InsertNewInstBefore(new GetElementPtrInst(I2, Other, "ctg2"), I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001927 return new PtrToIntInst(I2, CI->getType());
Andrew Lenharth4f339be2006-09-19 18:24:51 +00001928 }
1929 }
1930
Chris Lattner113f4f42002-06-25 16:13:24 +00001931 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +00001932}
1933
Chris Lattnerbdb0ce02003-07-22 21:46:59 +00001934// isSignBit - Return true if the value represented by the constant only has the
1935// highest order bit set.
1936static bool isSignBit(ConstantInt *CI) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001937 unsigned NumBits = CI->getType()->getPrimitiveSizeInBits();
Reid Spencere0fc4df2006-10-20 07:07:24 +00001938 return (CI->getZExtValue() & (~0ULL >> (64-NumBits))) == (1ULL << (NumBits-1));
Chris Lattnerbdb0ce02003-07-22 21:46:59 +00001939}
1940
Chris Lattner022167f2004-03-13 00:11:49 +00001941/// RemoveNoopCast - Strip off nonconverting casts from the value.
1942///
1943static Value *RemoveNoopCast(Value *V) {
1944 if (CastInst *CI = dyn_cast<CastInst>(V)) {
1945 const Type *CTy = CI->getType();
1946 const Type *OpTy = CI->getOperand(0)->getType();
1947 if (CTy->isInteger() && OpTy->isInteger()) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001948 if (CTy->getPrimitiveSizeInBits() == OpTy->getPrimitiveSizeInBits())
Chris Lattner022167f2004-03-13 00:11:49 +00001949 return RemoveNoopCast(CI->getOperand(0));
1950 } else if (isa<PointerType>(CTy) && isa<PointerType>(OpTy))
1951 return RemoveNoopCast(CI->getOperand(0));
1952 }
1953 return V;
1954}
1955
Chris Lattner113f4f42002-06-25 16:13:24 +00001956Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +00001957 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001958
Chris Lattnere6794492002-08-12 21:17:25 +00001959 if (Op0 == Op1) // sub X, X -> 0
1960 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner260ab202002-04-18 17:39:14 +00001961
Chris Lattnere6794492002-08-12 21:17:25 +00001962 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattnerbb74e222003-03-10 23:06:50 +00001963 if (Value *V = dyn_castNegVal(Op1))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001964 return BinaryOperator::createAdd(Op0, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +00001965
Chris Lattner81a7a232004-10-16 18:11:37 +00001966 if (isa<UndefValue>(Op0))
1967 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
1968 if (isa<UndefValue>(Op1))
1969 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
1970
Chris Lattner8f2f5982003-11-05 01:06:05 +00001971 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
1972 // Replace (-1 - A) with (~A)...
Chris Lattner3082c5a2003-02-18 19:28:33 +00001973 if (C->isAllOnesValue())
1974 return BinaryOperator::createNot(Op1);
Chris Lattnerad3c4952002-05-09 01:29:19 +00001975
Chris Lattner8f2f5982003-11-05 01:06:05 +00001976 // C - ~X == X + (1+C)
Reid Spencer4fdd96c2005-06-18 17:37:34 +00001977 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00001978 if (match(Op1, m_Not(m_Value(X))))
1979 return BinaryOperator::createAdd(X,
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001980 ConstantExpr::getAdd(C, ConstantInt::get(I.getType(), 1)));
Chris Lattner92295c52004-03-12 23:53:13 +00001981 // -((uint)X >> 31) -> ((int)X >> 31)
1982 // -((int)X >> 31) -> ((uint)X >> 31)
Chris Lattner022167f2004-03-13 00:11:49 +00001983 if (C->isNullValue()) {
1984 Value *NoopCastedRHS = RemoveNoopCast(Op1);
1985 if (ShiftInst *SI = dyn_cast<ShiftInst>(NoopCastedRHS))
Reid Spencerfdff9382006-11-08 06:47:33 +00001986 if (SI->getOpcode() == Instruction::LShr) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00001987 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
Chris Lattner92295c52004-03-12 23:53:13 +00001988 // Check to see if we are shifting out everything but the sign bit.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001989 if (CU->getZExtValue() ==
1990 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerfdff9382006-11-08 06:47:33 +00001991 // Ok, the transformation is safe. Insert AShr.
Reid Spencer193df252006-12-24 00:40:59 +00001992 // FIXME: Once integer types are signless, this cast should be
1993 // removed.
1994 Value *ShiftOp = SI->getOperand(0);
Reid Spencer193df252006-12-24 00:40:59 +00001995 return new ShiftInst(Instruction::AShr, ShiftOp, CU,
1996 SI->getName());
Chris Lattner92295c52004-03-12 23:53:13 +00001997 }
1998 }
Reid Spencerfdff9382006-11-08 06:47:33 +00001999 }
2000 else if (SI->getOpcode() == Instruction::AShr) {
2001 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2002 // Check to see if we are shifting out everything but the sign bit.
2003 if (CU->getZExtValue() ==
2004 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerc635f472006-12-31 05:48:39 +00002005
2006 // Ok, the transformation is safe. Insert LShr.
2007 return new ShiftInst(Instruction::LShr, SI->getOperand(0), CU,
2008 SI->getName());
Reid Spencerfdff9382006-11-08 06:47:33 +00002009 }
2010 }
2011 }
Chris Lattner022167f2004-03-13 00:11:49 +00002012 }
Chris Lattner183b3362004-04-09 19:05:30 +00002013
2014 // Try to fold constant sub into select arguments.
2015 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner86102b82005-01-01 16:22:27 +00002016 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00002017 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002018
2019 if (isa<PHINode>(Op0))
2020 if (Instruction *NV = FoldOpIntoPhi(I))
2021 return NV;
Chris Lattner8f2f5982003-11-05 01:06:05 +00002022 }
2023
Chris Lattnera9be4492005-04-07 16:15:25 +00002024 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2025 if (Op1I->getOpcode() == Instruction::Add &&
Chris Lattner7a002fe2006-12-02 00:13:08 +00002026 !Op0->getType()->isFPOrFPVector()) {
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00002027 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Chris Lattnera9be4492005-04-07 16:15:25 +00002028 return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00002029 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Chris Lattnera9be4492005-04-07 16:15:25 +00002030 return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00002031 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2032 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2033 // C1-(X+C2) --> (C1-C2)-X
2034 return BinaryOperator::createSub(ConstantExpr::getSub(CI1, CI2),
2035 Op1I->getOperand(0));
2036 }
Chris Lattnera9be4492005-04-07 16:15:25 +00002037 }
2038
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002039 if (Op1I->hasOneUse()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00002040 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2041 // is not used by anyone else...
2042 //
Chris Lattnerc2f0aa52004-02-02 20:09:56 +00002043 if (Op1I->getOpcode() == Instruction::Sub &&
Chris Lattner7a002fe2006-12-02 00:13:08 +00002044 !Op1I->getType()->isFPOrFPVector()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00002045 // Swap the two operands of the subexpr...
2046 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2047 Op1I->setOperand(0, IIOp1);
2048 Op1I->setOperand(1, IIOp0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002049
Chris Lattner3082c5a2003-02-18 19:28:33 +00002050 // Create the new top level add instruction...
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002051 return BinaryOperator::createAdd(Op0, Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002052 }
2053
2054 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2055 //
2056 if (Op1I->getOpcode() == Instruction::And &&
2057 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2058 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2059
Chris Lattner396dbfe2004-06-09 05:08:07 +00002060 Value *NewNot =
2061 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002062 return BinaryOperator::createAnd(Op0, NewNot);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002063 }
Chris Lattner57c8d992003-02-18 19:57:07 +00002064
Reid Spencer3c514952006-10-16 23:08:08 +00002065 // 0 - (X sdiv C) -> (X sdiv -C)
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002066 if (Op1I->getOpcode() == Instruction::SDiv)
Reid Spencere0fc4df2006-10-20 07:07:24 +00002067 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002068 if (CSI->isNullValue())
Chris Lattner0aee4b72004-10-06 15:08:25 +00002069 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002070 return BinaryOperator::createSDiv(Op1I->getOperand(0),
Chris Lattner0aee4b72004-10-06 15:08:25 +00002071 ConstantExpr::getNeg(DivRHS));
2072
Chris Lattner57c8d992003-02-18 19:57:07 +00002073 // X - X*C --> X * (1-C)
Reid Spencer4fdd96c2005-06-18 17:37:34 +00002074 ConstantInt *C2 = 0;
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002075 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00002076 Constant *CP1 =
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002077 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1), C2);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002078 return BinaryOperator::createMul(Op0, CP1);
Chris Lattner57c8d992003-02-18 19:57:07 +00002079 }
Chris Lattnerad3c4952002-05-09 01:29:19 +00002080 }
Chris Lattnera9be4492005-04-07 16:15:25 +00002081 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00002082
Chris Lattner7a002fe2006-12-02 00:13:08 +00002083 if (!Op0->getType()->isFPOrFPVector())
Chris Lattner47060462005-04-07 17:14:51 +00002084 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2085 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner411336f2005-01-19 21:50:18 +00002086 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2087 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2088 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2089 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner47060462005-04-07 17:14:51 +00002090 } else if (Op0I->getOpcode() == Instruction::Sub) {
2091 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
2092 return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
Chris Lattner411336f2005-01-19 21:50:18 +00002093 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002094
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002095 ConstantInt *C1;
2096 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2097 if (X == Op1) { // X*C - X --> X * (C-1)
2098 Constant *CP1 = ConstantExpr::getSub(C1, ConstantInt::get(I.getType(),1));
2099 return BinaryOperator::createMul(Op1, CP1);
2100 }
Chris Lattner57c8d992003-02-18 19:57:07 +00002101
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002102 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
2103 if (X == dyn_castFoldableMul(Op1, C2))
2104 return BinaryOperator::createMul(Op1, ConstantExpr::getSub(C1, C2));
2105 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002106 return 0;
Chris Lattner260ab202002-04-18 17:39:14 +00002107}
2108
Reid Spencer266e42b2006-12-23 06:05:41 +00002109/// isSignBitCheck - Given an exploded icmp instruction, return true if it
Chris Lattnere79e8542004-02-23 06:38:22 +00002110/// really just returns true if the most significant (sign) bit is set.
Reid Spencer266e42b2006-12-23 06:05:41 +00002111static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS) {
2112 switch (pred) {
2113 case ICmpInst::ICMP_SLT:
2114 // True if LHS s< RHS and RHS == 0
2115 return RHS->isNullValue();
2116 case ICmpInst::ICMP_SLE:
2117 // True if LHS s<= RHS and RHS == -1
2118 return RHS->isAllOnesValue();
2119 case ICmpInst::ICMP_UGE:
2120 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2121 return RHS->getZExtValue() == (1ULL <<
2122 (RHS->getType()->getPrimitiveSizeInBits()-1));
2123 case ICmpInst::ICMP_UGT:
2124 // True if LHS u> RHS and RHS == high-bit-mask - 1
2125 return RHS->getZExtValue() ==
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002126 (1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1))-1;
Reid Spencer266e42b2006-12-23 06:05:41 +00002127 default:
2128 return false;
Chris Lattnere79e8542004-02-23 06:38:22 +00002129 }
Chris Lattnere79e8542004-02-23 06:38:22 +00002130}
2131
Chris Lattner113f4f42002-06-25 16:13:24 +00002132Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00002133 bool Changed = SimplifyCommutative(I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002134 Value *Op0 = I.getOperand(0);
Chris Lattner260ab202002-04-18 17:39:14 +00002135
Chris Lattner81a7a232004-10-16 18:11:37 +00002136 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
2137 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2138
Chris Lattnere6794492002-08-12 21:17:25 +00002139 // Simplify mul instructions with a constant RHS...
Chris Lattner3082c5a2003-02-18 19:28:33 +00002140 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2141 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerede3fe02003-08-13 04:18:28 +00002142
2143 // ((X << C1)*C2) == (X * (C2 << C1))
2144 if (ShiftInst *SI = dyn_cast<ShiftInst>(Op0))
2145 if (SI->getOpcode() == Instruction::Shl)
2146 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002147 return BinaryOperator::createMul(SI->getOperand(0),
2148 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanb1c93172005-04-21 23:48:37 +00002149
Chris Lattnercce81be2003-09-11 22:24:54 +00002150 if (CI->isNullValue())
2151 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2152 if (CI->equalsInt(1)) // X * 1 == X
2153 return ReplaceInstUsesWith(I, Op0);
2154 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Chris Lattner35236d82003-06-25 17:09:20 +00002155 return BinaryOperator::createNeg(Op0, I.getName());
Chris Lattner31ba1292002-04-29 22:24:47 +00002156
Reid Spencere0fc4df2006-10-20 07:07:24 +00002157 int64_t Val = (int64_t)cast<ConstantInt>(CI)->getZExtValue();
Chris Lattner22d00a82005-08-02 19:16:58 +00002158 if (isPowerOf2_64(Val)) { // Replace X*(2^C) with X << C
2159 uint64_t C = Log2_64(Val);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002160 return new ShiftInst(Instruction::Shl, Op0,
Reid Spencerc635f472006-12-31 05:48:39 +00002161 ConstantInt::get(Type::Int8Ty, C));
Chris Lattner22d00a82005-08-02 19:16:58 +00002162 }
Robert Bocchino7b5b86c2004-07-27 21:02:21 +00002163 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00002164 if (Op1F->isNullValue())
2165 return ReplaceInstUsesWith(I, Op1);
Chris Lattner31ba1292002-04-29 22:24:47 +00002166
Chris Lattner3082c5a2003-02-18 19:28:33 +00002167 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2168 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2169 if (Op1F->getValue() == 1.0)
2170 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
2171 }
Chris Lattner32c01df2006-03-04 06:04:02 +00002172
2173 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2174 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2175 isa<ConstantInt>(Op0I->getOperand(1))) {
2176 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2177 Instruction *Add = BinaryOperator::createMul(Op0I->getOperand(0),
2178 Op1, "tmp");
2179 InsertNewInstBefore(Add, I);
2180 Value *C1C2 = ConstantExpr::getMul(Op1,
2181 cast<Constant>(Op0I->getOperand(1)));
2182 return BinaryOperator::createAdd(Add, C1C2);
2183
2184 }
Chris Lattner183b3362004-04-09 19:05:30 +00002185
2186 // Try to fold constant mul into select arguments.
2187 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00002188 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00002189 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002190
2191 if (isa<PHINode>(Op0))
2192 if (Instruction *NV = FoldOpIntoPhi(I))
2193 return NV;
Chris Lattner260ab202002-04-18 17:39:14 +00002194 }
2195
Chris Lattner934a64cf2003-03-10 23:23:04 +00002196 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
2197 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002198 return BinaryOperator::createMul(Op0v, Op1v);
Chris Lattner934a64cf2003-03-10 23:23:04 +00002199
Chris Lattner2635b522004-02-23 05:39:21 +00002200 // If one of the operands of the multiply is a cast from a boolean value, then
2201 // we know the bool is either zero or one, so this is a 'masking' multiply.
2202 // See if we can simplify things based on how the boolean was originally
2203 // formed.
2204 CastInst *BoolCast = 0;
Reid Spencer74a528b2006-12-13 18:21:21 +00002205 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(0)))
Reid Spencer542964f2007-01-11 18:21:29 +00002206 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattner2635b522004-02-23 05:39:21 +00002207 BoolCast = CI;
2208 if (!BoolCast)
Reid Spencer74a528b2006-12-13 18:21:21 +00002209 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
Reid Spencer542964f2007-01-11 18:21:29 +00002210 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattner2635b522004-02-23 05:39:21 +00002211 BoolCast = CI;
2212 if (BoolCast) {
Reid Spencer266e42b2006-12-23 06:05:41 +00002213 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
Chris Lattner2635b522004-02-23 05:39:21 +00002214 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2215 const Type *SCOpTy = SCIOp0->getType();
2216
Reid Spencer266e42b2006-12-23 06:05:41 +00002217 // If the icmp is true iff the sign bit of X is set, then convert this
Chris Lattnere79e8542004-02-23 06:38:22 +00002218 // multiply into a shift/and combination.
2219 if (isa<ConstantInt>(SCIOp1) &&
Reid Spencer266e42b2006-12-23 06:05:41 +00002220 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1))) {
Chris Lattner2635b522004-02-23 05:39:21 +00002221 // Shift the X value right to turn it into "all signbits".
Reid Spencerc635f472006-12-31 05:48:39 +00002222 Constant *Amt = ConstantInt::get(Type::Int8Ty,
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002223 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattnere79e8542004-02-23 06:38:22 +00002224 Value *V =
Reid Spencerfdff9382006-11-08 06:47:33 +00002225 InsertNewInstBefore(new ShiftInst(Instruction::AShr, SCIOp0, Amt,
Chris Lattnere79e8542004-02-23 06:38:22 +00002226 BoolCast->getOperand(0)->getName()+
2227 ".mask"), I);
Chris Lattner2635b522004-02-23 05:39:21 +00002228
2229 // If the multiply type is not the same as the source type, sign extend
2230 // or truncate to the multiply type.
Reid Spencer13bc5d72006-12-12 09:18:51 +00002231 if (I.getType() != V->getType()) {
2232 unsigned SrcBits = V->getType()->getPrimitiveSizeInBits();
2233 unsigned DstBits = I.getType()->getPrimitiveSizeInBits();
2234 Instruction::CastOps opcode =
2235 (SrcBits == DstBits ? Instruction::BitCast :
2236 (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2237 V = InsertCastBefore(opcode, V, I.getType(), I);
2238 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002239
Chris Lattner2635b522004-02-23 05:39:21 +00002240 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002241 return BinaryOperator::createAnd(V, OtherOp);
Chris Lattner2635b522004-02-23 05:39:21 +00002242 }
2243 }
2244 }
2245
Chris Lattner113f4f42002-06-25 16:13:24 +00002246 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +00002247}
2248
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002249/// This function implements the transforms on div instructions that work
2250/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2251/// used by the visitors to those instructions.
2252/// @brief Transforms common to all three div instructions
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002253Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002254 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner81a7a232004-10-16 18:11:37 +00002255
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002256 // undef / X -> 0
2257 if (isa<UndefValue>(Op0))
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002258 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002259
2260 // X / undef -> undef
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002261 if (isa<UndefValue>(Op1))
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002262 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002263
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002264 // Handle cases involving: div X, (select Cond, Y, Z)
Chris Lattnerd79dc792006-09-09 20:26:32 +00002265 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2266 // div X, (Cond ? 0 : Y) -> div X, Y. If the div and the select are in the
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002267 // same basic block, then we replace the select with Y, and the condition
2268 // of the select with false (if the cond value is in the same BB). If the
Chris Lattnerd79dc792006-09-09 20:26:32 +00002269 // select has uses other than the div, this allows them to be simplified
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002270 // also. Note that div X, Y is just as good as div X, 0 (undef)
Chris Lattnerd79dc792006-09-09 20:26:32 +00002271 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2272 if (ST->isNullValue()) {
2273 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2274 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng75b871f2007-01-11 12:24:14 +00002275 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
Chris Lattnerd79dc792006-09-09 20:26:32 +00002276 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2277 I.setOperand(1, SI->getOperand(2));
2278 else
2279 UpdateValueUsesWith(SI, SI->getOperand(2));
2280 return &I;
2281 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002282
Chris Lattnerd79dc792006-09-09 20:26:32 +00002283 // Likewise for: div X, (Cond ? Y : 0) -> div X, Y
2284 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2285 if (ST->isNullValue()) {
2286 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2287 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng75b871f2007-01-11 12:24:14 +00002288 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
Chris Lattnerd79dc792006-09-09 20:26:32 +00002289 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2290 I.setOperand(1, SI->getOperand(1));
2291 else
2292 UpdateValueUsesWith(SI, SI->getOperand(1));
2293 return &I;
2294 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002295 }
Chris Lattnerd79dc792006-09-09 20:26:32 +00002296
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002297 return 0;
2298}
Misha Brukmanb1c93172005-04-21 23:48:37 +00002299
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002300/// This function implements the transforms common to both integer division
2301/// instructions (udiv and sdiv). It is called by the visitors to those integer
2302/// division instructions.
2303/// @brief Common integer divide transforms
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002304Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002305 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2306
2307 if (Instruction *Common = commonDivTransforms(I))
2308 return Common;
2309
2310 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2311 // div X, 1 == X
2312 if (RHS->equalsInt(1))
2313 return ReplaceInstUsesWith(I, Op0);
2314
2315 // (X / C1) / C2 -> X / (C1*C2)
2316 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2317 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2318 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
2319 return BinaryOperator::create(I.getOpcode(), LHS->getOperand(0),
2320 ConstantExpr::getMul(RHS, LHSRHS));
Chris Lattner42362612005-04-08 04:03:26 +00002321 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002322
2323 if (!RHS->isNullValue()) { // avoid X udiv 0
2324 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2325 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2326 return R;
2327 if (isa<PHINode>(Op0))
2328 if (Instruction *NV = FoldOpIntoPhi(I))
2329 return NV;
2330 }
Chris Lattnerd79dc792006-09-09 20:26:32 +00002331 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002332
Chris Lattner3082c5a2003-02-18 19:28:33 +00002333 // 0 / X == 0, we don't need to preserve faults!
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002334 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattner3082c5a2003-02-18 19:28:33 +00002335 if (LHS->equalsInt(0))
2336 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2337
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002338 return 0;
2339}
2340
2341Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2342 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2343
2344 // Handle the integer div common cases
2345 if (Instruction *Common = commonIDivTransforms(I))
2346 return Common;
2347
2348 // X udiv C^2 -> X >> C
2349 // Check to see if this is an unsigned division with an exact power of 2,
2350 // if so, convert to a right shift.
2351 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
2352 if (uint64_t Val = C->getZExtValue()) // Don't break X / 0
2353 if (isPowerOf2_64(Val)) {
2354 uint64_t ShiftAmt = Log2_64(Val);
Reid Spencerfdff9382006-11-08 06:47:33 +00002355 return new ShiftInst(Instruction::LShr, Op0,
Reid Spencerc635f472006-12-31 05:48:39 +00002356 ConstantInt::get(Type::Int8Ty, ShiftAmt));
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002357 }
2358 }
2359
2360 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
2361 if (ShiftInst *RHSI = dyn_cast<ShiftInst>(I.getOperand(1))) {
2362 if (RHSI->getOpcode() == Instruction::Shl &&
2363 isa<ConstantInt>(RHSI->getOperand(0))) {
2364 uint64_t C1 = cast<ConstantInt>(RHSI->getOperand(0))->getZExtValue();
2365 if (isPowerOf2_64(C1)) {
2366 Value *N = RHSI->getOperand(1);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002367 const Type *NTy = N->getType();
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002368 if (uint64_t C2 = Log2_64(C1)) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002369 Constant *C2V = ConstantInt::get(NTy, C2);
2370 N = InsertNewInstBefore(BinaryOperator::createAdd(N, C2V, "tmp"), I);
Chris Lattner2e90b732006-02-05 07:54:04 +00002371 }
Reid Spencerfdff9382006-11-08 06:47:33 +00002372 return new ShiftInst(Instruction::LShr, Op0, N);
Chris Lattner2e90b732006-02-05 07:54:04 +00002373 }
2374 }
Chris Lattnerdd0c1742005-11-05 07:40:31 +00002375 }
2376
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002377 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
2378 // where C1&C2 are powers of two.
2379 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2380 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2381 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2)))
2382 if (!STO->isNullValue() && !STO->isNullValue()) {
2383 uint64_t TVA = STO->getZExtValue(), FVA = SFO->getZExtValue();
2384 if (isPowerOf2_64(TVA) && isPowerOf2_64(FVA)) {
2385 // Compute the shift amounts
2386 unsigned TSA = Log2_64(TVA), FSA = Log2_64(FVA);
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002387 // Construct the "on true" case of the select
Reid Spencerc635f472006-12-31 05:48:39 +00002388 Constant *TC = ConstantInt::get(Type::Int8Ty, TSA);
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002389 Instruction *TSI =
Reid Spencerfdff9382006-11-08 06:47:33 +00002390 new ShiftInst(Instruction::LShr, Op0, TC, SI->getName()+".t");
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002391 TSI = InsertNewInstBefore(TSI, I);
2392
2393 // Construct the "on false" case of the select
Reid Spencerc635f472006-12-31 05:48:39 +00002394 Constant *FC = ConstantInt::get(Type::Int8Ty, FSA);
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002395 Instruction *FSI =
Reid Spencerfdff9382006-11-08 06:47:33 +00002396 new ShiftInst(Instruction::LShr, Op0, FC, SI->getName()+".f");
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002397 FSI = InsertNewInstBefore(FSI, I);
2398
2399 // construct the select instruction and return it.
Reid Spencerfdff9382006-11-08 06:47:33 +00002400 return new SelectInst(SI->getOperand(0), TSI, FSI, SI->getName());
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002401 }
2402 }
2403 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002404 return 0;
2405}
2406
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002407Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
2408 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2409
2410 // Handle the integer div common cases
2411 if (Instruction *Common = commonIDivTransforms(I))
2412 return Common;
2413
2414 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2415 // sdiv X, -1 == -X
2416 if (RHS->isAllOnesValue())
2417 return BinaryOperator::createNeg(Op0);
2418
2419 // -X/C -> X/-C
2420 if (Value *LHSNeg = dyn_castNegVal(Op0))
2421 return BinaryOperator::createSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
2422 }
2423
2424 // If the sign bits of both operands are zero (i.e. we can prove they are
2425 // unsigned inputs), turn this into a udiv.
2426 if (I.getType()->isInteger()) {
2427 uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
2428 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2429 return BinaryOperator::createUDiv(Op0, Op1, I.getName());
2430 }
2431 }
2432
2433 return 0;
2434}
2435
2436Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
2437 return commonDivTransforms(I);
2438}
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002439
Chris Lattner85dda9a2006-03-02 06:50:58 +00002440/// GetFactor - If we can prove that the specified value is at least a multiple
2441/// of some factor, return that factor.
2442static Constant *GetFactor(Value *V) {
2443 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
2444 return CI;
2445
2446 // Unless we can be tricky, we know this is a multiple of 1.
2447 Constant *Result = ConstantInt::get(V->getType(), 1);
2448
2449 Instruction *I = dyn_cast<Instruction>(V);
2450 if (!I) return Result;
2451
2452 if (I->getOpcode() == Instruction::Mul) {
2453 // Handle multiplies by a constant, etc.
2454 return ConstantExpr::getMul(GetFactor(I->getOperand(0)),
2455 GetFactor(I->getOperand(1)));
2456 } else if (I->getOpcode() == Instruction::Shl) {
2457 // (X<<C) -> X * (1 << C)
2458 if (Constant *ShRHS = dyn_cast<Constant>(I->getOperand(1))) {
2459 ShRHS = ConstantExpr::getShl(Result, ShRHS);
2460 return ConstantExpr::getMul(GetFactor(I->getOperand(0)), ShRHS);
2461 }
2462 } else if (I->getOpcode() == Instruction::And) {
2463 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
2464 // X & 0xFFF0 is known to be a multiple of 16.
2465 unsigned Zeros = CountTrailingZeros_64(RHS->getZExtValue());
2466 if (Zeros != V->getType()->getPrimitiveSizeInBits())
2467 return ConstantExpr::getShl(Result,
Reid Spencerc635f472006-12-31 05:48:39 +00002468 ConstantInt::get(Type::Int8Ty, Zeros));
Chris Lattner85dda9a2006-03-02 06:50:58 +00002469 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002470 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
Chris Lattner85dda9a2006-03-02 06:50:58 +00002471 // Only handle int->int casts.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002472 if (!CI->isIntegerCast())
2473 return Result;
2474 Value *Op = CI->getOperand(0);
2475 return ConstantExpr::getCast(CI->getOpcode(), GetFactor(Op), V->getType());
Chris Lattner85dda9a2006-03-02 06:50:58 +00002476 }
2477 return Result;
2478}
2479
Reid Spencer7eb55b32006-11-02 01:53:59 +00002480/// This function implements the transforms on rem instructions that work
2481/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
2482/// is used by the visitors to those instructions.
2483/// @brief Transforms common to all three rem instructions
2484Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002485 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Reid Spencer7eb55b32006-11-02 01:53:59 +00002486
Chris Lattner0de4a8d2006-02-28 05:30:45 +00002487 // 0 % X == 0, we don't need to preserve faults!
2488 if (Constant *LHS = dyn_cast<Constant>(Op0))
2489 if (LHS->isNullValue())
2490 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2491
2492 if (isa<UndefValue>(Op0)) // undef % X -> 0
2493 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2494 if (isa<UndefValue>(Op1))
2495 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Reid Spencer7eb55b32006-11-02 01:53:59 +00002496
2497 // Handle cases involving: rem X, (select Cond, Y, Z)
2498 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2499 // rem X, (Cond ? 0 : Y) -> rem X, Y. If the rem and the select are in
2500 // the same basic block, then we replace the select with Y, and the
2501 // condition of the select with false (if the cond value is in the same
2502 // BB). If the select has uses other than the div, this allows them to be
2503 // simplified also.
2504 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2505 if (ST->isNullValue()) {
2506 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2507 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng75b871f2007-01-11 12:24:14 +00002508 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
Reid Spencer7eb55b32006-11-02 01:53:59 +00002509 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2510 I.setOperand(1, SI->getOperand(2));
2511 else
2512 UpdateValueUsesWith(SI, SI->getOperand(2));
Chris Lattner7fd5f072004-07-06 07:01:22 +00002513 return &I;
2514 }
Reid Spencer7eb55b32006-11-02 01:53:59 +00002515 // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
2516 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2517 if (ST->isNullValue()) {
2518 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2519 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng75b871f2007-01-11 12:24:14 +00002520 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
Reid Spencer7eb55b32006-11-02 01:53:59 +00002521 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2522 I.setOperand(1, SI->getOperand(1));
2523 else
2524 UpdateValueUsesWith(SI, SI->getOperand(1));
2525 return &I;
2526 }
Chris Lattnere9ff0ea2005-11-05 07:28:37 +00002527 }
Chris Lattner7fd5f072004-07-06 07:01:22 +00002528
Reid Spencer7eb55b32006-11-02 01:53:59 +00002529 return 0;
2530}
2531
2532/// This function implements the transforms common to both integer remainder
2533/// instructions (urem and srem). It is called by the visitors to those integer
2534/// remainder instructions.
2535/// @brief Common integer remainder transforms
2536Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
2537 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2538
2539 if (Instruction *common = commonRemTransforms(I))
2540 return common;
2541
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002542 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner0de4a8d2006-02-28 05:30:45 +00002543 // X % 0 == undef, we don't need to preserve faults!
2544 if (RHS->equalsInt(0))
2545 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2546
Chris Lattner3082c5a2003-02-18 19:28:33 +00002547 if (RHS->equalsInt(1)) // X % 1 == 0
2548 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2549
Chris Lattnerb70f1412006-02-28 05:49:21 +00002550 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2551 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2552 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2553 return R;
2554 } else if (isa<PHINode>(Op0I)) {
2555 if (Instruction *NV = FoldOpIntoPhi(I))
2556 return NV;
Chris Lattnerb70f1412006-02-28 05:49:21 +00002557 }
Reid Spencer7eb55b32006-11-02 01:53:59 +00002558 // (X * C1) % C2 --> 0 iff C1 % C2 == 0
2559 if (ConstantExpr::getSRem(GetFactor(Op0I), RHS)->isNullValue())
Chris Lattner85dda9a2006-03-02 06:50:58 +00002560 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerb70f1412006-02-28 05:49:21 +00002561 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00002562 }
2563
Reid Spencer7eb55b32006-11-02 01:53:59 +00002564 return 0;
2565}
2566
2567Instruction *InstCombiner::visitURem(BinaryOperator &I) {
2568 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2569
2570 if (Instruction *common = commonIRemTransforms(I))
2571 return common;
2572
2573 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2574 // X urem C^2 -> X and C
2575 // Check to see if this is an unsigned remainder with an exact power of 2,
2576 // if so, convert to a bitwise and.
2577 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
2578 if (isPowerOf2_64(C->getZExtValue()))
2579 return BinaryOperator::createAnd(Op0, SubOne(C));
2580 }
2581
Chris Lattner2e90b732006-02-05 07:54:04 +00002582 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00002583 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
2584 if (RHSI->getOpcode() == Instruction::Shl &&
2585 isa<ConstantInt>(RHSI->getOperand(0))) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002586 unsigned C1 = cast<ConstantInt>(RHSI->getOperand(0))->getZExtValue();
Chris Lattner2e90b732006-02-05 07:54:04 +00002587 if (isPowerOf2_64(C1)) {
2588 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
2589 Value *Add = InsertNewInstBefore(BinaryOperator::createAdd(RHSI, N1,
2590 "tmp"), I);
2591 return BinaryOperator::createAnd(Op0, Add);
2592 }
2593 }
Reid Spencer7eb55b32006-11-02 01:53:59 +00002594 }
Chris Lattnerd79dc792006-09-09 20:26:32 +00002595
Reid Spencer7eb55b32006-11-02 01:53:59 +00002596 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
2597 // where C1&C2 are powers of two.
2598 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2599 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2600 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
2601 // STO == 0 and SFO == 0 handled above.
2602 if (isPowerOf2_64(STO->getZExtValue()) &&
2603 isPowerOf2_64(SFO->getZExtValue())) {
2604 Value *TrueAnd = InsertNewInstBefore(
2605 BinaryOperator::createAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
2606 Value *FalseAnd = InsertNewInstBefore(
2607 BinaryOperator::createAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
2608 return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
2609 }
2610 }
Chris Lattner2e90b732006-02-05 07:54:04 +00002611 }
2612
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002613 return 0;
2614}
2615
Reid Spencer7eb55b32006-11-02 01:53:59 +00002616Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
2617 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2618
2619 if (Instruction *common = commonIRemTransforms(I))
2620 return common;
2621
2622 if (Value *RHSNeg = dyn_castNegVal(Op1))
2623 if (!isa<ConstantInt>(RHSNeg) ||
2624 cast<ConstantInt>(RHSNeg)->getSExtValue() > 0) {
2625 // X % -Y -> X % Y
2626 AddUsesToWorkList(I);
2627 I.setOperand(1, RHSNeg);
2628 return &I;
2629 }
2630
2631 // If the top bits of both operands are zero (i.e. we can prove they are
2632 // unsigned inputs), turn this into a urem.
2633 uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
2634 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2635 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
2636 return BinaryOperator::createURem(Op0, Op1, I.getName());
2637 }
2638
2639 return 0;
2640}
2641
2642Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00002643 return commonRemTransforms(I);
2644}
2645
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002646// isMaxValueMinusOne - return true if this is Max-1
Reid Spencer266e42b2006-12-23 06:05:41 +00002647static bool isMaxValueMinusOne(const ConstantInt *C, bool isSigned) {
2648 if (isSigned) {
2649 // Calculate 0111111111..11111
2650 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
2651 int64_t Val = INT64_MAX; // All ones
2652 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
2653 return C->getSExtValue() == Val-1;
2654 }
2655 return C->getZExtValue() == C->getType()->getIntegralTypeMask()-1;
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002656}
2657
2658// isMinValuePlusOne - return true if this is Min+1
Reid Spencer266e42b2006-12-23 06:05:41 +00002659static bool isMinValuePlusOne(const ConstantInt *C, bool isSigned) {
2660 if (isSigned) {
2661 // Calculate 1111111111000000000000
2662 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
2663 int64_t Val = -1; // All ones
2664 Val <<= TypeBits-1; // Shift over to the right spot
2665 return C->getSExtValue() == Val+1;
2666 }
2667 return C->getZExtValue() == 1; // unsigned
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002668}
2669
Chris Lattner35167c32004-06-09 07:59:58 +00002670// isOneBitSet - Return true if there is exactly one bit set in the specified
2671// constant.
2672static bool isOneBitSet(const ConstantInt *CI) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002673 uint64_t V = CI->getZExtValue();
Chris Lattner35167c32004-06-09 07:59:58 +00002674 return V && (V & (V-1)) == 0;
2675}
2676
Chris Lattner8fc5af42004-09-23 21:46:38 +00002677#if 0 // Currently unused
2678// isLowOnes - Return true if the constant is of the form 0+1+.
2679static bool isLowOnes(const ConstantInt *CI) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002680 uint64_t V = CI->getZExtValue();
Chris Lattner8fc5af42004-09-23 21:46:38 +00002681
2682 // There won't be bits set in parts that the type doesn't contain.
Reid Spencere0fc4df2006-10-20 07:07:24 +00002683 V &= ConstantInt::getAllOnesValue(CI->getType())->getZExtValue();
Chris Lattner8fc5af42004-09-23 21:46:38 +00002684
2685 uint64_t U = V+1; // If it is low ones, this should be a power of two.
2686 return U && V && (U & V) == 0;
2687}
2688#endif
2689
2690// isHighOnes - Return true if the constant is of the form 1+0+.
2691// This is the same as lowones(~X).
2692static bool isHighOnes(const ConstantInt *CI) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002693 uint64_t V = ~CI->getZExtValue();
Chris Lattner2c14cf72005-08-07 07:03:10 +00002694 if (~V == 0) return false; // 0's does not match "1+"
Chris Lattner8fc5af42004-09-23 21:46:38 +00002695
2696 // There won't be bits set in parts that the type doesn't contain.
Reid Spencere0fc4df2006-10-20 07:07:24 +00002697 V &= ConstantInt::getAllOnesValue(CI->getType())->getZExtValue();
Chris Lattner8fc5af42004-09-23 21:46:38 +00002698
2699 uint64_t U = V+1; // If it is low ones, this should be a power of two.
2700 return U && V && (U & V) == 0;
2701}
2702
Reid Spencer266e42b2006-12-23 06:05:41 +00002703/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
Chris Lattner3ac7c262003-08-13 20:16:26 +00002704/// are carefully arranged to allow folding of expressions such as:
2705///
2706/// (A < B) | (A > B) --> (A != B)
2707///
Reid Spencer266e42b2006-12-23 06:05:41 +00002708/// Note that this is only valid if the first and second predicates have the
2709/// same sign. Is illegal to do: (A u< B) | (A s> B)
Chris Lattner3ac7c262003-08-13 20:16:26 +00002710///
Reid Spencer266e42b2006-12-23 06:05:41 +00002711/// Three bits are used to represent the condition, as follows:
2712/// 0 A > B
2713/// 1 A == B
2714/// 2 A < B
2715///
2716/// <=> Value Definition
2717/// 000 0 Always false
2718/// 001 1 A > B
2719/// 010 2 A == B
2720/// 011 3 A >= B
2721/// 100 4 A < B
2722/// 101 5 A != B
2723/// 110 6 A <= B
2724/// 111 7 Always true
2725///
2726static unsigned getICmpCode(const ICmpInst *ICI) {
2727 switch (ICI->getPredicate()) {
Chris Lattner3ac7c262003-08-13 20:16:26 +00002728 // False -> 0
Reid Spencer266e42b2006-12-23 06:05:41 +00002729 case ICmpInst::ICMP_UGT: return 1; // 001
2730 case ICmpInst::ICMP_SGT: return 1; // 001
2731 case ICmpInst::ICMP_EQ: return 2; // 010
2732 case ICmpInst::ICMP_UGE: return 3; // 011
2733 case ICmpInst::ICMP_SGE: return 3; // 011
2734 case ICmpInst::ICMP_ULT: return 4; // 100
2735 case ICmpInst::ICMP_SLT: return 4; // 100
2736 case ICmpInst::ICMP_NE: return 5; // 101
2737 case ICmpInst::ICMP_ULE: return 6; // 110
2738 case ICmpInst::ICMP_SLE: return 6; // 110
Chris Lattner3ac7c262003-08-13 20:16:26 +00002739 // True -> 7
2740 default:
Reid Spencer266e42b2006-12-23 06:05:41 +00002741 assert(0 && "Invalid ICmp predicate!");
Chris Lattner3ac7c262003-08-13 20:16:26 +00002742 return 0;
2743 }
2744}
2745
Reid Spencer266e42b2006-12-23 06:05:41 +00002746/// getICmpValue - This is the complement of getICmpCode, which turns an
2747/// opcode and two operands into either a constant true or false, or a brand
2748/// new /// ICmp instruction. The sign is passed in to determine which kind
2749/// of predicate to use in new icmp instructions.
2750static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
2751 switch (code) {
2752 default: assert(0 && "Illegal ICmp code!");
Zhou Sheng75b871f2007-01-11 12:24:14 +00002753 case 0: return ConstantInt::getFalse();
Reid Spencer266e42b2006-12-23 06:05:41 +00002754 case 1:
2755 if (sign)
2756 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
2757 else
2758 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
2759 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
2760 case 3:
2761 if (sign)
2762 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
2763 else
2764 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
2765 case 4:
2766 if (sign)
2767 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
2768 else
2769 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
2770 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
2771 case 6:
2772 if (sign)
2773 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
2774 else
2775 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
Zhou Sheng75b871f2007-01-11 12:24:14 +00002776 case 7: return ConstantInt::getTrue();
Chris Lattner3ac7c262003-08-13 20:16:26 +00002777 }
2778}
2779
Reid Spencer266e42b2006-12-23 06:05:41 +00002780static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
2781 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
2782 (ICmpInst::isSignedPredicate(p1) &&
2783 (p2 == ICmpInst::ICMP_EQ || p2 == ICmpInst::ICMP_NE)) ||
2784 (ICmpInst::isSignedPredicate(p2) &&
2785 (p1 == ICmpInst::ICMP_EQ || p1 == ICmpInst::ICMP_NE));
2786}
2787
2788namespace {
2789// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
2790struct FoldICmpLogical {
Chris Lattner3ac7c262003-08-13 20:16:26 +00002791 InstCombiner &IC;
2792 Value *LHS, *RHS;
Reid Spencer266e42b2006-12-23 06:05:41 +00002793 ICmpInst::Predicate pred;
2794 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
2795 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
2796 pred(ICI->getPredicate()) {}
Chris Lattner3ac7c262003-08-13 20:16:26 +00002797 bool shouldApply(Value *V) const {
Reid Spencer266e42b2006-12-23 06:05:41 +00002798 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
2799 if (PredicatesFoldable(pred, ICI->getPredicate()))
2800 return (ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS ||
2801 ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS);
Chris Lattner3ac7c262003-08-13 20:16:26 +00002802 return false;
2803 }
Reid Spencer266e42b2006-12-23 06:05:41 +00002804 Instruction *apply(Instruction &Log) const {
2805 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
2806 if (ICI->getOperand(0) != LHS) {
2807 assert(ICI->getOperand(1) == LHS);
2808 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
Chris Lattner3ac7c262003-08-13 20:16:26 +00002809 }
2810
Reid Spencer266e42b2006-12-23 06:05:41 +00002811 unsigned LHSCode = getICmpCode(ICI);
2812 unsigned RHSCode = getICmpCode(cast<ICmpInst>(Log.getOperand(1)));
Chris Lattner3ac7c262003-08-13 20:16:26 +00002813 unsigned Code;
2814 switch (Log.getOpcode()) {
2815 case Instruction::And: Code = LHSCode & RHSCode; break;
2816 case Instruction::Or: Code = LHSCode | RHSCode; break;
2817 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner2caaaba2003-09-22 20:33:34 +00002818 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattner3ac7c262003-08-13 20:16:26 +00002819 }
2820
Reid Spencer266e42b2006-12-23 06:05:41 +00002821 Value *RV = getICmpValue(ICmpInst::isSignedPredicate(pred), Code, LHS, RHS);
Chris Lattner3ac7c262003-08-13 20:16:26 +00002822 if (Instruction *I = dyn_cast<Instruction>(RV))
2823 return I;
2824 // Otherwise, it's a constant boolean value...
2825 return IC.ReplaceInstUsesWith(Log, RV);
2826 }
2827};
Chris Lattnere3a63d12006-11-15 04:53:24 +00002828} // end anonymous namespace
Chris Lattner3ac7c262003-08-13 20:16:26 +00002829
Chris Lattnerba1cb382003-09-19 17:17:26 +00002830// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
2831// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
2832// guaranteed to be either a shift instruction or a binary operator.
2833Instruction *InstCombiner::OptAndOp(Instruction *Op,
Zhou Sheng75b871f2007-01-11 12:24:14 +00002834 ConstantInt *OpRHS,
2835 ConstantInt *AndRHS,
Chris Lattnerba1cb382003-09-19 17:17:26 +00002836 BinaryOperator &TheAnd) {
2837 Value *X = Op->getOperand(0);
Chris Lattnerfcf21a72004-01-12 19:47:05 +00002838 Constant *Together = 0;
2839 if (!isa<ShiftInst>(Op))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002840 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002841
Chris Lattnerba1cb382003-09-19 17:17:26 +00002842 switch (Op->getOpcode()) {
2843 case Instruction::Xor:
Chris Lattner86102b82005-01-01 16:22:27 +00002844 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00002845 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
2846 std::string OpName = Op->getName(); Op->setName("");
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002847 Instruction *And = BinaryOperator::createAnd(X, AndRHS, OpName);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002848 InsertNewInstBefore(And, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002849 return BinaryOperator::createXor(And, Together);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002850 }
2851 break;
2852 case Instruction::Or:
Chris Lattner86102b82005-01-01 16:22:27 +00002853 if (Together == AndRHS) // (X | C) & C --> C
2854 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002855
Chris Lattner86102b82005-01-01 16:22:27 +00002856 if (Op->hasOneUse() && Together != OpRHS) {
2857 // (X | C1) & C2 --> (X | (C1&C2)) & C2
2858 std::string Op0Name = Op->getName(); Op->setName("");
2859 Instruction *Or = BinaryOperator::createOr(X, Together, Op0Name);
2860 InsertNewInstBefore(Or, TheAnd);
2861 return BinaryOperator::createAnd(Or, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002862 }
2863 break;
2864 case Instruction::Add:
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002865 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00002866 // Adding a one to a single bit bit-field should be turned into an XOR
2867 // of the bit. First thing to check is to see if this AND is with a
2868 // single bit constant.
Reid Spencere0fc4df2006-10-20 07:07:24 +00002869 uint64_t AndRHSV = cast<ConstantInt>(AndRHS)->getZExtValue();
Chris Lattnerba1cb382003-09-19 17:17:26 +00002870
2871 // Clear bits that are not part of the constant.
Chris Lattner77defba2006-02-07 07:00:41 +00002872 AndRHSV &= AndRHS->getType()->getIntegralTypeMask();
Chris Lattnerba1cb382003-09-19 17:17:26 +00002873
2874 // If there is only one bit set...
Chris Lattner35167c32004-06-09 07:59:58 +00002875 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00002876 // Ok, at this point, we know that we are masking the result of the
2877 // ADD down to exactly one bit. If the constant we are adding has
2878 // no bits set below this bit, then we can eliminate the ADD.
Reid Spencere0fc4df2006-10-20 07:07:24 +00002879 uint64_t AddRHS = cast<ConstantInt>(OpRHS)->getZExtValue();
Misha Brukmanb1c93172005-04-21 23:48:37 +00002880
Chris Lattnerba1cb382003-09-19 17:17:26 +00002881 // Check to see if any bits below the one bit set in AndRHSV are set.
2882 if ((AddRHS & (AndRHSV-1)) == 0) {
2883 // If not, the only thing that can effect the output of the AND is
2884 // the bit specified by AndRHSV. If that bit is set, the effect of
2885 // the XOR is to toggle the bit. If it is clear, then the ADD has
2886 // no effect.
2887 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
2888 TheAnd.setOperand(0, X);
2889 return &TheAnd;
2890 } else {
2891 std::string Name = Op->getName(); Op->setName("");
2892 // Pull the XOR out of the AND.
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002893 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS, Name);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002894 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002895 return BinaryOperator::createXor(NewAnd, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002896 }
2897 }
2898 }
2899 }
2900 break;
Chris Lattner2da29172003-09-19 19:05:02 +00002901
2902 case Instruction::Shl: {
2903 // We know that the AND will not produce any of the bits shifted in, so if
2904 // the anded constant includes them, clear them now!
2905 //
Zhou Sheng75b871f2007-01-11 12:24:14 +00002906 Constant *AllOne = ConstantInt::getAllOnesValue(AndRHS->getType());
Chris Lattner7e794272004-09-24 15:21:34 +00002907 Constant *ShlMask = ConstantExpr::getShl(AllOne, OpRHS);
2908 Constant *CI = ConstantExpr::getAnd(AndRHS, ShlMask);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002909
Chris Lattner7e794272004-09-24 15:21:34 +00002910 if (CI == ShlMask) { // Masking out bits that the shift already masks
2911 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
2912 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner2da29172003-09-19 19:05:02 +00002913 TheAnd.setOperand(1, CI);
2914 return &TheAnd;
2915 }
2916 break;
Misha Brukmanb1c93172005-04-21 23:48:37 +00002917 }
Reid Spencerfdff9382006-11-08 06:47:33 +00002918 case Instruction::LShr:
2919 {
Chris Lattner2da29172003-09-19 19:05:02 +00002920 // We know that the AND will not produce any of the bits shifted in, so if
2921 // the anded constant includes them, clear them now! This only applies to
2922 // unsigned shifts, because a signed shr may bring in set bits!
2923 //
Zhou Sheng75b871f2007-01-11 12:24:14 +00002924 Constant *AllOne = ConstantInt::getAllOnesValue(AndRHS->getType());
Reid Spencerfdff9382006-11-08 06:47:33 +00002925 Constant *ShrMask = ConstantExpr::getLShr(AllOne, OpRHS);
2926 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
Chris Lattner7e794272004-09-24 15:21:34 +00002927
Reid Spencerfdff9382006-11-08 06:47:33 +00002928 if (CI == ShrMask) { // Masking out bits that the shift already masks.
2929 return ReplaceInstUsesWith(TheAnd, Op);
2930 } else if (CI != AndRHS) {
2931 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
2932 return &TheAnd;
2933 }
2934 break;
2935 }
2936 case Instruction::AShr:
2937 // Signed shr.
2938 // See if this is shifting in some sign extension, then masking it out
2939 // with an and.
2940 if (Op->hasOneUse()) {
Zhou Sheng75b871f2007-01-11 12:24:14 +00002941 Constant *AllOne = ConstantInt::getAllOnesValue(AndRHS->getType());
Reid Spencerfdff9382006-11-08 06:47:33 +00002942 Constant *ShrMask = ConstantExpr::getLShr(AllOne, OpRHS);
Reid Spencer2a499b02006-12-13 17:19:09 +00002943 Constant *C = ConstantExpr::getAnd(AndRHS, ShrMask);
2944 if (C == AndRHS) { // Masking out bits shifted in.
Reid Spencer13bc5d72006-12-12 09:18:51 +00002945 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
Reid Spencerfdff9382006-11-08 06:47:33 +00002946 // Make the argument unsigned.
2947 Value *ShVal = Op->getOperand(0);
Reid Spencer2a499b02006-12-13 17:19:09 +00002948 ShVal = InsertNewInstBefore(new ShiftInst(Instruction::LShr, ShVal,
2949 OpRHS, Op->getName()), TheAnd);
2950 return BinaryOperator::createAnd(ShVal, AndRHS, TheAnd.getName());
Chris Lattner7e794272004-09-24 15:21:34 +00002951 }
Chris Lattner2da29172003-09-19 19:05:02 +00002952 }
2953 break;
Chris Lattnerba1cb382003-09-19 17:17:26 +00002954 }
2955 return 0;
2956}
2957
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002958
Chris Lattner6862fbd2004-09-29 17:40:11 +00002959/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
2960/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
Reid Spencer266e42b2006-12-23 06:05:41 +00002961/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
2962/// whether to treat the V, Lo and HI as signed or not. IB is the location to
Chris Lattner6862fbd2004-09-29 17:40:11 +00002963/// insert new instructions.
2964Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencer266e42b2006-12-23 06:05:41 +00002965 bool isSigned, bool Inside,
2966 Instruction &IB) {
Zhou Sheng75b871f2007-01-11 12:24:14 +00002967 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
Reid Spencercddc9df2007-01-12 04:24:46 +00002968 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
Chris Lattner6862fbd2004-09-29 17:40:11 +00002969 "Lo is not <= Hi in range emission code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00002970
Chris Lattner6862fbd2004-09-29 17:40:11 +00002971 if (Inside) {
2972 if (Lo == Hi) // Trivially false.
Reid Spencer266e42b2006-12-23 06:05:41 +00002973 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002974
Reid Spencer266e42b2006-12-23 06:05:41 +00002975 // V >= Min && V < Hi --> V < Hi
Zhou Sheng75b871f2007-01-11 12:24:14 +00002976 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00002977 ICmpInst::Predicate pred = (isSigned ?
2978 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
2979 return new ICmpInst(pred, V, Hi);
2980 }
2981
2982 // Emit V-Lo <u Hi-Lo
2983 Constant *NegLo = ConstantExpr::getNeg(Lo);
2984 Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
Chris Lattner6862fbd2004-09-29 17:40:11 +00002985 InsertNewInstBefore(Add, IB);
Reid Spencer266e42b2006-12-23 06:05:41 +00002986 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
2987 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00002988 }
2989
2990 if (Lo == Hi) // Trivially true.
Reid Spencer266e42b2006-12-23 06:05:41 +00002991 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
Chris Lattner6862fbd2004-09-29 17:40:11 +00002992
Reid Spencer266e42b2006-12-23 06:05:41 +00002993 // V < Min || V >= Hi ->'V > Hi-1'
Chris Lattner6862fbd2004-09-29 17:40:11 +00002994 Hi = SubOne(cast<ConstantInt>(Hi));
Zhou Sheng75b871f2007-01-11 12:24:14 +00002995 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00002996 ICmpInst::Predicate pred = (isSigned ?
2997 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
2998 return new ICmpInst(pred, V, Hi);
2999 }
Reid Spencere0fc4df2006-10-20 07:07:24 +00003000
Reid Spencer266e42b2006-12-23 06:05:41 +00003001 // Emit V-Lo > Hi-1-Lo
3002 Constant *NegLo = ConstantExpr::getNeg(Lo);
3003 Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
Chris Lattner6862fbd2004-09-29 17:40:11 +00003004 InsertNewInstBefore(Add, IB);
Reid Spencer266e42b2006-12-23 06:05:41 +00003005 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3006 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00003007}
3008
Chris Lattnerb4b25302005-09-18 07:22:02 +00003009// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3010// any number of 0s on either side. The 1s are allowed to wrap from LSB to
3011// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3012// not, since all 1s are not contiguous.
Zhou Sheng75b871f2007-01-11 12:24:14 +00003013static bool isRunOfOnes(ConstantInt *Val, unsigned &MB, unsigned &ME) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00003014 uint64_t V = Val->getZExtValue();
Chris Lattnerb4b25302005-09-18 07:22:02 +00003015 if (!isShiftedMask_64(V)) return false;
3016
3017 // look for the first zero bit after the run of ones
3018 MB = 64-CountLeadingZeros_64((V - 1) ^ V);
3019 // look for the first non-zero bit
3020 ME = 64-CountLeadingZeros_64(V);
3021 return true;
3022}
3023
3024
3025
3026/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3027/// where isSub determines whether the operator is a sub. If we can fold one of
3028/// the following xforms:
Chris Lattneraf517572005-09-18 04:24:45 +00003029///
3030/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3031/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3032/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3033///
3034/// return (A +/- B).
3035///
3036Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
Zhou Sheng75b871f2007-01-11 12:24:14 +00003037 ConstantInt *Mask, bool isSub,
Chris Lattneraf517572005-09-18 04:24:45 +00003038 Instruction &I) {
3039 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3040 if (!LHSI || LHSI->getNumOperands() != 2 ||
3041 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3042
3043 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3044
3045 switch (LHSI->getOpcode()) {
3046 default: return 0;
3047 case Instruction::And:
Chris Lattnerb4b25302005-09-18 07:22:02 +00003048 if (ConstantExpr::getAnd(N, Mask) == Mask) {
3049 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Reid Spencere0fc4df2006-10-20 07:07:24 +00003050 if ((Mask->getZExtValue() & Mask->getZExtValue()+1) == 0)
Chris Lattnerb4b25302005-09-18 07:22:02 +00003051 break;
3052
3053 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3054 // part, we don't need any explicit masks to take them out of A. If that
3055 // is all N is, ignore it.
3056 unsigned MB, ME;
3057 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003058 uint64_t Mask = RHS->getType()->getIntegralTypeMask();
3059 Mask >>= 64-MB+1;
3060 if (MaskedValueIsZero(RHS, Mask))
Chris Lattnerb4b25302005-09-18 07:22:02 +00003061 break;
3062 }
3063 }
Chris Lattneraf517572005-09-18 04:24:45 +00003064 return 0;
3065 case Instruction::Or:
3066 case Instruction::Xor:
Chris Lattnerb4b25302005-09-18 07:22:02 +00003067 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Reid Spencere0fc4df2006-10-20 07:07:24 +00003068 if ((Mask->getZExtValue() & Mask->getZExtValue()+1) == 0 &&
Chris Lattnerb4b25302005-09-18 07:22:02 +00003069 ConstantExpr::getAnd(N, Mask)->isNullValue())
Chris Lattneraf517572005-09-18 04:24:45 +00003070 break;
3071 return 0;
3072 }
3073
3074 Instruction *New;
3075 if (isSub)
3076 New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
3077 else
3078 New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
3079 return InsertNewInstBefore(New, I);
3080}
3081
Chris Lattner113f4f42002-06-25 16:13:24 +00003082Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003083 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00003084 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003085
Chris Lattner81a7a232004-10-16 18:11:37 +00003086 if (isa<UndefValue>(Op1)) // X & undef -> 0
3087 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3088
Chris Lattner86102b82005-01-01 16:22:27 +00003089 // and X, X = X
3090 if (Op0 == Op1)
Chris Lattnere6794492002-08-12 21:17:25 +00003091 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003092
Chris Lattner5b2edb12006-02-12 08:02:11 +00003093 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner5997cf92006-02-08 03:25:32 +00003094 // purpose is to compute bits we don't care about.
Chris Lattner0157e7f2006-02-11 09:31:47 +00003095 uint64_t KnownZero, KnownOne;
Chris Lattnerd70d9f52006-03-25 21:58:26 +00003096 if (!isa<PackedType>(I.getType()) &&
3097 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
Chris Lattner0157e7f2006-02-11 09:31:47 +00003098 KnownZero, KnownOne))
Chris Lattner5997cf92006-02-08 03:25:32 +00003099 return &I;
3100
Zhou Sheng75b871f2007-01-11 12:24:14 +00003101 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00003102 uint64_t AndRHSMask = AndRHS->getZExtValue();
3103 uint64_t TypeMask = Op0->getType()->getIntegralTypeMask();
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00003104 uint64_t NotAndRHS = AndRHSMask^TypeMask;
Chris Lattner86102b82005-01-01 16:22:27 +00003105
Chris Lattnerba1cb382003-09-19 17:17:26 +00003106 // Optimize a variety of ((val OP C1) & C2) combinations...
3107 if (isa<BinaryOperator>(Op0) || isa<ShiftInst>(Op0)) {
3108 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner86102b82005-01-01 16:22:27 +00003109 Value *Op0LHS = Op0I->getOperand(0);
3110 Value *Op0RHS = Op0I->getOperand(1);
3111 switch (Op0I->getOpcode()) {
3112 case Instruction::Xor:
3113 case Instruction::Or:
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00003114 // If the mask is only needed on one incoming arm, push it up.
3115 if (Op0I->hasOneUse()) {
3116 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3117 // Not masking anything out for the LHS, move to RHS.
3118 Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
3119 Op0RHS->getName()+".masked");
3120 InsertNewInstBefore(NewRHS, I);
3121 return BinaryOperator::create(
3122 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003123 }
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003124 if (!isa<Constant>(Op0RHS) &&
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00003125 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3126 // Not masking anything out for the RHS, move to LHS.
3127 Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
3128 Op0LHS->getName()+".masked");
3129 InsertNewInstBefore(NewLHS, I);
3130 return BinaryOperator::create(
3131 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3132 }
3133 }
3134
Chris Lattner86102b82005-01-01 16:22:27 +00003135 break;
Chris Lattneraf517572005-09-18 04:24:45 +00003136 case Instruction::Add:
Chris Lattnerb4b25302005-09-18 07:22:02 +00003137 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3138 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3139 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3140 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
3141 return BinaryOperator::createAnd(V, AndRHS);
3142 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
3143 return BinaryOperator::createAnd(V, AndRHS); // Add commutes
Chris Lattneraf517572005-09-18 04:24:45 +00003144 break;
3145
3146 case Instruction::Sub:
Chris Lattnerb4b25302005-09-18 07:22:02 +00003147 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3148 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3149 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3150 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
3151 return BinaryOperator::createAnd(V, AndRHS);
Chris Lattneraf517572005-09-18 04:24:45 +00003152 break;
Chris Lattner86102b82005-01-01 16:22:27 +00003153 }
3154
Chris Lattner16464b32003-07-23 19:25:52 +00003155 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner86102b82005-01-01 16:22:27 +00003156 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerba1cb382003-09-19 17:17:26 +00003157 return Res;
Chris Lattner86102b82005-01-01 16:22:27 +00003158 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
Chris Lattner2c14cf72005-08-07 07:03:10 +00003159 // If this is an integer truncation or change from signed-to-unsigned, and
3160 // if the source is an and/or with immediate, transform it. This
3161 // frequently occurs for bitfield accesses.
3162 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003163 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
Chris Lattner2c14cf72005-08-07 07:03:10 +00003164 CastOp->getNumOperands() == 2)
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00003165 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1)))
Chris Lattner2c14cf72005-08-07 07:03:10 +00003166 if (CastOp->getOpcode() == Instruction::And) {
3167 // Change: and (cast (and X, C1) to T), C2
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003168 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
3169 // This will fold the two constants together, which may allow
3170 // other simplifications.
Reid Spencerbb65ebf2006-12-12 23:36:14 +00003171 Instruction *NewCast = CastInst::createTruncOrBitCast(
3172 CastOp->getOperand(0), I.getType(),
3173 CastOp->getName()+".shrunk");
Chris Lattner2c14cf72005-08-07 07:03:10 +00003174 NewCast = InsertNewInstBefore(NewCast, I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003175 // trunc_or_bitcast(C1)&C2
Reid Spencerbb65ebf2006-12-12 23:36:14 +00003176 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003177 C3 = ConstantExpr::getAnd(C3, AndRHS);
Chris Lattner2c14cf72005-08-07 07:03:10 +00003178 return BinaryOperator::createAnd(NewCast, C3);
3179 } else if (CastOp->getOpcode() == Instruction::Or) {
3180 // Change: and (cast (or X, C1) to T), C2
3181 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Chris Lattner2dc148e2006-12-12 19:11:20 +00003182 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Chris Lattner2c14cf72005-08-07 07:03:10 +00003183 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
3184 return ReplaceInstUsesWith(I, AndRHS);
3185 }
3186 }
Chris Lattner33217db2003-07-23 19:36:21 +00003187 }
Chris Lattner183b3362004-04-09 19:05:30 +00003188
3189 // Try to fold constant and into select arguments.
3190 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00003191 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00003192 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00003193 if (isa<PHINode>(Op0))
3194 if (Instruction *NV = FoldOpIntoPhi(I))
3195 return NV;
Chris Lattner49b47ae2003-07-23 17:57:01 +00003196 }
3197
Chris Lattnerbb74e222003-03-10 23:06:50 +00003198 Value *Op0NotVal = dyn_castNotVal(Op0);
3199 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00003200
Chris Lattner023a4832004-06-18 06:07:51 +00003201 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
3202 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3203
Misha Brukman9c003d82004-07-30 12:50:08 +00003204 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattnerbb74e222003-03-10 23:06:50 +00003205 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003206 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
3207 I.getName()+".demorgan");
Chris Lattner49b47ae2003-07-23 17:57:01 +00003208 InsertNewInstBefore(Or, I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00003209 return BinaryOperator::createNot(Or);
3210 }
Chris Lattner8b10ab32006-02-13 23:07:23 +00003211
3212 {
3213 Value *A = 0, *B = 0;
Chris Lattner8b10ab32006-02-13 23:07:23 +00003214 if (match(Op0, m_Or(m_Value(A), m_Value(B))))
3215 if (A == Op1 || B == Op1) // (A | ?) & A --> A
3216 return ReplaceInstUsesWith(I, Op1);
3217 if (match(Op1, m_Or(m_Value(A), m_Value(B))))
3218 if (A == Op0 || B == Op0) // A & (A | ?) --> A
3219 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerdcd07922006-04-01 08:03:55 +00003220
3221 if (Op0->hasOneUse() &&
3222 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3223 if (A == Op1) { // (A^B)&A -> A&(A^B)
3224 I.swapOperands(); // Simplify below
3225 std::swap(Op0, Op1);
3226 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
3227 cast<BinaryOperator>(Op0)->swapOperands();
3228 I.swapOperands(); // Simplify below
3229 std::swap(Op0, Op1);
3230 }
3231 }
3232 if (Op1->hasOneUse() &&
3233 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3234 if (B == Op0) { // B&(A^B) -> B&(B^A)
3235 cast<BinaryOperator>(Op1)->swapOperands();
3236 std::swap(A, B);
3237 }
3238 if (A == Op0) { // A&(A^B) -> A & ~B
3239 Instruction *NotB = BinaryOperator::createNot(B, "tmp");
3240 InsertNewInstBefore(NotB, I);
3241 return BinaryOperator::createAnd(A, NotB);
3242 }
3243 }
Chris Lattner8b10ab32006-02-13 23:07:23 +00003244 }
3245
Reid Spencer266e42b2006-12-23 06:05:41 +00003246 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
3247 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3248 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattner3ac7c262003-08-13 20:16:26 +00003249 return R;
3250
Chris Lattner623826c2004-09-28 21:48:02 +00003251 Value *LHSVal, *RHSVal;
3252 ConstantInt *LHSCst, *RHSCst;
Reid Spencer266e42b2006-12-23 06:05:41 +00003253 ICmpInst::Predicate LHSCC, RHSCC;
3254 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3255 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3256 if (LHSVal == RHSVal && // Found (X icmp C1) & (X icmp C2)
3257 // ICMP_[GL]E X, CST is folded to ICMP_[GL]T elsewhere.
3258 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3259 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3260 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
3261 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE) {
Chris Lattner623826c2004-09-28 21:48:02 +00003262 // Ensure that the larger constant is on the RHS.
Reid Spencer266e42b2006-12-23 06:05:41 +00003263 ICmpInst::Predicate GT = ICmpInst::isSignedPredicate(LHSCC) ?
3264 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
3265 Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3266 ICmpInst *LHS = cast<ICmpInst>(Op0);
Reid Spencercddc9df2007-01-12 04:24:46 +00003267 if (cast<ConstantInt>(Cmp)->getZExtValue()) {
Chris Lattner623826c2004-09-28 21:48:02 +00003268 std::swap(LHS, RHS);
3269 std::swap(LHSCst, RHSCst);
3270 std::swap(LHSCC, RHSCC);
3271 }
3272
Reid Spencer266e42b2006-12-23 06:05:41 +00003273 // At this point, we know we have have two icmp instructions
Chris Lattner623826c2004-09-28 21:48:02 +00003274 // comparing a value against two constants and and'ing the result
3275 // together. Because of the above check, we know that we only have
Reid Spencer266e42b2006-12-23 06:05:41 +00003276 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3277 // (from the FoldICmpLogical check above), that the two constants
3278 // are not equal and that the larger constant is on the RHS
Chris Lattner623826c2004-09-28 21:48:02 +00003279 assert(LHSCst != RHSCst && "Compares not folded above?");
3280
3281 switch (LHSCC) {
3282 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003283 case ICmpInst::ICMP_EQ:
Chris Lattner623826c2004-09-28 21:48:02 +00003284 switch (RHSCC) {
3285 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003286 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
3287 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3288 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
Zhou Sheng75b871f2007-01-11 12:24:14 +00003289 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00003290 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3291 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3292 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
Chris Lattner623826c2004-09-28 21:48:02 +00003293 return ReplaceInstUsesWith(I, LHS);
3294 }
Reid Spencer266e42b2006-12-23 06:05:41 +00003295 case ICmpInst::ICMP_NE:
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_ULT:
3299 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3300 return new ICmpInst(ICmpInst::ICMP_ULT, LHSVal, LHSCst);
3301 break; // (X != 13 & X u< 15) -> no change
3302 case ICmpInst::ICMP_SLT:
3303 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3304 return new ICmpInst(ICmpInst::ICMP_SLT, LHSVal, LHSCst);
3305 break; // (X != 13 & X s< 15) -> no change
3306 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
3307 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
3308 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
Chris Lattner623826c2004-09-28 21:48:02 +00003309 return ReplaceInstUsesWith(I, RHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00003310 case ICmpInst::ICMP_NE:
3311 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
Chris Lattner623826c2004-09-28 21:48:02 +00003312 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3313 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3314 LHSVal->getName()+".off");
3315 InsertNewInstBefore(Add, I);
Reid Spencerc635f472006-12-31 05:48:39 +00003316 return new ICmpInst(ICmpInst::ICMP_UGT, Add, AddCST);
Chris Lattner623826c2004-09-28 21:48:02 +00003317 }
3318 break; // (X != 13 & X != 15) -> no change
3319 }
3320 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00003321 case ICmpInst::ICMP_ULT:
Chris Lattner623826c2004-09-28 21:48:02 +00003322 switch (RHSCC) {
3323 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003324 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
3325 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Zhou Sheng75b871f2007-01-11 12:24:14 +00003326 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00003327 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
3328 break;
3329 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
3330 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
Chris Lattner623826c2004-09-28 21:48:02 +00003331 return ReplaceInstUsesWith(I, LHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00003332 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
3333 break;
Chris Lattner623826c2004-09-28 21:48:02 +00003334 }
Reid Spencer266e42b2006-12-23 06:05:41 +00003335 break;
3336 case ICmpInst::ICMP_SLT:
Chris Lattner623826c2004-09-28 21:48:02 +00003337 switch (RHSCC) {
3338 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003339 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
3340 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
Zhou Sheng75b871f2007-01-11 12:24:14 +00003341 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00003342 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
3343 break;
3344 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
3345 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
Chris Lattner623826c2004-09-28 21:48:02 +00003346 return ReplaceInstUsesWith(I, LHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00003347 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
3348 break;
Chris Lattner623826c2004-09-28 21:48:02 +00003349 }
Reid Spencer266e42b2006-12-23 06:05:41 +00003350 break;
3351 case ICmpInst::ICMP_UGT:
3352 switch (RHSCC) {
3353 default: assert(0 && "Unknown integer condition code!");
3354 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X > 13
3355 return ReplaceInstUsesWith(I, LHS);
3356 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
3357 return ReplaceInstUsesWith(I, RHS);
3358 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
3359 break;
3360 case ICmpInst::ICMP_NE:
3361 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3362 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3363 break; // (X u> 13 & X != 15) -> no change
3364 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) ->(X-14) <u 1
3365 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, false,
3366 true, I);
3367 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
3368 break;
3369 }
3370 break;
3371 case ICmpInst::ICMP_SGT:
3372 switch (RHSCC) {
3373 default: assert(0 && "Unknown integer condition code!");
3374 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X s> 13
3375 return ReplaceInstUsesWith(I, LHS);
3376 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
3377 return ReplaceInstUsesWith(I, RHS);
3378 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
3379 break;
3380 case ICmpInst::ICMP_NE:
3381 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3382 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3383 break; // (X s> 13 & X != 15) -> no change
3384 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) ->(X-14) s< 1
3385 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true,
3386 true, I);
3387 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
3388 break;
3389 }
3390 break;
Chris Lattner623826c2004-09-28 21:48:02 +00003391 }
3392 }
3393 }
3394
Chris Lattner3af10532006-05-05 06:39:07 +00003395 // fold (and (cast A), (cast B)) -> (cast (and A, B))
Reid Spencer799b5bf2006-12-13 08:27:15 +00003396 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
3397 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3398 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
3399 const Type *SrcTy = Op0C->getOperand(0)->getType();
3400 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegral() &&
3401 // Only do this if the casts both really cause code to be generated.
Reid Spencer266e42b2006-12-23 06:05:41 +00003402 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
3403 I.getType(), TD) &&
3404 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
3405 I.getType(), TD)) {
Reid Spencer799b5bf2006-12-13 08:27:15 +00003406 Instruction *NewOp = BinaryOperator::createAnd(Op0C->getOperand(0),
3407 Op1C->getOperand(0),
3408 I.getName());
3409 InsertNewInstBefore(NewOp, I);
3410 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
3411 }
Chris Lattner3af10532006-05-05 06:39:07 +00003412 }
Chris Lattnerf05d69a2006-11-14 07:46:50 +00003413
3414 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
3415 if (ShiftInst *SI1 = dyn_cast<ShiftInst>(Op1)) {
3416 if (ShiftInst *SI0 = dyn_cast<ShiftInst>(Op0))
3417 if (SI0->getOpcode() == SI1->getOpcode() &&
3418 SI0->getOperand(1) == SI1->getOperand(1) &&
3419 (SI0->hasOneUse() || SI1->hasOneUse())) {
3420 Instruction *NewOp =
3421 InsertNewInstBefore(BinaryOperator::createAnd(SI0->getOperand(0),
3422 SI1->getOperand(0),
3423 SI0->getName()), I);
3424 return new ShiftInst(SI1->getOpcode(), NewOp, SI1->getOperand(1));
3425 }
Chris Lattner3af10532006-05-05 06:39:07 +00003426 }
3427
Chris Lattner113f4f42002-06-25 16:13:24 +00003428 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003429}
3430
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003431/// CollectBSwapParts - Look to see if the specified value defines a single byte
3432/// in the result. If it does, and if the specified byte hasn't been filled in
3433/// yet, fill it in and return false.
3434static bool CollectBSwapParts(Value *V, std::vector<Value*> &ByteValues) {
3435 Instruction *I = dyn_cast<Instruction>(V);
3436 if (I == 0) return true;
3437
3438 // If this is an or instruction, it is an inner node of the bswap.
3439 if (I->getOpcode() == Instruction::Or)
3440 return CollectBSwapParts(I->getOperand(0), ByteValues) ||
3441 CollectBSwapParts(I->getOperand(1), ByteValues);
3442
3443 // If this is a shift by a constant int, and it is "24", then its operand
3444 // defines a byte. We only handle unsigned types here.
3445 if (isa<ShiftInst>(I) && isa<ConstantInt>(I->getOperand(1))) {
3446 // Not shifting the entire input by N-1 bytes?
Reid Spencere0fc4df2006-10-20 07:07:24 +00003447 if (cast<ConstantInt>(I->getOperand(1))->getZExtValue() !=
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003448 8*(ByteValues.size()-1))
3449 return true;
3450
3451 unsigned DestNo;
3452 if (I->getOpcode() == Instruction::Shl) {
3453 // X << 24 defines the top byte with the lowest of the input bytes.
3454 DestNo = ByteValues.size()-1;
3455 } else {
3456 // X >>u 24 defines the low byte with the highest of the input bytes.
3457 DestNo = 0;
3458 }
3459
3460 // If the destination byte value is already defined, the values are or'd
3461 // together, which isn't a bswap (unless it's an or of the same bits).
3462 if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
3463 return true;
3464 ByteValues[DestNo] = I->getOperand(0);
3465 return false;
3466 }
3467
3468 // Otherwise, we can only handle and(shift X, imm), imm). Bail out of if we
3469 // don't have this.
3470 Value *Shift = 0, *ShiftLHS = 0;
3471 ConstantInt *AndAmt = 0, *ShiftAmt = 0;
3472 if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
3473 !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
3474 return true;
3475 Instruction *SI = cast<Instruction>(Shift);
3476
3477 // Make sure that the shift amount is by a multiple of 8 and isn't too big.
Reid Spencere0fc4df2006-10-20 07:07:24 +00003478 if (ShiftAmt->getZExtValue() & 7 ||
3479 ShiftAmt->getZExtValue() > 8*ByteValues.size())
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003480 return true;
3481
3482 // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
3483 unsigned DestByte;
3484 for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
Reid Spencere0fc4df2006-10-20 07:07:24 +00003485 if (AndAmt->getZExtValue() == uint64_t(0xFF) << 8*DestByte)
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003486 break;
3487 // Unknown mask for bswap.
3488 if (DestByte == ByteValues.size()) return true;
3489
Reid Spencere0fc4df2006-10-20 07:07:24 +00003490 unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003491 unsigned SrcByte;
3492 if (SI->getOpcode() == Instruction::Shl)
3493 SrcByte = DestByte - ShiftBytes;
3494 else
3495 SrcByte = DestByte + ShiftBytes;
3496
3497 // If the SrcByte isn't a bswapped value from the DestByte, reject it.
3498 if (SrcByte != ByteValues.size()-DestByte-1)
3499 return true;
3500
3501 // If the destination byte value is already defined, the values are or'd
3502 // together, which isn't a bswap (unless it's an or of the same bits).
3503 if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
3504 return true;
3505 ByteValues[DestByte] = SI->getOperand(0);
3506 return false;
3507}
3508
3509/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
3510/// If so, insert the new bswap intrinsic and return it.
3511Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
3512 // We can only handle bswap of unsigned integers, and cannot bswap one byte.
Reid Spencerc635f472006-12-31 05:48:39 +00003513 if (I.getType() == Type::Int8Ty)
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003514 return 0;
3515
3516 /// ByteValues - For each byte of the result, we keep track of which value
3517 /// defines each byte.
3518 std::vector<Value*> ByteValues;
3519 ByteValues.resize(I.getType()->getPrimitiveSize());
3520
3521 // Try to find all the pieces corresponding to the bswap.
3522 if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
3523 CollectBSwapParts(I.getOperand(1), ByteValues))
3524 return 0;
3525
3526 // Check to see if all of the bytes come from the same value.
3527 Value *V = ByteValues[0];
3528 if (V == 0) return 0; // Didn't find a byte? Must be zero.
3529
3530 // Check to make sure that all of the bytes come from the same value.
3531 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
3532 if (ByteValues[i] != V)
3533 return 0;
3534
3535 // If they do then *success* we can turn this into a bswap. Figure out what
3536 // bswap to make it into.
3537 Module *M = I.getParent()->getParent()->getParent();
Chris Lattner091b6ea2006-07-11 18:31:26 +00003538 const char *FnName = 0;
Reid Spencerc635f472006-12-31 05:48:39 +00003539 if (I.getType() == Type::Int16Ty)
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003540 FnName = "llvm.bswap.i16";
Reid Spencerc635f472006-12-31 05:48:39 +00003541 else if (I.getType() == Type::Int32Ty)
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003542 FnName = "llvm.bswap.i32";
Reid Spencerc635f472006-12-31 05:48:39 +00003543 else if (I.getType() == Type::Int64Ty)
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003544 FnName = "llvm.bswap.i64";
3545 else
3546 assert(0 && "Unknown integer type!");
Chris Lattnerfbc524f2007-01-07 06:58:05 +00003547 Constant *F = M->getOrInsertFunction(FnName, I.getType(), I.getType(), NULL);
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003548 return new CallInst(F, V);
3549}
3550
3551
Chris Lattner113f4f42002-06-25 16:13:24 +00003552Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003553 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00003554 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003555
Chris Lattner81a7a232004-10-16 18:11:37 +00003556 if (isa<UndefValue>(Op1))
3557 return ReplaceInstUsesWith(I, // X | undef -> -1
Zhou Sheng75b871f2007-01-11 12:24:14 +00003558 ConstantInt::getAllOnesValue(I.getType()));
Chris Lattner81a7a232004-10-16 18:11:37 +00003559
Chris Lattner5b2edb12006-02-12 08:02:11 +00003560 // or X, X = X
3561 if (Op0 == Op1)
Chris Lattnere6794492002-08-12 21:17:25 +00003562 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003563
Chris Lattner5b2edb12006-02-12 08:02:11 +00003564 // See if we can simplify any instructions used by the instruction whose sole
3565 // purpose is to compute bits we don't care about.
3566 uint64_t KnownZero, KnownOne;
Chris Lattnerd70d9f52006-03-25 21:58:26 +00003567 if (!isa<PackedType>(I.getType()) &&
3568 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
Chris Lattner5b2edb12006-02-12 08:02:11 +00003569 KnownZero, KnownOne))
3570 return &I;
3571
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003572 // or X, -1 == -1
Zhou Sheng75b871f2007-01-11 12:24:14 +00003573 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner330628a2006-01-06 17:59:59 +00003574 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00003575 // (X & C1) | C2 --> (X | C2) & (C1|C2)
3576 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Chris Lattnerb62f5082005-05-09 04:58:36 +00003577 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0->getName());
3578 Op0->setName("");
Chris Lattnerd4252a72004-07-30 07:50:03 +00003579 InsertNewInstBefore(Or, I);
3580 return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, C1));
3581 }
Chris Lattner8f0d1562003-07-23 18:29:44 +00003582
Chris Lattnerd4252a72004-07-30 07:50:03 +00003583 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
3584 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
3585 std::string Op0Name = Op0->getName(); Op0->setName("");
3586 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
3587 InsertNewInstBefore(Or, I);
3588 return BinaryOperator::createXor(Or,
3589 ConstantExpr::getAnd(C1, ConstantExpr::getNot(RHS)));
Chris Lattner8f0d1562003-07-23 18:29:44 +00003590 }
Chris Lattner183b3362004-04-09 19:05:30 +00003591
3592 // Try to fold constant and into select arguments.
3593 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00003594 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00003595 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00003596 if (isa<PHINode>(Op0))
3597 if (Instruction *NV = FoldOpIntoPhi(I))
3598 return NV;
Chris Lattner8f0d1562003-07-23 18:29:44 +00003599 }
3600
Chris Lattner330628a2006-01-06 17:59:59 +00003601 Value *A = 0, *B = 0;
3602 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattner4294cec2005-05-07 23:49:08 +00003603
3604 if (match(Op0, m_And(m_Value(A), m_Value(B))))
3605 if (A == Op1 || B == Op1) // (A & ?) | A --> A
3606 return ReplaceInstUsesWith(I, Op1);
3607 if (match(Op1, m_And(m_Value(A), m_Value(B))))
3608 if (A == Op0 || B == Op0) // A | (A & ?) --> A
3609 return ReplaceInstUsesWith(I, Op0);
3610
Chris Lattnerb7845d62006-07-10 20:25:24 +00003611 // (A | B) | C and A | (B | C) -> bswap if possible.
3612 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003613 if (match(Op0, m_Or(m_Value(), m_Value())) ||
Chris Lattnerb7845d62006-07-10 20:25:24 +00003614 match(Op1, m_Or(m_Value(), m_Value())) ||
3615 (match(Op0, m_Shift(m_Value(), m_Value())) &&
3616 match(Op1, m_Shift(m_Value(), m_Value())))) {
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003617 if (Instruction *BSwap = MatchBSwap(I))
3618 return BSwap;
3619 }
3620
Chris Lattnerb62f5082005-05-09 04:58:36 +00003621 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
3622 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003623 MaskedValueIsZero(Op1, C1->getZExtValue())) {
Chris Lattnerb62f5082005-05-09 04:58:36 +00003624 Instruction *NOr = BinaryOperator::createOr(A, Op1, Op0->getName());
3625 Op0->setName("");
3626 return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
3627 }
3628
3629 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
3630 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003631 MaskedValueIsZero(Op0, C1->getZExtValue())) {
Chris Lattnerb62f5082005-05-09 04:58:36 +00003632 Instruction *NOr = BinaryOperator::createOr(A, Op0, Op1->getName());
3633 Op0->setName("");
3634 return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
3635 }
3636
Chris Lattner15212982005-09-18 03:42:07 +00003637 // (A & C1)|(B & C2)
Chris Lattnerd4252a72004-07-30 07:50:03 +00003638 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattner15212982005-09-18 03:42:07 +00003639 match(Op1, m_And(m_Value(B), m_ConstantInt(C2)))) {
3640
3641 if (A == B) // (A & C1)|(A & C2) == A & (C1|C2)
3642 return BinaryOperator::createAnd(A, ConstantExpr::getOr(C1, C2));
3643
3644
Chris Lattner01f56c62005-09-18 06:02:59 +00003645 // If we have: ((V + N) & C1) | (V & C2)
3646 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
3647 // replace with V+N.
3648 if (C1 == ConstantExpr::getNot(C2)) {
Chris Lattner330628a2006-01-06 17:59:59 +00003649 Value *V1 = 0, *V2 = 0;
Reid Spencere0fc4df2006-10-20 07:07:24 +00003650 if ((C2->getZExtValue() & (C2->getZExtValue()+1)) == 0 && // C2 == 0+1+
Chris Lattner01f56c62005-09-18 06:02:59 +00003651 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
3652 // Add commutes, try both ways.
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003653 if (V1 == B && MaskedValueIsZero(V2, C2->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003654 return ReplaceInstUsesWith(I, A);
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003655 if (V2 == B && MaskedValueIsZero(V1, C2->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003656 return ReplaceInstUsesWith(I, A);
3657 }
3658 // Or commutes, try both ways.
Reid Spencere0fc4df2006-10-20 07:07:24 +00003659 if ((C1->getZExtValue() & (C1->getZExtValue()+1)) == 0 &&
Chris Lattner01f56c62005-09-18 06:02:59 +00003660 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
3661 // Add commutes, try both ways.
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003662 if (V1 == A && MaskedValueIsZero(V2, C1->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003663 return ReplaceInstUsesWith(I, B);
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003664 if (V2 == A && MaskedValueIsZero(V1, C1->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003665 return ReplaceInstUsesWith(I, B);
Chris Lattner15212982005-09-18 03:42:07 +00003666 }
3667 }
3668 }
Chris Lattnerf05d69a2006-11-14 07:46:50 +00003669
3670 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
3671 if (ShiftInst *SI1 = dyn_cast<ShiftInst>(Op1)) {
3672 if (ShiftInst *SI0 = dyn_cast<ShiftInst>(Op0))
3673 if (SI0->getOpcode() == SI1->getOpcode() &&
3674 SI0->getOperand(1) == SI1->getOperand(1) &&
3675 (SI0->hasOneUse() || SI1->hasOneUse())) {
3676 Instruction *NewOp =
3677 InsertNewInstBefore(BinaryOperator::createOr(SI0->getOperand(0),
3678 SI1->getOperand(0),
3679 SI0->getName()), I);
3680 return new ShiftInst(SI1->getOpcode(), NewOp, SI1->getOperand(1));
3681 }
3682 }
Chris Lattner812aab72003-08-12 19:11:07 +00003683
Chris Lattnerd4252a72004-07-30 07:50:03 +00003684 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
3685 if (A == Op1) // ~A | A == -1
Misha Brukmanb1c93172005-04-21 23:48:37 +00003686 return ReplaceInstUsesWith(I,
Zhou Sheng75b871f2007-01-11 12:24:14 +00003687 ConstantInt::getAllOnesValue(I.getType()));
Chris Lattnerd4252a72004-07-30 07:50:03 +00003688 } else {
3689 A = 0;
3690 }
Chris Lattner4294cec2005-05-07 23:49:08 +00003691 // Note, A is still live here!
Chris Lattnerd4252a72004-07-30 07:50:03 +00003692 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
3693 if (Op0 == B)
Misha Brukmanb1c93172005-04-21 23:48:37 +00003694 return ReplaceInstUsesWith(I,
Zhou Sheng75b871f2007-01-11 12:24:14 +00003695 ConstantInt::getAllOnesValue(I.getType()));
Chris Lattner3e327a42003-03-10 23:13:59 +00003696
Misha Brukman9c003d82004-07-30 12:50:08 +00003697 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattnerd4252a72004-07-30 07:50:03 +00003698 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3699 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
3700 I.getName()+".demorgan"), I);
3701 return BinaryOperator::createNot(And);
3702 }
Chris Lattner3e327a42003-03-10 23:13:59 +00003703 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00003704
Reid Spencer266e42b2006-12-23 06:05:41 +00003705 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
3706 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
3707 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattner3ac7c262003-08-13 20:16:26 +00003708 return R;
3709
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003710 Value *LHSVal, *RHSVal;
3711 ConstantInt *LHSCst, *RHSCst;
Reid Spencer266e42b2006-12-23 06:05:41 +00003712 ICmpInst::Predicate LHSCC, RHSCC;
3713 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3714 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3715 if (LHSVal == RHSVal && // Found (X icmp C1) | (X icmp C2)
3716 // icmp [us][gl]e x, cst is folded to icmp [us][gl]t elsewhere.
3717 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3718 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3719 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
3720 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE) {
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003721 // Ensure that the larger constant is on the RHS.
Reid Spencer266e42b2006-12-23 06:05:41 +00003722 ICmpInst::Predicate GT = ICmpInst::isSignedPredicate(LHSCC) ?
3723 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
3724 Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3725 ICmpInst *LHS = cast<ICmpInst>(Op0);
Reid Spencercddc9df2007-01-12 04:24:46 +00003726 if (cast<ConstantInt>(Cmp)->getZExtValue()) {
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003727 std::swap(LHS, RHS);
3728 std::swap(LHSCst, RHSCst);
3729 std::swap(LHSCC, RHSCC);
3730 }
3731
Reid Spencer266e42b2006-12-23 06:05:41 +00003732 // At this point, we know we have have two icmp instructions
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003733 // comparing a value against two constants and or'ing the result
3734 // together. Because of the above check, we know that we only have
Reid Spencer266e42b2006-12-23 06:05:41 +00003735 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
3736 // FoldICmpLogical check above), that the two constants are not
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003737 // equal.
3738 assert(LHSCst != RHSCst && "Compares not folded above?");
3739
3740 switch (LHSCC) {
3741 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003742 case ICmpInst::ICMP_EQ:
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003743 switch (RHSCC) {
3744 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003745 case ICmpInst::ICMP_EQ:
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003746 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
3747 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3748 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3749 LHSVal->getName()+".off");
3750 InsertNewInstBefore(Add, I);
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003751 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
Reid Spencer266e42b2006-12-23 06:05:41 +00003752 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003753 }
Reid Spencer266e42b2006-12-23 06:05:41 +00003754 break; // (X == 13 | X == 15) -> no change
3755 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
3756 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
Chris Lattner5c219462005-04-19 06:04:18 +00003757 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00003758 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
3759 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
3760 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003761 return ReplaceInstUsesWith(I, RHS);
3762 }
3763 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00003764 case ICmpInst::ICMP_NE:
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003765 switch (RHSCC) {
3766 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003767 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
3768 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
3769 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003770 return ReplaceInstUsesWith(I, LHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00003771 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
3772 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
3773 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Zhou Sheng75b871f2007-01-11 12:24:14 +00003774 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003775 }
3776 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00003777 case ICmpInst::ICMP_ULT:
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 u< 13 | X == 14) -> no change
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003781 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00003782 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) ->(X-13) u> 2
3783 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false,
3784 false, I);
3785 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
3786 break;
3787 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
3788 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003789 return ReplaceInstUsesWith(I, RHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00003790 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
3791 break;
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003792 }
3793 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00003794 case ICmpInst::ICMP_SLT:
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003795 switch (RHSCC) {
3796 default: assert(0 && "Unknown integer condition code!");
Reid Spencer266e42b2006-12-23 06:05:41 +00003797 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
3798 break;
3799 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) ->(X-13) s> 2
3800 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), true,
3801 false, I);
3802 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
3803 break;
3804 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
3805 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
3806 return ReplaceInstUsesWith(I, RHS);
3807 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
3808 break;
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003809 }
Reid Spencer266e42b2006-12-23 06:05:41 +00003810 break;
3811 case ICmpInst::ICMP_UGT:
3812 switch (RHSCC) {
3813 default: assert(0 && "Unknown integer condition code!");
3814 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
3815 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
3816 return ReplaceInstUsesWith(I, LHS);
3817 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
3818 break;
3819 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
3820 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Zhou Sheng75b871f2007-01-11 12:24:14 +00003821 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00003822 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
3823 break;
3824 }
3825 break;
3826 case ICmpInst::ICMP_SGT:
3827 switch (RHSCC) {
3828 default: assert(0 && "Unknown integer condition code!");
3829 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
3830 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
3831 return ReplaceInstUsesWith(I, LHS);
3832 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
3833 break;
3834 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
3835 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Zhou Sheng75b871f2007-01-11 12:24:14 +00003836 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00003837 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
3838 break;
3839 }
3840 break;
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003841 }
3842 }
3843 }
Chris Lattner3af10532006-05-05 06:39:07 +00003844
3845 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Reid Spencer799b5bf2006-12-13 08:27:15 +00003846 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
Chris Lattner3af10532006-05-05 06:39:07 +00003847 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer799b5bf2006-12-13 08:27:15 +00003848 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
3849 const Type *SrcTy = Op0C->getOperand(0)->getType();
3850 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegral() &&
3851 // Only do this if the casts both really cause code to be generated.
Reid Spencer266e42b2006-12-23 06:05:41 +00003852 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
3853 I.getType(), TD) &&
3854 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
3855 I.getType(), TD)) {
Reid Spencer799b5bf2006-12-13 08:27:15 +00003856 Instruction *NewOp = BinaryOperator::createOr(Op0C->getOperand(0),
3857 Op1C->getOperand(0),
3858 I.getName());
3859 InsertNewInstBefore(NewOp, I);
3860 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
3861 }
Chris Lattner3af10532006-05-05 06:39:07 +00003862 }
Chris Lattner3af10532006-05-05 06:39:07 +00003863
Chris Lattner15212982005-09-18 03:42:07 +00003864
Chris Lattner113f4f42002-06-25 16:13:24 +00003865 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003866}
3867
Chris Lattnerc2076352004-02-16 01:20:27 +00003868// XorSelf - Implements: X ^ X --> 0
3869struct XorSelf {
3870 Value *RHS;
3871 XorSelf(Value *rhs) : RHS(rhs) {}
3872 bool shouldApply(Value *LHS) const { return LHS == RHS; }
3873 Instruction *apply(BinaryOperator &Xor) const {
3874 return &Xor;
3875 }
3876};
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003877
3878
Chris Lattner113f4f42002-06-25 16:13:24 +00003879Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003880 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00003881 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003882
Chris Lattner81a7a232004-10-16 18:11:37 +00003883 if (isa<UndefValue>(Op1))
3884 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
3885
Chris Lattnerc2076352004-02-16 01:20:27 +00003886 // xor X, X = 0, even if X is nested in a sequence of Xor's.
3887 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
3888 assert(Result == &I && "AssociativeOpt didn't work?");
Chris Lattnere6794492002-08-12 21:17:25 +00003889 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc2076352004-02-16 01:20:27 +00003890 }
Chris Lattner5b2edb12006-02-12 08:02:11 +00003891
3892 // See if we can simplify any instructions used by the instruction whose sole
3893 // purpose is to compute bits we don't care about.
3894 uint64_t KnownZero, KnownOne;
Chris Lattnerd70d9f52006-03-25 21:58:26 +00003895 if (!isa<PackedType>(I.getType()) &&
3896 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
Chris Lattner5b2edb12006-02-12 08:02:11 +00003897 KnownZero, KnownOne))
3898 return &I;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003899
Zhou Sheng75b871f2007-01-11 12:24:14 +00003900 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00003901 // xor (icmp A, B), true = not (icmp A, B) = !icmp A, B
3902 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Zhou Sheng75b871f2007-01-11 12:24:14 +00003903 if (RHS == ConstantInt::getTrue() && ICI->hasOneUse())
Reid Spencer266e42b2006-12-23 06:05:41 +00003904 return new ICmpInst(ICI->getInversePredicate(),
3905 ICI->getOperand(0), ICI->getOperand(1));
Chris Lattnere5806662003-11-04 23:50:51 +00003906
Reid Spencer266e42b2006-12-23 06:05:41 +00003907 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattner8f2f5982003-11-05 01:06:05 +00003908 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003909 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
3910 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003911 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
3912 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003913 ConstantInt::get(I.getType(), 1));
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003914 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003915 }
Chris Lattner023a4832004-06-18 06:07:51 +00003916
3917 // ~(~X & Y) --> (X | ~Y)
3918 if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
3919 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
3920 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
3921 Instruction *NotY =
Misha Brukmanb1c93172005-04-21 23:48:37 +00003922 BinaryOperator::createNot(Op0I->getOperand(1),
Chris Lattner023a4832004-06-18 06:07:51 +00003923 Op0I->getOperand(1)->getName()+".not");
3924 InsertNewInstBefore(NotY, I);
3925 return BinaryOperator::createOr(Op0NotVal, NotY);
3926 }
3927 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003928
Chris Lattner97638592003-07-23 21:37:07 +00003929 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner5b2edb12006-02-12 08:02:11 +00003930 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner0f68fa62003-11-04 23:37:10 +00003931 // ~(X-c) --> (-c-1)-X
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003932 if (RHS->isAllOnesValue()) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003933 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
3934 return BinaryOperator::createSub(
3935 ConstantExpr::getSub(NegOp0CI,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003936 ConstantInt::get(I.getType(), 1)),
Chris Lattner0f68fa62003-11-04 23:37:10 +00003937 Op0I->getOperand(0));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003938 }
Chris Lattnerf78df7c2006-02-26 19:57:54 +00003939 } else if (Op0I->getOpcode() == Instruction::Or) {
3940 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
3941 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getZExtValue())) {
3942 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
3943 // Anything in both C1 and C2 is known to be zero, remove it from
3944 // NewRHS.
3945 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
3946 NewRHS = ConstantExpr::getAnd(NewRHS,
3947 ConstantExpr::getNot(CommonBits));
3948 WorkList.push_back(Op0I);
3949 I.setOperand(0, Op0I->getOperand(0));
3950 I.setOperand(1, NewRHS);
3951 return &I;
3952 }
Chris Lattner97638592003-07-23 21:37:07 +00003953 }
Chris Lattnerb8d6e402002-08-20 18:24:26 +00003954 }
Chris Lattner183b3362004-04-09 19:05:30 +00003955
3956 // Try to fold constant and into select arguments.
3957 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00003958 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00003959 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00003960 if (isa<PHINode>(Op0))
3961 if (Instruction *NV = FoldOpIntoPhi(I))
3962 return NV;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003963 }
3964
Chris Lattnerbb74e222003-03-10 23:06:50 +00003965 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00003966 if (X == Op1)
3967 return ReplaceInstUsesWith(I,
Zhou Sheng75b871f2007-01-11 12:24:14 +00003968 ConstantInt::getAllOnesValue(I.getType()));
Chris Lattner3082c5a2003-02-18 19:28:33 +00003969
Chris Lattnerbb74e222003-03-10 23:06:50 +00003970 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00003971 if (X == Op0)
3972 return ReplaceInstUsesWith(I,
Zhou Sheng75b871f2007-01-11 12:24:14 +00003973 ConstantInt::getAllOnesValue(I.getType()));
Chris Lattner3082c5a2003-02-18 19:28:33 +00003974
Chris Lattnerdcd07922006-04-01 08:03:55 +00003975 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1))
Chris Lattnerb36d9082004-02-16 03:54:20 +00003976 if (Op1I->getOpcode() == Instruction::Or) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003977 if (Op1I->getOperand(0) == Op0) { // B^(B|A) == (A|B)^B
Chris Lattnerdcd07922006-04-01 08:03:55 +00003978 Op1I->swapOperands();
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003979 I.swapOperands();
3980 std::swap(Op0, Op1);
3981 } else if (Op1I->getOperand(1) == Op0) { // B^(A|B) == (A|B)^B
Chris Lattnerdcd07922006-04-01 08:03:55 +00003982 I.swapOperands(); // Simplified below.
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003983 std::swap(Op0, Op1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003984 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00003985 } else if (Op1I->getOpcode() == Instruction::Xor) {
3986 if (Op0 == Op1I->getOperand(0)) // A^(A^B) == B
3987 return ReplaceInstUsesWith(I, Op1I->getOperand(1));
3988 else if (Op0 == Op1I->getOperand(1)) // A^(B^A) == B
3989 return ReplaceInstUsesWith(I, Op1I->getOperand(0));
Chris Lattnerdcd07922006-04-01 08:03:55 +00003990 } else if (Op1I->getOpcode() == Instruction::And && Op1I->hasOneUse()) {
3991 if (Op1I->getOperand(0) == Op0) // A^(A&B) -> A^(B&A)
3992 Op1I->swapOperands();
3993 if (Op0 == Op1I->getOperand(1)) { // A^(B&A) -> (B&A)^A
3994 I.swapOperands(); // Simplified below.
3995 std::swap(Op0, Op1);
3996 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00003997 }
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003998
Chris Lattnerdcd07922006-04-01 08:03:55 +00003999 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00004000 if (Op0I->getOpcode() == Instruction::Or && Op0I->hasOneUse()) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00004001 if (Op0I->getOperand(0) == Op1) // (B|A)^B == (A|B)^B
Chris Lattnerdcd07922006-04-01 08:03:55 +00004002 Op0I->swapOperands();
Chris Lattnerdcf240a2003-03-10 21:43:22 +00004003 if (Op0I->getOperand(1) == Op1) { // (A|B)^B == A & ~B
Chris Lattnerdcd07922006-04-01 08:03:55 +00004004 Instruction *NotB = BinaryOperator::createNot(Op1, "tmp");
4005 InsertNewInstBefore(NotB, I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004006 return BinaryOperator::createAnd(Op0I->getOperand(0), NotB);
Chris Lattner1bbb7b62003-03-10 18:24:17 +00004007 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00004008 } else if (Op0I->getOpcode() == Instruction::Xor) {
4009 if (Op1 == Op0I->getOperand(0)) // (A^B)^A == B
4010 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
4011 else if (Op1 == Op0I->getOperand(1)) // (B^A)^A == B
4012 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattnerdcd07922006-04-01 08:03:55 +00004013 } else if (Op0I->getOpcode() == Instruction::And && Op0I->hasOneUse()) {
4014 if (Op0I->getOperand(0) == Op1) // (A&B)^A -> (B&A)^A
4015 Op0I->swapOperands();
Chris Lattner6cf49142006-04-01 22:05:01 +00004016 if (Op0I->getOperand(1) == Op1 && // (B&A)^A == ~B & A
4017 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattnerdcd07922006-04-01 08:03:55 +00004018 Instruction *N = BinaryOperator::createNot(Op0I->getOperand(0), "tmp");
4019 InsertNewInstBefore(N, I);
4020 return BinaryOperator::createAnd(N, Op1);
4021 }
Chris Lattner1bbb7b62003-03-10 18:24:17 +00004022 }
4023
Reid Spencer266e42b2006-12-23 06:05:41 +00004024 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
4025 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
4026 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattner3ac7c262003-08-13 20:16:26 +00004027 return R;
4028
Chris Lattner3af10532006-05-05 06:39:07 +00004029 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Reid Spencer799b5bf2006-12-13 08:27:15 +00004030 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
Chris Lattner3af10532006-05-05 06:39:07 +00004031 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer799b5bf2006-12-13 08:27:15 +00004032 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
4033 const Type *SrcTy = Op0C->getOperand(0)->getType();
4034 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegral() &&
4035 // Only do this if the casts both really cause code to be generated.
Reid Spencer266e42b2006-12-23 06:05:41 +00004036 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4037 I.getType(), TD) &&
4038 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4039 I.getType(), TD)) {
Reid Spencer799b5bf2006-12-13 08:27:15 +00004040 Instruction *NewOp = BinaryOperator::createXor(Op0C->getOperand(0),
4041 Op1C->getOperand(0),
4042 I.getName());
4043 InsertNewInstBefore(NewOp, I);
4044 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
4045 }
Chris Lattner3af10532006-05-05 06:39:07 +00004046 }
Chris Lattnerf05d69a2006-11-14 07:46:50 +00004047
4048 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
4049 if (ShiftInst *SI1 = dyn_cast<ShiftInst>(Op1)) {
4050 if (ShiftInst *SI0 = dyn_cast<ShiftInst>(Op0))
4051 if (SI0->getOpcode() == SI1->getOpcode() &&
4052 SI0->getOperand(1) == SI1->getOperand(1) &&
4053 (SI0->hasOneUse() || SI1->hasOneUse())) {
4054 Instruction *NewOp =
4055 InsertNewInstBefore(BinaryOperator::createXor(SI0->getOperand(0),
4056 SI1->getOperand(0),
4057 SI0->getName()), I);
4058 return new ShiftInst(SI1->getOpcode(), NewOp, SI1->getOperand(1));
4059 }
4060 }
Chris Lattner3af10532006-05-05 06:39:07 +00004061
Chris Lattner113f4f42002-06-25 16:13:24 +00004062 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004063}
4064
Chris Lattner6862fbd2004-09-29 17:40:11 +00004065static bool isPositive(ConstantInt *C) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00004066 return C->getSExtValue() >= 0;
Chris Lattner6862fbd2004-09-29 17:40:11 +00004067}
4068
4069/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
4070/// overflowed for this type.
4071static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
4072 ConstantInt *In2) {
4073 Result = cast<ConstantInt>(ConstantExpr::getAdd(In1, In2));
4074
Reid Spencerc635f472006-12-31 05:48:39 +00004075 return cast<ConstantInt>(Result)->getZExtValue() <
4076 cast<ConstantInt>(In1)->getZExtValue();
Chris Lattner6862fbd2004-09-29 17:40:11 +00004077}
4078
Chris Lattner0798af32005-01-13 20:14:25 +00004079/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
4080/// code necessary to compute the offset from the base pointer (without adding
4081/// in the base pointer). Return the result as a signed integer of intptr size.
4082static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
4083 TargetData &TD = IC.getTargetData();
4084 gep_type_iterator GTI = gep_type_begin(GEP);
Reid Spencer266e42b2006-12-23 06:05:41 +00004085 const Type *IntPtrTy = TD.getIntPtrType();
4086 Value *Result = Constant::getNullValue(IntPtrTy);
Chris Lattner0798af32005-01-13 20:14:25 +00004087
4088 // Build a mask for high order bits.
Chris Lattner77defba2006-02-07 07:00:41 +00004089 uint64_t PtrSizeMask = ~0ULL >> (64-TD.getPointerSize()*8);
Chris Lattner0798af32005-01-13 20:14:25 +00004090
Chris Lattner0798af32005-01-13 20:14:25 +00004091 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
4092 Value *Op = GEP->getOperand(i);
Chris Lattnerd35d2102005-01-13 23:26:48 +00004093 uint64_t Size = TD.getTypeSize(GTI.getIndexedType()) & PtrSizeMask;
Reid Spencer266e42b2006-12-23 06:05:41 +00004094 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
Chris Lattner0798af32005-01-13 20:14:25 +00004095 if (Constant *OpC = dyn_cast<Constant>(Op)) {
4096 if (!OpC->isNullValue()) {
Reid Spencer266e42b2006-12-23 06:05:41 +00004097 OpC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
Chris Lattner0798af32005-01-13 20:14:25 +00004098 Scale = ConstantExpr::getMul(OpC, Scale);
4099 if (Constant *RC = dyn_cast<Constant>(Result))
4100 Result = ConstantExpr::getAdd(RC, Scale);
4101 else {
4102 // Emit an add instruction.
4103 Result = IC.InsertNewInstBefore(
4104 BinaryOperator::createAdd(Result, Scale,
4105 GEP->getName()+".offs"), I);
4106 }
4107 }
4108 } else {
Chris Lattner7aa41cf2005-01-14 17:17:59 +00004109 // Convert to correct type.
Reid Spencer266e42b2006-12-23 06:05:41 +00004110 Op = IC.InsertNewInstBefore(CastInst::createSExtOrBitCast(Op, IntPtrTy,
Chris Lattner7aa41cf2005-01-14 17:17:59 +00004111 Op->getName()+".c"), I);
4112 if (Size != 1)
Chris Lattner4cb9fa32005-01-13 20:40:58 +00004113 // We'll let instcombine(mul) convert this to a shl if possible.
4114 Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
4115 GEP->getName()+".idx"), I);
Chris Lattner0798af32005-01-13 20:14:25 +00004116
4117 // Emit an add instruction.
Chris Lattner4cb9fa32005-01-13 20:40:58 +00004118 Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
Chris Lattner0798af32005-01-13 20:14:25 +00004119 GEP->getName()+".offs"), I);
4120 }
4121 }
4122 return Result;
4123}
4124
Reid Spencer266e42b2006-12-23 06:05:41 +00004125/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
Chris Lattner0798af32005-01-13 20:14:25 +00004126/// else. At this point we know that the GEP is on the LHS of the comparison.
Reid Spencer266e42b2006-12-23 06:05:41 +00004127Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
4128 ICmpInst::Predicate Cond,
4129 Instruction &I) {
Chris Lattner0798af32005-01-13 20:14:25 +00004130 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattner81e84172005-01-13 22:25:21 +00004131
4132 if (CastInst *CI = dyn_cast<CastInst>(RHS))
4133 if (isa<PointerType>(CI->getOperand(0)->getType()))
4134 RHS = CI->getOperand(0);
4135
Chris Lattner0798af32005-01-13 20:14:25 +00004136 Value *PtrBase = GEPLHS->getOperand(0);
4137 if (PtrBase == RHS) {
4138 // As an optimization, we don't actually have to compute the actual value of
Reid Spencer266e42b2006-12-23 06:05:41 +00004139 // OFFSET if this is a icmp_eq or icmp_ne comparison, just return whether
4140 // each index is zero or not.
4141 if (Cond == ICmpInst::ICMP_EQ || Cond == ICmpInst::ICMP_NE) {
Chris Lattner81e84172005-01-13 22:25:21 +00004142 Instruction *InVal = 0;
Chris Lattnercd517ff2005-01-28 19:32:01 +00004143 gep_type_iterator GTI = gep_type_begin(GEPLHS);
4144 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i, ++GTI) {
Chris Lattner81e84172005-01-13 22:25:21 +00004145 bool EmitIt = true;
4146 if (Constant *C = dyn_cast<Constant>(GEPLHS->getOperand(i))) {
4147 if (isa<UndefValue>(C)) // undef index -> undef.
4148 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
4149 if (C->isNullValue())
4150 EmitIt = false;
Chris Lattnercd517ff2005-01-28 19:32:01 +00004151 else if (TD->getTypeSize(GTI.getIndexedType()) == 0) {
4152 EmitIt = false; // This is indexing into a zero sized array?
Misha Brukmanb1c93172005-04-21 23:48:37 +00004153 } else if (isa<ConstantInt>(C))
Chris Lattner81e84172005-01-13 22:25:21 +00004154 return ReplaceInstUsesWith(I, // No comparison is needed here.
Reid Spencercddc9df2007-01-12 04:24:46 +00004155 ConstantInt::get(Type::Int1Ty,
4156 Cond == ICmpInst::ICMP_NE));
Chris Lattner81e84172005-01-13 22:25:21 +00004157 }
4158
4159 if (EmitIt) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00004160 Instruction *Comp =
Reid Spencer266e42b2006-12-23 06:05:41 +00004161 new ICmpInst(Cond, GEPLHS->getOperand(i),
Chris Lattner81e84172005-01-13 22:25:21 +00004162 Constant::getNullValue(GEPLHS->getOperand(i)->getType()));
4163 if (InVal == 0)
4164 InVal = Comp;
4165 else {
4166 InVal = InsertNewInstBefore(InVal, I);
4167 InsertNewInstBefore(Comp, I);
Reid Spencer266e42b2006-12-23 06:05:41 +00004168 if (Cond == ICmpInst::ICMP_NE) // True if any are unequal
Chris Lattner81e84172005-01-13 22:25:21 +00004169 InVal = BinaryOperator::createOr(InVal, Comp);
4170 else // True if all are equal
4171 InVal = BinaryOperator::createAnd(InVal, Comp);
4172 }
4173 }
4174 }
4175
4176 if (InVal)
4177 return InVal;
4178 else
Reid Spencer266e42b2006-12-23 06:05:41 +00004179 // No comparison is needed here, all indexes = 0
Reid Spencercddc9df2007-01-12 04:24:46 +00004180 ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4181 Cond == ICmpInst::ICMP_EQ));
Chris Lattner81e84172005-01-13 22:25:21 +00004182 }
Chris Lattner0798af32005-01-13 20:14:25 +00004183
Reid Spencer266e42b2006-12-23 06:05:41 +00004184 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner0798af32005-01-13 20:14:25 +00004185 // the result to fold to a constant!
4186 if (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) {
4187 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
4188 Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
Reid Spencer266e42b2006-12-23 06:05:41 +00004189 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
4190 Constant::getNullValue(Offset->getType()));
Chris Lattner0798af32005-01-13 20:14:25 +00004191 }
4192 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
Chris Lattnera21bf8d2005-04-25 20:17:30 +00004193 // If the base pointers are different, but the indices are the same, just
4194 // compare the base pointer.
4195 if (PtrBase != GEPRHS->getOperand(0)) {
4196 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00004197 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattnerbd43b9d2005-04-26 14:40:41 +00004198 GEPRHS->getOperand(0)->getType();
Chris Lattnera21bf8d2005-04-25 20:17:30 +00004199 if (IndicesTheSame)
4200 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4201 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4202 IndicesTheSame = false;
4203 break;
4204 }
4205
4206 // If all indices are the same, just compare the base pointers.
4207 if (IndicesTheSame)
Reid Spencer266e42b2006-12-23 06:05:41 +00004208 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
4209 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattnera21bf8d2005-04-25 20:17:30 +00004210
4211 // Otherwise, the base pointers are different and the indices are
4212 // different, bail out.
Chris Lattner0798af32005-01-13 20:14:25 +00004213 return 0;
Chris Lattnera21bf8d2005-04-25 20:17:30 +00004214 }
Chris Lattner0798af32005-01-13 20:14:25 +00004215
Chris Lattner81e84172005-01-13 22:25:21 +00004216 // If one of the GEPs has all zero indices, recurse.
4217 bool AllZeros = true;
4218 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4219 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
4220 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
4221 AllZeros = false;
4222 break;
4223 }
4224 if (AllZeros)
Reid Spencer266e42b2006-12-23 06:05:41 +00004225 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
4226 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner4fa89822005-01-14 00:20:05 +00004227
4228 // If the other GEP has all zero indices, recurse.
Chris Lattner81e84172005-01-13 22:25:21 +00004229 AllZeros = true;
4230 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4231 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
4232 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
4233 AllZeros = false;
4234 break;
4235 }
4236 if (AllZeros)
Reid Spencer266e42b2006-12-23 06:05:41 +00004237 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
Chris Lattner81e84172005-01-13 22:25:21 +00004238
Chris Lattner4fa89822005-01-14 00:20:05 +00004239 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
4240 // If the GEPs only differ by one index, compare it.
4241 unsigned NumDifferences = 0; // Keep track of # differences.
4242 unsigned DiffOperand = 0; // The operand that differs.
4243 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4244 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004245 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
4246 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattnerfc4429e2005-01-21 23:06:49 +00004247 // Irreconcilable differences.
Chris Lattner4fa89822005-01-14 00:20:05 +00004248 NumDifferences = 2;
4249 break;
4250 } else {
4251 if (NumDifferences++) break;
4252 DiffOperand = i;
4253 }
4254 }
4255
4256 if (NumDifferences == 0) // SAME GEP?
4257 return ReplaceInstUsesWith(I, // No comparison is needed here.
Reid Spencercddc9df2007-01-12 04:24:46 +00004258 ConstantInt::get(Type::Int1Ty,
4259 Cond == ICmpInst::ICMP_EQ));
Chris Lattner4fa89822005-01-14 00:20:05 +00004260 else if (NumDifferences == 1) {
Chris Lattnerfc4429e2005-01-21 23:06:49 +00004261 Value *LHSV = GEPLHS->getOperand(DiffOperand);
4262 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Reid Spencer266e42b2006-12-23 06:05:41 +00004263 // Make sure we do a signed comparison here.
4264 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
Chris Lattner4fa89822005-01-14 00:20:05 +00004265 }
4266 }
4267
Reid Spencer266e42b2006-12-23 06:05:41 +00004268 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner0798af32005-01-13 20:14:25 +00004269 // the result to fold to a constant!
4270 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
4271 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
4272 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
4273 Value *L = EmitGEPOffset(GEPLHS, I, *this);
4274 Value *R = EmitGEPOffset(GEPRHS, I, *this);
Reid Spencer266e42b2006-12-23 06:05:41 +00004275 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
Chris Lattner0798af32005-01-13 20:14:25 +00004276 }
4277 }
4278 return 0;
4279}
4280
Reid Spencer266e42b2006-12-23 06:05:41 +00004281Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
4282 bool Changed = SimplifyCompare(I);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004283 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004284
Reid Spencer266e42b2006-12-23 06:05:41 +00004285 // fcmp pred X, X
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004286 if (Op0 == Op1)
Reid Spencercddc9df2007-01-12 04:24:46 +00004287 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4288 isTrueWhenEqual(I)));
Chris Lattner1fc23f32002-05-09 20:11:54 +00004289
Reid Spencer266e42b2006-12-23 06:05:41 +00004290 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
Reid Spencer542964f2007-01-11 18:21:29 +00004291 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Chris Lattner81a7a232004-10-16 18:11:37 +00004292
Reid Spencer266e42b2006-12-23 06:05:41 +00004293 // Handle fcmp with constant RHS
4294 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
4295 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4296 switch (LHSI->getOpcode()) {
4297 case Instruction::PHI:
4298 if (Instruction *NV = FoldOpIntoPhi(I))
4299 return NV;
4300 break;
4301 case Instruction::Select:
4302 // If either operand of the select is a constant, we can fold the
4303 // comparison into the select arms, which will cause one to be
4304 // constant folded and the select turned into a bitwise or.
4305 Value *Op1 = 0, *Op2 = 0;
4306 if (LHSI->hasOneUse()) {
4307 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
4308 // Fold the known value into the constant operand.
4309 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
4310 // Insert a new FCmp of the other select operand.
4311 Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
4312 LHSI->getOperand(2), RHSC,
4313 I.getName()), I);
4314 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
4315 // Fold the known value into the constant operand.
4316 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
4317 // Insert a new FCmp of the other select operand.
4318 Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
4319 LHSI->getOperand(1), RHSC,
4320 I.getName()), I);
4321 }
4322 }
4323
4324 if (Op1)
4325 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
4326 break;
4327 }
4328 }
4329
4330 return Changed ? &I : 0;
4331}
4332
4333Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
4334 bool Changed = SimplifyCompare(I);
4335 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4336 const Type *Ty = Op0->getType();
4337
4338 // icmp X, X
4339 if (Op0 == Op1)
Reid Spencercddc9df2007-01-12 04:24:46 +00004340 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4341 isTrueWhenEqual(I)));
Reid Spencer266e42b2006-12-23 06:05:41 +00004342
4343 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
Reid Spencer542964f2007-01-11 18:21:29 +00004344 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Reid Spencer266e42b2006-12-23 06:05:41 +00004345
4346 // icmp of GlobalValues can never equal each other as long as they aren't
4347 // external weak linkage type.
4348 if (GlobalValue *GV0 = dyn_cast<GlobalValue>(Op0))
4349 if (GlobalValue *GV1 = dyn_cast<GlobalValue>(Op1))
4350 if (!GV0->hasExternalWeakLinkage() || !GV1->hasExternalWeakLinkage())
Reid Spencercddc9df2007-01-12 04:24:46 +00004351 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4352 !isTrueWhenEqual(I)));
Reid Spencer266e42b2006-12-23 06:05:41 +00004353
4354 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
Chris Lattner15ff1e12004-11-14 07:33:16 +00004355 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanb1c93172005-04-21 23:48:37 +00004356 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
4357 isa<ConstantPointerNull>(Op0)) &&
4358 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner15ff1e12004-11-14 07:33:16 +00004359 isa<ConstantPointerNull>(Op1)))
Reid Spencercddc9df2007-01-12 04:24:46 +00004360 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4361 !isTrueWhenEqual(I)));
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004362
Reid Spencer266e42b2006-12-23 06:05:41 +00004363 // icmp's with boolean values can always be turned into bitwise operations
Reid Spencer542964f2007-01-11 18:21:29 +00004364 if (Ty == Type::Int1Ty) {
Reid Spencer266e42b2006-12-23 06:05:41 +00004365 switch (I.getPredicate()) {
4366 default: assert(0 && "Invalid icmp instruction!");
4367 case ICmpInst::ICMP_EQ: { // icmp eq bool %A, %B -> ~(A^B)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004368 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004369 InsertNewInstBefore(Xor, I);
Chris Lattner16930792003-11-03 04:25:02 +00004370 return BinaryOperator::createNot(Xor);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004371 }
Reid Spencer266e42b2006-12-23 06:05:41 +00004372 case ICmpInst::ICMP_NE: // icmp eq bool %A, %B -> A^B
Chris Lattner4456da62004-08-11 00:50:51 +00004373 return BinaryOperator::createXor(Op0, Op1);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004374
Reid Spencer266e42b2006-12-23 06:05:41 +00004375 case ICmpInst::ICMP_UGT:
4376 case ICmpInst::ICMP_SGT:
4377 std::swap(Op0, Op1); // Change icmp gt -> icmp lt
Chris Lattner4456da62004-08-11 00:50:51 +00004378 // FALL THROUGH
Reid Spencer266e42b2006-12-23 06:05:41 +00004379 case ICmpInst::ICMP_ULT:
4380 case ICmpInst::ICMP_SLT: { // icmp lt bool A, B -> ~X & Y
Chris Lattner4456da62004-08-11 00:50:51 +00004381 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4382 InsertNewInstBefore(Not, I);
4383 return BinaryOperator::createAnd(Not, Op1);
4384 }
Reid Spencer266e42b2006-12-23 06:05:41 +00004385 case ICmpInst::ICMP_UGE:
4386 case ICmpInst::ICMP_SGE:
4387 std::swap(Op0, Op1); // Change icmp ge -> icmp le
Chris Lattner4456da62004-08-11 00:50:51 +00004388 // FALL THROUGH
Reid Spencer266e42b2006-12-23 06:05:41 +00004389 case ICmpInst::ICMP_ULE:
4390 case ICmpInst::ICMP_SLE: { // icmp le bool %A, %B -> ~A | B
Chris Lattner4456da62004-08-11 00:50:51 +00004391 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4392 InsertNewInstBefore(Not, I);
4393 return BinaryOperator::createOr(Not, Op1);
4394 }
4395 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004396 }
4397
Chris Lattner2dd01742004-06-09 04:24:29 +00004398 // See if we are doing a comparison between a constant and an instruction that
4399 // can be folded into the comparison.
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004400 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00004401 switch (I.getPredicate()) {
4402 default: break;
4403 case ICmpInst::ICMP_ULT: // A <u MIN -> FALSE
4404 if (CI->isMinValue(false))
Zhou Sheng75b871f2007-01-11 12:24:14 +00004405 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004406 if (CI->isMaxValue(false)) // A <u MAX -> A != MAX
4407 return new ICmpInst(ICmpInst::ICMP_NE, Op0,Op1);
4408 if (isMinValuePlusOne(CI,false)) // A <u MIN+1 -> A == MIN
4409 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
4410 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00004411
Reid Spencer266e42b2006-12-23 06:05:41 +00004412 case ICmpInst::ICMP_SLT:
4413 if (CI->isMinValue(true)) // A <s MIN -> FALSE
Zhou Sheng75b871f2007-01-11 12:24:14 +00004414 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004415 if (CI->isMaxValue(true)) // A <s MAX -> A != MAX
4416 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4417 if (isMinValuePlusOne(CI,true)) // A <s MIN+1 -> A == MIN
4418 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
4419 break;
4420
4421 case ICmpInst::ICMP_UGT:
4422 if (CI->isMaxValue(false)) // A >u MAX -> FALSE
Zhou Sheng75b871f2007-01-11 12:24:14 +00004423 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004424 if (CI->isMinValue(false)) // A >u MIN -> A != MIN
4425 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4426 if (isMaxValueMinusOne(CI, false)) // A >u MAX-1 -> A == MAX
4427 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
4428 break;
4429
4430 case ICmpInst::ICMP_SGT:
4431 if (CI->isMaxValue(true)) // A >s MAX -> FALSE
Zhou Sheng75b871f2007-01-11 12:24:14 +00004432 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004433 if (CI->isMinValue(true)) // A >s MIN -> A != MIN
4434 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4435 if (isMaxValueMinusOne(CI, true)) // A >s MAX-1 -> A == MAX
4436 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
4437 break;
4438
4439 case ICmpInst::ICMP_ULE:
4440 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
Zhou Sheng75b871f2007-01-11 12:24:14 +00004441 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004442 if (CI->isMinValue(false)) // A <=u MIN -> A == MIN
4443 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4444 if (isMaxValueMinusOne(CI,false)) // A <=u MAX-1 -> A != MAX
4445 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
4446 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00004447
Reid Spencer266e42b2006-12-23 06:05:41 +00004448 case ICmpInst::ICMP_SLE:
4449 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
Zhou Sheng75b871f2007-01-11 12:24:14 +00004450 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004451 if (CI->isMinValue(true)) // A <=s MIN -> A == MIN
4452 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4453 if (isMaxValueMinusOne(CI,true)) // A <=s MAX-1 -> A != MAX
4454 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
4455 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00004456
Reid Spencer266e42b2006-12-23 06:05:41 +00004457 case ICmpInst::ICMP_UGE:
4458 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
Zhou Sheng75b871f2007-01-11 12:24:14 +00004459 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004460 if (CI->isMaxValue(false)) // A >=u MAX -> A == MAX
4461 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4462 if (isMinValuePlusOne(CI,false)) // A >=u MIN-1 -> A != MIN
4463 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
4464 break;
4465
4466 case ICmpInst::ICMP_SGE:
4467 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
Zhou Sheng75b871f2007-01-11 12:24:14 +00004468 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004469 if (CI->isMaxValue(true)) // A >=s MAX -> A == MAX
4470 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4471 if (isMinValuePlusOne(CI,true)) // A >=s MIN-1 -> A != MIN
4472 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
4473 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00004474 }
4475
Reid Spencer266e42b2006-12-23 06:05:41 +00004476 // If we still have a icmp le or icmp ge instruction, turn it into the
4477 // appropriate icmp lt or icmp gt instruction. Since the border cases have
Chris Lattner6862fbd2004-09-29 17:40:11 +00004478 // already been handled above, this requires little checking.
4479 //
Reid Spencer266e42b2006-12-23 06:05:41 +00004480 if (I.getPredicate() == ICmpInst::ICMP_ULE)
4481 return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
4482 if (I.getPredicate() == ICmpInst::ICMP_SLE)
4483 return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
4484 if (I.getPredicate() == ICmpInst::ICMP_UGE)
4485 return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
4486 if (I.getPredicate() == ICmpInst::ICMP_SGE)
4487 return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
Chris Lattneree0f2802006-02-12 02:07:56 +00004488
4489 // See if we can fold the comparison based on bits known to be zero or one
4490 // in the input.
4491 uint64_t KnownZero, KnownOne;
4492 if (SimplifyDemandedBits(Op0, Ty->getIntegralTypeMask(),
4493 KnownZero, KnownOne, 0))
4494 return &I;
4495
4496 // Given the known and unknown bits, compute a range that the LHS could be
4497 // in.
4498 if (KnownOne | KnownZero) {
Reid Spencer266e42b2006-12-23 06:05:41 +00004499 // Compute the Min, Max and RHS values based on the known bits. For the
4500 // EQ and NE we use unsigned values.
Reid Spencer910f23f2006-12-23 19:17:57 +00004501 uint64_t UMin = 0, UMax = 0, URHSVal = 0;
4502 int64_t SMin = 0, SMax = 0, SRHSVal = 0;
Reid Spencer266e42b2006-12-23 06:05:41 +00004503 if (ICmpInst::isSignedPredicate(I.getPredicate())) {
4504 SRHSVal = CI->getSExtValue();
4505 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, SMin,
4506 SMax);
4507 } else {
4508 URHSVal = CI->getZExtValue();
4509 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, UMin,
4510 UMax);
4511 }
4512 switch (I.getPredicate()) { // LE/GE have been folded already.
4513 default: assert(0 && "Unknown icmp opcode!");
4514 case ICmpInst::ICMP_EQ:
4515 if (UMax < URHSVal || UMin > URHSVal)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004516 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004517 break;
4518 case ICmpInst::ICMP_NE:
4519 if (UMax < URHSVal || UMin > URHSVal)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004520 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004521 break;
4522 case ICmpInst::ICMP_ULT:
4523 if (UMax < URHSVal)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004524 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004525 if (UMin > URHSVal)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004526 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004527 break;
4528 case ICmpInst::ICMP_UGT:
4529 if (UMin > URHSVal)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004530 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004531 if (UMax < URHSVal)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004532 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004533 break;
4534 case ICmpInst::ICMP_SLT:
4535 if (SMax < SRHSVal)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004536 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004537 if (SMin > SRHSVal)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004538 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004539 break;
4540 case ICmpInst::ICMP_SGT:
4541 if (SMin > SRHSVal)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004542 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00004543 if (SMax < SRHSVal)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004544 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004545 break;
Chris Lattneree0f2802006-02-12 02:07:56 +00004546 }
4547 }
4548
Reid Spencer266e42b2006-12-23 06:05:41 +00004549 // Since the RHS is a ConstantInt (CI), if the left hand side is an
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004550 // instruction, see if that instruction also has constants so that the
Reid Spencer266e42b2006-12-23 06:05:41 +00004551 // instruction can be folded into the icmp
Chris Lattnere1e10e12004-05-25 06:32:08 +00004552 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004553 switch (LHSI->getOpcode()) {
4554 case Instruction::And:
4555 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
4556 LHSI->getOperand(0)->hasOneUse()) {
Chris Lattner4922a0e2006-09-18 05:27:43 +00004557 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
4558
Reid Spencer266e42b2006-12-23 06:05:41 +00004559 // If the LHS is an AND of a truncating cast, we can widen the
Chris Lattner4922a0e2006-09-18 05:27:43 +00004560 // and/compare to be the input width without changing the value
4561 // produced, eliminating a cast.
4562 if (CastInst *Cast = dyn_cast<CastInst>(LHSI->getOperand(0))) {
4563 // We can do this transformation if either the AND constant does not
4564 // have its sign bit set or if it is an equality comparison.
4565 // Extending a relational comparison when we're checking the sign
4566 // bit would not work.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00004567 if (Cast->hasOneUse() && isa<TruncInst>(Cast) &&
Chris Lattner4922a0e2006-09-18 05:27:43 +00004568 (I.isEquality() ||
4569 (AndCST->getZExtValue() == (uint64_t)AndCST->getSExtValue()) &&
4570 (CI->getZExtValue() == (uint64_t)CI->getSExtValue()))) {
4571 ConstantInt *NewCST;
4572 ConstantInt *NewCI;
Reid Spencerc635f472006-12-31 05:48:39 +00004573 NewCST = ConstantInt::get(Cast->getOperand(0)->getType(),
4574 AndCST->getZExtValue());
4575 NewCI = ConstantInt::get(Cast->getOperand(0)->getType(),
4576 CI->getZExtValue());
Chris Lattner4922a0e2006-09-18 05:27:43 +00004577 Instruction *NewAnd =
4578 BinaryOperator::createAnd(Cast->getOperand(0), NewCST,
4579 LHSI->getName());
4580 InsertNewInstBefore(NewAnd, I);
Reid Spencer266e42b2006-12-23 06:05:41 +00004581 return new ICmpInst(I.getPredicate(), NewAnd, NewCI);
Chris Lattner4922a0e2006-09-18 05:27:43 +00004582 }
4583 }
4584
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004585 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
4586 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
4587 // happens a LOT in code produced by the C front-end, for bitfield
4588 // access.
4589 ShiftInst *Shift = dyn_cast<ShiftInst>(LHSI->getOperand(0));
Chris Lattneree0f2802006-02-12 02:07:56 +00004590
4591 // Check to see if there is a noop-cast between the shift and the and.
4592 if (!Shift) {
4593 if (CastInst *CI = dyn_cast<CastInst>(LHSI->getOperand(0)))
Reid Spencer74a528b2006-12-13 18:21:21 +00004594 if (CI->getOpcode() == Instruction::BitCast)
Chris Lattneree0f2802006-02-12 02:07:56 +00004595 Shift = dyn_cast<ShiftInst>(CI->getOperand(0));
4596 }
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004597
Reid Spencere0fc4df2006-10-20 07:07:24 +00004598 ConstantInt *ShAmt;
4599 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
Chris Lattneree0f2802006-02-12 02:07:56 +00004600 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
4601 const Type *AndTy = AndCST->getType(); // Type of the and.
Misha Brukmanb1c93172005-04-21 23:48:37 +00004602
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004603 // We can fold this as long as we can't shift unknown bits
4604 // into the mask. This can only happen with signed shift
4605 // rights, as they sign-extend.
4606 if (ShAmt) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004607 bool CanFold = Shift->isLogicalShift();
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004608 if (!CanFold) {
4609 // To test for the bad case of the signed shr, see if any
4610 // of the bits shifted in could be tested after the mask.
Reid Spencere0fc4df2006-10-20 07:07:24 +00004611 int ShAmtVal = Ty->getPrimitiveSizeInBits()-ShAmt->getZExtValue();
Chris Lattnerc53cb9d2005-06-17 01:29:28 +00004612 if (ShAmtVal < 0) ShAmtVal = 0; // Out of range shift.
4613
Reid Spencerc635f472006-12-31 05:48:39 +00004614 Constant *OShAmt = ConstantInt::get(Type::Int8Ty, ShAmtVal);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004615 Constant *ShVal =
Chris Lattneree0f2802006-02-12 02:07:56 +00004616 ConstantExpr::getShl(ConstantInt::getAllOnesValue(AndTy),
4617 OShAmt);
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004618 if (ConstantExpr::getAnd(ShVal, AndCST)->isNullValue())
4619 CanFold = true;
4620 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004621
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004622 if (CanFold) {
Chris Lattner6afc02f2004-09-28 17:54:07 +00004623 Constant *NewCst;
4624 if (Shift->getOpcode() == Instruction::Shl)
Reid Spencerfdff9382006-11-08 06:47:33 +00004625 NewCst = ConstantExpr::getLShr(CI, ShAmt);
Chris Lattner6afc02f2004-09-28 17:54:07 +00004626 else
4627 NewCst = ConstantExpr::getShl(CI, ShAmt);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004628
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004629 // Check to see if we are shifting out any of the bits being
4630 // compared.
4631 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != CI){
4632 // If we shifted bits out, the fold is not going to work out.
4633 // As a special case, check to see if this means that the
4634 // result is always true or false now.
Reid Spencer266e42b2006-12-23 06:05:41 +00004635 if (I.getPredicate() == ICmpInst::ICMP_EQ)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004636 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004637 if (I.getPredicate() == ICmpInst::ICMP_NE)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004638 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004639 } else {
4640 I.setOperand(1, NewCst);
Chris Lattner6afc02f2004-09-28 17:54:07 +00004641 Constant *NewAndCST;
4642 if (Shift->getOpcode() == Instruction::Shl)
Reid Spencerfdff9382006-11-08 06:47:33 +00004643 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
Chris Lattner6afc02f2004-09-28 17:54:07 +00004644 else
4645 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
4646 LHSI->setOperand(1, NewAndCST);
Reid Spencer6ff3e732007-01-04 05:23:51 +00004647 LHSI->setOperand(0, Shift->getOperand(0));
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004648 WorkList.push_back(Shift); // Shift is dead.
4649 AddUsesToWorkList(I);
4650 return &I;
Chris Lattner1638de42004-07-21 19:50:44 +00004651 }
4652 }
Chris Lattner35167c32004-06-09 07:59:58 +00004653 }
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004654
4655 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
4656 // preferable because it allows the C<<Y expression to be hoisted out
4657 // of a loop if Y is invariant and X is not.
4658 if (Shift && Shift->hasOneUse() && CI->isNullValue() &&
Chris Lattnerde077922006-09-18 18:27:05 +00004659 I.isEquality() && !Shift->isArithmeticShift() &&
4660 isa<Instruction>(Shift->getOperand(0))) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004661 // Compute C << Y.
4662 Value *NS;
Reid Spencerfdff9382006-11-08 06:47:33 +00004663 if (Shift->getOpcode() == Instruction::LShr) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004664 NS = new ShiftInst(Instruction::Shl, AndCST, Shift->getOperand(1),
4665 "tmp");
4666 } else {
Reid Spencer2a499b02006-12-13 17:19:09 +00004667 // Insert a logical shift.
4668 NS = new ShiftInst(Instruction::LShr, AndCST,
Chris Lattner4922a0e2006-09-18 05:27:43 +00004669 Shift->getOperand(1), "tmp");
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004670 }
4671 InsertNewInstBefore(cast<Instruction>(NS), I);
4672
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004673 // Compute X & (C << Y).
Reid Spencer6ff3e732007-01-04 05:23:51 +00004674 Instruction *NewAnd = BinaryOperator::createAnd(
4675 Shift->getOperand(0), NS, LHSI->getName());
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004676 InsertNewInstBefore(NewAnd, I);
4677
4678 I.setOperand(0, NewAnd);
4679 return &I;
4680 }
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004681 }
4682 break;
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004683
Reid Spencer266e42b2006-12-23 06:05:41 +00004684 case Instruction::Shl: // (icmp pred (shl X, ShAmt), CI)
Reid Spencere0fc4df2006-10-20 07:07:24 +00004685 if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004686 if (I.isEquality()) {
Chris Lattner19b57f52005-06-15 20:53:31 +00004687 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
4688
4689 // Check that the shift amount is in range. If not, don't perform
4690 // undefined shifts. When the shift is visited it will be
4691 // simplified.
Reid Spencere0fc4df2006-10-20 07:07:24 +00004692 if (ShAmt->getZExtValue() >= TypeBits)
Chris Lattner19b57f52005-06-15 20:53:31 +00004693 break;
4694
Chris Lattner272d5ca2004-09-28 18:22:15 +00004695 // If we are comparing against bits always shifted out, the
4696 // comparison cannot succeed.
Misha Brukmanb1c93172005-04-21 23:48:37 +00004697 Constant *Comp =
Reid Spencerfdff9382006-11-08 06:47:33 +00004698 ConstantExpr::getShl(ConstantExpr::getLShr(CI, ShAmt), ShAmt);
Chris Lattner272d5ca2004-09-28 18:22:15 +00004699 if (Comp != CI) {// Comparing against a bit that we know is zero.
Reid Spencer266e42b2006-12-23 06:05:41 +00004700 bool IsICMP_NE = I.getPredicate() == ICmpInst::ICMP_NE;
Reid Spencercddc9df2007-01-12 04:24:46 +00004701 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
Chris Lattner272d5ca2004-09-28 18:22:15 +00004702 return ReplaceInstUsesWith(I, Cst);
4703 }
4704
4705 if (LHSI->hasOneUse()) {
4706 // Otherwise strength reduce the shift into an and.
Reid Spencere0fc4df2006-10-20 07:07:24 +00004707 unsigned ShAmtVal = (unsigned)ShAmt->getZExtValue();
Chris Lattner272d5ca2004-09-28 18:22:15 +00004708 uint64_t Val = (1ULL << (TypeBits-ShAmtVal))-1;
Reid Spencerc635f472006-12-31 05:48:39 +00004709 Constant *Mask = ConstantInt::get(CI->getType(), Val);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004710
Chris Lattner272d5ca2004-09-28 18:22:15 +00004711 Instruction *AndI =
4712 BinaryOperator::createAnd(LHSI->getOperand(0),
4713 Mask, LHSI->getName()+".mask");
4714 Value *And = InsertNewInstBefore(AndI, I);
Reid Spencer266e42b2006-12-23 06:05:41 +00004715 return new ICmpInst(I.getPredicate(), And,
Reid Spencerfdff9382006-11-08 06:47:33 +00004716 ConstantExpr::getLShr(CI, ShAmt));
Chris Lattner272d5ca2004-09-28 18:22:15 +00004717 }
4718 }
Chris Lattner272d5ca2004-09-28 18:22:15 +00004719 }
4720 break;
4721
Reid Spencer266e42b2006-12-23 06:05:41 +00004722 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
Reid Spencerfdff9382006-11-08 06:47:33 +00004723 case Instruction::AShr:
Reid Spencere0fc4df2006-10-20 07:07:24 +00004724 if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004725 if (I.isEquality()) {
Chris Lattner19b57f52005-06-15 20:53:31 +00004726 // Check that the shift amount is in range. If not, don't perform
4727 // undefined shifts. When the shift is visited it will be
4728 // simplified.
Chris Lattner104002b2005-06-16 01:52:07 +00004729 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
Reid Spencere0fc4df2006-10-20 07:07:24 +00004730 if (ShAmt->getZExtValue() >= TypeBits)
Chris Lattner19b57f52005-06-15 20:53:31 +00004731 break;
4732
Chris Lattner1023b872004-09-27 16:18:50 +00004733 // If we are comparing against bits always shifted out, the
4734 // comparison cannot succeed.
Reid Spencerfdff9382006-11-08 06:47:33 +00004735 Constant *Comp;
Reid Spencerc635f472006-12-31 05:48:39 +00004736 if (LHSI->getOpcode() == Instruction::LShr)
Reid Spencerfdff9382006-11-08 06:47:33 +00004737 Comp = ConstantExpr::getLShr(ConstantExpr::getShl(CI, ShAmt),
4738 ShAmt);
4739 else
4740 Comp = ConstantExpr::getAShr(ConstantExpr::getShl(CI, ShAmt),
4741 ShAmt);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004742
Chris Lattner1023b872004-09-27 16:18:50 +00004743 if (Comp != CI) {// Comparing against a bit that we know is zero.
Reid Spencer266e42b2006-12-23 06:05:41 +00004744 bool IsICMP_NE = I.getPredicate() == ICmpInst::ICMP_NE;
Reid Spencercddc9df2007-01-12 04:24:46 +00004745 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
Chris Lattner1023b872004-09-27 16:18:50 +00004746 return ReplaceInstUsesWith(I, Cst);
4747 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004748
Chris Lattner1023b872004-09-27 16:18:50 +00004749 if (LHSI->hasOneUse() || CI->isNullValue()) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00004750 unsigned ShAmtVal = (unsigned)ShAmt->getZExtValue();
Chris Lattner272d5ca2004-09-28 18:22:15 +00004751
Chris Lattner1023b872004-09-27 16:18:50 +00004752 // Otherwise strength reduce the shift into an and.
4753 uint64_t Val = ~0ULL; // All ones.
4754 Val <<= ShAmtVal; // Shift over to the right spot.
Reid Spencerc635f472006-12-31 05:48:39 +00004755 Val &= ~0ULL >> (64-TypeBits);
4756 Constant *Mask = ConstantInt::get(CI->getType(), Val);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004757
Chris Lattner1023b872004-09-27 16:18:50 +00004758 Instruction *AndI =
4759 BinaryOperator::createAnd(LHSI->getOperand(0),
4760 Mask, LHSI->getName()+".mask");
4761 Value *And = InsertNewInstBefore(AndI, I);
Reid Spencer266e42b2006-12-23 06:05:41 +00004762 return new ICmpInst(I.getPredicate(), And,
Chris Lattner1023b872004-09-27 16:18:50 +00004763 ConstantExpr::getShl(CI, ShAmt));
4764 }
Chris Lattner1023b872004-09-27 16:18:50 +00004765 }
4766 }
4767 break;
Chris Lattner7e794272004-09-24 15:21:34 +00004768
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004769 case Instruction::SDiv:
4770 case Instruction::UDiv:
Reid Spencer266e42b2006-12-23 06:05:41 +00004771 // Fold: icmp pred ([us]div X, C1), C2 -> range test
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004772 // Fold this div into the comparison, producing a range check.
4773 // Determine, based on the divide type, what the range is being
4774 // checked. If there is an overflow on the low or high side, remember
4775 // it, otherwise compute the range [low, hi) bounding the new value.
4776 // See: InsertRangeTest above for the kinds of replacements possible.
Chris Lattner6862fbd2004-09-29 17:40:11 +00004777 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004778 // FIXME: If the operand types don't match the type of the divide
4779 // then don't attempt this transform. The code below doesn't have the
4780 // logic to deal with a signed divide and an unsigned compare (and
4781 // vice versa). This is because (x /s C1) <s C2 produces different
4782 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
4783 // (x /u C1) <u C2. Simply casting the operands and result won't
4784 // work. :( The if statement below tests that condition and bails
4785 // if it finds it.
Reid Spencer266e42b2006-12-23 06:05:41 +00004786 bool DivIsSigned = LHSI->getOpcode() == Instruction::SDiv;
4787 if (!I.isEquality() && DivIsSigned != I.isSignedPredicate())
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004788 break;
4789
4790 // Initialize the variables that will indicate the nature of the
4791 // range check.
4792 bool LoOverflow = false, HiOverflow = false;
Chris Lattner6862fbd2004-09-29 17:40:11 +00004793 ConstantInt *LoBound = 0, *HiBound = 0;
4794
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004795 // Compute Prod = CI * DivRHS. We are essentially solving an equation
4796 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
4797 // C2 (CI). By solving for X we can turn this into a range check
4798 // instead of computing a divide.
4799 ConstantInt *Prod =
4800 cast<ConstantInt>(ConstantExpr::getMul(CI, DivRHS));
Chris Lattner6862fbd2004-09-29 17:40:11 +00004801
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004802 // Determine if the product overflows by seeing if the product is
4803 // not equal to the divide. Make sure we do the same kind of divide
4804 // as in the LHS instruction that we're folding.
4805 bool ProdOV = !DivRHS->isNullValue() &&
Reid Spencer266e42b2006-12-23 06:05:41 +00004806 (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004807 ConstantExpr::getUDiv(Prod, DivRHS)) != CI;
4808
Reid Spencer266e42b2006-12-23 06:05:41 +00004809 // Get the ICmp opcode
4810 ICmpInst::Predicate predicate = I.getPredicate();
Chris Lattnera92af962004-10-11 19:40:04 +00004811
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004812 if (DivRHS->isNullValue()) {
4813 // Don't hack on divide by zeros!
Reid Spencer266e42b2006-12-23 06:05:41 +00004814 } else if (!DivIsSigned) { // udiv
Chris Lattner6862fbd2004-09-29 17:40:11 +00004815 LoBound = Prod;
4816 LoOverflow = ProdOV;
4817 HiOverflow = ProdOV || AddWithOverflow(HiBound, LoBound, DivRHS);
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004818 } else if (isPositive(DivRHS)) { // Divisor is > 0.
Chris Lattner6862fbd2004-09-29 17:40:11 +00004819 if (CI->isNullValue()) { // (X / pos) op 0
4820 // Can't overflow.
4821 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
4822 HiBound = DivRHS;
4823 } else if (isPositive(CI)) { // (X / pos) op pos
4824 LoBound = Prod;
4825 LoOverflow = ProdOV;
4826 HiOverflow = ProdOV || AddWithOverflow(HiBound, Prod, DivRHS);
4827 } else { // (X / pos) op neg
4828 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
4829 LoOverflow = AddWithOverflow(LoBound, Prod,
4830 cast<ConstantInt>(DivRHSH));
4831 HiBound = Prod;
4832 HiOverflow = ProdOV;
4833 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004834 } else { // Divisor is < 0.
Chris Lattner6862fbd2004-09-29 17:40:11 +00004835 if (CI->isNullValue()) { // (X / neg) op 0
4836 LoBound = AddOne(DivRHS);
4837 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner73bcba52005-06-17 02:05:55 +00004838 if (HiBound == DivRHS)
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004839 LoBound = 0; // - INTMIN = INTMIN
Chris Lattner6862fbd2004-09-29 17:40:11 +00004840 } else if (isPositive(CI)) { // (X / neg) op pos
4841 HiOverflow = LoOverflow = ProdOV;
4842 if (!LoOverflow)
4843 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS));
4844 HiBound = AddOne(Prod);
4845 } else { // (X / neg) op neg
4846 LoBound = Prod;
4847 LoOverflow = HiOverflow = ProdOV;
4848 HiBound = cast<ConstantInt>(ConstantExpr::getSub(Prod, DivRHS));
4849 }
Chris Lattner0b41e862004-10-08 19:15:44 +00004850
Chris Lattnera92af962004-10-11 19:40:04 +00004851 // Dividing by a negate swaps the condition.
Reid Spencer266e42b2006-12-23 06:05:41 +00004852 predicate = ICmpInst::getSwappedPredicate(predicate);
Chris Lattner6862fbd2004-09-29 17:40:11 +00004853 }
4854
4855 if (LoBound) {
4856 Value *X = LHSI->getOperand(0);
Reid Spencer266e42b2006-12-23 06:05:41 +00004857 switch (predicate) {
4858 default: assert(0 && "Unhandled icmp opcode!");
4859 case ICmpInst::ICMP_EQ:
Chris Lattner6862fbd2004-09-29 17:40:11 +00004860 if (LoOverflow && HiOverflow)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004861 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattner6862fbd2004-09-29 17:40:11 +00004862 else if (HiOverflow)
Reid Spencer266e42b2006-12-23 06:05:41 +00004863 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
4864 ICmpInst::ICMP_UGE, X, LoBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00004865 else if (LoOverflow)
Reid Spencer266e42b2006-12-23 06:05:41 +00004866 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
4867 ICmpInst::ICMP_ULT, X, HiBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00004868 else
Reid Spencer266e42b2006-12-23 06:05:41 +00004869 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned,
4870 true, I);
4871 case ICmpInst::ICMP_NE:
Chris Lattner6862fbd2004-09-29 17:40:11 +00004872 if (LoOverflow && HiOverflow)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004873 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner6862fbd2004-09-29 17:40:11 +00004874 else if (HiOverflow)
Reid Spencer266e42b2006-12-23 06:05:41 +00004875 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
4876 ICmpInst::ICMP_ULT, X, LoBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00004877 else if (LoOverflow)
Reid Spencer266e42b2006-12-23 06:05:41 +00004878 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
4879 ICmpInst::ICMP_UGE, X, HiBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00004880 else
Reid Spencer266e42b2006-12-23 06:05:41 +00004881 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned,
4882 false, I);
4883 case ICmpInst::ICMP_ULT:
4884 case ICmpInst::ICMP_SLT:
Chris Lattner6862fbd2004-09-29 17:40:11 +00004885 if (LoOverflow)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004886 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004887 return new ICmpInst(predicate, X, LoBound);
4888 case ICmpInst::ICMP_UGT:
4889 case ICmpInst::ICMP_SGT:
Chris Lattner6862fbd2004-09-29 17:40:11 +00004890 if (HiOverflow)
Zhou Sheng75b871f2007-01-11 12:24:14 +00004891 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00004892 if (predicate == ICmpInst::ICMP_UGT)
4893 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
4894 else
4895 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
Chris Lattner6862fbd2004-09-29 17:40:11 +00004896 }
4897 }
4898 }
4899 break;
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004900 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004901
Reid Spencer266e42b2006-12-23 06:05:41 +00004902 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004903 if (I.isEquality()) {
Reid Spencer266e42b2006-12-23 06:05:41 +00004904 bool isICMP_NE = I.getPredicate() == ICmpInst::ICMP_NE;
Chris Lattnerd492a0b2003-07-23 17:02:11 +00004905
Reid Spencere0fc4df2006-10-20 07:07:24 +00004906 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
4907 // the second operand is a constant, simplify a bit.
Chris Lattnerc992add2003-08-13 05:33:12 +00004908 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
4909 switch (BO->getOpcode()) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00004910 case Instruction::SRem:
4911 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
4912 if (CI->isNullValue() && isa<ConstantInt>(BO->getOperand(1)) &&
4913 BO->hasOneUse()) {
4914 int64_t V = cast<ConstantInt>(BO->getOperand(1))->getSExtValue();
4915 if (V > 1 && isPowerOf2_64(V)) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00004916 Value *NewRem = InsertNewInstBefore(BinaryOperator::createURem(
4917 BO->getOperand(0), BO->getOperand(1), BO->getName()), I);
Reid Spencer266e42b2006-12-23 06:05:41 +00004918 return new ICmpInst(I.getPredicate(), NewRem,
4919 Constant::getNullValue(BO->getType()));
Chris Lattner23b47b62004-07-06 07:38:18 +00004920 }
Chris Lattner22d00a82005-08-02 19:16:58 +00004921 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004922 break;
Chris Lattnerc992add2003-08-13 05:33:12 +00004923 case Instruction::Add:
Chris Lattner6e079362004-06-27 22:51:36 +00004924 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
4925 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerb121ae12004-09-21 21:35:23 +00004926 if (BO->hasOneUse())
Reid Spencer266e42b2006-12-23 06:05:41 +00004927 return new ICmpInst(I.getPredicate(), BO->getOperand(0),
4928 ConstantExpr::getSub(CI, BOp1C));
Chris Lattner6e079362004-06-27 22:51:36 +00004929 } else if (CI->isNullValue()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00004930 // Replace ((add A, B) != 0) with (A != -B) if A or B is
4931 // efficiently invertible, or if the add has just this one use.
4932 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004933
Chris Lattnerc992add2003-08-13 05:33:12 +00004934 if (Value *NegVal = dyn_castNegVal(BOp1))
Reid Spencer266e42b2006-12-23 06:05:41 +00004935 return new ICmpInst(I.getPredicate(), BOp0, NegVal);
Chris Lattnerc992add2003-08-13 05:33:12 +00004936 else if (Value *NegVal = dyn_castNegVal(BOp0))
Reid Spencer266e42b2006-12-23 06:05:41 +00004937 return new ICmpInst(I.getPredicate(), NegVal, BOp1);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00004938 else if (BO->hasOneUse()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00004939 Instruction *Neg = BinaryOperator::createNeg(BOp1, BO->getName());
4940 BO->setName("");
4941 InsertNewInstBefore(Neg, I);
Reid Spencer266e42b2006-12-23 06:05:41 +00004942 return new ICmpInst(I.getPredicate(), BOp0, Neg);
Chris Lattnerc992add2003-08-13 05:33:12 +00004943 }
4944 }
4945 break;
4946 case Instruction::Xor:
4947 // For the xor case, we can xor two constants together, eliminating
4948 // the explicit xor.
4949 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
Reid Spencer266e42b2006-12-23 06:05:41 +00004950 return new ICmpInst(I.getPredicate(), BO->getOperand(0),
4951 ConstantExpr::getXor(CI, BOC));
Chris Lattnerc992add2003-08-13 05:33:12 +00004952
4953 // FALLTHROUGH
4954 case Instruction::Sub:
4955 // Replace (([sub|xor] A, B) != 0) with (A != B)
4956 if (CI->isNullValue())
Reid Spencer266e42b2006-12-23 06:05:41 +00004957 return new ICmpInst(I.getPredicate(), BO->getOperand(0),
4958 BO->getOperand(1));
Chris Lattnerc992add2003-08-13 05:33:12 +00004959 break;
4960
4961 case Instruction::Or:
4962 // If bits are being or'd in that are not present in the constant we
4963 // are comparing against, then the comparison could never succeed!
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00004964 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Chris Lattnerc8e7e292004-06-10 02:12:35 +00004965 Constant *NotCI = ConstantExpr::getNot(CI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004966 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Reid Spencercddc9df2007-01-12 04:24:46 +00004967 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4968 isICMP_NE));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00004969 }
Chris Lattnerc992add2003-08-13 05:33:12 +00004970 break;
4971
4972 case Instruction::And:
4973 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerd492a0b2003-07-23 17:02:11 +00004974 // If bits are being compared against that are and'd out, then the
4975 // comparison can never succeed!
Chris Lattnerc8e7e292004-06-10 02:12:35 +00004976 if (!ConstantExpr::getAnd(CI,
4977 ConstantExpr::getNot(BOC))->isNullValue())
Reid Spencercddc9df2007-01-12 04:24:46 +00004978 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4979 isICMP_NE));
Chris Lattnerc992add2003-08-13 05:33:12 +00004980
Chris Lattner35167c32004-06-09 07:59:58 +00004981 // If we have ((X & C) == C), turn it into ((X & C) != 0).
Chris Lattneree59d4b2004-06-10 02:33:20 +00004982 if (CI == BOC && isOneBitSet(CI))
Reid Spencer266e42b2006-12-23 06:05:41 +00004983 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
4984 ICmpInst::ICMP_NE, Op0,
4985 Constant::getNullValue(CI->getType()));
Chris Lattner35167c32004-06-09 07:59:58 +00004986
Reid Spencer266e42b2006-12-23 06:05:41 +00004987 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
Chris Lattnerc992add2003-08-13 05:33:12 +00004988 if (isSignBit(BOC)) {
4989 Value *X = BO->getOperand(0);
Reid Spencer266e42b2006-12-23 06:05:41 +00004990 Constant *Zero = Constant::getNullValue(X->getType());
4991 ICmpInst::Predicate pred = isICMP_NE ?
4992 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
4993 return new ICmpInst(pred, X, Zero);
Chris Lattnerc992add2003-08-13 05:33:12 +00004994 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004995
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004996 // ((X & ~7) == 0) --> X < 8
Chris Lattner8fc5af42004-09-23 21:46:38 +00004997 if (CI->isNullValue() && isHighOnes(BOC)) {
4998 Value *X = BO->getOperand(0);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004999 Constant *NegX = ConstantExpr::getNeg(BOC);
Reid Spencer266e42b2006-12-23 06:05:41 +00005000 ICmpInst::Predicate pred = isICMP_NE ?
5001 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
5002 return new ICmpInst(pred, X, NegX);
Chris Lattner8fc5af42004-09-23 21:46:38 +00005003 }
5004
Chris Lattnerd492a0b2003-07-23 17:02:11 +00005005 }
Chris Lattnerc992add2003-08-13 05:33:12 +00005006 default: break;
5007 }
Chris Lattnera7942b72006-11-29 05:02:16 +00005008 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Op0)) {
5009 // Handle set{eq|ne} <intrinsic>, intcst.
5010 switch (II->getIntrinsicID()) {
5011 default: break;
Reid Spencer266e42b2006-12-23 06:05:41 +00005012 case Intrinsic::bswap_i16:
5013 // icmp eq (bswap(x)), c -> icmp eq (x,bswap(c))
Chris Lattnera7942b72006-11-29 05:02:16 +00005014 WorkList.push_back(II); // Dead?
5015 I.setOperand(0, II->getOperand(1));
Reid Spencerc635f472006-12-31 05:48:39 +00005016 I.setOperand(1, ConstantInt::get(Type::Int16Ty,
Chris Lattnera7942b72006-11-29 05:02:16 +00005017 ByteSwap_16(CI->getZExtValue())));
5018 return &I;
Reid Spencer266e42b2006-12-23 06:05:41 +00005019 case Intrinsic::bswap_i32:
5020 // icmp eq (bswap(x)), c -> icmp eq (x,bswap(c))
Chris Lattnera7942b72006-11-29 05:02:16 +00005021 WorkList.push_back(II); // Dead?
5022 I.setOperand(0, II->getOperand(1));
Reid Spencerc635f472006-12-31 05:48:39 +00005023 I.setOperand(1, ConstantInt::get(Type::Int32Ty,
Chris Lattnera7942b72006-11-29 05:02:16 +00005024 ByteSwap_32(CI->getZExtValue())));
5025 return &I;
Reid Spencer266e42b2006-12-23 06:05:41 +00005026 case Intrinsic::bswap_i64:
5027 // icmp eq (bswap(x)), c -> icmp eq (x,bswap(c))
Chris Lattnera7942b72006-11-29 05:02:16 +00005028 WorkList.push_back(II); // Dead?
5029 I.setOperand(0, II->getOperand(1));
Reid Spencerc635f472006-12-31 05:48:39 +00005030 I.setOperand(1, ConstantInt::get(Type::Int64Ty,
Chris Lattnera7942b72006-11-29 05:02:16 +00005031 ByteSwap_64(CI->getZExtValue())));
5032 return &I;
5033 }
Chris Lattnerc992add2003-08-13 05:33:12 +00005034 }
Reid Spencer266e42b2006-12-23 06:05:41 +00005035 } else { // Not a ICMP_EQ/ICMP_NE
5036 // If the LHS is a cast from an integral value of the same size, then
5037 // since we know the RHS is a constant, try to simlify.
Chris Lattner2b55ea32004-02-23 07:16:20 +00005038 if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
5039 Value *CastOp = Cast->getOperand(0);
5040 const Type *SrcTy = CastOp->getType();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005041 unsigned SrcTySize = SrcTy->getPrimitiveSizeInBits();
Reid Spencer266e42b2006-12-23 06:05:41 +00005042 if (SrcTy->isInteger() &&
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005043 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
Reid Spencer266e42b2006-12-23 06:05:41 +00005044 // If this is an unsigned comparison, try to make the comparison use
5045 // smaller constant values.
5046 switch (I.getPredicate()) {
5047 default: break;
5048 case ICmpInst::ICMP_ULT: { // X u< 128 => X s> -1
5049 ConstantInt *CUI = cast<ConstantInt>(CI);
5050 if (CUI->getZExtValue() == 1ULL << (SrcTySize-1))
5051 return new ICmpInst(ICmpInst::ICMP_SGT, CastOp,
5052 ConstantInt::get(SrcTy, -1));
5053 break;
5054 }
5055 case ICmpInst::ICMP_UGT: { // X u> 127 => X s< 0
5056 ConstantInt *CUI = cast<ConstantInt>(CI);
5057 if (CUI->getZExtValue() == (1ULL << (SrcTySize-1))-1)
5058 return new ICmpInst(ICmpInst::ICMP_SLT, CastOp,
5059 Constant::getNullValue(SrcTy));
5060 break;
5061 }
Chris Lattner2b55ea32004-02-23 07:16:20 +00005062 }
Reid Spencer266e42b2006-12-23 06:05:41 +00005063
Chris Lattner2b55ea32004-02-23 07:16:20 +00005064 }
5065 }
Chris Lattnere967b342003-06-04 05:10:11 +00005066 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005067 }
5068
Reid Spencer266e42b2006-12-23 06:05:41 +00005069 // Handle icmp with constant RHS
Chris Lattner77c32c32005-04-23 15:31:55 +00005070 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5071 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5072 switch (LHSI->getOpcode()) {
Chris Lattnera816eee2005-05-01 04:42:15 +00005073 case Instruction::GetElementPtr:
5074 if (RHSC->isNullValue()) {
Reid Spencer266e42b2006-12-23 06:05:41 +00005075 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
Chris Lattnera816eee2005-05-01 04:42:15 +00005076 bool isAllZeros = true;
5077 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
5078 if (!isa<Constant>(LHSI->getOperand(i)) ||
5079 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
5080 isAllZeros = false;
5081 break;
5082 }
5083 if (isAllZeros)
Reid Spencer266e42b2006-12-23 06:05:41 +00005084 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
Chris Lattnera816eee2005-05-01 04:42:15 +00005085 Constant::getNullValue(LHSI->getOperand(0)->getType()));
5086 }
5087 break;
5088
Chris Lattner77c32c32005-04-23 15:31:55 +00005089 case Instruction::PHI:
5090 if (Instruction *NV = FoldOpIntoPhi(I))
5091 return NV;
5092 break;
5093 case Instruction::Select:
5094 // If either operand of the select is a constant, we can fold the
5095 // comparison into the select arms, which will cause one to be
5096 // constant folded and the select turned into a bitwise or.
5097 Value *Op1 = 0, *Op2 = 0;
5098 if (LHSI->hasOneUse()) {
5099 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5100 // Fold the known value into the constant operand.
Reid Spencer266e42b2006-12-23 06:05:41 +00005101 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5102 // Insert a new ICmp of the other select operand.
5103 Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5104 LHSI->getOperand(2), RHSC,
5105 I.getName()), I);
Chris Lattner77c32c32005-04-23 15:31:55 +00005106 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5107 // Fold the known value into the constant operand.
Reid Spencer266e42b2006-12-23 06:05:41 +00005108 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5109 // Insert a new ICmp of the other select operand.
5110 Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5111 LHSI->getOperand(1), RHSC,
5112 I.getName()), I);
Chris Lattner77c32c32005-04-23 15:31:55 +00005113 }
5114 }
Jeff Cohen82639852005-04-23 21:38:35 +00005115
Chris Lattner77c32c32005-04-23 15:31:55 +00005116 if (Op1)
5117 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
5118 break;
5119 }
5120 }
5121
Reid Spencer266e42b2006-12-23 06:05:41 +00005122 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
Chris Lattner0798af32005-01-13 20:14:25 +00005123 if (User *GEP = dyn_castGetElementPtr(Op0))
Reid Spencer266e42b2006-12-23 06:05:41 +00005124 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
Chris Lattner0798af32005-01-13 20:14:25 +00005125 return NI;
5126 if (User *GEP = dyn_castGetElementPtr(Op1))
Reid Spencer266e42b2006-12-23 06:05:41 +00005127 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
5128 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
Chris Lattner0798af32005-01-13 20:14:25 +00005129 return NI;
5130
Reid Spencer266e42b2006-12-23 06:05:41 +00005131 // Test to see if the operands of the icmp are casted versions of other
Chris Lattner64d87b02007-01-06 01:45:59 +00005132 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
5133 // now.
5134 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
5135 if (isa<PointerType>(Op0->getType()) &&
5136 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattner16930792003-11-03 04:25:02 +00005137 // We keep moving the cast from the left operand over to the right
5138 // operand, where it can often be eliminated completely.
Chris Lattner64d87b02007-01-06 01:45:59 +00005139 Op0 = CI->getOperand(0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00005140
Chris Lattner64d87b02007-01-06 01:45:59 +00005141 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
5142 // so eliminate it as well.
5143 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
5144 Op1 = CI2->getOperand(0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00005145
Chris Lattner16930792003-11-03 04:25:02 +00005146 // If Op1 is a constant, we can fold the cast into the constant.
Chris Lattner64d87b02007-01-06 01:45:59 +00005147 if (Op0->getType() != Op1->getType())
Chris Lattner16930792003-11-03 04:25:02 +00005148 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Reid Spencerbb65ebf2006-12-12 23:36:14 +00005149 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
Chris Lattner16930792003-11-03 04:25:02 +00005150 } else {
Reid Spencer266e42b2006-12-23 06:05:41 +00005151 // Otherwise, cast the RHS right before the icmp
Reid Spencer13bc5d72006-12-12 09:18:51 +00005152 Op1 = InsertCastBefore(Instruction::BitCast, Op1, Op0->getType(), I);
Chris Lattner16930792003-11-03 04:25:02 +00005153 }
Reid Spencer266e42b2006-12-23 06:05:41 +00005154 return new ICmpInst(I.getPredicate(), Op0, Op1);
Chris Lattner16930792003-11-03 04:25:02 +00005155 }
Chris Lattner64d87b02007-01-06 01:45:59 +00005156 }
5157
5158 if (isa<CastInst>(Op0)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00005159 // Handle the special case of: icmp (cast bool to X), <cst>
Chris Lattner6444c372003-11-03 05:17:03 +00005160 // This comes up when you have code like
5161 // int X = A < B;
5162 // if (X) ...
5163 // For generality, we handle any zero-extension of any operand comparison
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005164 // with a constant or another cast from the same type.
5165 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
Reid Spencer266e42b2006-12-23 06:05:41 +00005166 if (Instruction *R = visitICmpInstWithCastAndCast(I))
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005167 return R;
Chris Lattner6444c372003-11-03 05:17:03 +00005168 }
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00005169
Chris Lattnerb3f24c92006-09-18 04:22:48 +00005170 if (I.isEquality()) {
Chris Lattner17c7c032007-01-05 03:04:57 +00005171 Value *A, *B, *C, *D;
5172 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
5173 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
5174 Value *OtherVal = A == Op1 ? B : A;
5175 return new ICmpInst(I.getPredicate(), OtherVal,
5176 Constant::getNullValue(A->getType()));
5177 }
5178
5179 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
5180 // A^c1 == C^c2 --> A == C^(c1^c2)
5181 if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
5182 if (ConstantInt *C2 = dyn_cast<ConstantInt>(D))
5183 if (Op1->hasOneUse()) {
5184 Constant *NC = ConstantExpr::getXor(C1, C2);
5185 Instruction *Xor = BinaryOperator::createXor(C, NC, "tmp");
5186 return new ICmpInst(I.getPredicate(), A,
5187 InsertNewInstBefore(Xor, I));
5188 }
5189
5190 // A^B == A^D -> B == D
5191 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
5192 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
5193 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
5194 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
5195 }
5196 }
5197
5198 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
5199 (A == Op0 || B == Op0)) {
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00005200 // A == (A^B) -> B == 0
5201 Value *OtherVal = A == Op0 ? B : A;
Reid Spencer266e42b2006-12-23 06:05:41 +00005202 return new ICmpInst(I.getPredicate(), OtherVal,
5203 Constant::getNullValue(A->getType()));
Chris Lattner17c7c032007-01-05 03:04:57 +00005204 }
5205 if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00005206 // (A-B) == A -> B == 0
Reid Spencer266e42b2006-12-23 06:05:41 +00005207 return new ICmpInst(I.getPredicate(), B,
5208 Constant::getNullValue(B->getType()));
Chris Lattner17c7c032007-01-05 03:04:57 +00005209 }
5210 if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00005211 // A == (A-B) -> B == 0
Reid Spencer266e42b2006-12-23 06:05:41 +00005212 return new ICmpInst(I.getPredicate(), B,
5213 Constant::getNullValue(B->getType()));
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00005214 }
Chris Lattnerd12a4bf2006-11-14 06:06:06 +00005215
Chris Lattnerd12a4bf2006-11-14 06:06:06 +00005216 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
5217 if (Op0->hasOneUse() && Op1->hasOneUse() &&
5218 match(Op0, m_And(m_Value(A), m_Value(B))) &&
5219 match(Op1, m_And(m_Value(C), m_Value(D)))) {
5220 Value *X = 0, *Y = 0, *Z = 0;
5221
5222 if (A == C) {
5223 X = B; Y = D; Z = A;
5224 } else if (A == D) {
5225 X = B; Y = C; Z = A;
5226 } else if (B == C) {
5227 X = A; Y = D; Z = B;
5228 } else if (B == D) {
5229 X = A; Y = C; Z = B;
5230 }
5231
5232 if (X) { // Build (X^Y) & Z
5233 Op1 = InsertNewInstBefore(BinaryOperator::createXor(X, Y, "tmp"), I);
5234 Op1 = InsertNewInstBefore(BinaryOperator::createAnd(Op1, Z, "tmp"), I);
5235 I.setOperand(0, Op1);
5236 I.setOperand(1, Constant::getNullValue(Op1->getType()));
5237 return &I;
5238 }
5239 }
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00005240 }
Chris Lattner113f4f42002-06-25 16:13:24 +00005241 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005242}
5243
Reid Spencer266e42b2006-12-23 06:05:41 +00005244// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005245// We only handle extending casts so far.
5246//
Reid Spencer266e42b2006-12-23 06:05:41 +00005247Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
5248 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005249 Value *LHSCIOp = LHSCI->getOperand(0);
5250 const Type *SrcTy = LHSCIOp->getType();
Reid Spencer266e42b2006-12-23 06:05:41 +00005251 const Type *DestTy = LHSCI->getType();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005252 Value *RHSCIOp;
5253
Reid Spencer266e42b2006-12-23 06:05:41 +00005254 // We only handle extension cast instructions, so far. Enforce this.
5255 if (LHSCI->getOpcode() != Instruction::ZExt &&
5256 LHSCI->getOpcode() != Instruction::SExt)
Chris Lattner03f06f12005-01-17 03:20:02 +00005257 return 0;
5258
Reid Spencer266e42b2006-12-23 06:05:41 +00005259 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
5260 bool isSignedCmp = ICI.isSignedPredicate();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005261
Reid Spencer266e42b2006-12-23 06:05:41 +00005262 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005263 // Not an extension from the same type?
5264 RHSCIOp = CI->getOperand(0);
Reid Spencer266e42b2006-12-23 06:05:41 +00005265 if (RHSCIOp->getType() != LHSCIOp->getType())
5266 return 0;
5267 else
5268 // Okay, just insert a compare of the reduced operands now!
5269 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
Reid Spencer279fa252004-11-28 21:31:15 +00005270 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005271
Reid Spencer266e42b2006-12-23 06:05:41 +00005272 // If we aren't dealing with a constant on the RHS, exit early
5273 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
5274 if (!CI)
5275 return 0;
5276
5277 // Compute the constant that would happen if we truncated to SrcTy then
5278 // reextended to DestTy.
5279 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
5280 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
5281
5282 // If the re-extended constant didn't change...
5283 if (Res2 == CI) {
5284 // Make sure that sign of the Cmp and the sign of the Cast are the same.
5285 // For example, we might have:
5286 // %A = sext short %X to uint
5287 // %B = icmp ugt uint %A, 1330
5288 // It is incorrect to transform this into
5289 // %B = icmp ugt short %X, 1330
5290 // because %A may have negative value.
5291 //
5292 // However, it is OK if SrcTy is bool (See cast-set.ll testcase)
5293 // OR operation is EQ/NE.
Reid Spencer542964f2007-01-11 18:21:29 +00005294 if (isSignedExt == isSignedCmp || SrcTy == Type::Int1Ty || ICI.isEquality())
Reid Spencer266e42b2006-12-23 06:05:41 +00005295 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
5296 else
5297 return 0;
5298 }
5299
5300 // The re-extended constant changed so the constant cannot be represented
5301 // in the shorter type. Consequently, we cannot emit a simple comparison.
5302
5303 // First, handle some easy cases. We know the result cannot be equal at this
5304 // point so handle the ICI.isEquality() cases
5305 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Zhou Sheng75b871f2007-01-11 12:24:14 +00005306 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Reid Spencer266e42b2006-12-23 06:05:41 +00005307 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Zhou Sheng75b871f2007-01-11 12:24:14 +00005308 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
Reid Spencer266e42b2006-12-23 06:05:41 +00005309
5310 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
5311 // should have been folded away previously and not enter in here.
5312 Value *Result;
5313 if (isSignedCmp) {
5314 // We're performing a signed comparison.
5315 if (cast<ConstantInt>(CI)->getSExtValue() < 0)
Zhou Sheng75b871f2007-01-11 12:24:14 +00005316 Result = ConstantInt::getFalse(); // X < (small) --> false
Reid Spencer266e42b2006-12-23 06:05:41 +00005317 else
Zhou Sheng75b871f2007-01-11 12:24:14 +00005318 Result = ConstantInt::getTrue(); // X < (large) --> true
Reid Spencer266e42b2006-12-23 06:05:41 +00005319 } else {
5320 // We're performing an unsigned comparison.
5321 if (isSignedExt) {
5322 // We're performing an unsigned comp with a sign extended value.
5323 // This is true if the input is >= 0. [aka >s -1]
Zhou Sheng75b871f2007-01-11 12:24:14 +00005324 Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
Reid Spencer266e42b2006-12-23 06:05:41 +00005325 Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
5326 NegOne, ICI.getName()), ICI);
5327 } else {
5328 // Unsigned extend & unsigned compare -> always true.
Zhou Sheng75b871f2007-01-11 12:24:14 +00005329 Result = ConstantInt::getTrue();
Reid Spencer266e42b2006-12-23 06:05:41 +00005330 }
5331 }
5332
5333 // Finally, return the value computed.
5334 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
5335 ICI.getPredicate() == ICmpInst::ICMP_SLT) {
5336 return ReplaceInstUsesWith(ICI, Result);
5337 } else {
5338 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
5339 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
5340 "ICmp should be folded!");
5341 if (Constant *CI = dyn_cast<Constant>(Result))
5342 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
5343 else
5344 return BinaryOperator::createNot(Result);
5345 }
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005346}
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005347
Chris Lattnere8d6c602003-03-10 19:16:08 +00005348Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
Reid Spencerc635f472006-12-31 05:48:39 +00005349 assert(I.getOperand(1)->getType() == Type::Int8Ty);
Chris Lattner113f4f42002-06-25 16:13:24 +00005350 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005351
5352 // shl X, 0 == X and shr X, 0 == X
5353 // shl 0, X == 0 and shr 0, X == 0
Reid Spencerc635f472006-12-31 05:48:39 +00005354 if (Op1 == Constant::getNullValue(Type::Int8Ty) ||
Chris Lattnere6794492002-08-12 21:17:25 +00005355 Op0 == Constant::getNullValue(Op0->getType()))
5356 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf5b4ef72006-02-12 08:07:37 +00005357
Reid Spencer266e42b2006-12-23 06:05:41 +00005358 if (isa<UndefValue>(Op0)) {
5359 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
Chris Lattner67f05452004-10-16 23:28:04 +00005360 return ReplaceInstUsesWith(I, Op0);
Reid Spencer266e42b2006-12-23 06:05:41 +00005361 else // undef << X -> 0, undef >>u X -> 0
Chris Lattner81a7a232004-10-16 18:11:37 +00005362 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5363 }
5364 if (isa<UndefValue>(Op1)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00005365 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
5366 return ReplaceInstUsesWith(I, Op0);
5367 else // X << undef, X >>u undef -> 0
Chris Lattner81a7a232004-10-16 18:11:37 +00005368 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner81a7a232004-10-16 18:11:37 +00005369 }
5370
Chris Lattnerd4dee402006-11-10 23:38:52 +00005371 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
5372 if (I.getOpcode() == Instruction::AShr)
Reid Spencere0fc4df2006-10-20 07:07:24 +00005373 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Chris Lattnerd4dee402006-11-10 23:38:52 +00005374 if (CSI->isAllOnesValue())
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00005375 return ReplaceInstUsesWith(I, CSI);
5376
Chris Lattner183b3362004-04-09 19:05:30 +00005377 // Try to fold constant and into select arguments.
5378 if (isa<Constant>(Op0))
5379 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner86102b82005-01-01 16:22:27 +00005380 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00005381 return R;
5382
Chris Lattnerb18dbbf2005-05-08 17:34:56 +00005383 // See if we can turn a signed shr into an unsigned shr.
Chris Lattnerb3f24c92006-09-18 04:22:48 +00005384 if (I.isArithmeticShift()) {
Chris Lattnerc3ebf402006-02-07 07:27:52 +00005385 if (MaskedValueIsZero(Op0,
5386 1ULL << (I.getType()->getPrimitiveSizeInBits()-1))) {
Reid Spencerfdff9382006-11-08 06:47:33 +00005387 return new ShiftInst(Instruction::LShr, Op0, Op1, I.getName());
Chris Lattnerb18dbbf2005-05-08 17:34:56 +00005388 }
5389 }
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00005390
Reid Spencere0fc4df2006-10-20 07:07:24 +00005391 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
Reid Spencerc635f472006-12-31 05:48:39 +00005392 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
5393 return Res;
Chris Lattner14553932006-01-06 07:12:35 +00005394 return 0;
5395}
5396
Reid Spencere0fc4df2006-10-20 07:07:24 +00005397Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Chris Lattner14553932006-01-06 07:12:35 +00005398 ShiftInst &I) {
Reid Spencer266e42b2006-12-23 06:05:41 +00005399 bool isLeftShift = I.getOpcode() == Instruction::Shl;
5400 bool isSignedShift = I.getOpcode() == Instruction::AShr;
Chris Lattnerb3309392006-01-06 07:22:22 +00005401 bool isUnsignedShift = !isSignedShift;
Chris Lattner14553932006-01-06 07:12:35 +00005402
Chris Lattnerf5b4ef72006-02-12 08:07:37 +00005403 // See if we can simplify any instructions used by the instruction whose sole
5404 // purpose is to compute bits we don't care about.
5405 uint64_t KnownZero, KnownOne;
5406 if (SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
5407 KnownZero, KnownOne))
5408 return &I;
5409
Chris Lattner14553932006-01-06 07:12:35 +00005410 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
5411 // of a signed value.
5412 //
5413 unsigned TypeBits = Op0->getType()->getPrimitiveSizeInBits();
Reid Spencere0fc4df2006-10-20 07:07:24 +00005414 if (Op1->getZExtValue() >= TypeBits) {
Chris Lattnerb3309392006-01-06 07:22:22 +00005415 if (isUnsignedShift || isLeftShift)
Chris Lattner14553932006-01-06 07:12:35 +00005416 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
5417 else {
Reid Spencerc635f472006-12-31 05:48:39 +00005418 I.setOperand(1, ConstantInt::get(Type::Int8Ty, TypeBits-1));
Chris Lattner14553932006-01-06 07:12:35 +00005419 return &I;
Chris Lattnerf5ce2542004-02-23 20:30:06 +00005420 }
Chris Lattner14553932006-01-06 07:12:35 +00005421 }
5422
5423 // ((X*C1) << C2) == (X * (C1 << C2))
5424 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
5425 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
5426 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
5427 return BinaryOperator::createMul(BO->getOperand(0),
5428 ConstantExpr::getShl(BOOp, Op1));
5429
5430 // Try to fold constant and into select arguments.
5431 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5432 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5433 return R;
5434 if (isa<PHINode>(Op0))
5435 if (Instruction *NV = FoldOpIntoPhi(I))
5436 return NV;
5437
5438 if (Op0->hasOneUse()) {
Chris Lattner14553932006-01-06 07:12:35 +00005439 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
5440 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
5441 Value *V1, *V2;
5442 ConstantInt *CC;
5443 switch (Op0BO->getOpcode()) {
Chris Lattner27cb9db2005-09-18 05:12:10 +00005444 default: break;
5445 case Instruction::Add:
5446 case Instruction::And:
5447 case Instruction::Or:
5448 case Instruction::Xor:
5449 // These operators commute.
5450 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner797dee72005-09-18 06:30:59 +00005451 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
5452 match(Op0BO->getOperand(1),
Chris Lattner14553932006-01-06 07:12:35 +00005453 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Chris Lattner797dee72005-09-18 06:30:59 +00005454 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00005455 Op0BO->getOperand(0), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00005456 Op0BO->getName());
5457 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005458 Instruction *X =
5459 BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
5460 Op0BO->getOperand(1)->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00005461 InsertNewInstBefore(X, I); // (X + (Y << C))
5462 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
Chris Lattner14553932006-01-06 07:12:35 +00005463 C2 = ConstantExpr::getShl(C2, Op1);
Chris Lattner797dee72005-09-18 06:30:59 +00005464 return BinaryOperator::createAnd(X, C2);
5465 }
Chris Lattner14553932006-01-06 07:12:35 +00005466
Chris Lattner797dee72005-09-18 06:30:59 +00005467 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
5468 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
5469 match(Op0BO->getOperand(1),
5470 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner14553932006-01-06 07:12:35 +00005471 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005472 cast<BinaryOperator>(Op0BO->getOperand(1))->getOperand(0)->hasOneUse()) {
Chris Lattner797dee72005-09-18 06:30:59 +00005473 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00005474 Op0BO->getOperand(0), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00005475 Op0BO->getName());
5476 InsertNewInstBefore(YS, I); // (Y << C)
5477 Instruction *XM =
Chris Lattner14553932006-01-06 07:12:35 +00005478 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner797dee72005-09-18 06:30:59 +00005479 V1->getName()+".mask");
5480 InsertNewInstBefore(XM, I); // X & (CC << C)
5481
5482 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
5483 }
Chris Lattner14553932006-01-06 07:12:35 +00005484
Chris Lattner797dee72005-09-18 06:30:59 +00005485 // FALL THROUGH.
Chris Lattner27cb9db2005-09-18 05:12:10 +00005486 case Instruction::Sub:
5487 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner797dee72005-09-18 06:30:59 +00005488 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
5489 match(Op0BO->getOperand(0),
Chris Lattner14553932006-01-06 07:12:35 +00005490 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Chris Lattner797dee72005-09-18 06:30:59 +00005491 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00005492 Op0BO->getOperand(1), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00005493 Op0BO->getName());
5494 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005495 Instruction *X =
Chris Lattner1df0e982006-05-31 21:14:00 +00005496 BinaryOperator::create(Op0BO->getOpcode(), V1, YS,
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005497 Op0BO->getOperand(0)->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00005498 InsertNewInstBefore(X, I); // (X + (Y << C))
5499 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
Chris Lattner14553932006-01-06 07:12:35 +00005500 C2 = ConstantExpr::getShl(C2, Op1);
Chris Lattner797dee72005-09-18 06:30:59 +00005501 return BinaryOperator::createAnd(X, C2);
5502 }
Chris Lattner14553932006-01-06 07:12:35 +00005503
Chris Lattner1df0e982006-05-31 21:14:00 +00005504 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner797dee72005-09-18 06:30:59 +00005505 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
5506 match(Op0BO->getOperand(0),
5507 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner14553932006-01-06 07:12:35 +00005508 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005509 cast<BinaryOperator>(Op0BO->getOperand(0))
5510 ->getOperand(0)->hasOneUse()) {
Chris Lattner797dee72005-09-18 06:30:59 +00005511 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00005512 Op0BO->getOperand(1), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00005513 Op0BO->getName());
5514 InsertNewInstBefore(YS, I); // (Y << C)
5515 Instruction *XM =
Chris Lattner14553932006-01-06 07:12:35 +00005516 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner797dee72005-09-18 06:30:59 +00005517 V1->getName()+".mask");
5518 InsertNewInstBefore(XM, I); // X & (CC << C)
5519
Chris Lattner1df0e982006-05-31 21:14:00 +00005520 return BinaryOperator::create(Op0BO->getOpcode(), XM, YS);
Chris Lattner797dee72005-09-18 06:30:59 +00005521 }
Chris Lattner14553932006-01-06 07:12:35 +00005522
Chris Lattner27cb9db2005-09-18 05:12:10 +00005523 break;
Chris Lattner14553932006-01-06 07:12:35 +00005524 }
5525
5526
5527 // If the operand is an bitwise operator with a constant RHS, and the
5528 // shift is the only use, we can pull it out of the shift.
5529 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
5530 bool isValid = true; // Valid only for And, Or, Xor
5531 bool highBitSet = false; // Transform if high bit of constant set?
5532
5533 switch (Op0BO->getOpcode()) {
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00005534 default: isValid = false; break; // Do not perform transform!
Chris Lattner44bd3922004-10-08 03:46:20 +00005535 case Instruction::Add:
5536 isValid = isLeftShift;
5537 break;
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00005538 case Instruction::Or:
5539 case Instruction::Xor:
5540 highBitSet = false;
5541 break;
5542 case Instruction::And:
5543 highBitSet = true;
5544 break;
Chris Lattner14553932006-01-06 07:12:35 +00005545 }
5546
5547 // If this is a signed shift right, and the high bit is modified
5548 // by the logical operation, do not perform the transformation.
5549 // The highBitSet boolean indicates the value of the high bit of
5550 // the constant which would cause it to be modified for this
5551 // operation.
5552 //
Chris Lattnerb3309392006-01-06 07:22:22 +00005553 if (isValid && !isLeftShift && isSignedShift) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00005554 uint64_t Val = Op0C->getZExtValue();
Chris Lattner14553932006-01-06 07:12:35 +00005555 isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
5556 }
5557
5558 if (isValid) {
5559 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
5560
5561 Instruction *NewShift =
5562 new ShiftInst(I.getOpcode(), Op0BO->getOperand(0), Op1,
5563 Op0BO->getName());
5564 Op0BO->setName("");
5565 InsertNewInstBefore(NewShift, I);
5566
5567 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
5568 NewRHS);
5569 }
5570 }
5571 }
5572 }
5573
Chris Lattnereb372a02006-01-06 07:52:12 +00005574 // Find out if this is a shift of a shift by a constant.
5575 ShiftInst *ShiftOp = 0;
Chris Lattner14553932006-01-06 07:12:35 +00005576 if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0))
Chris Lattnereb372a02006-01-06 07:52:12 +00005577 ShiftOp = Op0SI;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005578 else if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
5579 // If this is a noop-integer cast of a shift instruction, use the shift.
5580 if (isa<ShiftInst>(CI->getOperand(0))) {
Chris Lattnereb372a02006-01-06 07:52:12 +00005581 ShiftOp = cast<ShiftInst>(CI->getOperand(0));
5582 }
5583 }
5584
Reid Spencere0fc4df2006-10-20 07:07:24 +00005585 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Chris Lattnereb372a02006-01-06 07:52:12 +00005586 // Find the operands and properties of the input shift. Note that the
5587 // signedness of the input shift may differ from the current shift if there
5588 // is a noop cast between the two.
Reid Spencer266e42b2006-12-23 06:05:41 +00005589 bool isShiftOfLeftShift = ShiftOp->getOpcode() == Instruction::Shl;
5590 bool isShiftOfSignedShift = ShiftOp->getOpcode() == Instruction::AShr;
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005591 bool isShiftOfUnsignedShift = !isShiftOfSignedShift;
Chris Lattnereb372a02006-01-06 07:52:12 +00005592
Reid Spencere0fc4df2006-10-20 07:07:24 +00005593 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Chris Lattnereb372a02006-01-06 07:52:12 +00005594
Reid Spencere0fc4df2006-10-20 07:07:24 +00005595 unsigned ShiftAmt1 = (unsigned)ShiftAmt1C->getZExtValue();
5596 unsigned ShiftAmt2 = (unsigned)Op1->getZExtValue();
Chris Lattnereb372a02006-01-06 07:52:12 +00005597
5598 // Check for (A << c1) << c2 and (A >> c1) >> c2.
5599 if (isLeftShift == isShiftOfLeftShift) {
5600 // Do not fold these shifts if the first one is signed and the second one
5601 // is unsigned and this is a right shift. Further, don't do any folding
5602 // on them.
5603 if (isShiftOfSignedShift && isUnsignedShift && !isLeftShift)
5604 return 0;
Chris Lattner14553932006-01-06 07:12:35 +00005605
Chris Lattnereb372a02006-01-06 07:52:12 +00005606 unsigned Amt = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
5607 if (Amt > Op0->getType()->getPrimitiveSizeInBits())
5608 Amt = Op0->getType()->getPrimitiveSizeInBits();
Chris Lattner14553932006-01-06 07:12:35 +00005609
Chris Lattnereb372a02006-01-06 07:52:12 +00005610 Value *Op = ShiftOp->getOperand(0);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005611 ShiftInst *ShiftResult = new ShiftInst(I.getOpcode(), Op,
Reid Spencerc635f472006-12-31 05:48:39 +00005612 ConstantInt::get(Type::Int8Ty, Amt));
Reid Spencerfdff9382006-11-08 06:47:33 +00005613 if (I.getType() == ShiftResult->getType())
5614 return ShiftResult;
5615 InsertNewInstBefore(ShiftResult, I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005616 return CastInst::create(Instruction::BitCast, ShiftResult, I.getType());
Chris Lattnereb372a02006-01-06 07:52:12 +00005617 }
5618
5619 // Check for (A << c1) >> c2 or (A >> c1) << c2. If we are dealing with
5620 // signed types, we can only support the (A >> c1) << c2 configuration,
5621 // because it can not turn an arbitrary bit of A into a sign bit.
5622 if (isUnsignedShift || isLeftShift) {
5623 // Calculate bitmask for what gets shifted off the edge.
Zhou Sheng75b871f2007-01-11 12:24:14 +00005624 Constant *C = ConstantInt::getAllOnesValue(I.getType());
Chris Lattnereb372a02006-01-06 07:52:12 +00005625 if (isLeftShift)
5626 C = ConstantExpr::getShl(C, ShiftAmt1C);
5627 else
Reid Spencerfdff9382006-11-08 06:47:33 +00005628 C = ConstantExpr::getLShr(C, ShiftAmt1C);
Chris Lattnereb372a02006-01-06 07:52:12 +00005629
5630 Value *Op = ShiftOp->getOperand(0);
Chris Lattnereb372a02006-01-06 07:52:12 +00005631
5632 Instruction *Mask =
5633 BinaryOperator::createAnd(Op, C, Op->getName()+".mask");
5634 InsertNewInstBefore(Mask, I);
5635
5636 // Figure out what flavor of shift we should use...
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005637 if (ShiftAmt1 == ShiftAmt2) {
Chris Lattnereb372a02006-01-06 07:52:12 +00005638 return ReplaceInstUsesWith(I, Mask); // (A << c) >> c === A & c2
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005639 } else if (ShiftAmt1 < ShiftAmt2) {
Chris Lattnereb372a02006-01-06 07:52:12 +00005640 return new ShiftInst(I.getOpcode(), Mask,
Reid Spencerc635f472006-12-31 05:48:39 +00005641 ConstantInt::get(Type::Int8Ty, ShiftAmt2-ShiftAmt1));
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005642 } else if (isShiftOfUnsignedShift || isShiftOfLeftShift) {
5643 if (isShiftOfUnsignedShift && !isShiftOfLeftShift && isSignedShift) {
Reid Spencerfdff9382006-11-08 06:47:33 +00005644 return new ShiftInst(Instruction::LShr, Mask,
Reid Spencerc635f472006-12-31 05:48:39 +00005645 ConstantInt::get(Type::Int8Ty, ShiftAmt1-ShiftAmt2));
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005646 } else {
5647 return new ShiftInst(ShiftOp->getOpcode(), Mask,
Reid Spencerc635f472006-12-31 05:48:39 +00005648 ConstantInt::get(Type::Int8Ty, ShiftAmt1-ShiftAmt2));
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005649 }
5650 } else {
5651 // (X >>s C1) << C2 where C1 > C2 === (X >>s (C1-C2)) & mask
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005652 Instruction *Shift =
Reid Spencer2a499b02006-12-13 17:19:09 +00005653 new ShiftInst(ShiftOp->getOpcode(), Mask,
Reid Spencerc635f472006-12-31 05:48:39 +00005654 ConstantInt::get(Type::Int8Ty, ShiftAmt1-ShiftAmt2));
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005655 InsertNewInstBefore(Shift, I);
5656
Zhou Sheng75b871f2007-01-11 12:24:14 +00005657 C = ConstantInt::getAllOnesValue(Shift->getType());
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005658 C = ConstantExpr::getShl(C, Op1);
Reid Spencer2a499b02006-12-13 17:19:09 +00005659 return BinaryOperator::createAnd(Shift, C, Op->getName()+".mask");
Chris Lattnereb372a02006-01-06 07:52:12 +00005660 }
5661 } else {
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005662 // We can handle signed (X << C1) >>s C2 if it's a sign extend. In
Chris Lattnereb372a02006-01-06 07:52:12 +00005663 // this case, C1 == C2 and C1 is 8, 16, or 32.
5664 if (ShiftAmt1 == ShiftAmt2) {
5665 const Type *SExtType = 0;
Chris Lattner655d08f2006-04-28 22:21:41 +00005666 switch (Op0->getType()->getPrimitiveSizeInBits() - ShiftAmt1) {
Reid Spencerc635f472006-12-31 05:48:39 +00005667 case 8 : SExtType = Type::Int8Ty; break;
5668 case 16: SExtType = Type::Int16Ty; break;
5669 case 32: SExtType = Type::Int32Ty; break;
Chris Lattnereb372a02006-01-06 07:52:12 +00005670 }
5671
5672 if (SExtType) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005673 Instruction *NewTrunc =
5674 new TruncInst(ShiftOp->getOperand(0), SExtType, "sext");
Chris Lattnereb372a02006-01-06 07:52:12 +00005675 InsertNewInstBefore(NewTrunc, I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005676 return new SExtInst(NewTrunc, I.getType());
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00005677 }
Chris Lattner27cb9db2005-09-18 05:12:10 +00005678 }
Chris Lattner86102b82005-01-01 16:22:27 +00005679 }
Chris Lattnereb372a02006-01-06 07:52:12 +00005680 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005681 return 0;
5682}
5683
Chris Lattner48a44f72002-05-02 17:06:02 +00005684
Chris Lattner8f663e82005-10-29 04:36:15 +00005685/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
5686/// expression. If so, decompose it, returning some value X, such that Val is
5687/// X*Scale+Offset.
5688///
5689static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
5690 unsigned &Offset) {
Reid Spencerc635f472006-12-31 05:48:39 +00005691 assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
Reid Spencere0fc4df2006-10-20 07:07:24 +00005692 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
Reid Spencerc635f472006-12-31 05:48:39 +00005693 Offset = CI->getZExtValue();
5694 Scale = 1;
5695 return ConstantInt::get(Type::Int32Ty, 0);
Chris Lattner8f663e82005-10-29 04:36:15 +00005696 } else if (Instruction *I = dyn_cast<Instruction>(Val)) {
5697 if (I->getNumOperands() == 2) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00005698 if (ConstantInt *CUI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Reid Spencerc635f472006-12-31 05:48:39 +00005699 if (I->getOpcode() == Instruction::Shl) {
5700 // This is a value scaled by '1 << the shift amt'.
5701 Scale = 1U << CUI->getZExtValue();
5702 Offset = 0;
5703 return I->getOperand(0);
5704 } else if (I->getOpcode() == Instruction::Mul) {
5705 // This value is scaled by 'CUI'.
5706 Scale = CUI->getZExtValue();
5707 Offset = 0;
5708 return I->getOperand(0);
5709 } else if (I->getOpcode() == Instruction::Add) {
5710 // We have X+C. Check to see if we really have (X*C2)+C1,
5711 // where C1 is divisible by C2.
5712 unsigned SubScale;
5713 Value *SubVal =
5714 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
5715 Offset += CUI->getZExtValue();
5716 if (SubScale > 1 && (Offset % SubScale == 0)) {
5717 Scale = SubScale;
5718 return SubVal;
Chris Lattner8f663e82005-10-29 04:36:15 +00005719 }
5720 }
5721 }
5722 }
5723 }
5724
5725 // Otherwise, we can't look past this.
5726 Scale = 1;
5727 Offset = 0;
5728 return Val;
5729}
5730
5731
Chris Lattner216be912005-10-24 06:03:58 +00005732/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
5733/// try to eliminate the cast by moving the type information into the alloc.
5734Instruction *InstCombiner::PromoteCastOfAllocation(CastInst &CI,
5735 AllocationInst &AI) {
5736 const PointerType *PTy = dyn_cast<PointerType>(CI.getType());
Chris Lattnerbb171802005-10-27 05:53:56 +00005737 if (!PTy) return 0; // Not casting the allocation to a pointer type.
Chris Lattner216be912005-10-24 06:03:58 +00005738
Chris Lattnerac87beb2005-10-24 06:22:12 +00005739 // Remove any uses of AI that are dead.
5740 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
5741 std::vector<Instruction*> DeadUsers;
5742 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
5743 Instruction *User = cast<Instruction>(*UI++);
5744 if (isInstructionTriviallyDead(User)) {
5745 while (UI != E && *UI == User)
5746 ++UI; // If this instruction uses AI more than once, don't break UI.
5747
5748 // Add operands to the worklist.
5749 AddUsesToWorkList(*User);
5750 ++NumDeadInst;
Bill Wendling5dbf43c2006-11-26 09:46:52 +00005751 DOUT << "IC: DCE: " << *User;
Chris Lattnerac87beb2005-10-24 06:22:12 +00005752
5753 User->eraseFromParent();
5754 removeFromWorkList(User);
5755 }
5756 }
5757
Chris Lattner216be912005-10-24 06:03:58 +00005758 // Get the type really allocated and the type casted to.
5759 const Type *AllocElTy = AI.getAllocatedType();
5760 const Type *CastElTy = PTy->getElementType();
5761 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner355ecc02005-10-24 06:26:18 +00005762
Chris Lattner7d190672006-10-01 19:40:58 +00005763 unsigned AllocElTyAlign = TD->getTypeAlignment(AllocElTy);
5764 unsigned CastElTyAlign = TD->getTypeAlignment(CastElTy);
Chris Lattner355ecc02005-10-24 06:26:18 +00005765 if (CastElTyAlign < AllocElTyAlign) return 0;
5766
Chris Lattner46705b22005-10-24 06:35:18 +00005767 // If the allocation has multiple uses, only promote it if we are strictly
5768 // increasing the alignment of the resultant allocation. If we keep it the
5769 // same, we open the door to infinite loops of various kinds.
5770 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
5771
Chris Lattner216be912005-10-24 06:03:58 +00005772 uint64_t AllocElTySize = TD->getTypeSize(AllocElTy);
5773 uint64_t CastElTySize = TD->getTypeSize(CastElTy);
Chris Lattnerbb171802005-10-27 05:53:56 +00005774 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner355ecc02005-10-24 06:26:18 +00005775
Chris Lattner8270c332005-10-29 03:19:53 +00005776 // See if we can satisfy the modulus by pulling a scale out of the array
5777 // size argument.
Chris Lattner8f663e82005-10-29 04:36:15 +00005778 unsigned ArraySizeScale, ArrayOffset;
5779 Value *NumElements = // See if the array size is a decomposable linear expr.
5780 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
5781
Chris Lattner8270c332005-10-29 03:19:53 +00005782 // If we can now satisfy the modulus, by using a non-1 scale, we really can
5783 // do the xform.
Chris Lattner8f663e82005-10-29 04:36:15 +00005784 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
5785 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattnerb3ecf962005-10-27 06:12:00 +00005786
Chris Lattner8270c332005-10-29 03:19:53 +00005787 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
5788 Value *Amt = 0;
5789 if (Scale == 1) {
5790 Amt = NumElements;
5791 } else {
Reid Spencere0fc4df2006-10-20 07:07:24 +00005792 // If the allocation size is constant, form a constant mul expression
Reid Spencerc635f472006-12-31 05:48:39 +00005793 Amt = ConstantInt::get(Type::Int32Ty, Scale);
5794 if (isa<ConstantInt>(NumElements))
Reid Spencere0fc4df2006-10-20 07:07:24 +00005795 Amt = ConstantExpr::getMul(
5796 cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
5797 // otherwise multiply the amount and the number of elements
Chris Lattner8270c332005-10-29 03:19:53 +00005798 else if (Scale != 1) {
5799 Instruction *Tmp = BinaryOperator::createMul(Amt, NumElements, "tmp");
5800 Amt = InsertNewInstBefore(Tmp, AI);
Chris Lattnerb3ecf962005-10-27 06:12:00 +00005801 }
Chris Lattnerbb171802005-10-27 05:53:56 +00005802 }
5803
Chris Lattner8f663e82005-10-29 04:36:15 +00005804 if (unsigned Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
Reid Spencerc635f472006-12-31 05:48:39 +00005805 Value *Off = ConstantInt::get(Type::Int32Ty, Offset);
Chris Lattner8f663e82005-10-29 04:36:15 +00005806 Instruction *Tmp = BinaryOperator::createAdd(Amt, Off, "tmp");
5807 Amt = InsertNewInstBefore(Tmp, AI);
5808 }
5809
Chris Lattner216be912005-10-24 06:03:58 +00005810 std::string Name = AI.getName(); AI.setName("");
5811 AllocationInst *New;
5812 if (isa<MallocInst>(AI))
Nate Begeman848622f2005-11-05 09:21:28 +00005813 New = new MallocInst(CastElTy, Amt, AI.getAlignment(), Name);
Chris Lattner216be912005-10-24 06:03:58 +00005814 else
Nate Begeman848622f2005-11-05 09:21:28 +00005815 New = new AllocaInst(CastElTy, Amt, AI.getAlignment(), Name);
Chris Lattner216be912005-10-24 06:03:58 +00005816 InsertNewInstBefore(New, AI);
Chris Lattner46705b22005-10-24 06:35:18 +00005817
5818 // If the allocation has multiple uses, insert a cast and change all things
5819 // that used it to use the new cast. This will also hack on CI, but it will
5820 // die soon.
5821 if (!AI.hasOneUse()) {
5822 AddUsesToWorkList(AI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005823 // New is the allocation instruction, pointer typed. AI is the original
5824 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
5825 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
Chris Lattner46705b22005-10-24 06:35:18 +00005826 InsertNewInstBefore(NewCast, AI);
5827 AI.replaceAllUsesWith(NewCast);
5828 }
Chris Lattner216be912005-10-24 06:03:58 +00005829 return ReplaceInstUsesWith(CI, New);
5830}
5831
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005832/// CanEvaluateInDifferentType - Return true if we can take the specified value
5833/// and return it without inserting any new casts. This is used by code that
5834/// tries to decide whether promoting or shrinking integer operations to wider
5835/// or smaller types will allow us to eliminate a truncate or extend.
5836static bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
5837 int &NumCastsRemoved) {
5838 if (isa<Constant>(V)) return true;
5839
5840 Instruction *I = dyn_cast<Instruction>(V);
5841 if (!I || !I->hasOneUse()) return false;
5842
5843 switch (I->getOpcode()) {
5844 case Instruction::And:
5845 case Instruction::Or:
5846 case Instruction::Xor:
5847 // These operators can all arbitrarily be extended or truncated.
5848 return CanEvaluateInDifferentType(I->getOperand(0), Ty, NumCastsRemoved) &&
5849 CanEvaluateInDifferentType(I->getOperand(1), Ty, NumCastsRemoved);
Chris Lattner960acb02006-11-29 07:18:39 +00005850 case Instruction::AShr:
5851 case Instruction::LShr:
5852 case Instruction::Shl:
5853 // If this is just a bitcast changing the sign of the operation, we can
5854 // convert if the operand can be converted.
5855 if (V->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
5856 return CanEvaluateInDifferentType(I->getOperand(0), Ty, NumCastsRemoved);
5857 break;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005858 case Instruction::Trunc:
5859 case Instruction::ZExt:
5860 case Instruction::SExt:
5861 case Instruction::BitCast:
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005862 // If this is a cast from the destination type, we can trivially eliminate
5863 // it, and this will remove a cast overall.
5864 if (I->getOperand(0)->getType() == Ty) {
Chris Lattner3fda3862006-06-28 17:34:50 +00005865 // If the first operand is itself a cast, and is eliminable, do not count
5866 // this as an eliminable cast. We would prefer to eliminate those two
5867 // casts first.
Reid Spencerde46e482006-11-02 20:25:50 +00005868 if (isa<CastInst>(I->getOperand(0)))
Chris Lattner3fda3862006-06-28 17:34:50 +00005869 return true;
5870
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005871 ++NumCastsRemoved;
5872 return true;
5873 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005874 break;
5875 default:
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005876 // TODO: Can handle more cases here.
5877 break;
5878 }
5879
5880 return false;
5881}
5882
5883/// EvaluateInDifferentType - Given an expression that
5884/// CanEvaluateInDifferentType returns true for, actually insert the code to
5885/// evaluate the expression.
Reid Spencer74a528b2006-12-13 18:21:21 +00005886Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
5887 bool isSigned ) {
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005888 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencer74a528b2006-12-13 18:21:21 +00005889 return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005890
5891 // Otherwise, it must be an instruction.
5892 Instruction *I = cast<Instruction>(V);
Chris Lattnerd0622b62006-05-20 23:14:03 +00005893 Instruction *Res = 0;
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005894 switch (I->getOpcode()) {
5895 case Instruction::And:
5896 case Instruction::Or:
5897 case Instruction::Xor: {
Reid Spencer74a528b2006-12-13 18:21:21 +00005898 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
5899 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005900 Res = BinaryOperator::create((Instruction::BinaryOps)I->getOpcode(),
5901 LHS, RHS, I->getName());
5902 break;
5903 }
Chris Lattner960acb02006-11-29 07:18:39 +00005904 case Instruction::AShr:
5905 case Instruction::LShr:
5906 case Instruction::Shl: {
Reid Spencer74a528b2006-12-13 18:21:21 +00005907 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
Chris Lattner960acb02006-11-29 07:18:39 +00005908 Res = new ShiftInst((Instruction::OtherOps)I->getOpcode(), LHS,
5909 I->getOperand(1), I->getName());
5910 break;
5911 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005912 case Instruction::Trunc:
5913 case Instruction::ZExt:
5914 case Instruction::SExt:
5915 case Instruction::BitCast:
5916 // If the source type of the cast is the type we're trying for then we can
5917 // just return the source. There's no need to insert it because its not new.
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005918 if (I->getOperand(0)->getType() == Ty)
5919 return I->getOperand(0);
5920
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005921 // Some other kind of cast, which shouldn't happen, so just ..
5922 // FALL THROUGH
5923 default:
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005924 // TODO: Can handle more cases here.
5925 assert(0 && "Unreachable!");
5926 break;
5927 }
5928
5929 return InsertNewInstBefore(Res, *I);
5930}
5931
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005932/// @brief Implement the transforms common to all CastInst visitors.
5933Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
Chris Lattner55d4bda2003-06-23 21:59:52 +00005934 Value *Src = CI.getOperand(0);
5935
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005936 // Casting undef to anything results in undef so might as just replace it and
5937 // get rid of the cast.
Chris Lattner81a7a232004-10-16 18:11:37 +00005938 if (isa<UndefValue>(Src)) // cast undef -> undef
5939 return ReplaceInstUsesWith(CI, UndefValue::get(CI.getType()));
5940
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005941 // Many cases of "cast of a cast" are eliminable. If its eliminable we just
5942 // eliminate it now.
Chris Lattner86102b82005-01-01 16:22:27 +00005943 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005944 if (Instruction::CastOps opc =
5945 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
5946 // The first cast (CSrc) is eliminable so we need to fix up or replace
5947 // the second cast (CI). CSrc will then have a good chance of being dead.
5948 return CastInst::create(opc, CSrc->getOperand(0), CI.getType());
Chris Lattner650b6da2002-08-02 20:00:25 +00005949 }
5950 }
Chris Lattner03841652004-05-25 04:29:21 +00005951
Chris Lattnerd0d51602003-06-21 23:12:02 +00005952 // If casting the result of a getelementptr instruction with no offset, turn
5953 // this into a cast of the original pointer!
5954 //
Chris Lattner55d4bda2003-06-23 21:59:52 +00005955 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattnerd0d51602003-06-21 23:12:02 +00005956 bool AllZeroOperands = true;
5957 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
5958 if (!isa<Constant>(GEP->getOperand(i)) ||
5959 !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
5960 AllZeroOperands = false;
5961 break;
5962 }
5963 if (AllZeroOperands) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005964 // Changing the cast operand is usually not a good idea but it is safe
5965 // here because the pointer operand is being replaced with another
5966 // pointer operand so the opcode doesn't need to change.
Chris Lattnerd0d51602003-06-21 23:12:02 +00005967 CI.setOperand(0, GEP->getOperand(0));
5968 return &CI;
5969 }
5970 }
Chris Lattnerec45a4c2006-11-21 17:05:13 +00005971
Chris Lattnerf4ad1652003-11-02 05:57:39 +00005972 // If we are casting a malloc or alloca to a pointer to a type of the same
5973 // size, rewrite the allocation instruction to allocate the "right" type.
Chris Lattnerf4ad1652003-11-02 05:57:39 +00005974 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
Chris Lattner216be912005-10-24 06:03:58 +00005975 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
5976 return V;
Chris Lattnerf4ad1652003-11-02 05:57:39 +00005977
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005978 // If we are casting a select then fold the cast into the select
Chris Lattner86102b82005-01-01 16:22:27 +00005979 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
5980 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
5981 return NV;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005982
5983 // If we are casting a PHI then fold the cast into the PHI
Chris Lattner6a4adcd2004-09-29 05:07:12 +00005984 if (isa<PHINode>(Src))
5985 if (Instruction *NV = FoldOpIntoPhi(CI))
5986 return NV;
Chris Lattnerb19a5c62006-04-12 18:09:35 +00005987
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005988 return 0;
5989}
5990
5991/// Only the TRUNC, ZEXT, SEXT, and BITCONVERT can have both operands as
5992/// integers. This function implements the common transforms for all those
5993/// cases.
5994/// @brief Implement the transforms common to CastInst with integer operands
5995Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
5996 if (Instruction *Result = commonCastTransforms(CI))
5997 return Result;
5998
5999 Value *Src = CI.getOperand(0);
6000 const Type *SrcTy = Src->getType();
6001 const Type *DestTy = CI.getType();
6002 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
6003 unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
6004
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006005 // See if we can simplify any instructions used by the LHS whose sole
6006 // purpose is to compute bits we don't care about.
6007 uint64_t KnownZero = 0, KnownOne = 0;
6008 if (SimplifyDemandedBits(&CI, DestTy->getIntegralTypeMask(),
6009 KnownZero, KnownOne))
6010 return &CI;
6011
6012 // If the source isn't an instruction or has more than one use then we
6013 // can't do anything more.
Reid Spencer266e42b2006-12-23 06:05:41 +00006014 Instruction *SrcI = dyn_cast<Instruction>(Src);
6015 if (!SrcI || !Src->hasOneUse())
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006016 return 0;
6017
6018 // Attempt to propagate the cast into the instruction.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006019 int NumCastsRemoved = 0;
6020 if (CanEvaluateInDifferentType(SrcI, DestTy, NumCastsRemoved)) {
6021 // If this cast is a truncate, evaluting in a different type always
6022 // eliminates the cast, so it is always a win. If this is a noop-cast
6023 // this just removes a noop cast which isn't pointful, but simplifies
6024 // the code. If this is a zero-extension, we need to do an AND to
6025 // maintain the clear top-part of the computation, so we require that
6026 // the input have eliminated at least one cast. If this is a sign
6027 // extension, we insert two new casts (to do the extension) so we
6028 // require that two casts have been eliminated.
6029 bool DoXForm = CI.isNoopCast(TD->getIntPtrType());
6030 if (!DoXForm) {
6031 switch (CI.getOpcode()) {
6032 case Instruction::Trunc:
6033 DoXForm = true;
6034 break;
6035 case Instruction::ZExt:
6036 DoXForm = NumCastsRemoved >= 1;
6037 break;
6038 case Instruction::SExt:
6039 DoXForm = NumCastsRemoved >= 2;
6040 break;
6041 case Instruction::BitCast:
6042 DoXForm = false;
6043 break;
6044 default:
6045 // All the others use floating point so we shouldn't actually
6046 // get here because of the check above.
6047 assert(!"Unknown cast type .. unreachable");
6048 break;
6049 }
6050 }
6051
6052 if (DoXForm) {
Reid Spencer74a528b2006-12-13 18:21:21 +00006053 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
6054 CI.getOpcode() == Instruction::SExt);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006055 assert(Res->getType() == DestTy);
6056 switch (CI.getOpcode()) {
6057 default: assert(0 && "Unknown cast type!");
6058 case Instruction::Trunc:
6059 case Instruction::BitCast:
6060 // Just replace this cast with the result.
6061 return ReplaceInstUsesWith(CI, Res);
6062 case Instruction::ZExt: {
6063 // We need to emit an AND to clear the high bits.
6064 assert(SrcBitSize < DestBitSize && "Not a zext?");
6065 Constant *C =
Reid Spencerc635f472006-12-31 05:48:39 +00006066 ConstantInt::get(Type::Int64Ty, (1ULL << SrcBitSize)-1);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006067 if (DestBitSize < 64)
6068 C = ConstantExpr::getTrunc(C, DestTy);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006069 return BinaryOperator::createAnd(Res, C);
6070 }
6071 case Instruction::SExt:
6072 // We need to emit a cast to truncate, then a cast to sext.
6073 return CastInst::create(Instruction::SExt,
Reid Spencer13bc5d72006-12-12 09:18:51 +00006074 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
6075 CI), DestTy);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006076 }
6077 }
6078 }
6079
6080 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
6081 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
6082
6083 switch (SrcI->getOpcode()) {
6084 case Instruction::Add:
6085 case Instruction::Mul:
6086 case Instruction::And:
6087 case Instruction::Or:
6088 case Instruction::Xor:
6089 // If we are discarding information, or just changing the sign,
6090 // rewrite.
6091 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
6092 // Don't insert two casts if they cannot be eliminated. We allow
6093 // two casts to be inserted if the sizes are the same. This could
6094 // only be converting signedness, which is a noop.
6095 if (DestBitSize == SrcBitSize ||
Reid Spencer266e42b2006-12-23 06:05:41 +00006096 !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
6097 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer2a499b02006-12-13 17:19:09 +00006098 Instruction::CastOps opcode = CI.getOpcode();
Reid Spencer13bc5d72006-12-12 09:18:51 +00006099 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
6100 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
6101 return BinaryOperator::create(
6102 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006103 }
6104 }
6105
6106 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
6107 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
6108 SrcI->getOpcode() == Instruction::Xor &&
Zhou Sheng75b871f2007-01-11 12:24:14 +00006109 Op1 == ConstantInt::getTrue() &&
Reid Spencer266e42b2006-12-23 06:05:41 +00006110 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00006111 Value *New = InsertOperandCastBefore(Instruction::ZExt, Op0, DestTy, &CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006112 return BinaryOperator::createXor(New, ConstantInt::get(CI.getType(), 1));
6113 }
6114 break;
6115 case Instruction::SDiv:
6116 case Instruction::UDiv:
6117 case Instruction::SRem:
6118 case Instruction::URem:
6119 // If we are just changing the sign, rewrite.
6120 if (DestBitSize == SrcBitSize) {
6121 // Don't insert two casts if they cannot be eliminated. We allow
6122 // two casts to be inserted if the sizes are the same. This could
6123 // only be converting signedness, which is a noop.
Reid Spencer266e42b2006-12-23 06:05:41 +00006124 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
6125 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00006126 Value *Op0c = InsertOperandCastBefore(Instruction::BitCast,
6127 Op0, DestTy, SrcI);
6128 Value *Op1c = InsertOperandCastBefore(Instruction::BitCast,
6129 Op1, DestTy, SrcI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006130 return BinaryOperator::create(
6131 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
6132 }
6133 }
6134 break;
6135
6136 case Instruction::Shl:
6137 // Allow changing the sign of the source operand. Do not allow
6138 // changing the size of the shift, UNLESS the shift amount is a
6139 // constant. We must not change variable sized shifts to a smaller
6140 // size, because it is undefined to shift more bits out than exist
6141 // in the value.
6142 if (DestBitSize == SrcBitSize ||
6143 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00006144 Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
6145 Instruction::BitCast : Instruction::Trunc);
6146 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006147 return new ShiftInst(Instruction::Shl, Op0c, Op1);
6148 }
6149 break;
6150 case Instruction::AShr:
6151 // If this is a signed shr, and if all bits shifted in are about to be
6152 // truncated off, turn it into an unsigned shr to allow greater
6153 // simplifications.
6154 if (DestBitSize < SrcBitSize &&
6155 isa<ConstantInt>(Op1)) {
6156 unsigned ShiftAmt = cast<ConstantInt>(Op1)->getZExtValue();
6157 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
6158 // Insert the new logical shift right.
6159 return new ShiftInst(Instruction::LShr, Op0, Op1);
6160 }
6161 }
6162 break;
6163
Reid Spencer266e42b2006-12-23 06:05:41 +00006164 case Instruction::ICmp:
6165 // If we are just checking for a icmp eq of a single bit and casting it
6166 // to an integer, then shift the bit to the appropriate place and then
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006167 // cast to integer to avoid the comparison.
6168 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
6169 uint64_t Op1CV = Op1C->getZExtValue();
6170 // cast (X == 0) to int --> X^1 iff X has only the low bit set.
6171 // cast (X == 0) to int --> (X>>1)^1 iff X has only the 2nd bit set.
6172 // cast (X == 1) to int --> X iff X has only the low bit set.
6173 // cast (X == 2) to int --> X>>1 iff X has only the 2nd bit set.
6174 // cast (X != 0) to int --> X iff X has only the low bit set.
6175 // cast (X != 0) to int --> X>>1 iff X has only the 2nd bit set.
6176 // cast (X != 1) to int --> X^1 iff X has only the low bit set.
6177 // cast (X != 2) to int --> (X>>1)^1 iff X has only the 2nd bit set.
6178 if (Op1CV == 0 || isPowerOf2_64(Op1CV)) {
6179 // If Op1C some other power of two, convert:
6180 uint64_t KnownZero, KnownOne;
6181 uint64_t TypeMask = Op1->getType()->getIntegralTypeMask();
6182 ComputeMaskedBits(Op0, TypeMask, KnownZero, KnownOne);
Reid Spencer266e42b2006-12-23 06:05:41 +00006183
6184 // This only works for EQ and NE
6185 ICmpInst::Predicate pred = cast<ICmpInst>(SrcI)->getPredicate();
6186 if (pred != ICmpInst::ICMP_NE && pred != ICmpInst::ICMP_EQ)
6187 break;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006188
6189 if (isPowerOf2_64(KnownZero^TypeMask)) { // Exactly 1 possible 1?
Reid Spencer266e42b2006-12-23 06:05:41 +00006190 bool isNE = pred == ICmpInst::ICMP_NE;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006191 if (Op1CV && (Op1CV != (KnownZero^TypeMask))) {
6192 // (X&4) == 2 --> false
6193 // (X&4) != 2 --> true
Reid Spencercddc9df2007-01-12 04:24:46 +00006194 Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
Reid Spencerbb65ebf2006-12-12 23:36:14 +00006195 Res = ConstantExpr::getZExt(Res, CI.getType());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006196 return ReplaceInstUsesWith(CI, Res);
6197 }
6198
6199 unsigned ShiftAmt = Log2_64(KnownZero^TypeMask);
6200 Value *In = Op0;
6201 if (ShiftAmt) {
6202 // Perform a logical shr by shiftamt.
6203 // Insert the shift to put the result in the low bit.
6204 In = InsertNewInstBefore(
6205 new ShiftInst(Instruction::LShr, In,
Reid Spencerc635f472006-12-31 05:48:39 +00006206 ConstantInt::get(Type::Int8Ty, ShiftAmt),
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006207 In->getName()+".lobit"), CI);
6208 }
6209
Reid Spencer266e42b2006-12-23 06:05:41 +00006210 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006211 Constant *One = ConstantInt::get(In->getType(), 1);
6212 In = BinaryOperator::createXor(In, One, "tmp");
6213 InsertNewInstBefore(cast<Instruction>(In), CI);
6214 }
6215
6216 if (CI.getType() == In->getType())
6217 return ReplaceInstUsesWith(CI, In);
6218 else
Reid Spencerbb65ebf2006-12-12 23:36:14 +00006219 return CastInst::createIntegerCast(In, CI.getType(), false/*ZExt*/);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006220 }
6221 }
6222 }
6223 break;
6224 }
6225 return 0;
6226}
6227
6228Instruction *InstCombiner::visitTrunc(CastInst &CI) {
Chris Lattnerd747f012006-11-29 07:04:07 +00006229 if (Instruction *Result = commonIntCastTransforms(CI))
6230 return Result;
6231
6232 Value *Src = CI.getOperand(0);
6233 const Type *Ty = CI.getType();
6234 unsigned DestBitWidth = Ty->getPrimitiveSizeInBits();
6235
6236 if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
6237 switch (SrcI->getOpcode()) {
6238 default: break;
6239 case Instruction::LShr:
6240 // We can shrink lshr to something smaller if we know the bits shifted in
6241 // are already zeros.
6242 if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
6243 unsigned ShAmt = ShAmtV->getZExtValue();
6244
6245 // Get a mask for the bits shifting in.
6246 uint64_t Mask = (~0ULL >> (64-ShAmt)) << DestBitWidth;
Reid Spencer13bc5d72006-12-12 09:18:51 +00006247 Value* SrcIOp0 = SrcI->getOperand(0);
6248 if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
Chris Lattnerd747f012006-11-29 07:04:07 +00006249 if (ShAmt >= DestBitWidth) // All zeros.
6250 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
6251
6252 // Okay, we can shrink this. Truncate the input, then return a new
6253 // shift.
Reid Spencer2a499b02006-12-13 17:19:09 +00006254 Value *V = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
Chris Lattnerd747f012006-11-29 07:04:07 +00006255 return new ShiftInst(Instruction::LShr, V, SrcI->getOperand(1));
6256 }
Chris Lattnerc209b582006-12-05 01:26:29 +00006257 } else { // This is a variable shr.
6258
6259 // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'. This is
6260 // more LLVM instructions, but allows '1 << Y' to be hoisted if
6261 // loop-invariant and CSE'd.
Reid Spencer542964f2007-01-11 18:21:29 +00006262 if (CI.getType() == Type::Int1Ty && SrcI->hasOneUse()) {
Chris Lattnerc209b582006-12-05 01:26:29 +00006263 Value *One = ConstantInt::get(SrcI->getType(), 1);
6264
6265 Value *V = InsertNewInstBefore(new ShiftInst(Instruction::Shl, One,
6266 SrcI->getOperand(1),
6267 "tmp"), CI);
6268 V = InsertNewInstBefore(BinaryOperator::createAnd(V,
6269 SrcI->getOperand(0),
6270 "tmp"), CI);
6271 Value *Zero = Constant::getNullValue(V->getType());
Reid Spencer266e42b2006-12-23 06:05:41 +00006272 return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
Chris Lattnerc209b582006-12-05 01:26:29 +00006273 }
Chris Lattnerd747f012006-11-29 07:04:07 +00006274 }
6275 break;
6276 }
6277 }
6278
6279 return 0;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006280}
6281
6282Instruction *InstCombiner::visitZExt(CastInst &CI) {
6283 // If one of the common conversion will work ..
6284 if (Instruction *Result = commonIntCastTransforms(CI))
6285 return Result;
6286
6287 Value *Src = CI.getOperand(0);
6288
6289 // If this is a cast of a cast
6290 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006291 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
6292 // types and if the sizes are just right we can convert this into a logical
6293 // 'and' which will be much cheaper than the pair of casts.
6294 if (isa<TruncInst>(CSrc)) {
6295 // Get the sizes of the types involved
6296 Value *A = CSrc->getOperand(0);
6297 unsigned SrcSize = A->getType()->getPrimitiveSizeInBits();
6298 unsigned MidSize = CSrc->getType()->getPrimitiveSizeInBits();
6299 unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
6300 // If we're actually extending zero bits and the trunc is a no-op
6301 if (MidSize < DstSize && SrcSize == DstSize) {
6302 // Replace both of the casts with an And of the type mask.
6303 uint64_t AndValue = CSrc->getType()->getIntegralTypeMask();
6304 Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
6305 Instruction *And =
6306 BinaryOperator::createAnd(CSrc->getOperand(0), AndConst);
6307 // Unfortunately, if the type changed, we need to cast it back.
6308 if (And->getType() != CI.getType()) {
6309 And->setName(CSrc->getName()+".mask");
6310 InsertNewInstBefore(And, CI);
Reid Spencerbb65ebf2006-12-12 23:36:14 +00006311 And = CastInst::createIntegerCast(And, CI.getType(), false/*ZExt*/);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006312 }
6313 return And;
6314 }
6315 }
6316 }
6317
6318 return 0;
6319}
6320
6321Instruction *InstCombiner::visitSExt(CastInst &CI) {
6322 return commonIntCastTransforms(CI);
6323}
6324
6325Instruction *InstCombiner::visitFPTrunc(CastInst &CI) {
6326 return commonCastTransforms(CI);
6327}
6328
6329Instruction *InstCombiner::visitFPExt(CastInst &CI) {
6330 return commonCastTransforms(CI);
6331}
6332
6333Instruction *InstCombiner::visitFPToUI(CastInst &CI) {
Reid Spencerad05ee92006-11-30 23:13:36 +00006334 return commonCastTransforms(CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006335}
6336
6337Instruction *InstCombiner::visitFPToSI(CastInst &CI) {
Reid Spencerad05ee92006-11-30 23:13:36 +00006338 return commonCastTransforms(CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006339}
6340
6341Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
6342 return commonCastTransforms(CI);
6343}
6344
6345Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
6346 return commonCastTransforms(CI);
6347}
6348
6349Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
Reid Spencerad05ee92006-11-30 23:13:36 +00006350 return commonCastTransforms(CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006351}
6352
6353Instruction *InstCombiner::visitIntToPtr(CastInst &CI) {
6354 return commonCastTransforms(CI);
6355}
6356
6357Instruction *InstCombiner::visitBitCast(CastInst &CI) {
6358
6359 // If the operands are integer typed then apply the integer transforms,
6360 // otherwise just apply the common ones.
6361 Value *Src = CI.getOperand(0);
6362 const Type *SrcTy = Src->getType();
6363 const Type *DestTy = CI.getType();
6364
6365 if (SrcTy->isInteger() && DestTy->isInteger()) {
6366 if (Instruction *Result = commonIntCastTransforms(CI))
6367 return Result;
6368 } else {
6369 if (Instruction *Result = commonCastTransforms(CI))
6370 return Result;
6371 }
6372
6373
6374 // Get rid of casts from one type to the same type. These are useless and can
6375 // be replaced by the operand.
6376 if (DestTy == Src->getType())
6377 return ReplaceInstUsesWith(CI, Src);
6378
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006379 // If the source and destination are pointers, and this cast is equivalent to
6380 // a getelementptr X, 0, 0, 0... turn it into the appropriate getelementptr.
6381 // This can enhance SROA and other transforms that want type-safe pointers.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006382 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
6383 if (const PointerType *SrcPTy = dyn_cast<PointerType>(SrcTy)) {
6384 const Type *DstElTy = DstPTy->getElementType();
6385 const Type *SrcElTy = SrcPTy->getElementType();
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006386
Reid Spencerc635f472006-12-31 05:48:39 +00006387 Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006388 unsigned NumZeros = 0;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006389 while (SrcElTy != DstElTy &&
6390 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
6391 SrcElTy->getNumContainedTypes() /* not "{}" */) {
6392 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006393 ++NumZeros;
6394 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00006395
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006396 // If we found a path from the src to dest, create the getelementptr now.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006397 if (SrcElTy == DstElTy) {
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006398 std::vector<Value*> Idxs(NumZeros+1, ZeroUInt);
6399 return new GetElementPtrInst(Src, Idxs);
6400 }
6401 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006402 }
Chris Lattnerdfae8be2003-07-24 17:35:25 +00006403
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006404 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
6405 if (SVI->hasOneUse()) {
6406 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
6407 // a bitconvert to a vector with the same # elts.
6408 if (isa<PackedType>(DestTy) &&
6409 cast<PackedType>(DestTy)->getNumElements() ==
6410 SVI->getType()->getNumElements()) {
6411 CastInst *Tmp;
6412 // If either of the operands is a cast from CI.getType(), then
6413 // evaluating the shuffle in the casted destination's type will allow
6414 // us to eliminate at least one cast.
6415 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
6416 Tmp->getOperand(0)->getType() == DestTy) ||
6417 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
6418 Tmp->getOperand(0)->getType() == DestTy)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00006419 Value *LHS = InsertOperandCastBefore(Instruction::BitCast,
6420 SVI->getOperand(0), DestTy, &CI);
6421 Value *RHS = InsertOperandCastBefore(Instruction::BitCast,
6422 SVI->getOperand(1), DestTy, &CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006423 // Return a new shuffle vector. Use the same element ID's, as we
6424 // know the vector types match #elts.
6425 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner99155be2006-05-25 23:24:33 +00006426 }
6427 }
6428 }
6429 }
Chris Lattner260ab202002-04-18 17:39:14 +00006430 return 0;
Chris Lattnerca081252001-12-14 16:52:21 +00006431}
6432
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006433/// GetSelectFoldableOperands - We want to turn code that looks like this:
6434/// %C = or %A, %B
6435/// %D = select %cond, %C, %A
6436/// into:
6437/// %C = select %cond, %B, 0
6438/// %D = or %A, %C
6439///
6440/// Assuming that the specified instruction is an operand to the select, return
6441/// a bitmask indicating which operands of this instruction are foldable if they
6442/// equal the other incoming value of the select.
6443///
6444static unsigned GetSelectFoldableOperands(Instruction *I) {
6445 switch (I->getOpcode()) {
6446 case Instruction::Add:
6447 case Instruction::Mul:
6448 case Instruction::And:
6449 case Instruction::Or:
6450 case Instruction::Xor:
6451 return 3; // Can fold through either operand.
6452 case Instruction::Sub: // Can only fold on the amount subtracted.
6453 case Instruction::Shl: // Can only fold on the shift amount.
Reid Spencerfdff9382006-11-08 06:47:33 +00006454 case Instruction::LShr:
6455 case Instruction::AShr:
Misha Brukmanb1c93172005-04-21 23:48:37 +00006456 return 1;
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006457 default:
6458 return 0; // Cannot fold
6459 }
6460}
6461
6462/// GetSelectFoldableConstant - For the same transformation as the previous
6463/// function, return the identity constant that goes into the select.
6464static Constant *GetSelectFoldableConstant(Instruction *I) {
6465 switch (I->getOpcode()) {
6466 default: assert(0 && "This cannot happen!"); abort();
6467 case Instruction::Add:
6468 case Instruction::Sub:
6469 case Instruction::Or:
6470 case Instruction::Xor:
6471 return Constant::getNullValue(I->getType());
6472 case Instruction::Shl:
Reid Spencerfdff9382006-11-08 06:47:33 +00006473 case Instruction::LShr:
6474 case Instruction::AShr:
Reid Spencerc635f472006-12-31 05:48:39 +00006475 return Constant::getNullValue(Type::Int8Ty);
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006476 case Instruction::And:
6477 return ConstantInt::getAllOnesValue(I->getType());
6478 case Instruction::Mul:
6479 return ConstantInt::get(I->getType(), 1);
6480 }
6481}
6482
Chris Lattner411336f2005-01-19 21:50:18 +00006483/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
6484/// have the same opcode and only one use each. Try to simplify this.
6485Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
6486 Instruction *FI) {
6487 if (TI->getNumOperands() == 1) {
6488 // If this is a non-volatile load or a cast from the same type,
6489 // merge.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006490 if (TI->isCast()) {
Chris Lattner411336f2005-01-19 21:50:18 +00006491 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
6492 return 0;
6493 } else {
6494 return 0; // unknown unary op.
6495 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00006496
Chris Lattner411336f2005-01-19 21:50:18 +00006497 // Fold this by inserting a select from the input values.
6498 SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
6499 FI->getOperand(0), SI.getName()+".v");
6500 InsertNewInstBefore(NewSI, SI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006501 return CastInst::create(Instruction::CastOps(TI->getOpcode()), NewSI,
6502 TI->getType());
Chris Lattner411336f2005-01-19 21:50:18 +00006503 }
6504
Reid Spencer266e42b2006-12-23 06:05:41 +00006505 // Only handle binary, compare and shift operators here.
Reid Spencer43c77d52006-12-23 18:58:04 +00006506 if (!isa<ShiftInst>(TI) && !isa<BinaryOperator>(TI))
Chris Lattner411336f2005-01-19 21:50:18 +00006507 return 0;
6508
6509 // Figure out if the operations have any operands in common.
6510 Value *MatchOp, *OtherOpT, *OtherOpF;
6511 bool MatchIsOpZero;
6512 if (TI->getOperand(0) == FI->getOperand(0)) {
6513 MatchOp = TI->getOperand(0);
6514 OtherOpT = TI->getOperand(1);
6515 OtherOpF = FI->getOperand(1);
6516 MatchIsOpZero = true;
6517 } else if (TI->getOperand(1) == FI->getOperand(1)) {
6518 MatchOp = TI->getOperand(1);
6519 OtherOpT = TI->getOperand(0);
6520 OtherOpF = FI->getOperand(0);
6521 MatchIsOpZero = false;
6522 } else if (!TI->isCommutative()) {
6523 return 0;
6524 } else if (TI->getOperand(0) == FI->getOperand(1)) {
6525 MatchOp = TI->getOperand(0);
6526 OtherOpT = TI->getOperand(1);
6527 OtherOpF = FI->getOperand(0);
6528 MatchIsOpZero = true;
6529 } else if (TI->getOperand(1) == FI->getOperand(0)) {
6530 MatchOp = TI->getOperand(1);
6531 OtherOpT = TI->getOperand(0);
6532 OtherOpF = FI->getOperand(1);
6533 MatchIsOpZero = true;
6534 } else {
6535 return 0;
6536 }
6537
6538 // If we reach here, they do have operations in common.
6539 SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
6540 OtherOpF, SI.getName()+".v");
6541 InsertNewInstBefore(NewSI, SI);
6542
6543 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
6544 if (MatchIsOpZero)
6545 return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
6546 else
6547 return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
Chris Lattner411336f2005-01-19 21:50:18 +00006548 }
Reid Spencer43c77d52006-12-23 18:58:04 +00006549
6550 assert(isa<ShiftInst>(TI) && "Should only have Shift here");
6551 if (MatchIsOpZero)
6552 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), MatchOp, NewSI);
6553 else
6554 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), NewSI, MatchOp);
Chris Lattner411336f2005-01-19 21:50:18 +00006555}
6556
Chris Lattnerb909e8b2004-03-12 05:52:32 +00006557Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattner533bc492004-03-30 19:37:13 +00006558 Value *CondVal = SI.getCondition();
6559 Value *TrueVal = SI.getTrueValue();
6560 Value *FalseVal = SI.getFalseValue();
6561
6562 // select true, X, Y -> X
6563 // select false, X, Y -> Y
Zhou Sheng75b871f2007-01-11 12:24:14 +00006564 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
Reid Spencercddc9df2007-01-12 04:24:46 +00006565 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
Chris Lattner533bc492004-03-30 19:37:13 +00006566
6567 // select C, X, X -> X
6568 if (TrueVal == FalseVal)
6569 return ReplaceInstUsesWith(SI, TrueVal);
6570
Chris Lattner81a7a232004-10-16 18:11:37 +00006571 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
6572 return ReplaceInstUsesWith(SI, FalseVal);
6573 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
6574 return ReplaceInstUsesWith(SI, TrueVal);
6575 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
6576 if (isa<Constant>(TrueVal))
6577 return ReplaceInstUsesWith(SI, TrueVal);
6578 else
6579 return ReplaceInstUsesWith(SI, FalseVal);
6580 }
6581
Reid Spencer542964f2007-01-11 18:21:29 +00006582 if (SI.getType() == Type::Int1Ty) {
Zhou Sheng75b871f2007-01-11 12:24:14 +00006583 ConstantInt *C;
6584 if ((C = dyn_cast<ConstantInt>(TrueVal)) &&
Reid Spencer542964f2007-01-11 18:21:29 +00006585 C->getType() == Type::Int1Ty) {
Reid Spencercddc9df2007-01-12 04:24:46 +00006586 if (C->getZExtValue()) {
Chris Lattner1c631e82004-04-08 04:43:23 +00006587 // Change: A = select B, true, C --> A = or B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00006588 return BinaryOperator::createOr(CondVal, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00006589 } else {
6590 // Change: A = select B, false, C --> A = and !B, C
6591 Value *NotCond =
6592 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
6593 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00006594 return BinaryOperator::createAnd(NotCond, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00006595 }
Zhou Sheng75b871f2007-01-11 12:24:14 +00006596 } else if ((C = dyn_cast<ConstantInt>(FalseVal)) &&
Reid Spencer542964f2007-01-11 18:21:29 +00006597 C->getType() == Type::Int1Ty) {
Reid Spencercddc9df2007-01-12 04:24:46 +00006598 if (C->getZExtValue() == false) {
Chris Lattner1c631e82004-04-08 04:43:23 +00006599 // Change: A = select B, C, false --> A = and B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00006600 return BinaryOperator::createAnd(CondVal, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00006601 } else {
6602 // Change: A = select B, C, true --> A = or !B, C
6603 Value *NotCond =
6604 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
6605 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00006606 return BinaryOperator::createOr(NotCond, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00006607 }
6608 }
Zhou Sheng75b871f2007-01-11 12:24:14 +00006609 }
Chris Lattner1c631e82004-04-08 04:43:23 +00006610
Chris Lattner183b3362004-04-09 19:05:30 +00006611 // Selecting between two integer constants?
6612 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
6613 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
6614 // select C, 1, 0 -> cast C to int
Reid Spencere0fc4df2006-10-20 07:07:24 +00006615 if (FalseValC->isNullValue() && TrueValC->getZExtValue() == 1) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006616 return CastInst::create(Instruction::ZExt, CondVal, SI.getType());
Reid Spencere0fc4df2006-10-20 07:07:24 +00006617 } else if (TrueValC->isNullValue() && FalseValC->getZExtValue() == 1) {
Chris Lattner183b3362004-04-09 19:05:30 +00006618 // select C, 0, 1 -> cast !C to int
6619 Value *NotCond =
6620 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
Chris Lattnercf7baf32004-04-09 18:19:44 +00006621 "not."+CondVal->getName()), SI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006622 return CastInst::create(Instruction::ZExt, NotCond, SI.getType());
Chris Lattnercf7baf32004-04-09 18:19:44 +00006623 }
Chris Lattner35167c32004-06-09 07:59:58 +00006624
Reid Spencer266e42b2006-12-23 06:05:41 +00006625 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Chris Lattner380c7e92006-09-20 04:44:59 +00006626
Reid Spencer266e42b2006-12-23 06:05:41 +00006627 // (x <s 0) ? -1 : 0 -> ashr x, 31
6628 // (x >u 2147483647) ? -1 : 0 -> ashr x, 31
Chris Lattner380c7e92006-09-20 04:44:59 +00006629 if (TrueValC->isAllOnesValue() && FalseValC->isNullValue())
6630 if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
6631 bool CanXForm = false;
Reid Spencer266e42b2006-12-23 06:05:41 +00006632 if (IC->isSignedPredicate())
Chris Lattner380c7e92006-09-20 04:44:59 +00006633 CanXForm = CmpCst->isNullValue() &&
Reid Spencer266e42b2006-12-23 06:05:41 +00006634 IC->getPredicate() == ICmpInst::ICMP_SLT;
Chris Lattner380c7e92006-09-20 04:44:59 +00006635 else {
6636 unsigned Bits = CmpCst->getType()->getPrimitiveSizeInBits();
Reid Spencere0fc4df2006-10-20 07:07:24 +00006637 CanXForm = (CmpCst->getZExtValue() == ~0ULL >> (64-Bits+1)) &&
Reid Spencer266e42b2006-12-23 06:05:41 +00006638 IC->getPredicate() == ICmpInst::ICMP_UGT;
Chris Lattner380c7e92006-09-20 04:44:59 +00006639 }
6640
6641 if (CanXForm) {
6642 // The comparison constant and the result are not neccessarily the
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006643 // same width. Make an all-ones value by inserting a AShr.
Chris Lattner380c7e92006-09-20 04:44:59 +00006644 Value *X = IC->getOperand(0);
Chris Lattner380c7e92006-09-20 04:44:59 +00006645 unsigned Bits = X->getType()->getPrimitiveSizeInBits();
Reid Spencerc635f472006-12-31 05:48:39 +00006646 Constant *ShAmt = ConstantInt::get(Type::Int8Ty, Bits-1);
Reid Spencerfdff9382006-11-08 06:47:33 +00006647 Instruction *SRA = new ShiftInst(Instruction::AShr, X,
Chris Lattner380c7e92006-09-20 04:44:59 +00006648 ShAmt, "ones");
6649 InsertNewInstBefore(SRA, SI);
6650
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006651 // Finally, convert to the type of the select RHS. We figure out
6652 // if this requires a SExt, Trunc or BitCast based on the sizes.
6653 Instruction::CastOps opc = Instruction::BitCast;
6654 unsigned SRASize = SRA->getType()->getPrimitiveSizeInBits();
6655 unsigned SISize = SI.getType()->getPrimitiveSizeInBits();
6656 if (SRASize < SISize)
6657 opc = Instruction::SExt;
6658 else if (SRASize > SISize)
6659 opc = Instruction::Trunc;
6660 return CastInst::create(opc, SRA, SI.getType());
Chris Lattner380c7e92006-09-20 04:44:59 +00006661 }
6662 }
6663
6664
6665 // If one of the constants is zero (we know they can't both be) and we
Reid Spencer266e42b2006-12-23 06:05:41 +00006666 // have a fcmp instruction with zero, and we have an 'and' with the
Chris Lattner380c7e92006-09-20 04:44:59 +00006667 // non-constant value, eliminate this whole mess. This corresponds to
6668 // cases like this: ((X & 27) ? 27 : 0)
6669 if (TrueValC->isNullValue() || FalseValC->isNullValue())
Chris Lattnerb3f24c92006-09-18 04:22:48 +00006670 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner35167c32004-06-09 07:59:58 +00006671 cast<Constant>(IC->getOperand(1))->isNullValue())
6672 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
6673 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00006674 isa<ConstantInt>(ICA->getOperand(1)) &&
6675 (ICA->getOperand(1) == TrueValC ||
6676 ICA->getOperand(1) == FalseValC) &&
Chris Lattner35167c32004-06-09 07:59:58 +00006677 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
6678 // Okay, now we know that everything is set up, we just don't
Reid Spencer266e42b2006-12-23 06:05:41 +00006679 // know whether we have a icmp_ne or icmp_eq and whether the
6680 // true or false val is the zero.
Chris Lattner35167c32004-06-09 07:59:58 +00006681 bool ShouldNotVal = !TrueValC->isNullValue();
Reid Spencer266e42b2006-12-23 06:05:41 +00006682 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
Chris Lattner35167c32004-06-09 07:59:58 +00006683 Value *V = ICA;
6684 if (ShouldNotVal)
6685 V = InsertNewInstBefore(BinaryOperator::create(
6686 Instruction::Xor, V, ICA->getOperand(1)), SI);
6687 return ReplaceInstUsesWith(SI, V);
6688 }
Chris Lattner380c7e92006-09-20 04:44:59 +00006689 }
Chris Lattner533bc492004-03-30 19:37:13 +00006690 }
Chris Lattner623fba12004-04-10 22:21:27 +00006691
6692 // See if we are selecting two values based on a comparison of the two values.
Reid Spencer266e42b2006-12-23 06:05:41 +00006693 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
6694 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
Chris Lattner623fba12004-04-10 22:21:27 +00006695 // Transform (X == Y) ? X : Y -> Y
Reid Spencer266e42b2006-12-23 06:05:41 +00006696 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ)
Chris Lattner623fba12004-04-10 22:21:27 +00006697 return ReplaceInstUsesWith(SI, FalseVal);
6698 // Transform (X != Y) ? X : Y -> X
Reid Spencer266e42b2006-12-23 06:05:41 +00006699 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
Chris Lattner623fba12004-04-10 22:21:27 +00006700 return ReplaceInstUsesWith(SI, TrueVal);
6701 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6702
Reid Spencer266e42b2006-12-23 06:05:41 +00006703 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
Chris Lattner623fba12004-04-10 22:21:27 +00006704 // Transform (X == Y) ? Y : X -> X
Reid Spencer266e42b2006-12-23 06:05:41 +00006705 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ)
Chris Lattner24cf0202004-04-11 01:39:19 +00006706 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattner623fba12004-04-10 22:21:27 +00006707 // Transform (X != Y) ? Y : X -> Y
Reid Spencer266e42b2006-12-23 06:05:41 +00006708 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
6709 return ReplaceInstUsesWith(SI, TrueVal);
6710 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6711 }
6712 }
6713
6714 // See if we are selecting two values based on a comparison of the two values.
6715 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal)) {
6716 if (ICI->getOperand(0) == TrueVal && ICI->getOperand(1) == FalseVal) {
6717 // Transform (X == Y) ? X : Y -> Y
6718 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
6719 return ReplaceInstUsesWith(SI, FalseVal);
6720 // Transform (X != Y) ? X : Y -> X
6721 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
6722 return ReplaceInstUsesWith(SI, TrueVal);
6723 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6724
6725 } else if (ICI->getOperand(0) == FalseVal && ICI->getOperand(1) == TrueVal){
6726 // Transform (X == Y) ? Y : X -> X
6727 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
6728 return ReplaceInstUsesWith(SI, FalseVal);
6729 // Transform (X != Y) ? Y : X -> Y
6730 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
Chris Lattner24cf0202004-04-11 01:39:19 +00006731 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattner623fba12004-04-10 22:21:27 +00006732 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6733 }
6734 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00006735
Chris Lattnera04c9042005-01-13 22:52:24 +00006736 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
6737 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
6738 if (TI->hasOneUse() && FI->hasOneUse()) {
Chris Lattnera04c9042005-01-13 22:52:24 +00006739 Instruction *AddOp = 0, *SubOp = 0;
6740
Chris Lattner411336f2005-01-19 21:50:18 +00006741 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
6742 if (TI->getOpcode() == FI->getOpcode())
6743 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
6744 return IV;
6745
6746 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
6747 // even legal for FP.
Chris Lattnera04c9042005-01-13 22:52:24 +00006748 if (TI->getOpcode() == Instruction::Sub &&
6749 FI->getOpcode() == Instruction::Add) {
6750 AddOp = FI; SubOp = TI;
6751 } else if (FI->getOpcode() == Instruction::Sub &&
6752 TI->getOpcode() == Instruction::Add) {
6753 AddOp = TI; SubOp = FI;
6754 }
6755
6756 if (AddOp) {
6757 Value *OtherAddOp = 0;
6758 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
6759 OtherAddOp = AddOp->getOperand(1);
6760 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
6761 OtherAddOp = AddOp->getOperand(0);
6762 }
6763
6764 if (OtherAddOp) {
Chris Lattnerb580d262006-02-24 18:05:58 +00006765 // So at this point we know we have (Y -> OtherAddOp):
6766 // select C, (add X, Y), (sub X, Z)
6767 Value *NegVal; // Compute -Z
6768 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
6769 NegVal = ConstantExpr::getNeg(C);
6770 } else {
6771 NegVal = InsertNewInstBefore(
6772 BinaryOperator::createNeg(SubOp->getOperand(1), "tmp"), SI);
Chris Lattnera04c9042005-01-13 22:52:24 +00006773 }
Chris Lattnerb580d262006-02-24 18:05:58 +00006774
6775 Value *NewTrueOp = OtherAddOp;
6776 Value *NewFalseOp = NegVal;
6777 if (AddOp != TI)
6778 std::swap(NewTrueOp, NewFalseOp);
6779 Instruction *NewSel =
6780 new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
6781
6782 NewSel = InsertNewInstBefore(NewSel, SI);
6783 return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
Chris Lattnera04c9042005-01-13 22:52:24 +00006784 }
6785 }
6786 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00006787
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006788 // See if we can fold the select into one of our operands.
6789 if (SI.getType()->isInteger()) {
6790 // See the comment above GetSelectFoldableOperands for a description of the
6791 // transformation we are doing here.
6792 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
6793 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
6794 !isa<Constant>(FalseVal))
6795 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
6796 unsigned OpToFold = 0;
6797 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
6798 OpToFold = 1;
6799 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
6800 OpToFold = 2;
6801 }
6802
6803 if (OpToFold) {
6804 Constant *C = GetSelectFoldableConstant(TVI);
6805 std::string Name = TVI->getName(); TVI->setName("");
6806 Instruction *NewSel =
6807 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C,
6808 Name);
6809 InsertNewInstBefore(NewSel, SI);
6810 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
6811 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
6812 else if (ShiftInst *SI = dyn_cast<ShiftInst>(TVI))
6813 return new ShiftInst(SI->getOpcode(), FalseVal, NewSel);
6814 else {
6815 assert(0 && "Unknown instruction!!");
6816 }
6817 }
6818 }
Chris Lattner6862fbd2004-09-29 17:40:11 +00006819
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006820 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
6821 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
6822 !isa<Constant>(TrueVal))
6823 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
6824 unsigned OpToFold = 0;
6825 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
6826 OpToFold = 1;
6827 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
6828 OpToFold = 2;
6829 }
6830
6831 if (OpToFold) {
6832 Constant *C = GetSelectFoldableConstant(FVI);
6833 std::string Name = FVI->getName(); FVI->setName("");
6834 Instruction *NewSel =
6835 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold),
6836 Name);
6837 InsertNewInstBefore(NewSel, SI);
6838 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
6839 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
6840 else if (ShiftInst *SI = dyn_cast<ShiftInst>(FVI))
6841 return new ShiftInst(SI->getOpcode(), TrueVal, NewSel);
6842 else {
6843 assert(0 && "Unknown instruction!!");
6844 }
6845 }
6846 }
6847 }
Chris Lattnerd6f636a2005-04-24 07:30:14 +00006848
6849 if (BinaryOperator::isNot(CondVal)) {
6850 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
6851 SI.setOperand(1, FalseVal);
6852 SI.setOperand(2, TrueVal);
6853 return &SI;
6854 }
6855
Chris Lattnerb909e8b2004-03-12 05:52:32 +00006856 return 0;
6857}
6858
Chris Lattner82f2ef22006-03-06 20:18:44 +00006859/// GetKnownAlignment - If the specified pointer has an alignment that we can
6860/// determine, return it, otherwise return 0.
6861static unsigned GetKnownAlignment(Value *V, TargetData *TD) {
6862 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
6863 unsigned Align = GV->getAlignment();
6864 if (Align == 0 && TD)
6865 Align = TD->getTypeAlignment(GV->getType()->getElementType());
6866 return Align;
6867 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
6868 unsigned Align = AI->getAlignment();
6869 if (Align == 0 && TD) {
6870 if (isa<AllocaInst>(AI))
6871 Align = TD->getTypeAlignment(AI->getType()->getElementType());
6872 else if (isa<MallocInst>(AI)) {
6873 // Malloc returns maximally aligned memory.
6874 Align = TD->getTypeAlignment(AI->getType()->getElementType());
6875 Align = std::max(Align, (unsigned)TD->getTypeAlignment(Type::DoubleTy));
Reid Spencerc635f472006-12-31 05:48:39 +00006876 Align = std::max(Align, (unsigned)TD->getTypeAlignment(Type::Int64Ty));
Chris Lattner82f2ef22006-03-06 20:18:44 +00006877 }
6878 }
6879 return Align;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006880 } else if (isa<BitCastInst>(V) ||
Chris Lattner53ef5a02006-03-07 01:28:57 +00006881 (isa<ConstantExpr>(V) &&
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006882 cast<ConstantExpr>(V)->getOpcode() == Instruction::BitCast)) {
Chris Lattner53ef5a02006-03-07 01:28:57 +00006883 User *CI = cast<User>(V);
Chris Lattner82f2ef22006-03-06 20:18:44 +00006884 if (isa<PointerType>(CI->getOperand(0)->getType()))
6885 return GetKnownAlignment(CI->getOperand(0), TD);
6886 return 0;
Chris Lattner53ef5a02006-03-07 01:28:57 +00006887 } else if (isa<GetElementPtrInst>(V) ||
6888 (isa<ConstantExpr>(V) &&
6889 cast<ConstantExpr>(V)->getOpcode()==Instruction::GetElementPtr)) {
6890 User *GEPI = cast<User>(V);
Chris Lattner82f2ef22006-03-06 20:18:44 +00006891 unsigned BaseAlignment = GetKnownAlignment(GEPI->getOperand(0), TD);
6892 if (BaseAlignment == 0) return 0;
6893
6894 // If all indexes are zero, it is just the alignment of the base pointer.
6895 bool AllZeroOperands = true;
6896 for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
6897 if (!isa<Constant>(GEPI->getOperand(i)) ||
6898 !cast<Constant>(GEPI->getOperand(i))->isNullValue()) {
6899 AllZeroOperands = false;
6900 break;
6901 }
6902 if (AllZeroOperands)
6903 return BaseAlignment;
6904
6905 // Otherwise, if the base alignment is >= the alignment we expect for the
6906 // base pointer type, then we know that the resultant pointer is aligned at
6907 // least as much as its type requires.
6908 if (!TD) return 0;
6909
6910 const Type *BasePtrTy = GEPI->getOperand(0)->getType();
6911 if (TD->getTypeAlignment(cast<PointerType>(BasePtrTy)->getElementType())
Chris Lattner53ef5a02006-03-07 01:28:57 +00006912 <= BaseAlignment) {
6913 const Type *GEPTy = GEPI->getType();
6914 return TD->getTypeAlignment(cast<PointerType>(GEPTy)->getElementType());
6915 }
Chris Lattner82f2ef22006-03-06 20:18:44 +00006916 return 0;
6917 }
6918 return 0;
6919}
6920
Chris Lattnerb909e8b2004-03-12 05:52:32 +00006921
Chris Lattnerc66b2232006-01-13 20:11:04 +00006922/// visitCallInst - CallInst simplification. This mostly only handles folding
6923/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
6924/// the heavy lifting.
6925///
Chris Lattner970c33a2003-06-19 17:00:31 +00006926Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattnerc66b2232006-01-13 20:11:04 +00006927 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
6928 if (!II) return visitCallSite(&CI);
6929
Chris Lattner51ea1272004-02-28 05:22:00 +00006930 // Intrinsics cannot occur in an invoke, so handle them here instead of in
6931 // visitCallSite.
Chris Lattnerc66b2232006-01-13 20:11:04 +00006932 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner00648e12004-10-12 04:52:52 +00006933 bool Changed = false;
6934
6935 // memmove/cpy/set of zero bytes is a noop.
6936 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
6937 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
6938
Chris Lattner00648e12004-10-12 04:52:52 +00006939 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencere0fc4df2006-10-20 07:07:24 +00006940 if (CI->getZExtValue() == 1) {
Chris Lattner00648e12004-10-12 04:52:52 +00006941 // Replace the instruction with just byte operations. We would
6942 // transform other cases to loads/stores, but we don't know if
6943 // alignment is sufficient.
6944 }
Chris Lattner51ea1272004-02-28 05:22:00 +00006945 }
6946
Chris Lattner00648e12004-10-12 04:52:52 +00006947 // If we have a memmove and the source operation is a constant global,
6948 // then the source and dest pointers can't alias, so we can change this
6949 // into a call to memcpy.
Chris Lattner82f2ef22006-03-06 20:18:44 +00006950 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(II)) {
Chris Lattner00648e12004-10-12 04:52:52 +00006951 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
6952 if (GVSrc->isConstant()) {
6953 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner681ef2f2006-03-03 01:34:17 +00006954 const char *Name;
Andrew Lenharth0ebb0b02006-11-03 22:45:50 +00006955 if (CI.getCalledFunction()->getFunctionType()->getParamType(2) ==
Reid Spencerc635f472006-12-31 05:48:39 +00006956 Type::Int32Ty)
Chris Lattner681ef2f2006-03-03 01:34:17 +00006957 Name = "llvm.memcpy.i32";
6958 else
6959 Name = "llvm.memcpy.i64";
Chris Lattnerfbc524f2007-01-07 06:58:05 +00006960 Constant *MemCpy = M->getOrInsertFunction(Name,
Chris Lattner00648e12004-10-12 04:52:52 +00006961 CI.getCalledFunction()->getFunctionType());
6962 CI.setOperand(0, MemCpy);
6963 Changed = true;
6964 }
Chris Lattner82f2ef22006-03-06 20:18:44 +00006965 }
Chris Lattner00648e12004-10-12 04:52:52 +00006966
Chris Lattner82f2ef22006-03-06 20:18:44 +00006967 // If we can determine a pointer alignment that is bigger than currently
6968 // set, update the alignment.
6969 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
6970 unsigned Alignment1 = GetKnownAlignment(MI->getOperand(1), TD);
6971 unsigned Alignment2 = GetKnownAlignment(MI->getOperand(2), TD);
6972 unsigned Align = std::min(Alignment1, Alignment2);
Reid Spencere0fc4df2006-10-20 07:07:24 +00006973 if (MI->getAlignment()->getZExtValue() < Align) {
Reid Spencerc635f472006-12-31 05:48:39 +00006974 MI->setAlignment(ConstantInt::get(Type::Int32Ty, Align));
Chris Lattner82f2ef22006-03-06 20:18:44 +00006975 Changed = true;
6976 }
6977 } else if (isa<MemSetInst>(MI)) {
6978 unsigned Alignment = GetKnownAlignment(MI->getDest(), TD);
Reid Spencere0fc4df2006-10-20 07:07:24 +00006979 if (MI->getAlignment()->getZExtValue() < Alignment) {
Reid Spencerc635f472006-12-31 05:48:39 +00006980 MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
Chris Lattner82f2ef22006-03-06 20:18:44 +00006981 Changed = true;
6982 }
6983 }
6984
Chris Lattnerc66b2232006-01-13 20:11:04 +00006985 if (Changed) return II;
Chris Lattner503221f2006-01-13 21:28:09 +00006986 } else {
6987 switch (II->getIntrinsicID()) {
6988 default: break;
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00006989 case Intrinsic::ppc_altivec_lvx:
6990 case Intrinsic::ppc_altivec_lvxl:
Chris Lattner36dd7c92006-04-17 22:26:56 +00006991 case Intrinsic::x86_sse_loadu_ps:
6992 case Intrinsic::x86_sse2_loadu_pd:
6993 case Intrinsic::x86_sse2_loadu_dq:
6994 // Turn PPC lvx -> load if the pointer is known aligned.
6995 // Turn X86 loadups -> load if the pointer is known aligned.
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00006996 if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00006997 Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(1),
Chris Lattnere79d2492006-04-06 19:19:17 +00006998 PointerType::get(II->getType()), CI);
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00006999 return new LoadInst(Ptr);
7000 }
7001 break;
7002 case Intrinsic::ppc_altivec_stvx:
7003 case Intrinsic::ppc_altivec_stvxl:
7004 // Turn stvx -> store if the pointer is known aligned.
7005 if (GetKnownAlignment(II->getOperand(2), TD) >= 16) {
Chris Lattnere79d2492006-04-06 19:19:17 +00007006 const Type *OpPtrTy = PointerType::get(II->getOperand(1)->getType());
Reid Spencer13bc5d72006-12-12 09:18:51 +00007007 Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(2),
7008 OpPtrTy, CI);
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00007009 return new StoreInst(II->getOperand(1), Ptr);
7010 }
7011 break;
Chris Lattner36dd7c92006-04-17 22:26:56 +00007012 case Intrinsic::x86_sse_storeu_ps:
7013 case Intrinsic::x86_sse2_storeu_pd:
7014 case Intrinsic::x86_sse2_storeu_dq:
7015 case Intrinsic::x86_sse2_storel_dq:
7016 // Turn X86 storeu -> store if the pointer is known aligned.
7017 if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
7018 const Type *OpPtrTy = PointerType::get(II->getOperand(2)->getType());
Reid Spencer13bc5d72006-12-12 09:18:51 +00007019 Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(1),
7020 OpPtrTy, CI);
Chris Lattner36dd7c92006-04-17 22:26:56 +00007021 return new StoreInst(II->getOperand(2), Ptr);
7022 }
7023 break;
Chris Lattner2deeaea2006-10-05 06:55:50 +00007024
7025 case Intrinsic::x86_sse_cvttss2si: {
7026 // These intrinsics only demands the 0th element of its input vector. If
7027 // we can simplify the input based on that, do so now.
7028 uint64_t UndefElts;
7029 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1,
7030 UndefElts)) {
7031 II->setOperand(1, V);
7032 return II;
7033 }
7034 break;
7035 }
7036
Chris Lattnere79d2492006-04-06 19:19:17 +00007037 case Intrinsic::ppc_altivec_vperm:
7038 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
7039 if (ConstantPacked *Mask = dyn_cast<ConstantPacked>(II->getOperand(3))) {
7040 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
7041
7042 // Check that all of the elements are integer constants or undefs.
7043 bool AllEltsOk = true;
7044 for (unsigned i = 0; i != 16; ++i) {
7045 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
7046 !isa<UndefValue>(Mask->getOperand(i))) {
7047 AllEltsOk = false;
7048 break;
7049 }
7050 }
7051
7052 if (AllEltsOk) {
7053 // Cast the input vectors to byte vectors.
Reid Spencer13bc5d72006-12-12 09:18:51 +00007054 Value *Op0 = InsertCastBefore(Instruction::BitCast,
7055 II->getOperand(1), Mask->getType(), CI);
7056 Value *Op1 = InsertCastBefore(Instruction::BitCast,
7057 II->getOperand(2), Mask->getType(), CI);
Chris Lattnere79d2492006-04-06 19:19:17 +00007058 Value *Result = UndefValue::get(Op0->getType());
7059
7060 // Only extract each element once.
7061 Value *ExtractedElts[32];
7062 memset(ExtractedElts, 0, sizeof(ExtractedElts));
7063
7064 for (unsigned i = 0; i != 16; ++i) {
7065 if (isa<UndefValue>(Mask->getOperand(i)))
7066 continue;
Reid Spencere0fc4df2006-10-20 07:07:24 +00007067 unsigned Idx =cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
Chris Lattnere79d2492006-04-06 19:19:17 +00007068 Idx &= 31; // Match the hardware behavior.
7069
7070 if (ExtractedElts[Idx] == 0) {
7071 Instruction *Elt =
Chris Lattner2deeaea2006-10-05 06:55:50 +00007072 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
Chris Lattnere79d2492006-04-06 19:19:17 +00007073 InsertNewInstBefore(Elt, CI);
7074 ExtractedElts[Idx] = Elt;
7075 }
7076
7077 // Insert this value into the result vector.
Chris Lattner2deeaea2006-10-05 06:55:50 +00007078 Result = new InsertElementInst(Result, ExtractedElts[Idx], i,"tmp");
Chris Lattnere79d2492006-04-06 19:19:17 +00007079 InsertNewInstBefore(cast<Instruction>(Result), CI);
7080 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007081 return CastInst::create(Instruction::BitCast, Result, CI.getType());
Chris Lattnere79d2492006-04-06 19:19:17 +00007082 }
7083 }
7084 break;
7085
Chris Lattner503221f2006-01-13 21:28:09 +00007086 case Intrinsic::stackrestore: {
7087 // If the save is right next to the restore, remove the restore. This can
7088 // happen when variable allocas are DCE'd.
7089 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
7090 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
7091 BasicBlock::iterator BI = SS;
7092 if (&*++BI == II)
7093 return EraseInstFromFunction(CI);
7094 }
7095 }
7096
7097 // If the stack restore is in a return/unwind block and if there are no
7098 // allocas or calls between the restore and the return, nuke the restore.
7099 TerminatorInst *TI = II->getParent()->getTerminator();
7100 if (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)) {
7101 BasicBlock::iterator BI = II;
7102 bool CannotRemove = false;
7103 for (++BI; &*BI != TI; ++BI) {
7104 if (isa<AllocaInst>(BI) ||
7105 (isa<CallInst>(BI) && !isa<IntrinsicInst>(BI))) {
7106 CannotRemove = true;
7107 break;
7108 }
7109 }
7110 if (!CannotRemove)
7111 return EraseInstFromFunction(CI);
7112 }
7113 break;
7114 }
7115 }
Chris Lattner00648e12004-10-12 04:52:52 +00007116 }
7117
Chris Lattnerc66b2232006-01-13 20:11:04 +00007118 return visitCallSite(II);
Chris Lattner970c33a2003-06-19 17:00:31 +00007119}
7120
7121// InvokeInst simplification
7122//
7123Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattneraec3d942003-10-07 22:32:43 +00007124 return visitCallSite(&II);
Chris Lattner970c33a2003-06-19 17:00:31 +00007125}
7126
Chris Lattneraec3d942003-10-07 22:32:43 +00007127// visitCallSite - Improvements for call and invoke instructions.
7128//
7129Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner75b4d1d2003-10-07 22:54:13 +00007130 bool Changed = false;
7131
7132 // If the callee is a constexpr cast of a function, attempt to move the cast
7133 // to the arguments of the call/invoke.
Chris Lattneraec3d942003-10-07 22:32:43 +00007134 if (transformConstExprCastCall(CS)) return 0;
7135
Chris Lattner75b4d1d2003-10-07 22:54:13 +00007136 Value *Callee = CS.getCalledValue();
Chris Lattner81a7a232004-10-16 18:11:37 +00007137
Chris Lattner61d9d812005-05-13 07:09:09 +00007138 if (Function *CalleeF = dyn_cast<Function>(Callee))
7139 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
7140 Instruction *OldCall = CS.getInstruction();
7141 // If the call and callee calling conventions don't match, this call must
7142 // be unreachable, as the call is undefined.
Zhou Sheng75b871f2007-01-11 12:24:14 +00007143 new StoreInst(ConstantInt::getTrue(),
Reid Spencer542964f2007-01-11 18:21:29 +00007144 UndefValue::get(PointerType::get(Type::Int1Ty)), OldCall);
Chris Lattner61d9d812005-05-13 07:09:09 +00007145 if (!OldCall->use_empty())
7146 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
7147 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
7148 return EraseInstFromFunction(*OldCall);
7149 return 0;
7150 }
7151
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007152 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
7153 // This instruction is not reachable, just remove it. We insert a store to
7154 // undef so that we know that this code is not reachable, despite the fact
7155 // that we can't modify the CFG here.
Zhou Sheng75b871f2007-01-11 12:24:14 +00007156 new StoreInst(ConstantInt::getTrue(),
Reid Spencer542964f2007-01-11 18:21:29 +00007157 UndefValue::get(PointerType::get(Type::Int1Ty)),
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007158 CS.getInstruction());
7159
7160 if (!CS.getInstruction()->use_empty())
7161 CS.getInstruction()->
7162 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
7163
7164 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
7165 // Don't break the CFG, insert a dummy cond branch.
7166 new BranchInst(II->getNormalDest(), II->getUnwindDest(),
Zhou Sheng75b871f2007-01-11 12:24:14 +00007167 ConstantInt::getTrue(), II);
Chris Lattner81a7a232004-10-16 18:11:37 +00007168 }
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007169 return EraseInstFromFunction(*CS.getInstruction());
7170 }
Chris Lattner81a7a232004-10-16 18:11:37 +00007171
Chris Lattner75b4d1d2003-10-07 22:54:13 +00007172 const PointerType *PTy = cast<PointerType>(Callee->getType());
7173 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
7174 if (FTy->isVarArg()) {
7175 // See if we can optimize any arguments passed through the varargs area of
7176 // the call.
7177 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
7178 E = CS.arg_end(); I != E; ++I)
7179 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
7180 // If this cast does not effect the value passed through the varargs
7181 // area, we can eliminate the use of the cast.
7182 Value *Op = CI->getOperand(0);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007183 if (CI->isLosslessCast()) {
Chris Lattner75b4d1d2003-10-07 22:54:13 +00007184 *I = Op;
7185 Changed = true;
7186 }
7187 }
7188 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00007189
Chris Lattner75b4d1d2003-10-07 22:54:13 +00007190 return Changed ? CS.getInstruction() : 0;
Chris Lattneraec3d942003-10-07 22:32:43 +00007191}
7192
Chris Lattner970c33a2003-06-19 17:00:31 +00007193// transformConstExprCastCall - If the callee is a constexpr cast of a function,
7194// attempt to move the cast to the arguments of the call/invoke.
7195//
7196bool InstCombiner::transformConstExprCastCall(CallSite CS) {
7197 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
7198 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007199 if (CE->getOpcode() != Instruction::BitCast ||
7200 !isa<Function>(CE->getOperand(0)))
Chris Lattner970c33a2003-06-19 17:00:31 +00007201 return false;
Reid Spencer87436872004-07-18 00:38:32 +00007202 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner970c33a2003-06-19 17:00:31 +00007203 Instruction *Caller = CS.getInstruction();
7204
7205 // Okay, this is a cast from a function to a different type. Unless doing so
7206 // would cause a type conversion of one of our arguments, change this call to
7207 // be a direct call with arguments casted to the appropriate types.
7208 //
7209 const FunctionType *FT = Callee->getFunctionType();
7210 const Type *OldRetTy = Caller->getType();
7211
Chris Lattner1f7942f2004-01-14 06:06:08 +00007212 // Check to see if we are changing the return type...
7213 if (OldRetTy != FT->getReturnType()) {
Chris Lattner400f9592007-01-06 02:09:32 +00007214 if (Callee->isExternal() && !Caller->use_empty() &&
Chris Lattner7051d752007-01-06 19:53:32 +00007215 OldRetTy != FT->getReturnType() &&
7216 // Conversion is ok if changing from pointer to int of same size.
7217 !(isa<PointerType>(FT->getReturnType()) &&
7218 TD->getIntPtrType() == OldRetTy))
Chris Lattner400f9592007-01-06 02:09:32 +00007219 return false; // Cannot transform this return value.
Chris Lattner1f7942f2004-01-14 06:06:08 +00007220
7221 // If the callsite is an invoke instruction, and the return value is used by
7222 // a PHI node in a successor, we cannot change the return type of the call
7223 // because there is no place to put the cast instruction (without breaking
7224 // the critical edge). Bail out in this case.
7225 if (!Caller->use_empty())
7226 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
7227 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
7228 UI != E; ++UI)
7229 if (PHINode *PN = dyn_cast<PHINode>(*UI))
7230 if (PN->getParent() == II->getNormalDest() ||
Chris Lattnerfae8ab32004-02-08 21:44:31 +00007231 PN->getParent() == II->getUnwindDest())
Chris Lattner1f7942f2004-01-14 06:06:08 +00007232 return false;
7233 }
Chris Lattner970c33a2003-06-19 17:00:31 +00007234
7235 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
7236 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanb1c93172005-04-21 23:48:37 +00007237
Chris Lattner970c33a2003-06-19 17:00:31 +00007238 CallSite::arg_iterator AI = CS.arg_begin();
7239 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
7240 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthebfa24e2006-06-28 01:01:52 +00007241 const Type *ActTy = (*AI)->getType();
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007242 ConstantInt *c = dyn_cast<ConstantInt>(*AI);
Andrew Lenharthebfa24e2006-06-28 01:01:52 +00007243 //Either we can cast directly, or we can upconvert the argument
Chris Lattner400f9592007-01-06 02:09:32 +00007244 bool isConvertible = ActTy == ParamTy ||
Chris Lattner7051d752007-01-06 19:53:32 +00007245 (isa<PointerType>(ParamTy) && isa<PointerType>(ActTy)) ||
Andrew Lenharthebfa24e2006-06-28 01:01:52 +00007246 (ParamTy->isIntegral() && ActTy->isIntegral() &&
Reid Spencer8f166b02007-01-08 16:32:00 +00007247 ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()) ||
7248 (c && ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()
7249 && c->getSExtValue() > 0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00007250 if (Callee->isExternal() && !isConvertible) return false;
Chris Lattner970c33a2003-06-19 17:00:31 +00007251 }
7252
7253 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
7254 Callee->isExternal())
7255 return false; // Do not delete arguments unless we have a function body...
7256
7257 // Okay, we decided that this is a safe thing to do: go ahead and start
7258 // inserting cast instructions as necessary...
7259 std::vector<Value*> Args;
7260 Args.reserve(NumActualArgs);
7261
7262 AI = CS.arg_begin();
7263 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
7264 const Type *ParamTy = FT->getParamType(i);
7265 if ((*AI)->getType() == ParamTy) {
7266 Args.push_back(*AI);
7267 } else {
Reid Spencer668d90f2006-12-18 08:47:13 +00007268 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
Reid Spencerc635f472006-12-31 05:48:39 +00007269 false, ParamTy, false);
Reid Spencer668d90f2006-12-18 08:47:13 +00007270 CastInst *NewCast = CastInst::create(opcode, *AI, ParamTy, "tmp");
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007271 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
Chris Lattner970c33a2003-06-19 17:00:31 +00007272 }
7273 }
7274
7275 // If the function takes more arguments than the call was taking, add them
7276 // now...
7277 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
7278 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
7279
7280 // If we are removing arguments to the function, emit an obnoxious warning...
7281 if (FT->getNumParams() < NumActualArgs)
7282 if (!FT->isVarArg()) {
Bill Wendlingf3baad32006-12-07 01:30:32 +00007283 cerr << "WARNING: While resolving call to function '"
7284 << Callee->getName() << "' arguments were dropped!\n";
Chris Lattner970c33a2003-06-19 17:00:31 +00007285 } else {
7286 // Add all of the arguments in their promoted form to the arg list...
7287 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
7288 const Type *PTy = getPromotedType((*AI)->getType());
7289 if (PTy != (*AI)->getType()) {
7290 // Must promote to pass through va_arg area!
Reid Spencerc635f472006-12-31 05:48:39 +00007291 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false,
7292 PTy, false);
Reid Spencer668d90f2006-12-18 08:47:13 +00007293 Instruction *Cast = CastInst::create(opcode, *AI, PTy, "tmp");
Chris Lattner970c33a2003-06-19 17:00:31 +00007294 InsertNewInstBefore(Cast, *Caller);
7295 Args.push_back(Cast);
7296 } else {
7297 Args.push_back(*AI);
7298 }
7299 }
7300 }
7301
7302 if (FT->getReturnType() == Type::VoidTy)
7303 Caller->setName(""); // Void type should not have a name...
7304
7305 Instruction *NC;
7306 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Chris Lattnerfae8ab32004-02-08 21:44:31 +00007307 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
Chris Lattner970c33a2003-06-19 17:00:31 +00007308 Args, Caller->getName(), Caller);
Chris Lattner05c703e2005-05-14 12:25:32 +00007309 cast<InvokeInst>(II)->setCallingConv(II->getCallingConv());
Chris Lattner970c33a2003-06-19 17:00:31 +00007310 } else {
7311 NC = new CallInst(Callee, Args, Caller->getName(), Caller);
Chris Lattner6aacb0f2005-05-06 06:48:21 +00007312 if (cast<CallInst>(Caller)->isTailCall())
7313 cast<CallInst>(NC)->setTailCall();
Chris Lattner05c703e2005-05-14 12:25:32 +00007314 cast<CallInst>(NC)->setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Chris Lattner970c33a2003-06-19 17:00:31 +00007315 }
7316
7317 // Insert a cast of the return type as necessary...
7318 Value *NV = NC;
7319 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
7320 if (NV->getType() != Type::VoidTy) {
Reid Spencer668d90f2006-12-18 08:47:13 +00007321 const Type *CallerTy = Caller->getType();
Reid Spencerc635f472006-12-31 05:48:39 +00007322 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
7323 CallerTy, false);
Reid Spencer668d90f2006-12-18 08:47:13 +00007324 NV = NC = CastInst::create(opcode, NC, CallerTy, "tmp");
Chris Lattner686767f2003-10-30 00:46:41 +00007325
7326 // If this is an invoke instruction, we should insert it after the first
7327 // non-phi, instruction in the normal successor block.
7328 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
7329 BasicBlock::iterator I = II->getNormalDest()->begin();
7330 while (isa<PHINode>(I)) ++I;
7331 InsertNewInstBefore(NC, *I);
7332 } else {
7333 // Otherwise, it's a call, just insert cast right after the call instr
7334 InsertNewInstBefore(NC, *Caller);
7335 }
Chris Lattner51ea1272004-02-28 05:22:00 +00007336 AddUsersToWorkList(*Caller);
Chris Lattner970c33a2003-06-19 17:00:31 +00007337 } else {
Chris Lattnere29d6342004-10-17 21:22:38 +00007338 NV = UndefValue::get(Caller->getType());
Chris Lattner970c33a2003-06-19 17:00:31 +00007339 }
7340 }
7341
7342 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
7343 Caller->replaceAllUsesWith(NV);
7344 Caller->getParent()->getInstList().erase(Caller);
7345 removeFromWorkList(Caller);
7346 return true;
7347}
7348
Chris Lattnercadac0c2006-11-01 04:51:18 +00007349/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
7350/// and if a/b/c/d and the add's all have a single use, turn this into two phi's
7351/// and a single binop.
7352Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
7353 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Chris Lattnereebea432006-11-01 07:43:41 +00007354 assert(isa<BinaryOperator>(FirstInst) || isa<ShiftInst>(FirstInst) ||
Reid Spencer266e42b2006-12-23 06:05:41 +00007355 isa<GetElementPtrInst>(FirstInst) || isa<CmpInst>(FirstInst));
Chris Lattnercadac0c2006-11-01 04:51:18 +00007356 unsigned Opc = FirstInst->getOpcode();
Chris Lattnercd62f112006-11-08 19:29:23 +00007357 Value *LHSVal = FirstInst->getOperand(0);
7358 Value *RHSVal = FirstInst->getOperand(1);
7359
7360 const Type *LHSType = LHSVal->getType();
7361 const Type *RHSType = RHSVal->getType();
Chris Lattnercadac0c2006-11-01 04:51:18 +00007362
7363 // Scan to see if all operands are the same opcode, all have one use, and all
7364 // kill their operands (i.e. the operands have one use).
Chris Lattnerdc826fc2006-11-01 04:55:47 +00007365 for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
Chris Lattnercadac0c2006-11-01 04:51:18 +00007366 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Chris Lattnerdc826fc2006-11-01 04:55:47 +00007367 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
Reid Spencer266e42b2006-12-23 06:05:41 +00007368 // Verify type of the LHS matches so we don't fold cmp's of different
Chris Lattnereebea432006-11-01 07:43:41 +00007369 // types or GEP's with different index types.
7370 I->getOperand(0)->getType() != LHSType ||
7371 I->getOperand(1)->getType() != RHSType)
Chris Lattnercadac0c2006-11-01 04:51:18 +00007372 return 0;
Reid Spencer266e42b2006-12-23 06:05:41 +00007373
7374 // If they are CmpInst instructions, check their predicates
7375 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
7376 if (cast<CmpInst>(I)->getPredicate() !=
7377 cast<CmpInst>(FirstInst)->getPredicate())
7378 return 0;
Chris Lattnercd62f112006-11-08 19:29:23 +00007379
7380 // Keep track of which operand needs a phi node.
7381 if (I->getOperand(0) != LHSVal) LHSVal = 0;
7382 if (I->getOperand(1) != RHSVal) RHSVal = 0;
Chris Lattnercadac0c2006-11-01 04:51:18 +00007383 }
7384
Chris Lattner4f218d52006-11-08 19:42:28 +00007385 // Otherwise, this is safe to transform, determine if it is profitable.
7386
7387 // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
7388 // Indexes are often folded into load/store instructions, so we don't want to
7389 // hide them behind a phi.
7390 if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
7391 return 0;
7392
Chris Lattnercadac0c2006-11-01 04:51:18 +00007393 Value *InLHS = FirstInst->getOperand(0);
Chris Lattnercadac0c2006-11-01 04:51:18 +00007394 Value *InRHS = FirstInst->getOperand(1);
Chris Lattner4f218d52006-11-08 19:42:28 +00007395 PHINode *NewLHS = 0, *NewRHS = 0;
Chris Lattnercd62f112006-11-08 19:29:23 +00007396 if (LHSVal == 0) {
7397 NewLHS = new PHINode(LHSType, FirstInst->getOperand(0)->getName()+".pn");
7398 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
7399 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
Chris Lattnereebea432006-11-01 07:43:41 +00007400 InsertNewInstBefore(NewLHS, PN);
7401 LHSVal = NewLHS;
7402 }
Chris Lattnercd62f112006-11-08 19:29:23 +00007403
7404 if (RHSVal == 0) {
7405 NewRHS = new PHINode(RHSType, FirstInst->getOperand(1)->getName()+".pn");
7406 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
7407 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
Chris Lattnereebea432006-11-01 07:43:41 +00007408 InsertNewInstBefore(NewRHS, PN);
7409 RHSVal = NewRHS;
7410 }
7411
Chris Lattnercd62f112006-11-08 19:29:23 +00007412 // Add all operands to the new PHIs.
7413 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7414 if (NewLHS) {
7415 Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
7416 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
7417 }
7418 if (NewRHS) {
7419 Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
7420 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
7421 }
7422 }
7423
Chris Lattnercadac0c2006-11-01 04:51:18 +00007424 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattnereebea432006-11-01 07:43:41 +00007425 return BinaryOperator::create(BinOp->getOpcode(), LHSVal, RHSVal);
Reid Spencer266e42b2006-12-23 06:05:41 +00007426 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
7427 return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal,
7428 RHSVal);
Chris Lattnereebea432006-11-01 07:43:41 +00007429 else if (ShiftInst *SI = dyn_cast<ShiftInst>(FirstInst))
7430 return new ShiftInst(SI->getOpcode(), LHSVal, RHSVal);
7431 else {
7432 assert(isa<GetElementPtrInst>(FirstInst));
7433 return new GetElementPtrInst(LHSVal, RHSVal);
7434 }
Chris Lattnercadac0c2006-11-01 04:51:18 +00007435}
7436
Chris Lattner14f82c72006-11-01 07:13:54 +00007437/// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
7438/// of the block that defines it. This means that it must be obvious the value
7439/// of the load is not changed from the point of the load to the end of the
7440/// block it is in.
7441static bool isSafeToSinkLoad(LoadInst *L) {
7442 BasicBlock::iterator BBI = L, E = L->getParent()->end();
7443
7444 for (++BBI; BBI != E; ++BBI)
7445 if (BBI->mayWriteToMemory())
7446 return false;
7447 return true;
7448}
7449
Chris Lattner970c33a2003-06-19 17:00:31 +00007450
Chris Lattner7515cab2004-11-14 19:13:23 +00007451// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
7452// operator and they all are only used by the PHI, PHI together their
7453// inputs, and do the operation once, to the result of the PHI.
7454Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
7455 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
7456
7457 // Scan the instruction, looking for input operations that can be folded away.
7458 // If all input operands to the phi are the same instruction (e.g. a cast from
7459 // the same type or "+42") we can pull the operation through the PHI, reducing
7460 // code size and simplifying code.
7461 Constant *ConstantOp = 0;
7462 const Type *CastSrcTy = 0;
Chris Lattner14f82c72006-11-01 07:13:54 +00007463 bool isVolatile = false;
Chris Lattner7515cab2004-11-14 19:13:23 +00007464 if (isa<CastInst>(FirstInst)) {
7465 CastSrcTy = FirstInst->getOperand(0)->getType();
Reid Spencer266e42b2006-12-23 06:05:41 +00007466 } else if (isa<BinaryOperator>(FirstInst) || isa<ShiftInst>(FirstInst) ||
7467 isa<CmpInst>(FirstInst)) {
7468 // Can fold binop, compare or shift here if the RHS is a constant,
7469 // otherwise call FoldPHIArgBinOpIntoPHI.
Chris Lattner7515cab2004-11-14 19:13:23 +00007470 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Chris Lattnercadac0c2006-11-01 04:51:18 +00007471 if (ConstantOp == 0)
7472 return FoldPHIArgBinOpIntoPHI(PN);
Chris Lattner14f82c72006-11-01 07:13:54 +00007473 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
7474 isVolatile = LI->isVolatile();
7475 // We can't sink the load if the loaded value could be modified between the
7476 // load and the PHI.
7477 if (LI->getParent() != PN.getIncomingBlock(0) ||
7478 !isSafeToSinkLoad(LI))
7479 return 0;
Chris Lattnereebea432006-11-01 07:43:41 +00007480 } else if (isa<GetElementPtrInst>(FirstInst)) {
Chris Lattner4f218d52006-11-08 19:42:28 +00007481 if (FirstInst->getNumOperands() == 2)
Chris Lattnereebea432006-11-01 07:43:41 +00007482 return FoldPHIArgBinOpIntoPHI(PN);
7483 // Can't handle general GEPs yet.
7484 return 0;
Chris Lattner7515cab2004-11-14 19:13:23 +00007485 } else {
7486 return 0; // Cannot fold this operation.
7487 }
7488
7489 // Check to see if all arguments are the same operation.
7490 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7491 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
7492 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
Reid Spencer266e42b2006-12-23 06:05:41 +00007493 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
Chris Lattner7515cab2004-11-14 19:13:23 +00007494 return 0;
7495 if (CastSrcTy) {
7496 if (I->getOperand(0)->getType() != CastSrcTy)
7497 return 0; // Cast operation must match.
Chris Lattner14f82c72006-11-01 07:13:54 +00007498 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00007499 // We can't sink the load if the loaded value could be modified between
7500 // the load and the PHI.
Chris Lattner14f82c72006-11-01 07:13:54 +00007501 if (LI->isVolatile() != isVolatile ||
7502 LI->getParent() != PN.getIncomingBlock(i) ||
7503 !isSafeToSinkLoad(LI))
7504 return 0;
Chris Lattner7515cab2004-11-14 19:13:23 +00007505 } else if (I->getOperand(1) != ConstantOp) {
7506 return 0;
7507 }
7508 }
7509
7510 // Okay, they are all the same operation. Create a new PHI node of the
7511 // correct type, and PHI together all of the LHS's of the instructions.
7512 PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
7513 PN.getName()+".in");
Chris Lattnerd8e20182005-01-29 00:39:08 +00007514 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattner46dd5a62004-11-14 19:29:34 +00007515
7516 Value *InVal = FirstInst->getOperand(0);
7517 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattner7515cab2004-11-14 19:13:23 +00007518
7519 // Add all operands to the new PHI.
Chris Lattner46dd5a62004-11-14 19:29:34 +00007520 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7521 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
7522 if (NewInVal != InVal)
7523 InVal = 0;
7524 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
7525 }
7526
7527 Value *PhiVal;
7528 if (InVal) {
7529 // The new PHI unions all of the same values together. This is really
7530 // common, so we handle it intelligently here for compile-time speed.
7531 PhiVal = InVal;
7532 delete NewPN;
7533 } else {
7534 InsertNewInstBefore(NewPN, PN);
7535 PhiVal = NewPN;
7536 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00007537
Chris Lattner7515cab2004-11-14 19:13:23 +00007538 // Insert and return the new operation.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007539 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
7540 return CastInst::create(FirstCI->getOpcode(), PhiVal, PN.getType());
Reid Spencerde46e482006-11-02 20:25:50 +00007541 else if (isa<LoadInst>(FirstInst))
Chris Lattner14f82c72006-11-01 07:13:54 +00007542 return new LoadInst(PhiVal, "", isVolatile);
Chris Lattner7515cab2004-11-14 19:13:23 +00007543 else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattner46dd5a62004-11-14 19:29:34 +00007544 return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
Reid Spencer266e42b2006-12-23 06:05:41 +00007545 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
7546 return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(),
7547 PhiVal, ConstantOp);
Chris Lattner7515cab2004-11-14 19:13:23 +00007548 else
7549 return new ShiftInst(cast<ShiftInst>(FirstInst)->getOpcode(),
Chris Lattner46dd5a62004-11-14 19:29:34 +00007550 PhiVal, ConstantOp);
Chris Lattner7515cab2004-11-14 19:13:23 +00007551}
Chris Lattner48a44f72002-05-02 17:06:02 +00007552
Chris Lattner71536432005-01-17 05:10:15 +00007553/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
7554/// that is dead.
7555static bool DeadPHICycle(PHINode *PN, std::set<PHINode*> &PotentiallyDeadPHIs) {
7556 if (PN->use_empty()) return true;
7557 if (!PN->hasOneUse()) return false;
7558
7559 // Remember this node, and if we find the cycle, return.
7560 if (!PotentiallyDeadPHIs.insert(PN).second)
7561 return true;
7562
7563 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
7564 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanb1c93172005-04-21 23:48:37 +00007565
Chris Lattner71536432005-01-17 05:10:15 +00007566 return false;
7567}
7568
Chris Lattnerbbbdd852002-05-06 18:06:38 +00007569// PHINode simplification
7570//
Chris Lattner113f4f42002-06-25 16:13:24 +00007571Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonbbf89902006-07-10 22:15:25 +00007572 // If LCSSA is around, don't mess with Phi nodes
7573 if (mustPreserveAnalysisID(LCSSAID)) return 0;
Owen Andersona6968f82006-07-10 19:03:49 +00007574
Owen Andersonae8aa642006-07-10 22:03:18 +00007575 if (Value *V = PN.hasConstantValue())
7576 return ReplaceInstUsesWith(PN, V);
7577
Owen Andersonae8aa642006-07-10 22:03:18 +00007578 // If all PHI operands are the same operation, pull them through the PHI,
7579 // reducing code size.
7580 if (isa<Instruction>(PN.getIncomingValue(0)) &&
7581 PN.getIncomingValue(0)->hasOneUse())
7582 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
7583 return Result;
7584
7585 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
7586 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
7587 // PHI)... break the cycle.
7588 if (PN.hasOneUse())
7589 if (PHINode *PU = dyn_cast<PHINode>(PN.use_back())) {
7590 std::set<PHINode*> PotentiallyDeadPHIs;
7591 PotentiallyDeadPHIs.insert(&PN);
7592 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
7593 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
7594 }
7595
Chris Lattner91daeb52003-12-19 05:58:40 +00007596 return 0;
Chris Lattnerbbbdd852002-05-06 18:06:38 +00007597}
7598
Reid Spencer13bc5d72006-12-12 09:18:51 +00007599static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
7600 Instruction *InsertPoint,
7601 InstCombiner *IC) {
Reid Spencer8f166b02007-01-08 16:32:00 +00007602 unsigned PtrSize = DTy->getPrimitiveSizeInBits();
7603 unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
Reid Spencer13bc5d72006-12-12 09:18:51 +00007604 // We must cast correctly to the pointer type. Ensure that we
7605 // sign extend the integer value if it is smaller as this is
7606 // used for address computation.
7607 Instruction::CastOps opcode =
7608 (VTySize < PtrSize ? Instruction::SExt :
7609 (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
7610 return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
Chris Lattner69193f92004-04-05 01:30:19 +00007611}
7612
Chris Lattner48a44f72002-05-02 17:06:02 +00007613
Chris Lattner113f4f42002-06-25 16:13:24 +00007614Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner5f667a62004-05-07 22:09:22 +00007615 Value *PtrOp = GEP.getOperand(0);
Chris Lattner471bd762003-05-22 19:07:21 +00007616 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
Chris Lattner113f4f42002-06-25 16:13:24 +00007617 // If so, eliminate the noop.
Chris Lattner8d0bacb2004-02-22 05:25:17 +00007618 if (GEP.getNumOperands() == 1)
Chris Lattner5f667a62004-05-07 22:09:22 +00007619 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner8d0bacb2004-02-22 05:25:17 +00007620
Chris Lattner81a7a232004-10-16 18:11:37 +00007621 if (isa<UndefValue>(GEP.getOperand(0)))
7622 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
7623
Chris Lattner8d0bacb2004-02-22 05:25:17 +00007624 bool HasZeroPointerIndex = false;
7625 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
7626 HasZeroPointerIndex = C->isNullValue();
7627
7628 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner5f667a62004-05-07 22:09:22 +00007629 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner48a44f72002-05-02 17:06:02 +00007630
Chris Lattner69193f92004-04-05 01:30:19 +00007631 // Eliminate unneeded casts for indices.
7632 bool MadeChange = false;
Chris Lattner2b2412d2004-04-07 18:38:20 +00007633 gep_type_iterator GTI = gep_type_begin(GEP);
7634 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI)
7635 if (isa<SequentialType>(*GTI)) {
7636 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
7637 Value *Src = CI->getOperand(0);
7638 const Type *SrcTy = Src->getType();
7639 const Type *DestTy = CI->getType();
7640 if (Src->getType()->isInteger()) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00007641 if (SrcTy->getPrimitiveSizeInBits() ==
7642 DestTy->getPrimitiveSizeInBits()) {
Chris Lattner2b2412d2004-04-07 18:38:20 +00007643 // We can always eliminate a cast from ulong or long to the other.
7644 // We can always eliminate a cast from uint to int or the other on
7645 // 32-bit pointer platforms.
Chris Lattnerd1f46d32005-04-24 06:59:08 +00007646 if (DestTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()){
Chris Lattner2b2412d2004-04-07 18:38:20 +00007647 MadeChange = true;
7648 GEP.setOperand(i, Src);
7649 }
Reid Spencer8f166b02007-01-08 16:32:00 +00007650 } else if (SrcTy->getPrimitiveSizeInBits() <
7651 DestTy->getPrimitiveSizeInBits() &&
Chris Lattner2b2412d2004-04-07 18:38:20 +00007652 SrcTy->getPrimitiveSize() == 4) {
Reid Spencer266e42b2006-12-23 06:05:41 +00007653 // We can eliminate a cast from [u]int to [u]long iff the target
7654 // is a 32-bit pointer target.
7655 if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
Chris Lattner2b2412d2004-04-07 18:38:20 +00007656 MadeChange = true;
7657 GEP.setOperand(i, Src);
7658 }
Chris Lattner69193f92004-04-05 01:30:19 +00007659 }
7660 }
7661 }
Chris Lattner2b2412d2004-04-07 18:38:20 +00007662 // If we are using a wider index than needed for this platform, shrink it
7663 // to what we need. If the incoming value needs a cast instruction,
7664 // insert it. This explicit cast can make subsequent optimizations more
7665 // obvious.
7666 Value *Op = GEP.getOperand(i);
7667 if (Op->getType()->getPrimitiveSize() > TD->getPointerSize())
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00007668 if (Constant *C = dyn_cast<Constant>(Op)) {
Reid Spencer266e42b2006-12-23 06:05:41 +00007669 GEP.setOperand(i, ConstantExpr::getTrunc(C, TD->getIntPtrType()));
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00007670 MadeChange = true;
7671 } else {
Reid Spencer13bc5d72006-12-12 09:18:51 +00007672 Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
7673 GEP);
Chris Lattner2b2412d2004-04-07 18:38:20 +00007674 GEP.setOperand(i, Op);
7675 MadeChange = true;
7676 }
Chris Lattner69193f92004-04-05 01:30:19 +00007677 }
7678 if (MadeChange) return &GEP;
7679
Chris Lattnerae7a0d32002-08-02 19:29:35 +00007680 // Combine Indices - If the source pointer to this getelementptr instruction
7681 // is a getelementptr instruction, combine the indices of the two
7682 // getelementptr instructions into a single instruction.
7683 //
Chris Lattner57c67b02004-03-25 22:59:29 +00007684 std::vector<Value*> SrcGEPOperands;
Chris Lattner0798af32005-01-13 20:14:25 +00007685 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattner57c67b02004-03-25 22:59:29 +00007686 SrcGEPOperands.assign(Src->op_begin(), Src->op_end());
Chris Lattner57c67b02004-03-25 22:59:29 +00007687
7688 if (!SrcGEPOperands.empty()) {
Chris Lattner5f667a62004-05-07 22:09:22 +00007689 // Note that if our source is a gep chain itself that we wait for that
7690 // chain to be resolved before we perform this transformation. This
7691 // avoids us creating a TON of code in some cases.
7692 //
7693 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
7694 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
7695 return 0; // Wait until our source is folded to completion.
7696
Chris Lattnerae7a0d32002-08-02 19:29:35 +00007697 std::vector<Value *> Indices;
Chris Lattner5f667a62004-05-07 22:09:22 +00007698
7699 // Find out whether the last index in the source GEP is a sequential idx.
7700 bool EndsWithSequential = false;
7701 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
7702 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattner8ec5f882004-05-08 22:41:42 +00007703 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00007704
Chris Lattnerae7a0d32002-08-02 19:29:35 +00007705 // Can we combine the two pointer arithmetics offsets?
Chris Lattner5f667a62004-05-07 22:09:22 +00007706 if (EndsWithSequential) {
Chris Lattner235af562003-03-05 22:33:14 +00007707 // Replace: gep (gep %P, long B), long A, ...
7708 // With: T = long A+B; gep %P, T, ...
7709 //
Chris Lattner5f667a62004-05-07 22:09:22 +00007710 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner69193f92004-04-05 01:30:19 +00007711 if (SO1 == Constant::getNullValue(SO1->getType())) {
7712 Sum = GO1;
7713 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
7714 Sum = SO1;
7715 } else {
7716 // If they aren't the same type, convert both to an integer of the
7717 // target's pointer size.
7718 if (SO1->getType() != GO1->getType()) {
7719 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00007720 SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
Chris Lattner69193f92004-04-05 01:30:19 +00007721 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00007722 GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
Chris Lattner69193f92004-04-05 01:30:19 +00007723 } else {
7724 unsigned PS = TD->getPointerSize();
Chris Lattner69193f92004-04-05 01:30:19 +00007725 if (SO1->getType()->getPrimitiveSize() == PS) {
7726 // Convert GO1 to SO1's type.
Reid Spencer13bc5d72006-12-12 09:18:51 +00007727 GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
Chris Lattner69193f92004-04-05 01:30:19 +00007728
7729 } else if (GO1->getType()->getPrimitiveSize() == PS) {
7730 // Convert SO1 to GO1's type.
Reid Spencer13bc5d72006-12-12 09:18:51 +00007731 SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
Chris Lattner69193f92004-04-05 01:30:19 +00007732 } else {
7733 const Type *PT = TD->getIntPtrType();
Reid Spencer13bc5d72006-12-12 09:18:51 +00007734 SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
7735 GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
Chris Lattner69193f92004-04-05 01:30:19 +00007736 }
7737 }
7738 }
Chris Lattner5f667a62004-05-07 22:09:22 +00007739 if (isa<Constant>(SO1) && isa<Constant>(GO1))
7740 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
7741 else {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00007742 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
7743 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner5f667a62004-05-07 22:09:22 +00007744 }
Chris Lattner69193f92004-04-05 01:30:19 +00007745 }
Chris Lattner5f667a62004-05-07 22:09:22 +00007746
7747 // Recycle the GEP we already have if possible.
7748 if (SrcGEPOperands.size() == 2) {
7749 GEP.setOperand(0, SrcGEPOperands[0]);
7750 GEP.setOperand(1, Sum);
7751 return &GEP;
7752 } else {
7753 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
7754 SrcGEPOperands.end()-1);
7755 Indices.push_back(Sum);
7756 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
7757 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00007758 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner69193f92004-04-05 01:30:19 +00007759 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00007760 SrcGEPOperands.size() != 1) {
Chris Lattnerae7a0d32002-08-02 19:29:35 +00007761 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattner57c67b02004-03-25 22:59:29 +00007762 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
7763 SrcGEPOperands.end());
Chris Lattnerae7a0d32002-08-02 19:29:35 +00007764 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
7765 }
7766
7767 if (!Indices.empty())
Chris Lattner57c67b02004-03-25 22:59:29 +00007768 return new GetElementPtrInst(SrcGEPOperands[0], Indices, GEP.getName());
Chris Lattnerc59af1d2002-08-17 22:21:59 +00007769
Chris Lattner5f667a62004-05-07 22:09:22 +00007770 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattnerc59af1d2002-08-17 22:21:59 +00007771 // GEP of global variable. If all of the indices for this GEP are
7772 // constants, we can promote this to a constexpr instead of an instruction.
7773
7774 // Scan for nonconstants...
7775 std::vector<Constant*> Indices;
7776 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
7777 for (; I != E && isa<Constant>(*I); ++I)
7778 Indices.push_back(cast<Constant>(*I));
7779
7780 if (I == E) { // If they are all constants...
Chris Lattnerf3edc492004-07-18 18:59:44 +00007781 Constant *CE = ConstantExpr::getGetElementPtr(GV, Indices);
Chris Lattnerc59af1d2002-08-17 22:21:59 +00007782
7783 // Replace all uses of the GEP with the new constexpr...
7784 return ReplaceInstUsesWith(GEP, CE);
7785 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007786 } else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast?
Chris Lattner567b81f2005-09-13 00:40:14 +00007787 if (!isa<PointerType>(X->getType())) {
7788 // Not interesting. Source pointer must be a cast from pointer.
7789 } else if (HasZeroPointerIndex) {
7790 // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
7791 // into : GEP [10 x ubyte]* X, long 0, ...
7792 //
7793 // This occurs when the program declares an array extern like "int X[];"
7794 //
7795 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
7796 const PointerType *XTy = cast<PointerType>(X->getType());
7797 if (const ArrayType *XATy =
7798 dyn_cast<ArrayType>(XTy->getElementType()))
7799 if (const ArrayType *CATy =
7800 dyn_cast<ArrayType>(CPTy->getElementType()))
7801 if (CATy->getElementType() == XATy->getElementType()) {
7802 // At this point, we know that the cast source type is a pointer
7803 // to an array of the same type as the destination pointer
7804 // array. Because the array type is never stepped over (there
7805 // is a leading zero) we can fold the cast into this GEP.
7806 GEP.setOperand(0, X);
7807 return &GEP;
7808 }
7809 } else if (GEP.getNumOperands() == 2) {
7810 // Transform things like:
Chris Lattner2a893292005-09-13 18:36:04 +00007811 // %t = getelementptr ubyte* cast ([2 x int]* %str to uint*), uint %V
7812 // into: %t1 = getelementptr [2 x int*]* %str, int 0, uint %V; cast
Chris Lattner567b81f2005-09-13 00:40:14 +00007813 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
7814 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
7815 if (isa<ArrayType>(SrcElTy) &&
7816 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
7817 TD->getTypeSize(ResElTy)) {
7818 Value *V = InsertNewInstBefore(
Reid Spencerc635f472006-12-31 05:48:39 +00007819 new GetElementPtrInst(X, Constant::getNullValue(Type::Int32Ty),
Chris Lattner567b81f2005-09-13 00:40:14 +00007820 GEP.getOperand(1), GEP.getName()), GEP);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007821 // V and GEP are both pointer types --> BitCast
7822 return new BitCastInst(V, GEP.getType());
Chris Lattner8d0bacb2004-02-22 05:25:17 +00007823 }
Chris Lattner2a893292005-09-13 18:36:04 +00007824
7825 // Transform things like:
7826 // getelementptr sbyte* cast ([100 x double]* X to sbyte*), int %tmp
7827 // (where tmp = 8*tmp2) into:
7828 // getelementptr [100 x double]* %arr, int 0, int %tmp.2
7829
7830 if (isa<ArrayType>(SrcElTy) &&
Reid Spencerc635f472006-12-31 05:48:39 +00007831 (ResElTy == Type::Int8Ty || ResElTy == Type::Int8Ty)) {
Chris Lattner2a893292005-09-13 18:36:04 +00007832 uint64_t ArrayEltSize =
7833 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType());
7834
7835 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
7836 // allow either a mul, shift, or constant here.
7837 Value *NewIdx = 0;
7838 ConstantInt *Scale = 0;
7839 if (ArrayEltSize == 1) {
7840 NewIdx = GEP.getOperand(1);
7841 Scale = ConstantInt::get(NewIdx->getType(), 1);
7842 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Chris Lattnera393e4d2005-09-14 17:32:56 +00007843 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner2a893292005-09-13 18:36:04 +00007844 Scale = CI;
7845 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
7846 if (Inst->getOpcode() == Instruction::Shl &&
7847 isa<ConstantInt>(Inst->getOperand(1))) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00007848 unsigned ShAmt =
7849 cast<ConstantInt>(Inst->getOperand(1))->getZExtValue();
Reid Spencer266e42b2006-12-23 06:05:41 +00007850 Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmt);
Chris Lattner2a893292005-09-13 18:36:04 +00007851 NewIdx = Inst->getOperand(0);
7852 } else if (Inst->getOpcode() == Instruction::Mul &&
7853 isa<ConstantInt>(Inst->getOperand(1))) {
7854 Scale = cast<ConstantInt>(Inst->getOperand(1));
7855 NewIdx = Inst->getOperand(0);
7856 }
7857 }
7858
7859 // If the index will be to exactly the right offset with the scale taken
7860 // out, perform the transformation.
Reid Spencere0fc4df2006-10-20 07:07:24 +00007861 if (Scale && Scale->getZExtValue() % ArrayEltSize == 0) {
Reid Spencerde46e482006-11-02 20:25:50 +00007862 if (isa<ConstantInt>(Scale))
Reid Spencere0fc4df2006-10-20 07:07:24 +00007863 Scale = ConstantInt::get(Scale->getType(),
7864 Scale->getZExtValue() / ArrayEltSize);
7865 if (Scale->getZExtValue() != 1) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00007866 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
7867 true /*SExt*/);
Chris Lattner2a893292005-09-13 18:36:04 +00007868 Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
7869 NewIdx = InsertNewInstBefore(Sc, GEP);
7870 }
7871
7872 // Insert the new GEP instruction.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007873 Instruction *NewGEP =
Reid Spencerc635f472006-12-31 05:48:39 +00007874 new GetElementPtrInst(X, Constant::getNullValue(Type::Int32Ty),
Chris Lattner2a893292005-09-13 18:36:04 +00007875 NewIdx, GEP.getName());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007876 NewGEP = InsertNewInstBefore(NewGEP, GEP);
7877 // The NewGEP must be pointer typed, so must the old one -> BitCast
7878 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner2a893292005-09-13 18:36:04 +00007879 }
7880 }
Chris Lattner8d0bacb2004-02-22 05:25:17 +00007881 }
Chris Lattnerca081252001-12-14 16:52:21 +00007882 }
7883
Chris Lattnerca081252001-12-14 16:52:21 +00007884 return 0;
7885}
7886
Chris Lattner1085bdf2002-11-04 16:18:53 +00007887Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
7888 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
7889 if (AI.isArrayAllocation()) // Check C != 1
Reid Spencere0fc4df2006-10-20 07:07:24 +00007890 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
7891 const Type *NewTy =
7892 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Chris Lattnera2620ac2002-11-09 00:49:43 +00007893 AllocationInst *New = 0;
Chris Lattner1085bdf2002-11-04 16:18:53 +00007894
7895 // Create and insert the replacement instruction...
7896 if (isa<MallocInst>(AI))
Nate Begeman848622f2005-11-05 09:21:28 +00007897 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00007898 else {
7899 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Nate Begeman848622f2005-11-05 09:21:28 +00007900 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00007901 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00007902
7903 InsertNewInstBefore(New, AI);
Misha Brukmanb1c93172005-04-21 23:48:37 +00007904
Chris Lattner1085bdf2002-11-04 16:18:53 +00007905 // Scan to the end of the allocation instructions, to skip over a block of
7906 // allocas if possible...
7907 //
7908 BasicBlock::iterator It = New;
7909 while (isa<AllocationInst>(*It)) ++It;
7910
7911 // Now that I is pointing to the first non-allocation-inst in the block,
7912 // insert our getelementptr instruction...
7913 //
Reid Spencerc635f472006-12-31 05:48:39 +00007914 Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
Chris Lattner809dfac2005-05-04 19:10:26 +00007915 Value *V = new GetElementPtrInst(New, NullIdx, NullIdx,
7916 New->getName()+".sub", It);
Chris Lattner1085bdf2002-11-04 16:18:53 +00007917
7918 // Now make everything use the getelementptr instead of the original
7919 // allocation.
Chris Lattnerabb77c92004-03-19 06:08:10 +00007920 return ReplaceInstUsesWith(AI, V);
Chris Lattner81a7a232004-10-16 18:11:37 +00007921 } else if (isa<UndefValue>(AI.getArraySize())) {
7922 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner1085bdf2002-11-04 16:18:53 +00007923 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00007924
7925 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
7926 // Note that we only do this for alloca's, because malloc should allocate and
7927 // return a unique pointer, even for a zero byte allocation.
Misha Brukmanb1c93172005-04-21 23:48:37 +00007928 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
Chris Lattner49df6ce2004-07-02 22:55:47 +00007929 TD->getTypeSize(AI.getAllocatedType()) == 0)
Chris Lattnerabb77c92004-03-19 06:08:10 +00007930 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
7931
Chris Lattner1085bdf2002-11-04 16:18:53 +00007932 return 0;
7933}
7934
Chris Lattner8427bff2003-12-07 01:24:23 +00007935Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
7936 Value *Op = FI.getOperand(0);
7937
7938 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
7939 if (CastInst *CI = dyn_cast<CastInst>(Op))
7940 if (isa<PointerType>(CI->getOperand(0)->getType())) {
7941 FI.setOperand(0, CI->getOperand(0));
7942 return &FI;
7943 }
7944
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007945 // free undef -> unreachable.
7946 if (isa<UndefValue>(Op)) {
7947 // Insert a new store to null because we cannot modify the CFG here.
Zhou Sheng75b871f2007-01-11 12:24:14 +00007948 new StoreInst(ConstantInt::getTrue(),
Reid Spencer542964f2007-01-11 18:21:29 +00007949 UndefValue::get(PointerType::get(Type::Int1Ty)), &FI);
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007950 return EraseInstFromFunction(FI);
7951 }
7952
Chris Lattnerf3a36602004-02-28 04:57:37 +00007953 // If we have 'free null' delete the instruction. This can happen in stl code
7954 // when lots of inlining happens.
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007955 if (isa<ConstantPointerNull>(Op))
Chris Lattner51ea1272004-02-28 05:22:00 +00007956 return EraseInstFromFunction(FI);
Chris Lattnerf3a36602004-02-28 04:57:37 +00007957
Chris Lattner8427bff2003-12-07 01:24:23 +00007958 return 0;
7959}
7960
7961
Chris Lattner72684fe2005-01-31 05:51:45 +00007962/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Chris Lattner35e24772004-07-13 01:49:43 +00007963static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
7964 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00007965 Value *CastOp = CI->getOperand(0);
Chris Lattner35e24772004-07-13 01:49:43 +00007966
7967 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00007968 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Chris Lattner35e24772004-07-13 01:49:43 +00007969 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00007970
Chris Lattnerebca4762006-04-02 05:37:12 +00007971 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
7972 isa<PackedType>(DestPTy)) {
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00007973 // If the source is an array, the code below will not succeed. Check to
7974 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
7975 // constants.
7976 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
7977 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
7978 if (ASrcTy->getNumElements() != 0) {
Reid Spencerc635f472006-12-31 05:48:39 +00007979 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::Int32Ty));
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00007980 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
7981 SrcTy = cast<PointerType>(CastOp->getType());
7982 SrcPTy = SrcTy->getElementType();
7983 }
7984
Chris Lattnerebca4762006-04-02 05:37:12 +00007985 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
7986 isa<PackedType>(SrcPTy)) &&
Chris Lattnerecfa9b52005-03-29 06:37:47 +00007987 // Do not allow turning this into a load of an integer, which is then
7988 // casted to a pointer, this pessimizes pointer analysis a lot.
7989 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00007990 IC.getTargetData().getTypeSize(SrcPTy) ==
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00007991 IC.getTargetData().getTypeSize(DestPTy)) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00007992
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00007993 // Okay, we are casting from one integer or pointer type to another of
7994 // the same size. Instead of casting the pointer before the load, cast
7995 // the result of the loaded value.
7996 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
7997 CI->getName(),
7998 LI.isVolatile()),LI);
7999 // Now cast the result of the load.
Reid Spencerbb65ebf2006-12-12 23:36:14 +00008000 return new BitCastInst(NewLoad, LI.getType());
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00008001 }
Chris Lattner35e24772004-07-13 01:49:43 +00008002 }
8003 }
8004 return 0;
8005}
8006
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008007/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattnere6f13092004-09-19 19:18:10 +00008008/// from this value cannot trap. If it is not obviously safe to load from the
8009/// specified pointer, we do a quick local scan of the basic block containing
8010/// ScanFrom, to determine if the address is already accessed.
8011static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
8012 // If it is an alloca or global variable, it is always safe to load from.
8013 if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
8014
8015 // Otherwise, be a little bit agressive by scanning the local block where we
8016 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00008017 // from/to. If so, the previous load or store would have already trapped,
8018 // so there is no harm doing an extra load (also, CSE will later eliminate
8019 // the load entirely).
Chris Lattnere6f13092004-09-19 19:18:10 +00008020 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
8021
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00008022 while (BBI != E) {
Chris Lattnere6f13092004-09-19 19:18:10 +00008023 --BBI;
8024
8025 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
8026 if (LI->getOperand(0) == V) return true;
8027 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
8028 if (SI->getOperand(1) == V) return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +00008029
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00008030 }
Chris Lattnere6f13092004-09-19 19:18:10 +00008031 return false;
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008032}
8033
Chris Lattner0f1d8a32003-06-26 05:06:25 +00008034Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
8035 Value *Op = LI.getOperand(0);
Chris Lattner7e8af382004-01-12 04:13:56 +00008036
Chris Lattnera9d84e32005-05-01 04:24:53 +00008037 // load (cast X) --> cast (load X) iff safe
Reid Spencerde46e482006-11-02 20:25:50 +00008038 if (isa<CastInst>(Op))
Chris Lattnera9d84e32005-05-01 04:24:53 +00008039 if (Instruction *Res = InstCombineLoadCast(*this, LI))
8040 return Res;
8041
8042 // None of the following transforms are legal for volatile loads.
8043 if (LI.isVolatile()) return 0;
Chris Lattnerb990f7d2005-09-12 22:00:15 +00008044
Chris Lattnerb990f7d2005-09-12 22:00:15 +00008045 if (&LI.getParent()->front() != &LI) {
8046 BasicBlock::iterator BBI = &LI; --BBI;
Chris Lattnere0bfdf12005-09-12 22:21:03 +00008047 // If the instruction immediately before this is a store to the same
8048 // address, do a simple form of store->load forwarding.
Chris Lattnerb990f7d2005-09-12 22:00:15 +00008049 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
8050 if (SI->getOperand(1) == LI.getOperand(0))
8051 return ReplaceInstUsesWith(LI, SI->getOperand(0));
Chris Lattnere0bfdf12005-09-12 22:21:03 +00008052 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
8053 if (LIB->getOperand(0) == LI.getOperand(0))
8054 return ReplaceInstUsesWith(LI, LIB);
Chris Lattnerb990f7d2005-09-12 22:00:15 +00008055 }
Chris Lattnera9d84e32005-05-01 04:24:53 +00008056
8057 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op))
8058 if (isa<ConstantPointerNull>(GEPI->getOperand(0)) ||
8059 isa<UndefValue>(GEPI->getOperand(0))) {
8060 // Insert a new store to null instruction before the load to indicate
8061 // that this code is not reachable. We do this instead of inserting
8062 // an unreachable instruction directly because we cannot modify the
8063 // CFG.
8064 new StoreInst(UndefValue::get(LI.getType()),
8065 Constant::getNullValue(Op->getType()), &LI);
8066 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
8067 }
8068
Chris Lattner81a7a232004-10-16 18:11:37 +00008069 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattnera9d84e32005-05-01 04:24:53 +00008070 // load null/undef -> undef
8071 if ((C->isNullValue() || isa<UndefValue>(C))) {
Chris Lattner8ba9ec92004-10-18 02:59:09 +00008072 // Insert a new store to null instruction before the load to indicate that
8073 // this code is not reachable. We do this instead of inserting an
8074 // unreachable instruction directly because we cannot modify the CFG.
Chris Lattnera9d84e32005-05-01 04:24:53 +00008075 new StoreInst(UndefValue::get(LI.getType()),
8076 Constant::getNullValue(Op->getType()), &LI);
Chris Lattner81a7a232004-10-16 18:11:37 +00008077 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner8ba9ec92004-10-18 02:59:09 +00008078 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00008079
Chris Lattner81a7a232004-10-16 18:11:37 +00008080 // Instcombine load (constant global) into the value loaded.
8081 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
8082 if (GV->isConstant() && !GV->isExternal())
8083 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanb1c93172005-04-21 23:48:37 +00008084
Chris Lattner81a7a232004-10-16 18:11:37 +00008085 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
8086 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
8087 if (CE->getOpcode() == Instruction::GetElementPtr) {
8088 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
8089 if (GV->isConstant() && !GV->isExternal())
Chris Lattner0b011ec2005-09-26 05:28:06 +00008090 if (Constant *V =
8091 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
Chris Lattner81a7a232004-10-16 18:11:37 +00008092 return ReplaceInstUsesWith(LI, V);
Chris Lattnera9d84e32005-05-01 04:24:53 +00008093 if (CE->getOperand(0)->isNullValue()) {
8094 // Insert a new store to null instruction before the load to indicate
8095 // that this code is not reachable. We do this instead of inserting
8096 // an unreachable instruction directly because we cannot modify the
8097 // CFG.
8098 new StoreInst(UndefValue::get(LI.getType()),
8099 Constant::getNullValue(Op->getType()), &LI);
8100 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
8101 }
8102
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008103 } else if (CE->isCast()) {
Chris Lattner81a7a232004-10-16 18:11:37 +00008104 if (Instruction *Res = InstCombineLoadCast(*this, LI))
8105 return Res;
8106 }
8107 }
Chris Lattnere228ee52004-04-08 20:39:49 +00008108
Chris Lattnera9d84e32005-05-01 04:24:53 +00008109 if (Op->hasOneUse()) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008110 // Change select and PHI nodes to select values instead of addresses: this
8111 // helps alias analysis out a lot, allows many others simplifications, and
8112 // exposes redundancy in the code.
8113 //
8114 // Note that we cannot do the transformation unless we know that the
8115 // introduced loads cannot trap! Something like this is valid as long as
8116 // the condition is always false: load (select bool %C, int* null, int* %G),
8117 // but it would not be valid if we transformed it to load from null
8118 // unconditionally.
8119 //
8120 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
8121 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattnere6f13092004-09-19 19:18:10 +00008122 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
8123 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008124 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner42618552004-09-20 10:15:10 +00008125 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008126 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner42618552004-09-20 10:15:10 +00008127 SI->getOperand(2)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008128 return new SelectInst(SI->getCondition(), V1, V2);
8129 }
8130
Chris Lattnerbdcf41a2004-09-23 15:46:00 +00008131 // load (select (cond, null, P)) -> load P
8132 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
8133 if (C->isNullValue()) {
8134 LI.setOperand(0, SI->getOperand(2));
8135 return &LI;
8136 }
8137
8138 // load (select (cond, P, null)) -> load P
8139 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
8140 if (C->isNullValue()) {
8141 LI.setOperand(0, SI->getOperand(1));
8142 return &LI;
8143 }
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00008144 }
8145 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00008146 return 0;
8147}
8148
Chris Lattner72684fe2005-01-31 05:51:45 +00008149/// InstCombineStoreToCast - Fold 'store V, (cast P)' -> store (cast V), P'
8150/// when possible.
8151static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
8152 User *CI = cast<User>(SI.getOperand(1));
8153 Value *CastOp = CI->getOperand(0);
8154
8155 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
8156 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
8157 const Type *SrcPTy = SrcTy->getElementType();
8158
8159 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
8160 // If the source is an array, the code below will not succeed. Check to
8161 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
8162 // constants.
8163 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
8164 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
8165 if (ASrcTy->getNumElements() != 0) {
Reid Spencerc635f472006-12-31 05:48:39 +00008166 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::Int32Ty));
Chris Lattner72684fe2005-01-31 05:51:45 +00008167 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
8168 SrcTy = cast<PointerType>(CastOp->getType());
8169 SrcPTy = SrcTy->getElementType();
8170 }
8171
8172 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00008173 IC.getTargetData().getTypeSize(SrcPTy) ==
Chris Lattner72684fe2005-01-31 05:51:45 +00008174 IC.getTargetData().getTypeSize(DestPTy)) {
8175
8176 // Okay, we are casting from one integer or pointer type to another of
8177 // the same size. Instead of casting the pointer before the store, cast
8178 // the value to be stored.
8179 Value *NewCast;
Reid Spencerbb65ebf2006-12-12 23:36:14 +00008180 Instruction::CastOps opcode = Instruction::BitCast;
8181 Value *SIOp0 = SI.getOperand(0);
Reid Spencer74a528b2006-12-13 18:21:21 +00008182 if (isa<PointerType>(SrcPTy)) {
Reid Spencerbb65ebf2006-12-12 23:36:14 +00008183 if (SIOp0->getType()->isIntegral())
8184 opcode = Instruction::IntToPtr;
8185 } else if (SrcPTy->isIntegral()) {
Reid Spencer74a528b2006-12-13 18:21:21 +00008186 if (isa<PointerType>(SIOp0->getType()))
Reid Spencerbb65ebf2006-12-12 23:36:14 +00008187 opcode = Instruction::PtrToInt;
8188 }
8189 if (Constant *C = dyn_cast<Constant>(SIOp0))
8190 NewCast = ConstantExpr::getCast(opcode, C, SrcPTy);
Chris Lattner72684fe2005-01-31 05:51:45 +00008191 else
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008192 NewCast = IC.InsertNewInstBefore(
Reid Spencerbb65ebf2006-12-12 23:36:14 +00008193 CastInst::create(opcode, SIOp0, SrcPTy, SIOp0->getName()+".c"), SI);
Chris Lattner72684fe2005-01-31 05:51:45 +00008194 return new StoreInst(NewCast, CastOp);
8195 }
8196 }
8197 }
8198 return 0;
8199}
8200
Chris Lattner31f486c2005-01-31 05:36:43 +00008201Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
8202 Value *Val = SI.getOperand(0);
8203 Value *Ptr = SI.getOperand(1);
8204
8205 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner5997cf92006-02-08 03:25:32 +00008206 EraseInstFromFunction(SI);
Chris Lattner31f486c2005-01-31 05:36:43 +00008207 ++NumCombined;
8208 return 0;
8209 }
8210
Chris Lattner5997cf92006-02-08 03:25:32 +00008211 // Do really simple DSE, to catch cases where there are several consequtive
8212 // stores to the same location, separated by a few arithmetic operations. This
8213 // situation often occurs with bitfield accesses.
8214 BasicBlock::iterator BBI = &SI;
8215 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
8216 --ScanInsts) {
8217 --BBI;
8218
8219 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
8220 // Prev store isn't volatile, and stores to the same location?
8221 if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
8222 ++NumDeadStore;
8223 ++BBI;
8224 EraseInstFromFunction(*PrevSI);
8225 continue;
8226 }
8227 break;
8228 }
8229
Chris Lattnerdab43b22006-05-26 19:19:20 +00008230 // If this is a load, we have to stop. However, if the loaded value is from
8231 // the pointer we're loading and is producing the pointer we're storing,
8232 // then *this* store is dead (X = load P; store X -> P).
8233 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
8234 if (LI == Val && LI->getOperand(0) == Ptr) {
8235 EraseInstFromFunction(SI);
8236 ++NumCombined;
8237 return 0;
8238 }
8239 // Otherwise, this is a load from some other location. Stores before it
8240 // may not be dead.
8241 break;
8242 }
8243
Chris Lattner5997cf92006-02-08 03:25:32 +00008244 // Don't skip over loads or things that can modify memory.
Chris Lattnerdab43b22006-05-26 19:19:20 +00008245 if (BBI->mayWriteToMemory())
Chris Lattner5997cf92006-02-08 03:25:32 +00008246 break;
8247 }
8248
8249
8250 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner31f486c2005-01-31 05:36:43 +00008251
8252 // store X, null -> turns into 'unreachable' in SimplifyCFG
8253 if (isa<ConstantPointerNull>(Ptr)) {
8254 if (!isa<UndefValue>(Val)) {
8255 SI.setOperand(0, UndefValue::get(Val->getType()));
8256 if (Instruction *U = dyn_cast<Instruction>(Val))
8257 WorkList.push_back(U); // Dropped a use.
8258 ++NumCombined;
8259 }
8260 return 0; // Do not modify these!
8261 }
8262
8263 // store undef, Ptr -> noop
8264 if (isa<UndefValue>(Val)) {
Chris Lattner5997cf92006-02-08 03:25:32 +00008265 EraseInstFromFunction(SI);
Chris Lattner31f486c2005-01-31 05:36:43 +00008266 ++NumCombined;
8267 return 0;
8268 }
8269
Chris Lattner72684fe2005-01-31 05:51:45 +00008270 // If the pointer destination is a cast, see if we can fold the cast into the
8271 // source instead.
Reid Spencerde46e482006-11-02 20:25:50 +00008272 if (isa<CastInst>(Ptr))
Chris Lattner72684fe2005-01-31 05:51:45 +00008273 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
8274 return Res;
8275 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008276 if (CE->isCast())
Chris Lattner72684fe2005-01-31 05:51:45 +00008277 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
8278 return Res;
8279
Chris Lattner219175c2005-09-12 23:23:25 +00008280
8281 // If this store is the last instruction in the basic block, and if the block
8282 // ends with an unconditional branch, try to move it to the successor block.
Chris Lattner5997cf92006-02-08 03:25:32 +00008283 BBI = &SI; ++BBI;
Chris Lattner219175c2005-09-12 23:23:25 +00008284 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
8285 if (BI->isUnconditional()) {
8286 // Check to see if the successor block has exactly two incoming edges. If
8287 // so, see if the other predecessor contains a store to the same location.
8288 // if so, insert a PHI node (if needed) and move the stores down.
8289 BasicBlock *Dest = BI->getSuccessor(0);
8290
8291 pred_iterator PI = pred_begin(Dest);
8292 BasicBlock *Other = 0;
8293 if (*PI != BI->getParent())
8294 Other = *PI;
8295 ++PI;
8296 if (PI != pred_end(Dest)) {
8297 if (*PI != BI->getParent())
8298 if (Other)
8299 Other = 0;
8300 else
8301 Other = *PI;
8302 if (++PI != pred_end(Dest))
8303 Other = 0;
8304 }
8305 if (Other) { // If only one other pred...
8306 BBI = Other->getTerminator();
8307 // Make sure this other block ends in an unconditional branch and that
8308 // there is an instruction before the branch.
8309 if (isa<BranchInst>(BBI) && cast<BranchInst>(BBI)->isUnconditional() &&
8310 BBI != Other->begin()) {
8311 --BBI;
8312 StoreInst *OtherStore = dyn_cast<StoreInst>(BBI);
8313
8314 // If this instruction is a store to the same location.
8315 if (OtherStore && OtherStore->getOperand(1) == SI.getOperand(1)) {
8316 // Okay, we know we can perform this transformation. Insert a PHI
8317 // node now if we need it.
8318 Value *MergedVal = OtherStore->getOperand(0);
8319 if (MergedVal != SI.getOperand(0)) {
8320 PHINode *PN = new PHINode(MergedVal->getType(), "storemerge");
8321 PN->reserveOperandSpace(2);
8322 PN->addIncoming(SI.getOperand(0), SI.getParent());
8323 PN->addIncoming(OtherStore->getOperand(0), Other);
8324 MergedVal = InsertNewInstBefore(PN, Dest->front());
8325 }
8326
8327 // Advance to a place where it is safe to insert the new store and
8328 // insert it.
8329 BBI = Dest->begin();
8330 while (isa<PHINode>(BBI)) ++BBI;
8331 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
8332 OtherStore->isVolatile()), *BBI);
8333
8334 // Nuke the old stores.
Chris Lattner5997cf92006-02-08 03:25:32 +00008335 EraseInstFromFunction(SI);
8336 EraseInstFromFunction(*OtherStore);
Chris Lattner219175c2005-09-12 23:23:25 +00008337 ++NumCombined;
8338 return 0;
8339 }
8340 }
8341 }
8342 }
8343
Chris Lattner31f486c2005-01-31 05:36:43 +00008344 return 0;
8345}
8346
8347
Chris Lattner9eef8a72003-06-04 04:46:00 +00008348Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
8349 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4fdd96c2005-06-18 17:37:34 +00008350 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00008351 BasicBlock *TrueDest;
8352 BasicBlock *FalseDest;
8353 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
8354 !isa<Constant>(X)) {
8355 // Swap Destinations and condition...
8356 BI.setCondition(X);
8357 BI.setSuccessor(0, FalseDest);
8358 BI.setSuccessor(1, TrueDest);
8359 return &BI;
8360 }
8361
Reid Spencer266e42b2006-12-23 06:05:41 +00008362 // Cannonicalize fcmp_one -> fcmp_oeq
8363 FCmpInst::Predicate FPred; Value *Y;
8364 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
8365 TrueDest, FalseDest)))
8366 if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
8367 FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
8368 FCmpInst *I = cast<FCmpInst>(BI.getCondition());
Chris Lattnerd4252a72004-07-30 07:50:03 +00008369 std::string Name = I->getName(); I->setName("");
Reid Spencer266e42b2006-12-23 06:05:41 +00008370 FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
8371 Value *NewSCC = new FCmpInst(NewPred, X, Y, Name, I);
8372 // Swap Destinations and condition...
8373 BI.setCondition(NewSCC);
8374 BI.setSuccessor(0, FalseDest);
8375 BI.setSuccessor(1, TrueDest);
8376 removeFromWorkList(I);
8377 I->getParent()->getInstList().erase(I);
8378 WorkList.push_back(cast<Instruction>(NewSCC));
8379 return &BI;
8380 }
8381
8382 // Cannonicalize icmp_ne -> icmp_eq
8383 ICmpInst::Predicate IPred;
8384 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
8385 TrueDest, FalseDest)))
8386 if ((IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
8387 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
8388 IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
8389 ICmpInst *I = cast<ICmpInst>(BI.getCondition());
8390 std::string Name = I->getName(); I->setName("");
8391 ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
8392 Value *NewSCC = new ICmpInst(NewPred, X, Y, Name, I);
Chris Lattnere967b342003-06-04 05:10:11 +00008393 // Swap Destinations and condition...
Chris Lattnerd4252a72004-07-30 07:50:03 +00008394 BI.setCondition(NewSCC);
Chris Lattnere967b342003-06-04 05:10:11 +00008395 BI.setSuccessor(0, FalseDest);
8396 BI.setSuccessor(1, TrueDest);
Chris Lattnerd4252a72004-07-30 07:50:03 +00008397 removeFromWorkList(I);
8398 I->getParent()->getInstList().erase(I);
8399 WorkList.push_back(cast<Instruction>(NewSCC));
Chris Lattnere967b342003-06-04 05:10:11 +00008400 return &BI;
8401 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00008402
Chris Lattner9eef8a72003-06-04 04:46:00 +00008403 return 0;
8404}
Chris Lattner1085bdf2002-11-04 16:18:53 +00008405
Chris Lattner4c9c20a2004-07-03 00:26:11 +00008406Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
8407 Value *Cond = SI.getCondition();
8408 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
8409 if (I->getOpcode() == Instruction::Add)
8410 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
8411 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
8412 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattner81a7a232004-10-16 18:11:37 +00008413 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner4c9c20a2004-07-03 00:26:11 +00008414 AddRHS));
8415 SI.setOperand(0, I->getOperand(0));
8416 WorkList.push_back(I);
8417 return &SI;
8418 }
8419 }
8420 return 0;
8421}
8422
Chris Lattner6bc98652006-03-05 00:22:33 +00008423/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
8424/// is to leave as a vector operation.
8425static bool CheapToScalarize(Value *V, bool isConstant) {
8426 if (isa<ConstantAggregateZero>(V))
8427 return true;
8428 if (ConstantPacked *C = dyn_cast<ConstantPacked>(V)) {
8429 if (isConstant) return true;
8430 // If all elts are the same, we can extract.
8431 Constant *Op0 = C->getOperand(0);
8432 for (unsigned i = 1; i < C->getNumOperands(); ++i)
8433 if (C->getOperand(i) != Op0)
8434 return false;
8435 return true;
8436 }
8437 Instruction *I = dyn_cast<Instruction>(V);
8438 if (!I) return false;
8439
8440 // Insert element gets simplified to the inserted element or is deleted if
8441 // this is constant idx extract element and its a constant idx insertelt.
8442 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
8443 isa<ConstantInt>(I->getOperand(2)))
8444 return true;
8445 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
8446 return true;
8447 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
8448 if (BO->hasOneUse() &&
8449 (CheapToScalarize(BO->getOperand(0), isConstant) ||
8450 CheapToScalarize(BO->getOperand(1), isConstant)))
8451 return true;
Reid Spencer266e42b2006-12-23 06:05:41 +00008452 if (CmpInst *CI = dyn_cast<CmpInst>(I))
8453 if (CI->hasOneUse() &&
8454 (CheapToScalarize(CI->getOperand(0), isConstant) ||
8455 CheapToScalarize(CI->getOperand(1), isConstant)))
8456 return true;
Chris Lattner6bc98652006-03-05 00:22:33 +00008457
8458 return false;
8459}
8460
Chris Lattner12249be2006-05-25 23:48:38 +00008461/// getShuffleMask - Read and decode a shufflevector mask. It turns undef
8462/// elements into values that are larger than the #elts in the input.
8463static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
8464 unsigned NElts = SVI->getType()->getNumElements();
8465 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
8466 return std::vector<unsigned>(NElts, 0);
8467 if (isa<UndefValue>(SVI->getOperand(2)))
8468 return std::vector<unsigned>(NElts, 2*NElts);
8469
8470 std::vector<unsigned> Result;
8471 const ConstantPacked *CP = cast<ConstantPacked>(SVI->getOperand(2));
8472 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
8473 if (isa<UndefValue>(CP->getOperand(i)))
8474 Result.push_back(NElts*2); // undef -> 8
8475 else
Reid Spencere0fc4df2006-10-20 07:07:24 +00008476 Result.push_back(cast<ConstantInt>(CP->getOperand(i))->getZExtValue());
Chris Lattner12249be2006-05-25 23:48:38 +00008477 return Result;
8478}
8479
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008480/// FindScalarElement - Given a vector and an element number, see if the scalar
8481/// value is already around as a register, for example if it were inserted then
8482/// extracted from the vector.
8483static Value *FindScalarElement(Value *V, unsigned EltNo) {
8484 assert(isa<PackedType>(V->getType()) && "Not looking at a vector?");
8485 const PackedType *PTy = cast<PackedType>(V->getType());
Chris Lattner2d37f922006-04-10 23:06:36 +00008486 unsigned Width = PTy->getNumElements();
8487 if (EltNo >= Width) // Out of range access.
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008488 return UndefValue::get(PTy->getElementType());
8489
8490 if (isa<UndefValue>(V))
8491 return UndefValue::get(PTy->getElementType());
8492 else if (isa<ConstantAggregateZero>(V))
8493 return Constant::getNullValue(PTy->getElementType());
8494 else if (ConstantPacked *CP = dyn_cast<ConstantPacked>(V))
8495 return CP->getOperand(EltNo);
8496 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
8497 // If this is an insert to a variable element, we don't know what it is.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008498 if (!isa<ConstantInt>(III->getOperand(2)))
8499 return 0;
8500 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008501
8502 // If this is an insert to the element we are looking for, return the
8503 // inserted value.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008504 if (EltNo == IIElt)
8505 return III->getOperand(1);
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008506
8507 // Otherwise, the insertelement doesn't modify the value, recurse on its
8508 // vector input.
8509 return FindScalarElement(III->getOperand(0), EltNo);
Chris Lattner2d37f922006-04-10 23:06:36 +00008510 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Chris Lattner12249be2006-05-25 23:48:38 +00008511 unsigned InEl = getShuffleMask(SVI)[EltNo];
8512 if (InEl < Width)
8513 return FindScalarElement(SVI->getOperand(0), InEl);
8514 else if (InEl < Width*2)
8515 return FindScalarElement(SVI->getOperand(1), InEl - Width);
8516 else
8517 return UndefValue::get(PTy->getElementType());
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008518 }
8519
8520 // Otherwise, we don't know.
8521 return 0;
8522}
8523
Robert Bocchinoa8352962006-01-13 22:48:06 +00008524Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008525
Chris Lattner92346c32006-03-31 18:25:14 +00008526 // If packed val is undef, replace extract with scalar undef.
8527 if (isa<UndefValue>(EI.getOperand(0)))
8528 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
8529
8530 // If packed val is constant 0, replace extract with scalar 0.
8531 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
8532 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
8533
Robert Bocchinoa8352962006-01-13 22:48:06 +00008534 if (ConstantPacked *C = dyn_cast<ConstantPacked>(EI.getOperand(0))) {
8535 // If packed val is constant with uniform operands, replace EI
8536 // with that operand
Chris Lattner6bc98652006-03-05 00:22:33 +00008537 Constant *op0 = C->getOperand(0);
Robert Bocchinoa8352962006-01-13 22:48:06 +00008538 for (unsigned i = 1; i < C->getNumOperands(); ++i)
Chris Lattner6bc98652006-03-05 00:22:33 +00008539 if (C->getOperand(i) != op0) {
8540 op0 = 0;
8541 break;
8542 }
8543 if (op0)
8544 return ReplaceInstUsesWith(EI, op0);
Robert Bocchinoa8352962006-01-13 22:48:06 +00008545 }
Chris Lattner6bc98652006-03-05 00:22:33 +00008546
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008547 // If extracting a specified index from the vector, see if we can recursively
8548 // find a previously computed scalar that was inserted into the vector.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008549 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Chris Lattner2deeaea2006-10-05 06:55:50 +00008550 // This instruction only demands the single element from the input vector.
8551 // If the input vector has a single use, simplify it based on this use
8552 // property.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008553 uint64_t IndexVal = IdxC->getZExtValue();
Chris Lattner2deeaea2006-10-05 06:55:50 +00008554 if (EI.getOperand(0)->hasOneUse()) {
8555 uint64_t UndefElts;
8556 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Reid Spencere0fc4df2006-10-20 07:07:24 +00008557 1 << IndexVal,
Chris Lattner2deeaea2006-10-05 06:55:50 +00008558 UndefElts)) {
8559 EI.setOperand(0, V);
8560 return &EI;
8561 }
8562 }
8563
Reid Spencere0fc4df2006-10-20 07:07:24 +00008564 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008565 return ReplaceInstUsesWith(EI, Elt);
Chris Lattner2d37f922006-04-10 23:06:36 +00008566 }
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008567
Chris Lattner83f65782006-05-25 22:53:38 +00008568 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Robert Bocchinoa8352962006-01-13 22:48:06 +00008569 if (I->hasOneUse()) {
8570 // Push extractelement into predecessor operation if legal and
8571 // profitable to do so
8572 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Chris Lattner6bc98652006-03-05 00:22:33 +00008573 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
8574 if (CheapToScalarize(BO, isConstantElt)) {
8575 ExtractElementInst *newEI0 =
8576 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
8577 EI.getName()+".lhs");
8578 ExtractElementInst *newEI1 =
8579 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
8580 EI.getName()+".rhs");
8581 InsertNewInstBefore(newEI0, EI);
8582 InsertNewInstBefore(newEI1, EI);
8583 return BinaryOperator::create(BO->getOpcode(), newEI0, newEI1);
8584 }
Reid Spencerde46e482006-11-02 20:25:50 +00008585 } else if (isa<LoadInst>(I)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00008586 Value *Ptr = InsertCastBefore(Instruction::BitCast, I->getOperand(0),
Robert Bocchinoa8352962006-01-13 22:48:06 +00008587 PointerType::get(EI.getType()), EI);
8588 GetElementPtrInst *GEP =
Reid Spencera736fdf2006-11-29 01:11:01 +00008589 new GetElementPtrInst(Ptr, EI.getOperand(1), I->getName() + ".gep");
Robert Bocchinoa8352962006-01-13 22:48:06 +00008590 InsertNewInstBefore(GEP, EI);
8591 return new LoadInst(GEP);
Chris Lattner83f65782006-05-25 22:53:38 +00008592 }
8593 }
8594 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
8595 // Extracting the inserted element?
8596 if (IE->getOperand(2) == EI.getOperand(1))
8597 return ReplaceInstUsesWith(EI, IE->getOperand(1));
8598 // If the inserted and extracted elements are constants, they must not
8599 // be the same value, extract from the pre-inserted value instead.
8600 if (isa<Constant>(IE->getOperand(2)) &&
8601 isa<Constant>(EI.getOperand(1))) {
8602 AddUsesToWorkList(EI);
8603 EI.setOperand(0, IE->getOperand(0));
8604 return &EI;
8605 }
8606 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
8607 // If this is extracting an element from a shufflevector, figure out where
8608 // it came from and extract from the appropriate input element instead.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008609 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
8610 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
Chris Lattner12249be2006-05-25 23:48:38 +00008611 Value *Src;
8612 if (SrcIdx < SVI->getType()->getNumElements())
8613 Src = SVI->getOperand(0);
8614 else if (SrcIdx < SVI->getType()->getNumElements()*2) {
8615 SrcIdx -= SVI->getType()->getNumElements();
8616 Src = SVI->getOperand(1);
8617 } else {
8618 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattner612fa8e2006-03-30 22:02:40 +00008619 }
Chris Lattner2deeaea2006-10-05 06:55:50 +00008620 return new ExtractElementInst(Src, SrcIdx);
Robert Bocchinoa8352962006-01-13 22:48:06 +00008621 }
8622 }
Chris Lattner83f65782006-05-25 22:53:38 +00008623 }
Robert Bocchinoa8352962006-01-13 22:48:06 +00008624 return 0;
8625}
8626
Chris Lattner90951862006-04-16 00:51:47 +00008627/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
8628/// elements from either LHS or RHS, return the shuffle mask and true.
8629/// Otherwise, return false.
8630static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
8631 std::vector<Constant*> &Mask) {
8632 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
8633 "Invalid CollectSingleShuffleElements");
8634 unsigned NumElts = cast<PackedType>(V->getType())->getNumElements();
8635
8636 if (isa<UndefValue>(V)) {
Reid Spencerc635f472006-12-31 05:48:39 +00008637 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattner90951862006-04-16 00:51:47 +00008638 return true;
8639 } else if (V == LHS) {
8640 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc635f472006-12-31 05:48:39 +00008641 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattner90951862006-04-16 00:51:47 +00008642 return true;
8643 } else if (V == RHS) {
8644 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc635f472006-12-31 05:48:39 +00008645 Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
Chris Lattner90951862006-04-16 00:51:47 +00008646 return true;
8647 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
8648 // If this is an insert of an extract from some other vector, include it.
8649 Value *VecOp = IEI->getOperand(0);
8650 Value *ScalarOp = IEI->getOperand(1);
8651 Value *IdxOp = IEI->getOperand(2);
8652
Chris Lattnerb6cb64b2006-04-27 21:14:21 +00008653 if (!isa<ConstantInt>(IdxOp))
8654 return false;
Reid Spencere0fc4df2006-10-20 07:07:24 +00008655 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerb6cb64b2006-04-27 21:14:21 +00008656
8657 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
8658 // Okay, we can handle this if the vector we are insertinting into is
8659 // transitively ok.
8660 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
8661 // If so, update the mask to reflect the inserted undef.
Reid Spencerc635f472006-12-31 05:48:39 +00008662 Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
Chris Lattnerb6cb64b2006-04-27 21:14:21 +00008663 return true;
8664 }
8665 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
8666 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner90951862006-04-16 00:51:47 +00008667 EI->getOperand(0)->getType() == V->getType()) {
8668 unsigned ExtractedIdx =
Reid Spencere0fc4df2006-10-20 07:07:24 +00008669 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattner90951862006-04-16 00:51:47 +00008670
8671 // This must be extracting from either LHS or RHS.
8672 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
8673 // Okay, we can handle this if the vector we are insertinting into is
8674 // transitively ok.
8675 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
8676 // If so, update the mask to reflect the inserted value.
8677 if (EI->getOperand(0) == LHS) {
8678 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc635f472006-12-31 05:48:39 +00008679 ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattner90951862006-04-16 00:51:47 +00008680 } else {
8681 assert(EI->getOperand(0) == RHS);
8682 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc635f472006-12-31 05:48:39 +00008683 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
Chris Lattner90951862006-04-16 00:51:47 +00008684
8685 }
8686 return true;
8687 }
8688 }
8689 }
8690 }
8691 }
8692 // TODO: Handle shufflevector here!
8693
8694 return false;
8695}
8696
8697/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
8698/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
8699/// that computes V and the LHS value of the shuffle.
Chris Lattner39fac442006-04-15 01:39:45 +00008700static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Chris Lattner90951862006-04-16 00:51:47 +00008701 Value *&RHS) {
8702 assert(isa<PackedType>(V->getType()) &&
8703 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattner39fac442006-04-15 01:39:45 +00008704 "Invalid shuffle!");
8705 unsigned NumElts = cast<PackedType>(V->getType())->getNumElements();
8706
8707 if (isa<UndefValue>(V)) {
Reid Spencerc635f472006-12-31 05:48:39 +00008708 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattner39fac442006-04-15 01:39:45 +00008709 return V;
8710 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencerc635f472006-12-31 05:48:39 +00008711 Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
Chris Lattner39fac442006-04-15 01:39:45 +00008712 return V;
8713 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
8714 // If this is an insert of an extract from some other vector, include it.
8715 Value *VecOp = IEI->getOperand(0);
8716 Value *ScalarOp = IEI->getOperand(1);
8717 Value *IdxOp = IEI->getOperand(2);
8718
8719 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
8720 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
8721 EI->getOperand(0)->getType() == V->getType()) {
8722 unsigned ExtractedIdx =
Reid Spencere0fc4df2006-10-20 07:07:24 +00008723 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
8724 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattner39fac442006-04-15 01:39:45 +00008725
8726 // Either the extracted from or inserted into vector must be RHSVec,
8727 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner90951862006-04-16 00:51:47 +00008728 if (EI->getOperand(0) == RHS || RHS == 0) {
8729 RHS = EI->getOperand(0);
8730 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
Chris Lattner39fac442006-04-15 01:39:45 +00008731 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc635f472006-12-31 05:48:39 +00008732 ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
Chris Lattner39fac442006-04-15 01:39:45 +00008733 return V;
8734 }
8735
Chris Lattner90951862006-04-16 00:51:47 +00008736 if (VecOp == RHS) {
8737 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
Chris Lattner39fac442006-04-15 01:39:45 +00008738 // Everything but the extracted element is replaced with the RHS.
8739 for (unsigned i = 0; i != NumElts; ++i) {
8740 if (i != InsertedIdx)
Reid Spencerc635f472006-12-31 05:48:39 +00008741 Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
Chris Lattner39fac442006-04-15 01:39:45 +00008742 }
8743 return V;
8744 }
Chris Lattner90951862006-04-16 00:51:47 +00008745
8746 // If this insertelement is a chain that comes from exactly these two
8747 // vectors, return the vector and the effective shuffle.
8748 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
8749 return EI->getOperand(0);
8750
Chris Lattner39fac442006-04-15 01:39:45 +00008751 }
8752 }
8753 }
Chris Lattner90951862006-04-16 00:51:47 +00008754 // TODO: Handle shufflevector here!
Chris Lattner39fac442006-04-15 01:39:45 +00008755
8756 // Otherwise, can't do anything fancy. Return an identity vector.
8757 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc635f472006-12-31 05:48:39 +00008758 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattner39fac442006-04-15 01:39:45 +00008759 return V;
8760}
8761
8762Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
8763 Value *VecOp = IE.getOperand(0);
8764 Value *ScalarOp = IE.getOperand(1);
8765 Value *IdxOp = IE.getOperand(2);
8766
8767 // If the inserted element was extracted from some other vector, and if the
8768 // indexes are constant, try to turn this into a shufflevector operation.
8769 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
8770 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
8771 EI->getOperand(0)->getType() == IE.getType()) {
8772 unsigned NumVectorElts = IE.getType()->getNumElements();
Reid Spencere0fc4df2006-10-20 07:07:24 +00008773 unsigned ExtractedIdx=cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
8774 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattner39fac442006-04-15 01:39:45 +00008775
8776 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
8777 return ReplaceInstUsesWith(IE, VecOp);
8778
8779 if (InsertedIdx >= NumVectorElts) // Out of range insert.
8780 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
8781
8782 // If we are extracting a value from a vector, then inserting it right
8783 // back into the same place, just use the input vector.
8784 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
8785 return ReplaceInstUsesWith(IE, VecOp);
8786
8787 // We could theoretically do this for ANY input. However, doing so could
8788 // turn chains of insertelement instructions into a chain of shufflevector
8789 // instructions, and right now we do not merge shufflevectors. As such,
8790 // only do this in a situation where it is clear that there is benefit.
8791 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
8792 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
8793 // the values of VecOp, except then one read from EIOp0.
8794 // Build a new shuffle mask.
8795 std::vector<Constant*> Mask;
8796 if (isa<UndefValue>(VecOp))
Reid Spencerc635f472006-12-31 05:48:39 +00008797 Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
Chris Lattner39fac442006-04-15 01:39:45 +00008798 else {
8799 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
Reid Spencerc635f472006-12-31 05:48:39 +00008800 Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
Chris Lattner39fac442006-04-15 01:39:45 +00008801 NumVectorElts));
8802 }
Reid Spencerc635f472006-12-31 05:48:39 +00008803 Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattner39fac442006-04-15 01:39:45 +00008804 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
8805 ConstantPacked::get(Mask));
8806 }
8807
8808 // If this insertelement isn't used by some other insertelement, turn it
8809 // (and any insertelements it points to), into one big shuffle.
8810 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
8811 std::vector<Constant*> Mask;
Chris Lattner90951862006-04-16 00:51:47 +00008812 Value *RHS = 0;
8813 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
8814 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
8815 // We now have a shuffle of LHS, RHS, Mask.
8816 return new ShuffleVectorInst(LHS, RHS, ConstantPacked::get(Mask));
Chris Lattner39fac442006-04-15 01:39:45 +00008817 }
8818 }
8819 }
8820
8821 return 0;
8822}
8823
8824
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008825Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
8826 Value *LHS = SVI.getOperand(0);
8827 Value *RHS = SVI.getOperand(1);
Chris Lattner12249be2006-05-25 23:48:38 +00008828 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008829
8830 bool MadeChange = false;
8831
Chris Lattner2deeaea2006-10-05 06:55:50 +00008832 // Undefined shuffle mask -> undefined value.
Chris Lattner12249be2006-05-25 23:48:38 +00008833 if (isa<UndefValue>(SVI.getOperand(2)))
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008834 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
8835
Chris Lattnerd7b6ea12007-01-05 07:36:08 +00008836 // If we have shuffle(x, undef, mask) and any elements of mask refer to
Chris Lattner39fac442006-04-15 01:39:45 +00008837 // the undef, change them to undefs.
Chris Lattnerd7b6ea12007-01-05 07:36:08 +00008838 if (isa<UndefValue>(SVI.getOperand(1))) {
8839 // Scan to see if there are any references to the RHS. If so, replace them
8840 // with undef element refs and set MadeChange to true.
8841 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
8842 if (Mask[i] >= e && Mask[i] != 2*e) {
8843 Mask[i] = 2*e;
8844 MadeChange = true;
8845 }
8846 }
8847
8848 if (MadeChange) {
8849 // Remap any references to RHS to use LHS.
8850 std::vector<Constant*> Elts;
8851 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
8852 if (Mask[i] == 2*e)
8853 Elts.push_back(UndefValue::get(Type::Int32Ty));
8854 else
8855 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
8856 }
8857 SVI.setOperand(2, ConstantPacked::get(Elts));
8858 }
8859 }
Chris Lattner39fac442006-04-15 01:39:45 +00008860
Chris Lattner12249be2006-05-25 23:48:38 +00008861 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
8862 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
8863 if (LHS == RHS || isa<UndefValue>(LHS)) {
8864 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008865 // shuffle(undef,undef,mask) -> undef.
8866 return ReplaceInstUsesWith(SVI, LHS);
8867 }
8868
Chris Lattner12249be2006-05-25 23:48:38 +00008869 // Remap any references to RHS to use LHS.
8870 std::vector<Constant*> Elts;
8871 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner0e477162006-05-26 00:29:06 +00008872 if (Mask[i] >= 2*e)
Reid Spencerc635f472006-12-31 05:48:39 +00008873 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner0e477162006-05-26 00:29:06 +00008874 else {
8875 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
8876 (Mask[i] < e && isa<UndefValue>(LHS)))
8877 Mask[i] = 2*e; // Turn into undef.
8878 else
8879 Mask[i] &= (e-1); // Force to LHS.
Reid Spencerc635f472006-12-31 05:48:39 +00008880 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
Chris Lattner0e477162006-05-26 00:29:06 +00008881 }
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008882 }
Chris Lattner12249be2006-05-25 23:48:38 +00008883 SVI.setOperand(0, SVI.getOperand(1));
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008884 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Chris Lattner12249be2006-05-25 23:48:38 +00008885 SVI.setOperand(2, ConstantPacked::get(Elts));
Chris Lattner0e477162006-05-26 00:29:06 +00008886 LHS = SVI.getOperand(0);
8887 RHS = SVI.getOperand(1);
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008888 MadeChange = true;
8889 }
8890
Chris Lattner0e477162006-05-26 00:29:06 +00008891 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner12249be2006-05-25 23:48:38 +00008892 bool isLHSID = true, isRHSID = true;
Chris Lattner34cebe72006-04-16 00:03:56 +00008893
Chris Lattner12249be2006-05-25 23:48:38 +00008894 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
8895 if (Mask[i] >= e*2) continue; // Ignore undef values.
8896 // Is this an identity shuffle of the LHS value?
8897 isLHSID &= (Mask[i] == i);
8898
8899 // Is this an identity shuffle of the RHS value?
8900 isRHSID &= (Mask[i]-e == i);
Chris Lattner34cebe72006-04-16 00:03:56 +00008901 }
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008902
Chris Lattner12249be2006-05-25 23:48:38 +00008903 // Eliminate identity shuffles.
8904 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
8905 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008906
Chris Lattner0e477162006-05-26 00:29:06 +00008907 // If the LHS is a shufflevector itself, see if we can combine it with this
8908 // one without producing an unusual shuffle. Here we are really conservative:
8909 // we are absolutely afraid of producing a shuffle mask not in the input
8910 // program, because the code gen may not be smart enough to turn a merged
8911 // shuffle into two specific shuffles: it may produce worse code. As such,
8912 // we only merge two shuffles if the result is one of the two input shuffle
8913 // masks. In this case, merging the shuffles just removes one instruction,
8914 // which we know is safe. This is good for things like turning:
8915 // (splat(splat)) -> splat.
8916 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
8917 if (isa<UndefValue>(RHS)) {
8918 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
8919
8920 std::vector<unsigned> NewMask;
8921 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
8922 if (Mask[i] >= 2*e)
8923 NewMask.push_back(2*e);
8924 else
8925 NewMask.push_back(LHSMask[Mask[i]]);
8926
8927 // If the result mask is equal to the src shuffle or this shuffle mask, do
8928 // the replacement.
8929 if (NewMask == LHSMask || NewMask == Mask) {
8930 std::vector<Constant*> Elts;
8931 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
8932 if (NewMask[i] >= e*2) {
Reid Spencerc635f472006-12-31 05:48:39 +00008933 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner0e477162006-05-26 00:29:06 +00008934 } else {
Reid Spencerc635f472006-12-31 05:48:39 +00008935 Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
Chris Lattner0e477162006-05-26 00:29:06 +00008936 }
8937 }
8938 return new ShuffleVectorInst(LHSSVI->getOperand(0),
8939 LHSSVI->getOperand(1),
8940 ConstantPacked::get(Elts));
8941 }
8942 }
8943 }
8944
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008945 return MadeChange ? &SVI : 0;
8946}
8947
8948
Robert Bocchinoa8352962006-01-13 22:48:06 +00008949
Chris Lattner99f48c62002-09-02 04:59:56 +00008950void InstCombiner::removeFromWorkList(Instruction *I) {
8951 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
8952 WorkList.end());
8953}
8954
Chris Lattner39c98bb2004-12-08 23:43:58 +00008955
8956/// TryToSinkInstruction - Try to move the specified instruction from its
8957/// current block into the beginning of DestBlock, which can only happen if it's
8958/// safe to move the instruction past all of the instructions between it and the
8959/// end of its block.
8960static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
8961 assert(I->hasOneUse() && "Invariants didn't hold!");
8962
Chris Lattnerc4f67e62005-10-27 17:13:11 +00008963 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
8964 if (isa<PHINode>(I) || I->mayWriteToMemory()) return false;
Misha Brukmanb1c93172005-04-21 23:48:37 +00008965
Chris Lattner39c98bb2004-12-08 23:43:58 +00008966 // Do not sink alloca instructions out of the entry block.
8967 if (isa<AllocaInst>(I) && I->getParent() == &DestBlock->getParent()->front())
8968 return false;
8969
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00008970 // We can only sink load instructions if there is nothing between the load and
8971 // the end of block that could change the value.
8972 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00008973 for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
8974 Scan != E; ++Scan)
8975 if (Scan->mayWriteToMemory())
8976 return false;
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00008977 }
Chris Lattner39c98bb2004-12-08 23:43:58 +00008978
8979 BasicBlock::iterator InsertPos = DestBlock->begin();
8980 while (isa<PHINode>(InsertPos)) ++InsertPos;
8981
Chris Lattner9f269e42005-08-08 19:11:57 +00008982 I->moveBefore(InsertPos);
Chris Lattner39c98bb2004-12-08 23:43:58 +00008983 ++NumSunkInst;
8984 return true;
8985}
8986
Chris Lattner1443bc52006-05-11 17:11:52 +00008987/// OptimizeConstantExpr - Given a constant expression and target data layout
Reid Spencer13bc5d72006-12-12 09:18:51 +00008988/// information, symbolically evaluate the constant expr to something simpler
Chris Lattner1443bc52006-05-11 17:11:52 +00008989/// if possible.
8990static Constant *OptimizeConstantExpr(ConstantExpr *CE, const TargetData *TD) {
8991 if (!TD) return CE;
8992
8993 Constant *Ptr = CE->getOperand(0);
8994 if (CE->getOpcode() == Instruction::GetElementPtr && Ptr->isNullValue() &&
8995 cast<PointerType>(Ptr->getType())->getElementType()->isSized()) {
8996 // If this is a constant expr gep that is effectively computing an
8997 // "offsetof", fold it into 'cast int Size to T*' instead of 'gep 0, 0, 12'
8998 bool isFoldableGEP = true;
8999 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
9000 if (!isa<ConstantInt>(CE->getOperand(i)))
9001 isFoldableGEP = false;
9002 if (isFoldableGEP) {
9003 std::vector<Value*> Ops(CE->op_begin()+1, CE->op_end());
9004 uint64_t Offset = TD->getIndexedOffset(Ptr->getType(), Ops);
Reid Spencer2a499b02006-12-13 17:19:09 +00009005 Constant *C = ConstantInt::get(TD->getIntPtrType(), Offset);
Reid Spencer13bc5d72006-12-12 09:18:51 +00009006 return ConstantExpr::getIntToPtr(C, CE->getType());
Chris Lattner1443bc52006-05-11 17:11:52 +00009007 }
9008 }
9009
9010 return CE;
9011}
9012
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009013
9014/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
9015/// all reachable code to the worklist.
9016///
9017/// This has a couple of tricks to make the code faster and more powerful. In
9018/// particular, we constant fold and DCE instructions as we go, to avoid adding
9019/// them to the worklist (this significantly speeds up instcombine on code where
9020/// many instructions are dead or constant). Additionally, if we find a branch
9021/// whose condition is a known constant, we only visit the reachable successors.
9022///
9023static void AddReachableCodeToWorklist(BasicBlock *BB,
9024 std::set<BasicBlock*> &Visited,
Chris Lattner1443bc52006-05-11 17:11:52 +00009025 std::vector<Instruction*> &WorkList,
9026 const TargetData *TD) {
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009027 // We have now visited this block! If we've already been here, bail out.
9028 if (!Visited.insert(BB).second) return;
9029
9030 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
9031 Instruction *Inst = BBI++;
9032
9033 // DCE instruction if trivially dead.
9034 if (isInstructionTriviallyDead(Inst)) {
9035 ++NumDeadInst;
Bill Wendling5dbf43c2006-11-26 09:46:52 +00009036 DOUT << "IC: DCE: " << *Inst;
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009037 Inst->eraseFromParent();
9038 continue;
9039 }
9040
9041 // ConstantProp instruction if trivially constant.
9042 if (Constant *C = ConstantFoldInstruction(Inst)) {
Chris Lattner1443bc52006-05-11 17:11:52 +00009043 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
9044 C = OptimizeConstantExpr(CE, TD);
Bill Wendling5dbf43c2006-11-26 09:46:52 +00009045 DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009046 Inst->replaceAllUsesWith(C);
9047 ++NumConstProp;
9048 Inst->eraseFromParent();
9049 continue;
9050 }
9051
9052 WorkList.push_back(Inst);
9053 }
9054
9055 // Recursively visit successors. If this is a branch or switch on a constant,
9056 // only visit the reachable successor.
9057 TerminatorInst *TI = BB->getTerminator();
9058 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
Zhou Sheng75b871f2007-01-11 12:24:14 +00009059 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition()) &&
Reid Spencer542964f2007-01-11 18:21:29 +00009060 BI->getCondition()->getType() == Type::Int1Ty) {
Reid Spencercddc9df2007-01-12 04:24:46 +00009061 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Chris Lattner1443bc52006-05-11 17:11:52 +00009062 AddReachableCodeToWorklist(BI->getSuccessor(!CondVal), Visited, WorkList,
9063 TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009064 return;
9065 }
9066 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
9067 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
9068 // See if this is an explicit destination.
9069 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
9070 if (SI->getCaseValue(i) == Cond) {
Chris Lattner1443bc52006-05-11 17:11:52 +00009071 AddReachableCodeToWorklist(SI->getSuccessor(i), Visited, WorkList,TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009072 return;
9073 }
9074
9075 // Otherwise it is the default destination.
Chris Lattner1443bc52006-05-11 17:11:52 +00009076 AddReachableCodeToWorklist(SI->getSuccessor(0), Visited, WorkList, TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009077 return;
9078 }
9079 }
9080
9081 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
Chris Lattner1443bc52006-05-11 17:11:52 +00009082 AddReachableCodeToWorklist(TI->getSuccessor(i), Visited, WorkList, TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009083}
9084
Chris Lattner113f4f42002-06-25 16:13:24 +00009085bool InstCombiner::runOnFunction(Function &F) {
Chris Lattner260ab202002-04-18 17:39:14 +00009086 bool Changed = false;
Chris Lattnerf4ad1652003-11-02 05:57:39 +00009087 TD = &getAnalysis<TargetData>();
Chris Lattnerca081252001-12-14 16:52:21 +00009088
Chris Lattner4ed40f72005-07-07 20:40:38 +00009089 {
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009090 // Do a depth-first traversal of the function, populate the worklist with
9091 // the reachable instructions. Ignore blocks that are not reachable. Keep
9092 // track of which blocks we visit.
Chris Lattner4ed40f72005-07-07 20:40:38 +00009093 std::set<BasicBlock*> Visited;
Chris Lattner1443bc52006-05-11 17:11:52 +00009094 AddReachableCodeToWorklist(F.begin(), Visited, WorkList, TD);
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00009095
Chris Lattner4ed40f72005-07-07 20:40:38 +00009096 // Do a quick scan over the function. If we find any blocks that are
9097 // unreachable, remove any instructions inside of them. This prevents
9098 // the instcombine code from having to deal with some bad special cases.
9099 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
9100 if (!Visited.count(BB)) {
9101 Instruction *Term = BB->getTerminator();
9102 while (Term != BB->begin()) { // Remove instrs bottom-up
9103 BasicBlock::iterator I = Term; --I;
Chris Lattner2d3a7a62004-04-27 15:13:33 +00009104
Bill Wendling5dbf43c2006-11-26 09:46:52 +00009105 DOUT << "IC: DCE: " << *I;
Chris Lattner4ed40f72005-07-07 20:40:38 +00009106 ++NumDeadInst;
9107
9108 if (!I->use_empty())
9109 I->replaceAllUsesWith(UndefValue::get(I->getType()));
9110 I->eraseFromParent();
9111 }
9112 }
9113 }
Chris Lattnerca081252001-12-14 16:52:21 +00009114
9115 while (!WorkList.empty()) {
9116 Instruction *I = WorkList.back(); // Get an instruction from the worklist
9117 WorkList.pop_back();
9118
Chris Lattner1443bc52006-05-11 17:11:52 +00009119 // Check to see if we can DCE the instruction.
Chris Lattner99f48c62002-09-02 04:59:56 +00009120 if (isInstructionTriviallyDead(I)) {
Chris Lattner1443bc52006-05-11 17:11:52 +00009121 // Add operands to the worklist.
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009122 if (I->getNumOperands() < 4)
Chris Lattner51ea1272004-02-28 05:22:00 +00009123 AddUsesToWorkList(*I);
Chris Lattner99f48c62002-09-02 04:59:56 +00009124 ++NumDeadInst;
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009125
Bill Wendling5dbf43c2006-11-26 09:46:52 +00009126 DOUT << "IC: DCE: " << *I;
Chris Lattnercd517ff2005-01-28 19:32:01 +00009127
9128 I->eraseFromParent();
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009129 removeFromWorkList(I);
9130 continue;
9131 }
Chris Lattner99f48c62002-09-02 04:59:56 +00009132
Chris Lattner1443bc52006-05-11 17:11:52 +00009133 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattner99f48c62002-09-02 04:59:56 +00009134 if (Constant *C = ConstantFoldInstruction(I)) {
Chris Lattner1443bc52006-05-11 17:11:52 +00009135 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
9136 C = OptimizeConstantExpr(CE, TD);
Bill Wendling5dbf43c2006-11-26 09:46:52 +00009137 DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
Chris Lattnercd517ff2005-01-28 19:32:01 +00009138
Chris Lattner1443bc52006-05-11 17:11:52 +00009139 // Add operands to the worklist.
Chris Lattner51ea1272004-02-28 05:22:00 +00009140 AddUsesToWorkList(*I);
Chris Lattnerc6509f42002-12-05 22:41:53 +00009141 ReplaceInstUsesWith(*I, C);
9142
Chris Lattner99f48c62002-09-02 04:59:56 +00009143 ++NumConstProp;
Chris Lattnera36ee4e2006-05-10 19:00:36 +00009144 I->eraseFromParent();
Chris Lattner800aaaf2003-10-07 15:17:02 +00009145 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009146 continue;
Chris Lattner99f48c62002-09-02 04:59:56 +00009147 }
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009148
Chris Lattner39c98bb2004-12-08 23:43:58 +00009149 // See if we can trivially sink this instruction to a successor basic block.
9150 if (I->hasOneUse()) {
9151 BasicBlock *BB = I->getParent();
9152 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
9153 if (UserParent != BB) {
9154 bool UserIsSuccessor = false;
9155 // See if the user is one of our successors.
9156 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
9157 if (*SI == UserParent) {
9158 UserIsSuccessor = true;
9159 break;
9160 }
9161
9162 // If the user is one of our immediate successors, and if that successor
9163 // only has us as a predecessors (we'd have to split the critical edge
9164 // otherwise), we can keep going.
9165 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
9166 next(pred_begin(UserParent)) == pred_end(UserParent))
9167 // Okay, the CFG is simple enough, try to sink this instruction.
9168 Changed |= TryToSinkInstruction(I, UserParent);
9169 }
9170 }
9171
Chris Lattnerca081252001-12-14 16:52:21 +00009172 // Now that we have an instruction, try combining it to simplify it...
Chris Lattnerae7a0d32002-08-02 19:29:35 +00009173 if (Instruction *Result = visit(*I)) {
Chris Lattner0b18c1d2002-05-10 15:38:35 +00009174 ++NumCombined;
Chris Lattner260ab202002-04-18 17:39:14 +00009175 // Should we replace the old instruction with a new one?
Chris Lattner053c0932002-05-14 15:24:07 +00009176 if (Result != I) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +00009177 DOUT << "IC: Old = " << *I
9178 << " New = " << *Result;
Chris Lattner7d2a5392004-03-13 23:54:27 +00009179
Chris Lattner396dbfe2004-06-09 05:08:07 +00009180 // Everything uses the new instruction now.
9181 I->replaceAllUsesWith(Result);
9182
9183 // Push the new instruction and any users onto the worklist.
9184 WorkList.push_back(Result);
9185 AddUsersToWorkList(*Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009186
9187 // Move the name to the new instruction first...
9188 std::string OldName = I->getName(); I->setName("");
Chris Lattner950fc782003-10-07 22:58:41 +00009189 Result->setName(OldName);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009190
9191 // Insert the new instruction into the basic block...
9192 BasicBlock *InstParent = I->getParent();
Chris Lattner7515cab2004-11-14 19:13:23 +00009193 BasicBlock::iterator InsertPos = I;
9194
9195 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
9196 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
9197 ++InsertPos;
9198
9199 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009200
Chris Lattner63d75af2004-05-01 23:27:23 +00009201 // Make sure that we reprocess all operands now that we reduced their
9202 // use counts.
Chris Lattnerb643a9e2004-05-01 23:19:52 +00009203 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
9204 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
9205 WorkList.push_back(OpI);
9206
Chris Lattner396dbfe2004-06-09 05:08:07 +00009207 // Instructions can end up on the worklist more than once. Make sure
9208 // we do not process an instruction that has been deleted.
9209 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00009210
9211 // Erase the old instruction.
9212 InstParent->getInstList().erase(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00009213 } else {
Bill Wendling5dbf43c2006-11-26 09:46:52 +00009214 DOUT << "IC: MOD = " << *I;
Chris Lattner7d2a5392004-03-13 23:54:27 +00009215
Chris Lattnerae7a0d32002-08-02 19:29:35 +00009216 // If the instruction was modified, it's possible that it is now dead.
9217 // if so, remove it.
Chris Lattner63d75af2004-05-01 23:27:23 +00009218 if (isInstructionTriviallyDead(I)) {
9219 // Make sure we process all operands now that we are reducing their
9220 // use counts.
9221 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
9222 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
9223 WorkList.push_back(OpI);
Misha Brukmanb1c93172005-04-21 23:48:37 +00009224
Chris Lattner63d75af2004-05-01 23:27:23 +00009225 // Instructions may end up in the worklist more than once. Erase all
Robert Bocchinoa8352962006-01-13 22:48:06 +00009226 // occurrences of this instruction.
Chris Lattner99f48c62002-09-02 04:59:56 +00009227 removeFromWorkList(I);
Chris Lattner31f486c2005-01-31 05:36:43 +00009228 I->eraseFromParent();
Chris Lattner396dbfe2004-06-09 05:08:07 +00009229 } else {
9230 WorkList.push_back(Result);
9231 AddUsersToWorkList(*Result);
Chris Lattnerae7a0d32002-08-02 19:29:35 +00009232 }
Chris Lattner053c0932002-05-14 15:24:07 +00009233 }
Chris Lattner260ab202002-04-18 17:39:14 +00009234 Changed = true;
Chris Lattnerca081252001-12-14 16:52:21 +00009235 }
9236 }
9237
Chris Lattner260ab202002-04-18 17:39:14 +00009238 return Changed;
Chris Lattner04805fa2002-02-26 21:46:54 +00009239}
9240
Brian Gaeke38b79e82004-07-27 17:43:21 +00009241FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattner260ab202002-04-18 17:39:14 +00009242 return new InstCombiner();
Chris Lattner04805fa2002-02-26 21:46:54 +00009243}
Brian Gaeke960707c2003-11-11 22:41:34 +00009244