blob: b12c6b58414a6e849c925dc5ed2caf4978df2dda [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.
Chris Lattnerbfb1d032003-07-23 21:41:57 +000027// 3. SetCC instructions are converted from <,>,<=,>= to ==,!= if possible
28// 4. All SetCC 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 Lattner260ab202002-04-18 17:39:14 +000058namespace {
Chris Lattnerbf3a0992002-10-01 22:38:41 +000059 Statistic<> NumCombined ("instcombine", "Number of insts combined");
60 Statistic<> NumConstProp("instcombine", "Number of constant folds");
61 Statistic<> NumDeadInst ("instcombine", "Number of dead inst eliminated");
Chris Lattner5997cf92006-02-08 03:25:32 +000062 Statistic<> NumDeadStore("instcombine", "Number of dead stores eliminated");
Chris Lattner39c98bb2004-12-08 23:43:58 +000063 Statistic<> NumSunkInst ("instcombine", "Number of instructions sunk");
Chris Lattnerbf3a0992002-10-01 22:38:41 +000064
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);
Chris Lattnerd1f46d32005-04-24 06:59:08 +0000146 Instruction *visitSetCondInst(SetCondInst &I);
147 Instruction *visitSetCondInstWithCastAndCast(SetCondInst &SCI);
148
Chris Lattner0798af32005-01-13 20:14:25 +0000149 Instruction *FoldGEPSetCC(User *GEPLHS, Value *RHS,
150 Instruction::BinaryOps Cond, Instruction &I);
Chris Lattnere8d6c602003-03-10 19:16:08 +0000151 Instruction *visitShiftInst(ShiftInst &I);
Reid Spencere0fc4df2006-10-20 07:07:24 +0000152 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Chris Lattner14553932006-01-06 07:12:35 +0000153 ShiftInst &I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000154 Instruction *commonCastTransforms(CastInst &CI);
155 Instruction *commonIntCastTransforms(CastInst &CI);
156 Instruction *visitTrunc(CastInst &CI);
157 Instruction *visitZExt(CastInst &CI);
158 Instruction *visitSExt(CastInst &CI);
159 Instruction *visitFPTrunc(CastInst &CI);
160 Instruction *visitFPExt(CastInst &CI);
161 Instruction *visitFPToUI(CastInst &CI);
162 Instruction *visitFPToSI(CastInst &CI);
163 Instruction *visitUIToFP(CastInst &CI);
164 Instruction *visitSIToFP(CastInst &CI);
165 Instruction *visitPtrToInt(CastInst &CI);
166 Instruction *visitIntToPtr(CastInst &CI);
167 Instruction *visitBitCast(CastInst &CI);
Chris Lattner411336f2005-01-19 21:50:18 +0000168 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
169 Instruction *FI);
Chris Lattnerb909e8b2004-03-12 05:52:32 +0000170 Instruction *visitSelectInst(SelectInst &CI);
Chris Lattner970c33a2003-06-19 17:00:31 +0000171 Instruction *visitCallInst(CallInst &CI);
172 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner113f4f42002-06-25 16:13:24 +0000173 Instruction *visitPHINode(PHINode &PN);
174 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Chris Lattner1085bdf2002-11-04 16:18:53 +0000175 Instruction *visitAllocationInst(AllocationInst &AI);
Chris Lattner8427bff2003-12-07 01:24:23 +0000176 Instruction *visitFreeInst(FreeInst &FI);
Chris Lattner0f1d8a32003-06-26 05:06:25 +0000177 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattner31f486c2005-01-31 05:36:43 +0000178 Instruction *visitStoreInst(StoreInst &SI);
Chris Lattner9eef8a72003-06-04 04:46:00 +0000179 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner4c9c20a2004-07-03 00:26:11 +0000180 Instruction *visitSwitchInst(SwitchInst &SI);
Chris Lattner39fac442006-04-15 01:39:45 +0000181 Instruction *visitInsertElementInst(InsertElementInst &IE);
Robert Bocchinoa8352962006-01-13 22:48:06 +0000182 Instruction *visitExtractElementInst(ExtractElementInst &EI);
Chris Lattnerfbb77a42006-04-10 22:45:52 +0000183 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
Chris Lattner260ab202002-04-18 17:39:14 +0000184
185 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner113f4f42002-06-25 16:13:24 +0000186 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000187
Chris Lattner970c33a2003-06-19 17:00:31 +0000188 private:
Chris Lattneraec3d942003-10-07 22:32:43 +0000189 Instruction *visitCallSite(CallSite CS);
Chris Lattner970c33a2003-06-19 17:00:31 +0000190 bool transformConstExprCastCall(CallSite CS);
191
Chris Lattner69193f92004-04-05 01:30:19 +0000192 public:
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000193 // InsertNewInstBefore - insert an instruction New before instruction Old
194 // in the program. Add the new instruction to the worklist.
195 //
Chris Lattner623826c2004-09-28 21:48:02 +0000196 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattner65217ff2002-08-23 18:32:43 +0000197 assert(New && New->getParent() == 0 &&
198 "New instruction already inserted into a basic block!");
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000199 BasicBlock *BB = Old.getParent();
200 BB->getInstList().insert(&Old, New); // Insert inst
201 WorkList.push_back(New); // Add to worklist
Chris Lattnere79e8542004-02-23 06:38:22 +0000202 return New;
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000203 }
204
Chris Lattner7e794272004-09-24 15:21:34 +0000205 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
206 /// This also adds the cast to the worklist. Finally, this returns the
207 /// cast.
208 Value *InsertCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
209 if (V->getType() == Ty) return V;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000210
Chris Lattnere79d2492006-04-06 19:19:17 +0000211 if (Constant *CV = dyn_cast<Constant>(V))
212 return ConstantExpr::getCast(CV, Ty);
213
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000214 Instruction *C = CastInst::createInferredCast(V, Ty, V->getName(), &Pos);
Chris Lattner7e794272004-09-24 15:21:34 +0000215 WorkList.push_back(C);
216 return C;
217 }
218
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000219 // ReplaceInstUsesWith - This method is to be used when an instruction is
220 // found to be dead, replacable with another preexisting expression. Here
221 // we add all uses of I to the worklist, replace all uses of I with the new
222 // value, then return I, so that the inst combiner will know that I was
223 // modified.
224 //
225 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattner51ea1272004-02-28 05:22:00 +0000226 AddUsersToWorkList(I); // Add all modified instrs to worklist
Chris Lattner8953b902004-04-05 02:10:19 +0000227 if (&I != V) {
228 I.replaceAllUsesWith(V);
229 return &I;
230 } else {
231 // If we are replacing the instruction with itself, this must be in a
232 // segment of unreachable code, so just clobber the instruction.
Chris Lattner8ba9ec92004-10-18 02:59:09 +0000233 I.replaceAllUsesWith(UndefValue::get(I.getType()));
Chris Lattner8953b902004-04-05 02:10:19 +0000234 return &I;
235 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000236 }
Chris Lattner51ea1272004-02-28 05:22:00 +0000237
Chris Lattner2590e512006-02-07 06:56:34 +0000238 // UpdateValueUsesWith - This method is to be used when an value is
239 // found to be replacable with another preexisting expression or was
240 // updated. Here we add all uses of I to the worklist, replace all uses of
241 // I with the new value (unless the instruction was just updated), then
242 // return true, so that the inst combiner will know that I was modified.
243 //
244 bool UpdateValueUsesWith(Value *Old, Value *New) {
245 AddUsersToWorkList(*Old); // Add all modified instrs to worklist
246 if (Old != New)
247 Old->replaceAllUsesWith(New);
248 if (Instruction *I = dyn_cast<Instruction>(Old))
249 WorkList.push_back(I);
Chris Lattner5b2edb12006-02-12 08:02:11 +0000250 if (Instruction *I = dyn_cast<Instruction>(New))
251 WorkList.push_back(I);
Chris Lattner2590e512006-02-07 06:56:34 +0000252 return true;
253 }
254
Chris Lattner51ea1272004-02-28 05:22:00 +0000255 // EraseInstFromFunction - When dealing with an instruction that has side
256 // effects or produces a void value, we can't rely on DCE to delete the
257 // instruction. Instead, visit methods should return the value returned by
258 // this function.
259 Instruction *EraseInstFromFunction(Instruction &I) {
260 assert(I.use_empty() && "Cannot erase instruction that is used!");
261 AddUsesToWorkList(I);
262 removeFromWorkList(&I);
Chris Lattner95307542004-11-18 21:41:39 +0000263 I.eraseFromParent();
Chris Lattner51ea1272004-02-28 05:22:00 +0000264 return 0; // Don't do anything with FI
265 }
266
Chris Lattner3ac7c262003-08-13 20:16:26 +0000267 private:
Chris Lattnerdfae8be2003-07-24 17:35:25 +0000268 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
269 /// InsertBefore instruction. This is specialized a bit to avoid inserting
270 /// casts that are known to not do anything...
271 ///
272 Value *InsertOperandCastBefore(Value *V, const Type *DestTy,
273 Instruction *InsertBefore);
274
Chris Lattner7fb29e12003-03-11 00:12:48 +0000275 // SimplifyCommutative - This performs a few simplifications for commutative
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000276 // operators.
Chris Lattner7fb29e12003-03-11 00:12:48 +0000277 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerba1cb382003-09-19 17:17:26 +0000278
Chris Lattner0157e7f2006-02-11 09:31:47 +0000279 bool SimplifyDemandedBits(Value *V, uint64_t Mask,
280 uint64_t &KnownZero, uint64_t &KnownOne,
281 unsigned Depth = 0);
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000282
Chris Lattner2deeaea2006-10-05 06:55:50 +0000283 Value *SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
284 uint64_t &UndefElts, unsigned Depth = 0);
285
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000286 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
287 // PHI node as operand #0, see if we can fold the instruction into the PHI
288 // (which is only possible if all operands to the PHI are constants).
289 Instruction *FoldOpIntoPhi(Instruction &I);
290
Chris Lattner7515cab2004-11-14 19:13:23 +0000291 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
292 // operator and they all are only used by the PHI, PHI together their
293 // inputs, and do the operation once, to the result of the PHI.
294 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
Chris Lattnercadac0c2006-11-01 04:51:18 +0000295 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
296
297
Chris Lattnerba1cb382003-09-19 17:17:26 +0000298 Instruction *OptAndOp(Instruction *Op, ConstantIntegral *OpRHS,
299 ConstantIntegral *AndRHS, BinaryOperator &TheAnd);
Chris Lattneraf517572005-09-18 04:24:45 +0000300
301 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantIntegral *Mask,
302 bool isSub, Instruction &I);
Chris Lattner6862fbd2004-09-29 17:40:11 +0000303 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
304 bool Inside, Instruction &IB);
Chris Lattner216be912005-10-24 06:03:58 +0000305 Instruction *PromoteCastOfAllocation(CastInst &CI, AllocationInst &AI);
Chris Lattnerc482a9e2006-06-15 19:07:26 +0000306 Instruction *MatchBSwap(BinaryOperator &I);
307
Chris Lattner1ebbe6a2006-05-13 02:06:03 +0000308 Value *EvaluateInDifferentType(Value *V, const Type *Ty);
Chris Lattner260ab202002-04-18 17:39:14 +0000309 };
Chris Lattnerb28b6802002-07-23 18:06:35 +0000310
Chris Lattnerc2d3d312006-08-27 22:42:52 +0000311 RegisterPass<InstCombiner> X("instcombine", "Combine redundant instructions");
Chris Lattner260ab202002-04-18 17:39:14 +0000312}
313
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000314// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattner81a7a232004-10-16 18:11:37 +0000315// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000316static unsigned getComplexity(Value *V) {
317 if (isa<Instruction>(V)) {
318 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
Chris Lattner81a7a232004-10-16 18:11:37 +0000319 return 3;
320 return 4;
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000321 }
Chris Lattner81a7a232004-10-16 18:11:37 +0000322 if (isa<Argument>(V)) return 3;
323 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000324}
Chris Lattner260ab202002-04-18 17:39:14 +0000325
Chris Lattner7fb29e12003-03-11 00:12:48 +0000326// isOnlyUse - Return true if this instruction will be deleted if we stop using
327// it.
328static bool isOnlyUse(Value *V) {
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000329 return V->hasOneUse() || isa<Constant>(V);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000330}
331
Chris Lattnere79e8542004-02-23 06:38:22 +0000332// getPromotedType - Return the specified type promoted as it would be to pass
333// though a va_arg area...
334static const Type *getPromotedType(const Type *Ty) {
Chris Lattner97bfcea2004-06-17 18:16:02 +0000335 switch (Ty->getTypeID()) {
Chris Lattnere79e8542004-02-23 06:38:22 +0000336 case Type::SByteTyID:
337 case Type::ShortTyID: return Type::IntTy;
338 case Type::UByteTyID:
339 case Type::UShortTyID: return Type::UIntTy;
340 case Type::FloatTyID: return Type::DoubleTy;
341 default: return Ty;
342 }
343}
344
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000345/// getBitCastOperand - If the specified operand is a CastInst or a constant
346/// expression bitcast, return the operand value, otherwise return null.
347static Value *getBitCastOperand(Value *V) {
348 if (BitCastInst *I = dyn_cast<BitCastInst>(V))
Chris Lattner567b81f2005-09-13 00:40:14 +0000349 return I->getOperand(0);
350 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000351 if (CE->getOpcode() == Instruction::BitCast)
Chris Lattner567b81f2005-09-13 00:40:14 +0000352 return CE->getOperand(0);
353 return 0;
354}
355
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000356/// This function is a wrapper around CastInst::isEliminableCastPair. It
357/// simply extracts arguments and returns what that function returns.
358/// @Determine if it is valid to eliminate a Convert pair
359static Instruction::CastOps
360isEliminableCastPair(
361 const CastInst *CI, ///< The first cast instruction
362 unsigned opcode, ///< The opcode of the second cast instruction
363 const Type *DstTy, ///< The target type for the second cast instruction
364 TargetData *TD ///< The target data for pointer size
365) {
366
367 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
368 const Type *MidTy = CI->getType(); // B from above
Chris Lattner1d441ad2006-05-06 09:00:16 +0000369
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000370 // Get the opcodes of the two Cast instructions
371 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
372 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
Chris Lattner1d441ad2006-05-06 09:00:16 +0000373
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000374 return Instruction::CastOps(
375 CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
376 DstTy, TD->getIntPtrType()));
Chris Lattner1d441ad2006-05-06 09:00:16 +0000377}
378
379/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
380/// in any code being generated. It does not require codegen if V is simple
381/// enough or if the cast can be folded into other casts.
382static bool ValueRequiresCast(const Value *V, const Type *Ty, TargetData *TD) {
383 if (V->getType() == Ty || isa<Constant>(V)) return false;
384
385 // If this is a noop cast, it isn't real codegen.
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000386 if (V->getType()->canLosslesslyBitCastTo(Ty))
Chris Lattner1d441ad2006-05-06 09:00:16 +0000387 return false;
388
Chris Lattner99155be2006-05-25 23:24:33 +0000389 // If this is another cast that can be eliminated, it isn't codegen either.
Chris Lattner1d441ad2006-05-06 09:00:16 +0000390 if (const CastInst *CI = dyn_cast<CastInst>(V))
Reid Spencer14fbdd52006-12-04 02:48:01 +0000391 if (isEliminableCastPair(CI, CastInst::getCastOpcode(
392 V, V->getType()->isSigned(), Ty, Ty->isSigned()), Ty, TD))
Chris Lattner1d441ad2006-05-06 09:00:16 +0000393 return false;
394 return true;
395}
396
397/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
398/// InsertBefore instruction. This is specialized a bit to avoid inserting
399/// casts that are known to not do anything...
400///
401Value *InstCombiner::InsertOperandCastBefore(Value *V, const Type *DestTy,
402 Instruction *InsertBefore) {
403 if (V->getType() == DestTy) return V;
404 if (Constant *C = dyn_cast<Constant>(V))
405 return ConstantExpr::getCast(C, DestTy);
406
Reid Spencer00c482b2006-10-26 19:19:06 +0000407 return InsertCastBefore(V, DestTy, *InsertBefore);
Chris Lattner1d441ad2006-05-06 09:00:16 +0000408}
409
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000410// SimplifyCommutative - This performs a few simplifications for commutative
411// operators:
Chris Lattner260ab202002-04-18 17:39:14 +0000412//
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000413// 1. Order operands such that they are listed from right (least complex) to
414// left (most complex). This puts constants before unary operators before
415// binary operators.
416//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000417// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
418// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000419//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000420bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000421 bool Changed = false;
422 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
423 Changed = !I.swapOperands();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000424
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000425 if (!I.isAssociative()) return Changed;
426 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattner7fb29e12003-03-11 00:12:48 +0000427 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
428 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
429 if (isa<Constant>(I.getOperand(1))) {
Chris Lattner34428442003-05-27 16:40:51 +0000430 Constant *Folded = ConstantExpr::get(I.getOpcode(),
431 cast<Constant>(I.getOperand(1)),
432 cast<Constant>(Op->getOperand(1)));
Chris Lattner7fb29e12003-03-11 00:12:48 +0000433 I.setOperand(0, Op->getOperand(0));
434 I.setOperand(1, Folded);
435 return true;
436 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
437 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
438 isOnlyUse(Op) && isOnlyUse(Op1)) {
439 Constant *C1 = cast<Constant>(Op->getOperand(1));
440 Constant *C2 = cast<Constant>(Op1->getOperand(1));
441
442 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner34428442003-05-27 16:40:51 +0000443 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000444 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
445 Op1->getOperand(0),
446 Op1->getName(), &I);
447 WorkList.push_back(New);
448 I.setOperand(0, New);
449 I.setOperand(1, Folded);
450 return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000451 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000452 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000453 return Changed;
Chris Lattner260ab202002-04-18 17:39:14 +0000454}
Chris Lattnerca081252001-12-14 16:52:21 +0000455
Chris Lattnerbb74e222003-03-10 23:06:50 +0000456// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
457// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattner9fa53de2002-05-06 16:49:18 +0000458//
Chris Lattnerbb74e222003-03-10 23:06:50 +0000459static inline Value *dyn_castNegVal(Value *V) {
460 if (BinaryOperator::isNeg(V))
Chris Lattnerd6f636a2005-04-24 07:30:14 +0000461 return BinaryOperator::getNegArgument(V);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000462
Chris Lattner9ad0d552004-12-14 20:08:06 +0000463 // Constants can be considered to be negated values if they can be folded.
464 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
465 return ConstantExpr::getNeg(C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000466 return 0;
Chris Lattner9fa53de2002-05-06 16:49:18 +0000467}
468
Chris Lattnerbb74e222003-03-10 23:06:50 +0000469static inline Value *dyn_castNotVal(Value *V) {
470 if (BinaryOperator::isNot(V))
Chris Lattnerd6f636a2005-04-24 07:30:14 +0000471 return BinaryOperator::getNotArgument(V);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000472
473 // Constants can be considered to be not'ed values...
Chris Lattnerdd65d862003-04-30 22:34:06 +0000474 if (ConstantIntegral *C = dyn_cast<ConstantIntegral>(V))
Chris Lattnerc8e7e292004-06-10 02:12:35 +0000475 return ConstantExpr::getNot(C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000476 return 0;
477}
478
Chris Lattner7fb29e12003-03-11 00:12:48 +0000479// dyn_castFoldableMul - If this value is a multiply that can be folded into
480// other computations (because it has a constant operand), return the
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000481// non-constant operand of the multiply, and set CST to point to the multiplier.
482// Otherwise, return null.
Chris Lattner7fb29e12003-03-11 00:12:48 +0000483//
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000484static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000485 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000486 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattner7fb29e12003-03-11 00:12:48 +0000487 if (I->getOpcode() == Instruction::Mul)
Chris Lattner970136362004-11-15 05:54:07 +0000488 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattner7fb29e12003-03-11 00:12:48 +0000489 return I->getOperand(0);
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000490 if (I->getOpcode() == Instruction::Shl)
Chris Lattner970136362004-11-15 05:54:07 +0000491 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000492 // The multiplier is really 1 << CST.
493 Constant *One = ConstantInt::get(V->getType(), 1);
494 CST = cast<ConstantInt>(ConstantExpr::getShl(One, CST));
495 return I->getOperand(0);
496 }
497 }
Chris Lattner7fb29e12003-03-11 00:12:48 +0000498 return 0;
Chris Lattner3082c5a2003-02-18 19:28:33 +0000499}
Chris Lattner31ae8632002-08-14 17:51:49 +0000500
Chris Lattner0798af32005-01-13 20:14:25 +0000501/// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
502/// expression, return it.
503static User *dyn_castGetElementPtr(Value *V) {
504 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
505 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
506 if (CE->getOpcode() == Instruction::GetElementPtr)
507 return cast<User>(V);
508 return false;
509}
510
Chris Lattner623826c2004-09-28 21:48:02 +0000511// AddOne, SubOne - Add or subtract a constant one from an integer constant...
Chris Lattner6862fbd2004-09-29 17:40:11 +0000512static ConstantInt *AddOne(ConstantInt *C) {
513 return cast<ConstantInt>(ConstantExpr::getAdd(C,
514 ConstantInt::get(C->getType(), 1)));
Chris Lattner623826c2004-09-28 21:48:02 +0000515}
Chris Lattner6862fbd2004-09-29 17:40:11 +0000516static ConstantInt *SubOne(ConstantInt *C) {
517 return cast<ConstantInt>(ConstantExpr::getSub(C,
518 ConstantInt::get(C->getType(), 1)));
Chris Lattner623826c2004-09-28 21:48:02 +0000519}
520
Chris Lattner0157e7f2006-02-11 09:31:47 +0000521/// GetConstantInType - Return a ConstantInt with the specified type and value.
522///
Chris Lattneree0f2802006-02-12 02:07:56 +0000523static ConstantIntegral *GetConstantInType(const Type *Ty, uint64_t Val) {
Reid Spencere0fc4df2006-10-20 07:07:24 +0000524 if (Ty->isUnsigned())
525 return ConstantInt::get(Ty, Val);
Chris Lattneree0f2802006-02-12 02:07:56 +0000526 else if (Ty->getTypeID() == Type::BoolTyID)
527 return ConstantBool::get(Val);
Chris Lattner0157e7f2006-02-11 09:31:47 +0000528 int64_t SVal = Val;
529 SVal <<= 64-Ty->getPrimitiveSizeInBits();
530 SVal >>= 64-Ty->getPrimitiveSizeInBits();
Reid Spencere0fc4df2006-10-20 07:07:24 +0000531 return ConstantInt::get(Ty, SVal);
Chris Lattner0157e7f2006-02-11 09:31:47 +0000532}
533
534
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.
Chris Lattner4534dd592006-02-09 07:38:58 +0000547 if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(V)) {
548 // 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();
758 I->setOperand(OpNo, GetConstantInType(OpC->getType(), Val));
759 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) {
Chris Lattner0157e7f2006-02-11 09:31:47 +0000819 if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(V)) {
820 // 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) {
960 Constant *AndC = GetConstantInType(I->getType(),
961 ~KnownOne & DemandedMask);
962 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.
1086 uint64_t InDemandedBits = ~0ULL >> 64-BitWidth+NLZ;
1087
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)
1245 return UpdateValueUsesWith(I, GetConstantInType(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
Chris Lattner623826c2004-09-28 21:48:02 +00001451// isTrueWhenEqual - Return true if the specified setcondinst instruction is
1452// true when both operands are equal...
1453//
1454static bool isTrueWhenEqual(Instruction &I) {
1455 return I.getOpcode() == Instruction::SetEQ ||
1456 I.getOpcode() == Instruction::SetGE ||
1457 I.getOpcode() == Instruction::SetLE;
1458}
Chris Lattnerb8b97502003-08-13 19:01:45 +00001459
1460/// AssociativeOpt - Perform an optimization on an associative operator. This
1461/// function is designed to check a chain of associative operators for a
1462/// potential to apply a certain optimization. Since the optimization may be
1463/// applicable if the expression was reassociated, this checks the chain, then
1464/// reassociates the expression as necessary to expose the optimization
1465/// opportunity. This makes use of a special Functor, which must define
1466/// 'shouldApply' and 'apply' methods.
1467///
1468template<typename Functor>
1469Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1470 unsigned Opcode = Root.getOpcode();
1471 Value *LHS = Root.getOperand(0);
1472
1473 // Quick check, see if the immediate LHS matches...
1474 if (F.shouldApply(LHS))
1475 return F.apply(Root);
1476
1477 // Otherwise, if the LHS is not of the same opcode as the root, return.
1478 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001479 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattnerb8b97502003-08-13 19:01:45 +00001480 // Should we apply this transform to the RHS?
1481 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1482
1483 // If not to the RHS, check to see if we should apply to the LHS...
1484 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1485 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1486 ShouldApply = true;
1487 }
1488
1489 // If the functor wants to apply the optimization to the RHS of LHSI,
1490 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1491 if (ShouldApply) {
1492 BasicBlock *BB = Root.getParent();
Misha Brukmanb1c93172005-04-21 23:48:37 +00001493
Chris Lattnerb8b97502003-08-13 19:01:45 +00001494 // Now all of the instructions are in the current basic block, go ahead
1495 // and perform the reassociation.
1496 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1497
1498 // First move the selected RHS to the LHS of the root...
1499 Root.setOperand(0, LHSI->getOperand(1));
1500
1501 // Make what used to be the LHS of the root be the user of the root...
1502 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner284d3b02004-04-16 18:08:07 +00001503 if (&Root == TmpLHSI) {
Chris Lattner8953b902004-04-05 02:10:19 +00001504 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1505 return 0;
1506 }
Chris Lattner284d3b02004-04-16 18:08:07 +00001507 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattnerb8b97502003-08-13 19:01:45 +00001508 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner284d3b02004-04-16 18:08:07 +00001509 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
1510 BasicBlock::iterator ARI = &Root; ++ARI;
1511 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
1512 ARI = Root;
Chris Lattnerb8b97502003-08-13 19:01:45 +00001513
1514 // Now propagate the ExtraOperand down the chain of instructions until we
1515 // get to LHSI.
1516 while (TmpLHSI != LHSI) {
1517 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner284d3b02004-04-16 18:08:07 +00001518 // Move the instruction to immediately before the chain we are
1519 // constructing to avoid breaking dominance properties.
1520 NextLHSI->getParent()->getInstList().remove(NextLHSI);
1521 BB->getInstList().insert(ARI, NextLHSI);
1522 ARI = NextLHSI;
1523
Chris Lattnerb8b97502003-08-13 19:01:45 +00001524 Value *NextOp = NextLHSI->getOperand(1);
1525 NextLHSI->setOperand(1, ExtraOperand);
1526 TmpLHSI = NextLHSI;
1527 ExtraOperand = NextOp;
1528 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001529
Chris Lattnerb8b97502003-08-13 19:01:45 +00001530 // Now that the instructions are reassociated, have the functor perform
1531 // the transformation...
1532 return F.apply(Root);
1533 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001534
Chris Lattnerb8b97502003-08-13 19:01:45 +00001535 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1536 }
1537 return 0;
1538}
1539
1540
1541// AddRHS - Implements: X + X --> X << 1
1542struct AddRHS {
1543 Value *RHS;
1544 AddRHS(Value *rhs) : RHS(rhs) {}
1545 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1546 Instruction *apply(BinaryOperator &Add) const {
1547 return new ShiftInst(Instruction::Shl, Add.getOperand(0),
1548 ConstantInt::get(Type::UByteTy, 1));
1549 }
1550};
1551
1552// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1553// iff C1&C2 == 0
1554struct AddMaskingAnd {
1555 Constant *C2;
1556 AddMaskingAnd(Constant *c) : C2(c) {}
1557 bool shouldApply(Value *LHS) const {
Chris Lattnerd4252a72004-07-30 07:50:03 +00001558 ConstantInt *C1;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001559 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Chris Lattnerd4252a72004-07-30 07:50:03 +00001560 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattnerb8b97502003-08-13 19:01:45 +00001561 }
1562 Instruction *apply(BinaryOperator &Add) const {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001563 return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattnerb8b97502003-08-13 19:01:45 +00001564 }
1565};
1566
Chris Lattner86102b82005-01-01 16:22:27 +00001567static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner183b3362004-04-09 19:05:30 +00001568 InstCombiner *IC) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001569 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
Chris Lattner86102b82005-01-01 16:22:27 +00001570 if (Constant *SOC = dyn_cast<Constant>(SO))
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001571 return ConstantExpr::getCast(CI->getOpcode(), SOC, I.getType());
Misha Brukmanb1c93172005-04-21 23:48:37 +00001572
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001573 return IC->InsertNewInstBefore(CastInst::create(
1574 CI->getOpcode(), SO, I.getType(), SO->getName() + ".cast"), I);
Chris Lattner86102b82005-01-01 16:22:27 +00001575 }
1576
Chris Lattner183b3362004-04-09 19:05:30 +00001577 // Figure out if the constant is the left or the right argument.
Chris Lattner86102b82005-01-01 16:22:27 +00001578 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1579 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattnerb8b97502003-08-13 19:01:45 +00001580
Chris Lattner183b3362004-04-09 19:05:30 +00001581 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1582 if (ConstIsRHS)
Chris Lattner86102b82005-01-01 16:22:27 +00001583 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1584 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner183b3362004-04-09 19:05:30 +00001585 }
1586
1587 Value *Op0 = SO, *Op1 = ConstOperand;
1588 if (!ConstIsRHS)
1589 std::swap(Op0, Op1);
1590 Instruction *New;
Chris Lattner86102b82005-01-01 16:22:27 +00001591 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1592 New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
1593 else if (ShiftInst *SI = dyn_cast<ShiftInst>(&I))
1594 New = new ShiftInst(SI->getOpcode(), Op0, Op1, SO->getName()+".sh");
Chris Lattnerf9d96652004-04-10 19:15:56 +00001595 else {
Chris Lattner183b3362004-04-09 19:05:30 +00001596 assert(0 && "Unknown binary instruction type!");
Chris Lattnerf9d96652004-04-10 19:15:56 +00001597 abort();
1598 }
Chris Lattner86102b82005-01-01 16:22:27 +00001599 return IC->InsertNewInstBefore(New, I);
1600}
1601
1602// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1603// constant as the other operand, try to fold the binary operator into the
1604// select arguments. This also works for Cast instructions, which obviously do
1605// not have a second operand.
1606static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1607 InstCombiner *IC) {
1608 // Don't modify shared select instructions
1609 if (!SI->hasOneUse()) return 0;
1610 Value *TV = SI->getOperand(1);
1611 Value *FV = SI->getOperand(2);
1612
1613 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner374e6592005-04-21 05:43:13 +00001614 // Bool selects with constant operands can be folded to logical ops.
1615 if (SI->getType() == Type::BoolTy) return 0;
1616
Chris Lattner86102b82005-01-01 16:22:27 +00001617 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1618 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1619
1620 return new SelectInst(SI->getCondition(), SelectTrueVal,
1621 SelectFalseVal);
1622 }
1623 return 0;
Chris Lattner183b3362004-04-09 19:05:30 +00001624}
1625
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001626
1627/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1628/// node as operand #0, see if we can fold the instruction into the PHI (which
1629/// is only possible if all operands to the PHI are constants).
1630Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1631 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattner7515cab2004-11-14 19:13:23 +00001632 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner04689872006-09-09 22:02:56 +00001633 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001634
Chris Lattner04689872006-09-09 22:02:56 +00001635 // Check to see if all of the operands of the PHI are constants. If there is
1636 // one non-constant value, remember the BB it is. If there is more than one
1637 // bail out.
1638 BasicBlock *NonConstBB = 0;
1639 for (unsigned i = 0; i != NumPHIValues; ++i)
1640 if (!isa<Constant>(PN->getIncomingValue(i))) {
1641 if (NonConstBB) return 0; // More than one non-const value.
1642 NonConstBB = PN->getIncomingBlock(i);
1643
1644 // If the incoming non-constant value is in I's block, we have an infinite
1645 // loop.
1646 if (NonConstBB == I.getParent())
1647 return 0;
1648 }
1649
1650 // If there is exactly one non-constant value, we can insert a copy of the
1651 // operation in that block. However, if this is a critical edge, we would be
1652 // inserting the computation one some other paths (e.g. inside a loop). Only
1653 // do this if the pred block is unconditionally branching into the phi block.
1654 if (NonConstBB) {
1655 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1656 if (!BI || !BI->isUnconditional()) return 0;
1657 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001658
1659 // Okay, we can do the transformation: create the new PHI node.
1660 PHINode *NewPN = new PHINode(I.getType(), I.getName());
1661 I.setName("");
Chris Lattnerd8e20182005-01-29 00:39:08 +00001662 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001663 InsertNewInstBefore(NewPN, *PN);
1664
1665 // Next, add all of the operands to the PHI.
1666 if (I.getNumOperands() == 2) {
1667 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattner7515cab2004-11-14 19:13:23 +00001668 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner04689872006-09-09 22:02:56 +00001669 Value *InV;
1670 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1671 InV = ConstantExpr::get(I.getOpcode(), InC, C);
1672 } else {
1673 assert(PN->getIncomingBlock(i) == NonConstBB);
1674 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1675 InV = BinaryOperator::create(BO->getOpcode(),
1676 PN->getIncomingValue(i), C, "phitmp",
1677 NonConstBB->getTerminator());
1678 else if (ShiftInst *SI = dyn_cast<ShiftInst>(&I))
1679 InV = new ShiftInst(SI->getOpcode(),
1680 PN->getIncomingValue(i), C, "phitmp",
1681 NonConstBB->getTerminator());
1682 else
1683 assert(0 && "Unknown binop!");
1684
1685 WorkList.push_back(cast<Instruction>(InV));
1686 }
1687 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001688 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001689 } else {
1690 CastInst *CI = cast<CastInst>(&I);
1691 const Type *RetTy = CI->getType();
Chris Lattner7515cab2004-11-14 19:13:23 +00001692 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner04689872006-09-09 22:02:56 +00001693 Value *InV;
1694 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001695 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Chris Lattner04689872006-09-09 22:02:56 +00001696 } else {
1697 assert(PN->getIncomingBlock(i) == NonConstBB);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001698 InV = CastInst::create(CI->getOpcode(), PN->getIncomingValue(i),
1699 I.getType(), "phitmp",
1700 NonConstBB->getTerminator());
Chris Lattner04689872006-09-09 22:02:56 +00001701 WorkList.push_back(cast<Instruction>(InV));
1702 }
1703 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001704 }
1705 }
1706 return ReplaceInstUsesWith(I, NewPN);
1707}
1708
Chris Lattner113f4f42002-06-25 16:13:24 +00001709Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001710 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00001711 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattner9fa53de2002-05-06 16:49:18 +00001712
Chris Lattnercf4a9962004-04-10 22:01:55 +00001713 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattner81a7a232004-10-16 18:11:37 +00001714 // X + undef -> undef
1715 if (isa<UndefValue>(RHS))
1716 return ReplaceInstUsesWith(I, RHS);
1717
Chris Lattnercf4a9962004-04-10 22:01:55 +00001718 // X + 0 --> X
Chris Lattner7a002fe2006-12-02 00:13:08 +00001719 if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
Chris Lattner7fde91e2005-10-17 17:56:38 +00001720 if (RHSC->isNullValue())
1721 return ReplaceInstUsesWith(I, LHS);
Chris Lattnerda1b1522005-10-17 20:18:38 +00001722 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
1723 if (CFP->isExactlyValue(-0.0))
1724 return ReplaceInstUsesWith(I, LHS);
Chris Lattner7fde91e2005-10-17 17:56:38 +00001725 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001726
Chris Lattnercf4a9962004-04-10 22:01:55 +00001727 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattner6e2c15c2006-11-09 05:12:27 +00001728 // X + (signbit) --> X ^ signbit
Chris Lattner92a68652006-02-07 08:05:22 +00001729 uint64_t Val = CI->getZExtValue();
Chris Lattner77defba2006-02-07 07:00:41 +00001730 if (Val == (1ULL << (CI->getType()->getPrimitiveSizeInBits()-1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001731 return BinaryOperator::createXor(LHS, RHS);
Chris Lattner6e2c15c2006-11-09 05:12:27 +00001732
1733 // See if SimplifyDemandedBits can simplify this. This handles stuff like
1734 // (X & 254)+1 -> (X&254)|1
1735 uint64_t KnownZero, KnownOne;
1736 if (!isa<PackedType>(I.getType()) &&
1737 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
1738 KnownZero, KnownOne))
1739 return &I;
Chris Lattnercf4a9962004-04-10 22:01:55 +00001740 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001741
1742 if (isa<PHINode>(LHS))
1743 if (Instruction *NV = FoldOpIntoPhi(I))
1744 return NV;
Chris Lattner0b3557f2005-09-24 23:43:33 +00001745
Chris Lattner330628a2006-01-06 17:59:59 +00001746 ConstantInt *XorRHS = 0;
1747 Value *XorLHS = 0;
Chris Lattner0b3557f2005-09-24 23:43:33 +00001748 if (match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
1749 unsigned TySizeBits = I.getType()->getPrimitiveSizeInBits();
1750 int64_t RHSSExt = cast<ConstantInt>(RHSC)->getSExtValue();
1751 uint64_t RHSZExt = cast<ConstantInt>(RHSC)->getZExtValue();
1752
1753 uint64_t C0080Val = 1ULL << 31;
1754 int64_t CFF80Val = -C0080Val;
1755 unsigned Size = 32;
1756 do {
1757 if (TySizeBits > Size) {
1758 bool Found = false;
1759 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
1760 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
1761 if (RHSSExt == CFF80Val) {
1762 if (XorRHS->getZExtValue() == C0080Val)
1763 Found = true;
1764 } else if (RHSZExt == C0080Val) {
1765 if (XorRHS->getSExtValue() == CFF80Val)
1766 Found = true;
1767 }
1768 if (Found) {
1769 // This is a sign extend if the top bits are known zero.
Chris Lattner4534dd592006-02-09 07:38:58 +00001770 uint64_t Mask = ~0ULL;
Chris Lattnerc3ebf402006-02-07 07:27:52 +00001771 Mask <<= 64-(TySizeBits-Size);
Chris Lattner4534dd592006-02-09 07:38:58 +00001772 Mask &= XorLHS->getType()->getIntegralTypeMask();
Chris Lattnerc3ebf402006-02-07 07:27:52 +00001773 if (!MaskedValueIsZero(XorLHS, Mask))
Chris Lattner0b3557f2005-09-24 23:43:33 +00001774 Size = 0; // Not a sign ext, but can't be any others either.
1775 goto FoundSExt;
1776 }
1777 }
1778 Size >>= 1;
1779 C0080Val >>= Size;
1780 CFF80Val >>= Size;
1781 } while (Size >= 8);
1782
1783FoundSExt:
1784 const Type *MiddleType = 0;
1785 switch (Size) {
1786 default: break;
1787 case 32: MiddleType = Type::IntTy; break;
1788 case 16: MiddleType = Type::ShortTy; break;
1789 case 8: MiddleType = Type::SByteTy; break;
1790 }
1791 if (MiddleType) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001792 Instruction *NewTrunc =
1793 CastInst::createInferredCast(XorLHS, MiddleType, "sext");
Chris Lattner0b3557f2005-09-24 23:43:33 +00001794 InsertNewInstBefore(NewTrunc, I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001795 return new SExtInst(NewTrunc, I.getType());
Chris Lattner0b3557f2005-09-24 23:43:33 +00001796 }
1797 }
Chris Lattnercf4a9962004-04-10 22:01:55 +00001798 }
Chris Lattner9fa53de2002-05-06 16:49:18 +00001799
Chris Lattnerb8b97502003-08-13 19:01:45 +00001800 // X + X --> X << 1
Robert Bocchino7b5b86c2004-07-27 21:02:21 +00001801 if (I.getType()->isInteger()) {
Chris Lattnerb8b97502003-08-13 19:01:45 +00001802 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Chris Lattner47060462005-04-07 17:14:51 +00001803
1804 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
1805 if (RHSI->getOpcode() == Instruction::Sub)
1806 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
1807 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
1808 }
1809 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
1810 if (LHSI->getOpcode() == Instruction::Sub)
1811 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
1812 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
1813 }
Robert Bocchino7b5b86c2004-07-27 21:02:21 +00001814 }
Chris Lattnerede3fe02003-08-13 04:18:28 +00001815
Chris Lattner147e9752002-05-08 22:46:53 +00001816 // -A + B --> B - A
Chris Lattnerbb74e222003-03-10 23:06:50 +00001817 if (Value *V = dyn_castNegVal(LHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001818 return BinaryOperator::createSub(RHS, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +00001819
1820 // A + -B --> A - B
Chris Lattnerbb74e222003-03-10 23:06:50 +00001821 if (!isa<Constant>(RHS))
1822 if (Value *V = dyn_castNegVal(RHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001823 return BinaryOperator::createSub(LHS, V);
Chris Lattner260ab202002-04-18 17:39:14 +00001824
Misha Brukmanb1c93172005-04-21 23:48:37 +00001825
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001826 ConstantInt *C2;
1827 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
1828 if (X == RHS) // X*C + X --> X * (C+1)
1829 return BinaryOperator::createMul(RHS, AddOne(C2));
1830
1831 // X*C1 + X*C2 --> X * (C1+C2)
1832 ConstantInt *C1;
1833 if (X == dyn_castFoldableMul(RHS, C1))
1834 return BinaryOperator::createMul(X, ConstantExpr::getAdd(C1, C2));
Chris Lattner57c8d992003-02-18 19:57:07 +00001835 }
1836
1837 // X + X*C --> X * (C+1)
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001838 if (dyn_castFoldableMul(RHS, C2) == LHS)
1839 return BinaryOperator::createMul(LHS, AddOne(C2));
1840
Chris Lattner57c8d992003-02-18 19:57:07 +00001841
Chris Lattnerb8b97502003-08-13 19:01:45 +00001842 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattnerd4252a72004-07-30 07:50:03 +00001843 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattnerb8b97502003-08-13 19:01:45 +00001844 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2))) return R;
Chris Lattner7fb29e12003-03-11 00:12:48 +00001845
Chris Lattnerb9cde762003-10-02 15:11:26 +00001846 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner330628a2006-01-06 17:59:59 +00001847 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00001848 if (match(LHS, m_Not(m_Value(X)))) { // ~X + C --> (C-1) - X
1849 Constant *C= ConstantExpr::getSub(CRHS, ConstantInt::get(I.getType(), 1));
1850 return BinaryOperator::createSub(C, X);
Chris Lattnerb9cde762003-10-02 15:11:26 +00001851 }
Chris Lattnerd4252a72004-07-30 07:50:03 +00001852
Chris Lattnerbff91d92004-10-08 05:07:56 +00001853 // (X & FF00) + xx00 -> (X+xx00) & FF00
1854 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
1855 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
1856 if (Anded == CRHS) {
1857 // See if all bits from the first bit set in the Add RHS up are included
1858 // in the mask. First, get the rightmost bit.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001859 uint64_t AddRHSV = CRHS->getZExtValue();
Chris Lattnerbff91d92004-10-08 05:07:56 +00001860
1861 // Form a mask of all bits from the lowest bit added through the top.
1862 uint64_t AddRHSHighBits = ~((AddRHSV & -AddRHSV)-1);
Chris Lattner77defba2006-02-07 07:00:41 +00001863 AddRHSHighBits &= C2->getType()->getIntegralTypeMask();
Chris Lattnerbff91d92004-10-08 05:07:56 +00001864
1865 // See if the and mask includes all of these bits.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001866 uint64_t AddRHSHighBitsAnd = AddRHSHighBits & C2->getZExtValue();
Misha Brukmanb1c93172005-04-21 23:48:37 +00001867
Chris Lattnerbff91d92004-10-08 05:07:56 +00001868 if (AddRHSHighBits == AddRHSHighBitsAnd) {
1869 // Okay, the xform is safe. Insert the new add pronto.
1870 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
1871 LHS->getName()), I);
1872 return BinaryOperator::createAnd(NewAdd, C2);
1873 }
1874 }
1875 }
1876
Chris Lattnerd4252a72004-07-30 07:50:03 +00001877 // Try to fold constant add into select arguments.
1878 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner86102b82005-01-01 16:22:27 +00001879 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattnerd4252a72004-07-30 07:50:03 +00001880 return R;
Chris Lattnerb9cde762003-10-02 15:11:26 +00001881 }
1882
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001883 // add (cast *A to intptrtype) B ->
1884 // cast (GEP (cast *A to sbyte*) B) ->
1885 // intptrtype
Andrew Lenharth4f339be2006-09-19 18:24:51 +00001886 {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001887 CastInst *CI = dyn_cast<CastInst>(LHS);
1888 Value *Other = RHS;
Andrew Lenharth4f339be2006-09-19 18:24:51 +00001889 if (!CI) {
1890 CI = dyn_cast<CastInst>(RHS);
1891 Other = LHS;
1892 }
Andrew Lenharth44cb67a2006-09-20 15:37:57 +00001893 if (CI && CI->getType()->isSized() &&
1894 (CI->getType()->getPrimitiveSize() ==
1895 TD->getIntPtrType()->getPrimitiveSize())
1896 && isa<PointerType>(CI->getOperand(0)->getType())) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001897 Value *I2 = InsertCastBefore(CI->getOperand(0),
Andrew Lenharth44cb67a2006-09-20 15:37:57 +00001898 PointerType::get(Type::SByteTy), I);
1899 I2 = InsertNewInstBefore(new GetElementPtrInst(I2, Other, "ctg2"), I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001900 return new PtrToIntInst(I2, CI->getType());
Andrew Lenharth4f339be2006-09-19 18:24:51 +00001901 }
1902 }
1903
Chris Lattner113f4f42002-06-25 16:13:24 +00001904 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +00001905}
1906
Chris Lattnerbdb0ce02003-07-22 21:46:59 +00001907// isSignBit - Return true if the value represented by the constant only has the
1908// highest order bit set.
1909static bool isSignBit(ConstantInt *CI) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001910 unsigned NumBits = CI->getType()->getPrimitiveSizeInBits();
Reid Spencere0fc4df2006-10-20 07:07:24 +00001911 return (CI->getZExtValue() & (~0ULL >> (64-NumBits))) == (1ULL << (NumBits-1));
Chris Lattnerbdb0ce02003-07-22 21:46:59 +00001912}
1913
Chris Lattner022167f2004-03-13 00:11:49 +00001914/// RemoveNoopCast - Strip off nonconverting casts from the value.
1915///
1916static Value *RemoveNoopCast(Value *V) {
1917 if (CastInst *CI = dyn_cast<CastInst>(V)) {
1918 const Type *CTy = CI->getType();
1919 const Type *OpTy = CI->getOperand(0)->getType();
1920 if (CTy->isInteger() && OpTy->isInteger()) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001921 if (CTy->getPrimitiveSizeInBits() == OpTy->getPrimitiveSizeInBits())
Chris Lattner022167f2004-03-13 00:11:49 +00001922 return RemoveNoopCast(CI->getOperand(0));
1923 } else if (isa<PointerType>(CTy) && isa<PointerType>(OpTy))
1924 return RemoveNoopCast(CI->getOperand(0));
1925 }
1926 return V;
1927}
1928
Chris Lattner113f4f42002-06-25 16:13:24 +00001929Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +00001930 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001931
Chris Lattnere6794492002-08-12 21:17:25 +00001932 if (Op0 == Op1) // sub X, X -> 0
1933 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner260ab202002-04-18 17:39:14 +00001934
Chris Lattnere6794492002-08-12 21:17:25 +00001935 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattnerbb74e222003-03-10 23:06:50 +00001936 if (Value *V = dyn_castNegVal(Op1))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001937 return BinaryOperator::createAdd(Op0, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +00001938
Chris Lattner81a7a232004-10-16 18:11:37 +00001939 if (isa<UndefValue>(Op0))
1940 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
1941 if (isa<UndefValue>(Op1))
1942 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
1943
Chris Lattner8f2f5982003-11-05 01:06:05 +00001944 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
1945 // Replace (-1 - A) with (~A)...
Chris Lattner3082c5a2003-02-18 19:28:33 +00001946 if (C->isAllOnesValue())
1947 return BinaryOperator::createNot(Op1);
Chris Lattnerad3c4952002-05-09 01:29:19 +00001948
Chris Lattner8f2f5982003-11-05 01:06:05 +00001949 // C - ~X == X + (1+C)
Reid Spencer4fdd96c2005-06-18 17:37:34 +00001950 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00001951 if (match(Op1, m_Not(m_Value(X))))
1952 return BinaryOperator::createAdd(X,
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001953 ConstantExpr::getAdd(C, ConstantInt::get(I.getType(), 1)));
Chris Lattner92295c52004-03-12 23:53:13 +00001954 // -((uint)X >> 31) -> ((int)X >> 31)
1955 // -((int)X >> 31) -> ((uint)X >> 31)
Chris Lattner022167f2004-03-13 00:11:49 +00001956 if (C->isNullValue()) {
1957 Value *NoopCastedRHS = RemoveNoopCast(Op1);
1958 if (ShiftInst *SI = dyn_cast<ShiftInst>(NoopCastedRHS))
Reid Spencerfdff9382006-11-08 06:47:33 +00001959 if (SI->getOpcode() == Instruction::LShr) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00001960 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
Chris Lattner92295c52004-03-12 23:53:13 +00001961 // Check to see if we are shifting out everything but the sign bit.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001962 if (CU->getZExtValue() ==
1963 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerfdff9382006-11-08 06:47:33 +00001964 // Ok, the transformation is safe. Insert AShr.
1965 return new ShiftInst(Instruction::AShr, SI->getOperand(0),
1966 CU, SI->getName());
Chris Lattner92295c52004-03-12 23:53:13 +00001967 }
1968 }
Reid Spencerfdff9382006-11-08 06:47:33 +00001969 }
1970 else if (SI->getOpcode() == Instruction::AShr) {
1971 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
1972 // Check to see if we are shifting out everything but the sign bit.
1973 if (CU->getZExtValue() ==
1974 SI->getType()->getPrimitiveSizeInBits()-1) {
1975 // Ok, the transformation is safe. Insert LShr.
1976 return new ShiftInst(Instruction::LShr, SI->getOperand(0),
1977 CU, SI->getName());
1978 }
1979 }
1980 }
Chris Lattner022167f2004-03-13 00:11:49 +00001981 }
Chris Lattner183b3362004-04-09 19:05:30 +00001982
1983 // Try to fold constant sub into select arguments.
1984 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner86102b82005-01-01 16:22:27 +00001985 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00001986 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001987
1988 if (isa<PHINode>(Op0))
1989 if (Instruction *NV = FoldOpIntoPhi(I))
1990 return NV;
Chris Lattner8f2f5982003-11-05 01:06:05 +00001991 }
1992
Chris Lattnera9be4492005-04-07 16:15:25 +00001993 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
1994 if (Op1I->getOpcode() == Instruction::Add &&
Chris Lattner7a002fe2006-12-02 00:13:08 +00001995 !Op0->getType()->isFPOrFPVector()) {
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00001996 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Chris Lattnera9be4492005-04-07 16:15:25 +00001997 return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00001998 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Chris Lattnera9be4492005-04-07 16:15:25 +00001999 return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00002000 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2001 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2002 // C1-(X+C2) --> (C1-C2)-X
2003 return BinaryOperator::createSub(ConstantExpr::getSub(CI1, CI2),
2004 Op1I->getOperand(0));
2005 }
Chris Lattnera9be4492005-04-07 16:15:25 +00002006 }
2007
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002008 if (Op1I->hasOneUse()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00002009 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2010 // is not used by anyone else...
2011 //
Chris Lattnerc2f0aa52004-02-02 20:09:56 +00002012 if (Op1I->getOpcode() == Instruction::Sub &&
Chris Lattner7a002fe2006-12-02 00:13:08 +00002013 !Op1I->getType()->isFPOrFPVector()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00002014 // Swap the two operands of the subexpr...
2015 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2016 Op1I->setOperand(0, IIOp1);
2017 Op1I->setOperand(1, IIOp0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002018
Chris Lattner3082c5a2003-02-18 19:28:33 +00002019 // Create the new top level add instruction...
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002020 return BinaryOperator::createAdd(Op0, Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002021 }
2022
2023 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2024 //
2025 if (Op1I->getOpcode() == Instruction::And &&
2026 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2027 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2028
Chris Lattner396dbfe2004-06-09 05:08:07 +00002029 Value *NewNot =
2030 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002031 return BinaryOperator::createAnd(Op0, NewNot);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002032 }
Chris Lattner57c8d992003-02-18 19:57:07 +00002033
Reid Spencer3c514952006-10-16 23:08:08 +00002034 // 0 - (X sdiv C) -> (X sdiv -C)
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002035 if (Op1I->getOpcode() == Instruction::SDiv)
Reid Spencere0fc4df2006-10-20 07:07:24 +00002036 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002037 if (CSI->isNullValue())
Chris Lattner0aee4b72004-10-06 15:08:25 +00002038 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002039 return BinaryOperator::createSDiv(Op1I->getOperand(0),
Chris Lattner0aee4b72004-10-06 15:08:25 +00002040 ConstantExpr::getNeg(DivRHS));
2041
Chris Lattner57c8d992003-02-18 19:57:07 +00002042 // X - X*C --> X * (1-C)
Reid Spencer4fdd96c2005-06-18 17:37:34 +00002043 ConstantInt *C2 = 0;
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002044 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00002045 Constant *CP1 =
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002046 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1), C2);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002047 return BinaryOperator::createMul(Op0, CP1);
Chris Lattner57c8d992003-02-18 19:57:07 +00002048 }
Chris Lattnerad3c4952002-05-09 01:29:19 +00002049 }
Chris Lattnera9be4492005-04-07 16:15:25 +00002050 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00002051
Chris Lattner7a002fe2006-12-02 00:13:08 +00002052 if (!Op0->getType()->isFPOrFPVector())
Chris Lattner47060462005-04-07 17:14:51 +00002053 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2054 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner411336f2005-01-19 21:50:18 +00002055 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2056 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2057 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2058 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner47060462005-04-07 17:14:51 +00002059 } else if (Op0I->getOpcode() == Instruction::Sub) {
2060 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
2061 return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
Chris Lattner411336f2005-01-19 21:50:18 +00002062 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002063
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002064 ConstantInt *C1;
2065 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2066 if (X == Op1) { // X*C - X --> X * (C-1)
2067 Constant *CP1 = ConstantExpr::getSub(C1, ConstantInt::get(I.getType(),1));
2068 return BinaryOperator::createMul(Op1, CP1);
2069 }
Chris Lattner57c8d992003-02-18 19:57:07 +00002070
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002071 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
2072 if (X == dyn_castFoldableMul(Op1, C2))
2073 return BinaryOperator::createMul(Op1, ConstantExpr::getSub(C1, C2));
2074 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002075 return 0;
Chris Lattner260ab202002-04-18 17:39:14 +00002076}
2077
Chris Lattnere79e8542004-02-23 06:38:22 +00002078/// isSignBitCheck - Given an exploded setcc instruction, return true if it is
2079/// really just returns true if the most significant (sign) bit is set.
2080static bool isSignBitCheck(unsigned Opcode, Value *LHS, ConstantInt *RHS) {
2081 if (RHS->getType()->isSigned()) {
2082 // True if source is LHS < 0 or LHS <= -1
2083 return Opcode == Instruction::SetLT && RHS->isNullValue() ||
2084 Opcode == Instruction::SetLE && RHS->isAllOnesValue();
2085 } else {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002086 ConstantInt *RHSC = cast<ConstantInt>(RHS);
Chris Lattnere79e8542004-02-23 06:38:22 +00002087 // True if source is LHS > 127 or LHS >= 128, where the constants depend on
2088 // the size of the integer type.
2089 if (Opcode == Instruction::SetGE)
Reid Spencere0fc4df2006-10-20 07:07:24 +00002090 return RHSC->getZExtValue() ==
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002091 1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1);
Chris Lattnere79e8542004-02-23 06:38:22 +00002092 if (Opcode == Instruction::SetGT)
Reid Spencere0fc4df2006-10-20 07:07:24 +00002093 return RHSC->getZExtValue() ==
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002094 (1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1))-1;
Chris Lattnere79e8542004-02-23 06:38:22 +00002095 }
2096 return false;
2097}
2098
Chris Lattner113f4f42002-06-25 16:13:24 +00002099Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00002100 bool Changed = SimplifyCommutative(I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002101 Value *Op0 = I.getOperand(0);
Chris Lattner260ab202002-04-18 17:39:14 +00002102
Chris Lattner81a7a232004-10-16 18:11:37 +00002103 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
2104 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2105
Chris Lattnere6794492002-08-12 21:17:25 +00002106 // Simplify mul instructions with a constant RHS...
Chris Lattner3082c5a2003-02-18 19:28:33 +00002107 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2108 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerede3fe02003-08-13 04:18:28 +00002109
2110 // ((X << C1)*C2) == (X * (C2 << C1))
2111 if (ShiftInst *SI = dyn_cast<ShiftInst>(Op0))
2112 if (SI->getOpcode() == Instruction::Shl)
2113 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002114 return BinaryOperator::createMul(SI->getOperand(0),
2115 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanb1c93172005-04-21 23:48:37 +00002116
Chris Lattnercce81be2003-09-11 22:24:54 +00002117 if (CI->isNullValue())
2118 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2119 if (CI->equalsInt(1)) // X * 1 == X
2120 return ReplaceInstUsesWith(I, Op0);
2121 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Chris Lattner35236d82003-06-25 17:09:20 +00002122 return BinaryOperator::createNeg(Op0, I.getName());
Chris Lattner31ba1292002-04-29 22:24:47 +00002123
Reid Spencere0fc4df2006-10-20 07:07:24 +00002124 int64_t Val = (int64_t)cast<ConstantInt>(CI)->getZExtValue();
Chris Lattner22d00a82005-08-02 19:16:58 +00002125 if (isPowerOf2_64(Val)) { // Replace X*(2^C) with X << C
2126 uint64_t C = Log2_64(Val);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002127 return new ShiftInst(Instruction::Shl, Op0,
Reid Spencere0fc4df2006-10-20 07:07:24 +00002128 ConstantInt::get(Type::UByteTy, C));
Chris Lattner22d00a82005-08-02 19:16:58 +00002129 }
Robert Bocchino7b5b86c2004-07-27 21:02:21 +00002130 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00002131 if (Op1F->isNullValue())
2132 return ReplaceInstUsesWith(I, Op1);
Chris Lattner31ba1292002-04-29 22:24:47 +00002133
Chris Lattner3082c5a2003-02-18 19:28:33 +00002134 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2135 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2136 if (Op1F->getValue() == 1.0)
2137 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
2138 }
Chris Lattner32c01df2006-03-04 06:04:02 +00002139
2140 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2141 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2142 isa<ConstantInt>(Op0I->getOperand(1))) {
2143 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2144 Instruction *Add = BinaryOperator::createMul(Op0I->getOperand(0),
2145 Op1, "tmp");
2146 InsertNewInstBefore(Add, I);
2147 Value *C1C2 = ConstantExpr::getMul(Op1,
2148 cast<Constant>(Op0I->getOperand(1)));
2149 return BinaryOperator::createAdd(Add, C1C2);
2150
2151 }
Chris Lattner183b3362004-04-09 19:05:30 +00002152
2153 // Try to fold constant mul into select arguments.
2154 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00002155 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00002156 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002157
2158 if (isa<PHINode>(Op0))
2159 if (Instruction *NV = FoldOpIntoPhi(I))
2160 return NV;
Chris Lattner260ab202002-04-18 17:39:14 +00002161 }
2162
Chris Lattner934a64cf2003-03-10 23:23:04 +00002163 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
2164 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002165 return BinaryOperator::createMul(Op0v, Op1v);
Chris Lattner934a64cf2003-03-10 23:23:04 +00002166
Chris Lattner2635b522004-02-23 05:39:21 +00002167 // If one of the operands of the multiply is a cast from a boolean value, then
2168 // we know the bool is either zero or one, so this is a 'masking' multiply.
2169 // See if we can simplify things based on how the boolean was originally
2170 // formed.
2171 CastInst *BoolCast = 0;
2172 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(0)))
2173 if (CI->getOperand(0)->getType() == Type::BoolTy)
2174 BoolCast = CI;
2175 if (!BoolCast)
2176 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(1)))
2177 if (CI->getOperand(0)->getType() == Type::BoolTy)
2178 BoolCast = CI;
2179 if (BoolCast) {
2180 if (SetCondInst *SCI = dyn_cast<SetCondInst>(BoolCast->getOperand(0))) {
2181 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2182 const Type *SCOpTy = SCIOp0->getType();
2183
Chris Lattnere79e8542004-02-23 06:38:22 +00002184 // If the setcc is true iff the sign bit of X is set, then convert this
2185 // multiply into a shift/and combination.
2186 if (isa<ConstantInt>(SCIOp1) &&
2187 isSignBitCheck(SCI->getOpcode(), SCIOp0, cast<ConstantInt>(SCIOp1))) {
Chris Lattner2635b522004-02-23 05:39:21 +00002188 // Shift the X value right to turn it into "all signbits".
Reid Spencere0fc4df2006-10-20 07:07:24 +00002189 Constant *Amt = ConstantInt::get(Type::UByteTy,
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002190 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattnere79e8542004-02-23 06:38:22 +00002191 if (SCIOp0->getType()->isUnsigned()) {
Chris Lattner97bfcea2004-06-17 18:16:02 +00002192 const Type *NewTy = SCIOp0->getType()->getSignedVersion();
Reid Spencer00c482b2006-10-26 19:19:06 +00002193 SCIOp0 = InsertCastBefore(SCIOp0, NewTy, I);
Chris Lattnere79e8542004-02-23 06:38:22 +00002194 }
2195
2196 Value *V =
Reid Spencerfdff9382006-11-08 06:47:33 +00002197 InsertNewInstBefore(new ShiftInst(Instruction::AShr, SCIOp0, Amt,
Chris Lattnere79e8542004-02-23 06:38:22 +00002198 BoolCast->getOperand(0)->getName()+
2199 ".mask"), I);
Chris Lattner2635b522004-02-23 05:39:21 +00002200
2201 // If the multiply type is not the same as the source type, sign extend
2202 // or truncate to the multiply type.
2203 if (I.getType() != V->getType())
Reid Spencer00c482b2006-10-26 19:19:06 +00002204 V = InsertCastBefore(V, I.getType(), I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002205
Chris Lattner2635b522004-02-23 05:39:21 +00002206 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002207 return BinaryOperator::createAnd(V, OtherOp);
Chris Lattner2635b522004-02-23 05:39:21 +00002208 }
2209 }
2210 }
2211
Chris Lattner113f4f42002-06-25 16:13:24 +00002212 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +00002213}
2214
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002215/// This function implements the transforms on div instructions that work
2216/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2217/// used by the visitors to those instructions.
2218/// @brief Transforms common to all three div instructions
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002219Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002220 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner81a7a232004-10-16 18:11:37 +00002221
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002222 // undef / X -> 0
2223 if (isa<UndefValue>(Op0))
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002224 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002225
2226 // X / undef -> undef
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002227 if (isa<UndefValue>(Op1))
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002228 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002229
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002230 // Handle cases involving: div X, (select Cond, Y, Z)
Chris Lattnerd79dc792006-09-09 20:26:32 +00002231 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2232 // div X, (Cond ? 0 : Y) -> div X, Y. If the div and the select are in the
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002233 // same basic block, then we replace the select with Y, and the condition
2234 // of the select with false (if the cond value is in the same BB). If the
Chris Lattnerd79dc792006-09-09 20:26:32 +00002235 // select has uses other than the div, this allows them to be simplified
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002236 // also. Note that div X, Y is just as good as div X, 0 (undef)
Chris Lattnerd79dc792006-09-09 20:26:32 +00002237 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2238 if (ST->isNullValue()) {
2239 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2240 if (CondI && CondI->getParent() == I.getParent())
Chris Lattner6ab03f62006-09-28 23:35:22 +00002241 UpdateValueUsesWith(CondI, ConstantBool::getFalse());
Chris Lattnerd79dc792006-09-09 20:26:32 +00002242 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2243 I.setOperand(1, SI->getOperand(2));
2244 else
2245 UpdateValueUsesWith(SI, SI->getOperand(2));
2246 return &I;
2247 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002248
Chris Lattnerd79dc792006-09-09 20:26:32 +00002249 // Likewise for: div X, (Cond ? Y : 0) -> div X, Y
2250 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2251 if (ST->isNullValue()) {
2252 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2253 if (CondI && CondI->getParent() == I.getParent())
Chris Lattner6ab03f62006-09-28 23:35:22 +00002254 UpdateValueUsesWith(CondI, ConstantBool::getTrue());
Chris Lattnerd79dc792006-09-09 20:26:32 +00002255 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2256 I.setOperand(1, SI->getOperand(1));
2257 else
2258 UpdateValueUsesWith(SI, SI->getOperand(1));
2259 return &I;
2260 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002261 }
Chris Lattnerd79dc792006-09-09 20:26:32 +00002262
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002263 return 0;
2264}
Misha Brukmanb1c93172005-04-21 23:48:37 +00002265
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002266/// This function implements the transforms common to both integer division
2267/// instructions (udiv and sdiv). It is called by the visitors to those integer
2268/// division instructions.
2269/// @brief Common integer divide transforms
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002270Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002271 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2272
2273 if (Instruction *Common = commonDivTransforms(I))
2274 return Common;
2275
2276 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2277 // div X, 1 == X
2278 if (RHS->equalsInt(1))
2279 return ReplaceInstUsesWith(I, Op0);
2280
2281 // (X / C1) / C2 -> X / (C1*C2)
2282 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2283 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2284 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
2285 return BinaryOperator::create(I.getOpcode(), LHS->getOperand(0),
2286 ConstantExpr::getMul(RHS, LHSRHS));
Chris Lattner42362612005-04-08 04:03:26 +00002287 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002288
2289 if (!RHS->isNullValue()) { // avoid X udiv 0
2290 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2291 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2292 return R;
2293 if (isa<PHINode>(Op0))
2294 if (Instruction *NV = FoldOpIntoPhi(I))
2295 return NV;
2296 }
Chris Lattnerd79dc792006-09-09 20:26:32 +00002297 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002298
Chris Lattner3082c5a2003-02-18 19:28:33 +00002299 // 0 / X == 0, we don't need to preserve faults!
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002300 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattner3082c5a2003-02-18 19:28:33 +00002301 if (LHS->equalsInt(0))
2302 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2303
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002304 return 0;
2305}
2306
2307Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2308 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2309
2310 // Handle the integer div common cases
2311 if (Instruction *Common = commonIDivTransforms(I))
2312 return Common;
2313
2314 // X udiv C^2 -> X >> C
2315 // Check to see if this is an unsigned division with an exact power of 2,
2316 // if so, convert to a right shift.
2317 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
2318 if (uint64_t Val = C->getZExtValue()) // Don't break X / 0
2319 if (isPowerOf2_64(Val)) {
2320 uint64_t ShiftAmt = Log2_64(Val);
Reid Spencerfdff9382006-11-08 06:47:33 +00002321 return new ShiftInst(Instruction::LShr, Op0,
2322 ConstantInt::get(Type::UByteTy, ShiftAmt));
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002323 }
2324 }
2325
2326 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
2327 if (ShiftInst *RHSI = dyn_cast<ShiftInst>(I.getOperand(1))) {
2328 if (RHSI->getOpcode() == Instruction::Shl &&
2329 isa<ConstantInt>(RHSI->getOperand(0))) {
2330 uint64_t C1 = cast<ConstantInt>(RHSI->getOperand(0))->getZExtValue();
2331 if (isPowerOf2_64(C1)) {
2332 Value *N = RHSI->getOperand(1);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002333 const Type *NTy = N->getType();
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002334 if (uint64_t C2 = Log2_64(C1)) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002335 Constant *C2V = ConstantInt::get(NTy, C2);
2336 N = InsertNewInstBefore(BinaryOperator::createAdd(N, C2V, "tmp"), I);
Chris Lattner2e90b732006-02-05 07:54:04 +00002337 }
Reid Spencerfdff9382006-11-08 06:47:33 +00002338 return new ShiftInst(Instruction::LShr, Op0, N);
Chris Lattner2e90b732006-02-05 07:54:04 +00002339 }
2340 }
Chris Lattnerdd0c1742005-11-05 07:40:31 +00002341 }
2342
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002343 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
2344 // where C1&C2 are powers of two.
2345 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2346 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2347 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2)))
2348 if (!STO->isNullValue() && !STO->isNullValue()) {
2349 uint64_t TVA = STO->getZExtValue(), FVA = SFO->getZExtValue();
2350 if (isPowerOf2_64(TVA) && isPowerOf2_64(FVA)) {
2351 // Compute the shift amounts
2352 unsigned TSA = Log2_64(TVA), FSA = Log2_64(FVA);
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002353 // Construct the "on true" case of the select
2354 Constant *TC = ConstantInt::get(Type::UByteTy, TSA);
2355 Instruction *TSI =
Reid Spencerfdff9382006-11-08 06:47:33 +00002356 new ShiftInst(Instruction::LShr, Op0, TC, SI->getName()+".t");
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002357 TSI = InsertNewInstBefore(TSI, I);
2358
2359 // Construct the "on false" case of the select
2360 Constant *FC = ConstantInt::get(Type::UByteTy, FSA);
2361 Instruction *FSI =
Reid Spencerfdff9382006-11-08 06:47:33 +00002362 new ShiftInst(Instruction::LShr, Op0, FC, SI->getName()+".f");
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002363 FSI = InsertNewInstBefore(FSI, I);
2364
2365 // construct the select instruction and return it.
Reid Spencerfdff9382006-11-08 06:47:33 +00002366 return new SelectInst(SI->getOperand(0), TSI, FSI, SI->getName());
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002367 }
2368 }
2369 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002370 return 0;
2371}
2372
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002373Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
2374 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2375
2376 // Handle the integer div common cases
2377 if (Instruction *Common = commonIDivTransforms(I))
2378 return Common;
2379
2380 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2381 // sdiv X, -1 == -X
2382 if (RHS->isAllOnesValue())
2383 return BinaryOperator::createNeg(Op0);
2384
2385 // -X/C -> X/-C
2386 if (Value *LHSNeg = dyn_castNegVal(Op0))
2387 return BinaryOperator::createSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
2388 }
2389
2390 // If the sign bits of both operands are zero (i.e. we can prove they are
2391 // unsigned inputs), turn this into a udiv.
2392 if (I.getType()->isInteger()) {
2393 uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
2394 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2395 return BinaryOperator::createUDiv(Op0, Op1, I.getName());
2396 }
2397 }
2398
2399 return 0;
2400}
2401
2402Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
2403 return commonDivTransforms(I);
2404}
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002405
Chris Lattner85dda9a2006-03-02 06:50:58 +00002406/// GetFactor - If we can prove that the specified value is at least a multiple
2407/// of some factor, return that factor.
2408static Constant *GetFactor(Value *V) {
2409 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
2410 return CI;
2411
2412 // Unless we can be tricky, we know this is a multiple of 1.
2413 Constant *Result = ConstantInt::get(V->getType(), 1);
2414
2415 Instruction *I = dyn_cast<Instruction>(V);
2416 if (!I) return Result;
2417
2418 if (I->getOpcode() == Instruction::Mul) {
2419 // Handle multiplies by a constant, etc.
2420 return ConstantExpr::getMul(GetFactor(I->getOperand(0)),
2421 GetFactor(I->getOperand(1)));
2422 } else if (I->getOpcode() == Instruction::Shl) {
2423 // (X<<C) -> X * (1 << C)
2424 if (Constant *ShRHS = dyn_cast<Constant>(I->getOperand(1))) {
2425 ShRHS = ConstantExpr::getShl(Result, ShRHS);
2426 return ConstantExpr::getMul(GetFactor(I->getOperand(0)), ShRHS);
2427 }
2428 } else if (I->getOpcode() == Instruction::And) {
2429 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
2430 // X & 0xFFF0 is known to be a multiple of 16.
2431 unsigned Zeros = CountTrailingZeros_64(RHS->getZExtValue());
2432 if (Zeros != V->getType()->getPrimitiveSizeInBits())
2433 return ConstantExpr::getShl(Result,
Reid Spencere0fc4df2006-10-20 07:07:24 +00002434 ConstantInt::get(Type::UByteTy, Zeros));
Chris Lattner85dda9a2006-03-02 06:50:58 +00002435 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002436 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
Chris Lattner85dda9a2006-03-02 06:50:58 +00002437 // Only handle int->int casts.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002438 if (!CI->isIntegerCast())
2439 return Result;
2440 Value *Op = CI->getOperand(0);
2441 return ConstantExpr::getCast(CI->getOpcode(), GetFactor(Op), V->getType());
Chris Lattner85dda9a2006-03-02 06:50:58 +00002442 }
2443 return Result;
2444}
2445
Reid Spencer7eb55b32006-11-02 01:53:59 +00002446/// This function implements the transforms on rem instructions that work
2447/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
2448/// is used by the visitors to those instructions.
2449/// @brief Transforms common to all three rem instructions
2450Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002451 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Reid Spencer7eb55b32006-11-02 01:53:59 +00002452
Chris Lattner0de4a8d2006-02-28 05:30:45 +00002453 // 0 % X == 0, we don't need to preserve faults!
2454 if (Constant *LHS = dyn_cast<Constant>(Op0))
2455 if (LHS->isNullValue())
2456 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2457
2458 if (isa<UndefValue>(Op0)) // undef % X -> 0
2459 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2460 if (isa<UndefValue>(Op1))
2461 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Reid Spencer7eb55b32006-11-02 01:53:59 +00002462
2463 // Handle cases involving: rem X, (select Cond, Y, Z)
2464 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2465 // rem X, (Cond ? 0 : Y) -> rem X, Y. If the rem and the select are in
2466 // the same basic block, then we replace the select with Y, and the
2467 // condition of the select with false (if the cond value is in the same
2468 // BB). If the select has uses other than the div, this allows them to be
2469 // simplified also.
2470 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2471 if (ST->isNullValue()) {
2472 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2473 if (CondI && CondI->getParent() == I.getParent())
2474 UpdateValueUsesWith(CondI, ConstantBool::getFalse());
2475 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2476 I.setOperand(1, SI->getOperand(2));
2477 else
2478 UpdateValueUsesWith(SI, SI->getOperand(2));
Chris Lattner7fd5f072004-07-06 07:01:22 +00002479 return &I;
2480 }
Reid Spencer7eb55b32006-11-02 01:53:59 +00002481 // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
2482 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2483 if (ST->isNullValue()) {
2484 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2485 if (CondI && CondI->getParent() == I.getParent())
2486 UpdateValueUsesWith(CondI, ConstantBool::getTrue());
2487 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2488 I.setOperand(1, SI->getOperand(1));
2489 else
2490 UpdateValueUsesWith(SI, SI->getOperand(1));
2491 return &I;
2492 }
Chris Lattnere9ff0ea2005-11-05 07:28:37 +00002493 }
Chris Lattner7fd5f072004-07-06 07:01:22 +00002494
Reid Spencer7eb55b32006-11-02 01:53:59 +00002495 return 0;
2496}
2497
2498/// This function implements the transforms common to both integer remainder
2499/// instructions (urem and srem). It is called by the visitors to those integer
2500/// remainder instructions.
2501/// @brief Common integer remainder transforms
2502Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
2503 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2504
2505 if (Instruction *common = commonRemTransforms(I))
2506 return common;
2507
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002508 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner0de4a8d2006-02-28 05:30:45 +00002509 // X % 0 == undef, we don't need to preserve faults!
2510 if (RHS->equalsInt(0))
2511 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2512
Chris Lattner3082c5a2003-02-18 19:28:33 +00002513 if (RHS->equalsInt(1)) // X % 1 == 0
2514 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2515
Chris Lattnerb70f1412006-02-28 05:49:21 +00002516 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2517 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2518 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2519 return R;
2520 } else if (isa<PHINode>(Op0I)) {
2521 if (Instruction *NV = FoldOpIntoPhi(I))
2522 return NV;
Chris Lattnerb70f1412006-02-28 05:49:21 +00002523 }
Reid Spencer7eb55b32006-11-02 01:53:59 +00002524 // (X * C1) % C2 --> 0 iff C1 % C2 == 0
2525 if (ConstantExpr::getSRem(GetFactor(Op0I), RHS)->isNullValue())
Chris Lattner85dda9a2006-03-02 06:50:58 +00002526 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerb70f1412006-02-28 05:49:21 +00002527 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00002528 }
2529
Reid Spencer7eb55b32006-11-02 01:53:59 +00002530 return 0;
2531}
2532
2533Instruction *InstCombiner::visitURem(BinaryOperator &I) {
2534 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2535
2536 if (Instruction *common = commonIRemTransforms(I))
2537 return common;
2538
2539 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2540 // X urem C^2 -> X and C
2541 // Check to see if this is an unsigned remainder with an exact power of 2,
2542 // if so, convert to a bitwise and.
2543 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
2544 if (isPowerOf2_64(C->getZExtValue()))
2545 return BinaryOperator::createAnd(Op0, SubOne(C));
2546 }
2547
Chris Lattner2e90b732006-02-05 07:54:04 +00002548 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00002549 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
2550 if (RHSI->getOpcode() == Instruction::Shl &&
2551 isa<ConstantInt>(RHSI->getOperand(0))) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002552 unsigned C1 = cast<ConstantInt>(RHSI->getOperand(0))->getZExtValue();
Chris Lattner2e90b732006-02-05 07:54:04 +00002553 if (isPowerOf2_64(C1)) {
2554 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
2555 Value *Add = InsertNewInstBefore(BinaryOperator::createAdd(RHSI, N1,
2556 "tmp"), I);
2557 return BinaryOperator::createAnd(Op0, Add);
2558 }
2559 }
Reid Spencer7eb55b32006-11-02 01:53:59 +00002560 }
Chris Lattnerd79dc792006-09-09 20:26:32 +00002561
Reid Spencer7eb55b32006-11-02 01:53:59 +00002562 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
2563 // where C1&C2 are powers of two.
2564 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2565 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2566 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
2567 // STO == 0 and SFO == 0 handled above.
2568 if (isPowerOf2_64(STO->getZExtValue()) &&
2569 isPowerOf2_64(SFO->getZExtValue())) {
2570 Value *TrueAnd = InsertNewInstBefore(
2571 BinaryOperator::createAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
2572 Value *FalseAnd = InsertNewInstBefore(
2573 BinaryOperator::createAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
2574 return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
2575 }
2576 }
Chris Lattner2e90b732006-02-05 07:54:04 +00002577 }
2578
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002579 return 0;
2580}
2581
Reid Spencer7eb55b32006-11-02 01:53:59 +00002582Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
2583 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2584
2585 if (Instruction *common = commonIRemTransforms(I))
2586 return common;
2587
2588 if (Value *RHSNeg = dyn_castNegVal(Op1))
2589 if (!isa<ConstantInt>(RHSNeg) ||
2590 cast<ConstantInt>(RHSNeg)->getSExtValue() > 0) {
2591 // X % -Y -> X % Y
2592 AddUsesToWorkList(I);
2593 I.setOperand(1, RHSNeg);
2594 return &I;
2595 }
2596
2597 // If the top bits of both operands are zero (i.e. we can prove they are
2598 // unsigned inputs), turn this into a urem.
2599 uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
2600 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2601 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
2602 return BinaryOperator::createURem(Op0, Op1, I.getName());
2603 }
2604
2605 return 0;
2606}
2607
2608Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00002609 return commonRemTransforms(I);
2610}
2611
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002612// isMaxValueMinusOne - return true if this is Max-1
Chris Lattnere6794492002-08-12 21:17:25 +00002613static bool isMaxValueMinusOne(const ConstantInt *C) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002614 if (C->getType()->isUnsigned())
2615 return C->getZExtValue() == C->getType()->getIntegralTypeMask()-1;
Misha Brukmanb1c93172005-04-21 23:48:37 +00002616
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002617 // Calculate 0111111111..11111
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002618 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002619 int64_t Val = INT64_MAX; // All ones
2620 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
Reid Spencere0fc4df2006-10-20 07:07:24 +00002621 return C->getSExtValue() == Val-1;
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002622}
2623
2624// isMinValuePlusOne - return true if this is Min+1
Chris Lattnere6794492002-08-12 21:17:25 +00002625static bool isMinValuePlusOne(const ConstantInt *C) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002626 if (C->getType()->isUnsigned())
2627 return C->getZExtValue() == 1;
Misha Brukmanb1c93172005-04-21 23:48:37 +00002628
2629 // Calculate 1111111111000000000000
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002630 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002631 int64_t Val = -1; // All ones
2632 Val <<= TypeBits-1; // Shift over to the right spot
Reid Spencere0fc4df2006-10-20 07:07:24 +00002633 return C->getSExtValue() == Val+1;
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002634}
2635
Chris Lattner35167c32004-06-09 07:59:58 +00002636// isOneBitSet - Return true if there is exactly one bit set in the specified
2637// constant.
2638static bool isOneBitSet(const ConstantInt *CI) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002639 uint64_t V = CI->getZExtValue();
Chris Lattner35167c32004-06-09 07:59:58 +00002640 return V && (V & (V-1)) == 0;
2641}
2642
Chris Lattner8fc5af42004-09-23 21:46:38 +00002643#if 0 // Currently unused
2644// isLowOnes - Return true if the constant is of the form 0+1+.
2645static bool isLowOnes(const ConstantInt *CI) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002646 uint64_t V = CI->getZExtValue();
Chris Lattner8fc5af42004-09-23 21:46:38 +00002647
2648 // There won't be bits set in parts that the type doesn't contain.
Reid Spencere0fc4df2006-10-20 07:07:24 +00002649 V &= ConstantInt::getAllOnesValue(CI->getType())->getZExtValue();
Chris Lattner8fc5af42004-09-23 21:46:38 +00002650
2651 uint64_t U = V+1; // If it is low ones, this should be a power of two.
2652 return U && V && (U & V) == 0;
2653}
2654#endif
2655
2656// isHighOnes - Return true if the constant is of the form 1+0+.
2657// This is the same as lowones(~X).
2658static bool isHighOnes(const ConstantInt *CI) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002659 uint64_t V = ~CI->getZExtValue();
Chris Lattner2c14cf72005-08-07 07:03:10 +00002660 if (~V == 0) return false; // 0's does not match "1+"
Chris Lattner8fc5af42004-09-23 21:46:38 +00002661
2662 // There won't be bits set in parts that the type doesn't contain.
Reid Spencere0fc4df2006-10-20 07:07:24 +00002663 V &= ConstantInt::getAllOnesValue(CI->getType())->getZExtValue();
Chris Lattner8fc5af42004-09-23 21:46:38 +00002664
2665 uint64_t U = V+1; // If it is low ones, this should be a power of two.
2666 return U && V && (U & V) == 0;
2667}
2668
2669
Chris Lattner3ac7c262003-08-13 20:16:26 +00002670/// getSetCondCode - Encode a setcc opcode into a three bit mask. These bits
2671/// are carefully arranged to allow folding of expressions such as:
2672///
2673/// (A < B) | (A > B) --> (A != B)
2674///
2675/// Bit value '4' represents that the comparison is true if A > B, bit value '2'
2676/// represents that the comparison is true if A == B, and bit value '1' is true
2677/// if A < B.
2678///
2679static unsigned getSetCondCode(const SetCondInst *SCI) {
2680 switch (SCI->getOpcode()) {
2681 // False -> 0
2682 case Instruction::SetGT: return 1;
2683 case Instruction::SetEQ: return 2;
2684 case Instruction::SetGE: return 3;
2685 case Instruction::SetLT: return 4;
2686 case Instruction::SetNE: return 5;
2687 case Instruction::SetLE: return 6;
2688 // True -> 7
2689 default:
2690 assert(0 && "Invalid SetCC opcode!");
2691 return 0;
2692 }
2693}
2694
2695/// getSetCCValue - This is the complement of getSetCondCode, which turns an
2696/// opcode and two operands into either a constant true or false, or a brand new
2697/// SetCC instruction.
2698static Value *getSetCCValue(unsigned Opcode, Value *LHS, Value *RHS) {
2699 switch (Opcode) {
Chris Lattner6ab03f62006-09-28 23:35:22 +00002700 case 0: return ConstantBool::getFalse();
Chris Lattner3ac7c262003-08-13 20:16:26 +00002701 case 1: return new SetCondInst(Instruction::SetGT, LHS, RHS);
2702 case 2: return new SetCondInst(Instruction::SetEQ, LHS, RHS);
2703 case 3: return new SetCondInst(Instruction::SetGE, LHS, RHS);
2704 case 4: return new SetCondInst(Instruction::SetLT, LHS, RHS);
2705 case 5: return new SetCondInst(Instruction::SetNE, LHS, RHS);
2706 case 6: return new SetCondInst(Instruction::SetLE, LHS, RHS);
Chris Lattner6ab03f62006-09-28 23:35:22 +00002707 case 7: return ConstantBool::getTrue();
Chris Lattner3ac7c262003-08-13 20:16:26 +00002708 default: assert(0 && "Illegal SetCCCode!"); return 0;
2709 }
2710}
2711
2712// FoldSetCCLogical - Implements (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
Chris Lattnere3a63d12006-11-15 04:53:24 +00002713namespace {
Chris Lattner3ac7c262003-08-13 20:16:26 +00002714struct FoldSetCCLogical {
2715 InstCombiner &IC;
2716 Value *LHS, *RHS;
2717 FoldSetCCLogical(InstCombiner &ic, SetCondInst *SCI)
2718 : IC(ic), LHS(SCI->getOperand(0)), RHS(SCI->getOperand(1)) {}
2719 bool shouldApply(Value *V) const {
2720 if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
2721 return (SCI->getOperand(0) == LHS && SCI->getOperand(1) == RHS ||
2722 SCI->getOperand(0) == RHS && SCI->getOperand(1) == LHS);
2723 return false;
2724 }
2725 Instruction *apply(BinaryOperator &Log) const {
2726 SetCondInst *SCI = cast<SetCondInst>(Log.getOperand(0));
2727 if (SCI->getOperand(0) != LHS) {
2728 assert(SCI->getOperand(1) == LHS);
2729 SCI->swapOperands(); // Swap the LHS and RHS of the SetCC
2730 }
2731
2732 unsigned LHSCode = getSetCondCode(SCI);
2733 unsigned RHSCode = getSetCondCode(cast<SetCondInst>(Log.getOperand(1)));
2734 unsigned Code;
2735 switch (Log.getOpcode()) {
2736 case Instruction::And: Code = LHSCode & RHSCode; break;
2737 case Instruction::Or: Code = LHSCode | RHSCode; break;
2738 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner2caaaba2003-09-22 20:33:34 +00002739 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattner3ac7c262003-08-13 20:16:26 +00002740 }
2741
2742 Value *RV = getSetCCValue(Code, LHS, RHS);
2743 if (Instruction *I = dyn_cast<Instruction>(RV))
2744 return I;
2745 // Otherwise, it's a constant boolean value...
2746 return IC.ReplaceInstUsesWith(Log, RV);
2747 }
2748};
Chris Lattnere3a63d12006-11-15 04:53:24 +00002749} // end anonymous namespace
Chris Lattner3ac7c262003-08-13 20:16:26 +00002750
Chris Lattnerba1cb382003-09-19 17:17:26 +00002751// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
2752// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
2753// guaranteed to be either a shift instruction or a binary operator.
2754Instruction *InstCombiner::OptAndOp(Instruction *Op,
2755 ConstantIntegral *OpRHS,
2756 ConstantIntegral *AndRHS,
2757 BinaryOperator &TheAnd) {
2758 Value *X = Op->getOperand(0);
Chris Lattnerfcf21a72004-01-12 19:47:05 +00002759 Constant *Together = 0;
2760 if (!isa<ShiftInst>(Op))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002761 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002762
Chris Lattnerba1cb382003-09-19 17:17:26 +00002763 switch (Op->getOpcode()) {
2764 case Instruction::Xor:
Chris Lattner86102b82005-01-01 16:22:27 +00002765 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00002766 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
2767 std::string OpName = Op->getName(); Op->setName("");
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002768 Instruction *And = BinaryOperator::createAnd(X, AndRHS, OpName);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002769 InsertNewInstBefore(And, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002770 return BinaryOperator::createXor(And, Together);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002771 }
2772 break;
2773 case Instruction::Or:
Chris Lattner86102b82005-01-01 16:22:27 +00002774 if (Together == AndRHS) // (X | C) & C --> C
2775 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002776
Chris Lattner86102b82005-01-01 16:22:27 +00002777 if (Op->hasOneUse() && Together != OpRHS) {
2778 // (X | C1) & C2 --> (X | (C1&C2)) & C2
2779 std::string Op0Name = Op->getName(); Op->setName("");
2780 Instruction *Or = BinaryOperator::createOr(X, Together, Op0Name);
2781 InsertNewInstBefore(Or, TheAnd);
2782 return BinaryOperator::createAnd(Or, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002783 }
2784 break;
2785 case Instruction::Add:
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002786 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00002787 // Adding a one to a single bit bit-field should be turned into an XOR
2788 // of the bit. First thing to check is to see if this AND is with a
2789 // single bit constant.
Reid Spencere0fc4df2006-10-20 07:07:24 +00002790 uint64_t AndRHSV = cast<ConstantInt>(AndRHS)->getZExtValue();
Chris Lattnerba1cb382003-09-19 17:17:26 +00002791
2792 // Clear bits that are not part of the constant.
Chris Lattner77defba2006-02-07 07:00:41 +00002793 AndRHSV &= AndRHS->getType()->getIntegralTypeMask();
Chris Lattnerba1cb382003-09-19 17:17:26 +00002794
2795 // If there is only one bit set...
Chris Lattner35167c32004-06-09 07:59:58 +00002796 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00002797 // Ok, at this point, we know that we are masking the result of the
2798 // ADD down to exactly one bit. If the constant we are adding has
2799 // no bits set below this bit, then we can eliminate the ADD.
Reid Spencere0fc4df2006-10-20 07:07:24 +00002800 uint64_t AddRHS = cast<ConstantInt>(OpRHS)->getZExtValue();
Misha Brukmanb1c93172005-04-21 23:48:37 +00002801
Chris Lattnerba1cb382003-09-19 17:17:26 +00002802 // Check to see if any bits below the one bit set in AndRHSV are set.
2803 if ((AddRHS & (AndRHSV-1)) == 0) {
2804 // If not, the only thing that can effect the output of the AND is
2805 // the bit specified by AndRHSV. If that bit is set, the effect of
2806 // the XOR is to toggle the bit. If it is clear, then the ADD has
2807 // no effect.
2808 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
2809 TheAnd.setOperand(0, X);
2810 return &TheAnd;
2811 } else {
2812 std::string Name = Op->getName(); Op->setName("");
2813 // Pull the XOR out of the AND.
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002814 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS, Name);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002815 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002816 return BinaryOperator::createXor(NewAnd, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002817 }
2818 }
2819 }
2820 }
2821 break;
Chris Lattner2da29172003-09-19 19:05:02 +00002822
2823 case Instruction::Shl: {
2824 // We know that the AND will not produce any of the bits shifted in, so if
2825 // the anded constant includes them, clear them now!
2826 //
2827 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner7e794272004-09-24 15:21:34 +00002828 Constant *ShlMask = ConstantExpr::getShl(AllOne, OpRHS);
2829 Constant *CI = ConstantExpr::getAnd(AndRHS, ShlMask);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002830
Chris Lattner7e794272004-09-24 15:21:34 +00002831 if (CI == ShlMask) { // Masking out bits that the shift already masks
2832 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
2833 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner2da29172003-09-19 19:05:02 +00002834 TheAnd.setOperand(1, CI);
2835 return &TheAnd;
2836 }
2837 break;
Misha Brukmanb1c93172005-04-21 23:48:37 +00002838 }
Reid Spencerfdff9382006-11-08 06:47:33 +00002839 case Instruction::LShr:
2840 {
Chris Lattner2da29172003-09-19 19:05:02 +00002841 // We know that the AND will not produce any of the bits shifted in, so if
2842 // the anded constant includes them, clear them now! This only applies to
2843 // unsigned shifts, because a signed shr may bring in set bits!
2844 //
Reid Spencerfdff9382006-11-08 06:47:33 +00002845 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
2846 Constant *ShrMask = ConstantExpr::getLShr(AllOne, OpRHS);
2847 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
Chris Lattner7e794272004-09-24 15:21:34 +00002848
Reid Spencerfdff9382006-11-08 06:47:33 +00002849 if (CI == ShrMask) { // Masking out bits that the shift already masks.
2850 return ReplaceInstUsesWith(TheAnd, Op);
2851 } else if (CI != AndRHS) {
2852 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
2853 return &TheAnd;
2854 }
2855 break;
2856 }
2857 case Instruction::AShr:
2858 // Signed shr.
2859 // See if this is shifting in some sign extension, then masking it out
2860 // with an and.
2861 if (Op->hasOneUse()) {
2862 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
2863 Constant *ShrMask = ConstantExpr::getLShr(AllOne, OpRHS);
2864 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
2865 if (CI == AndRHS) { // Masking out bits shifted in.
2866 // Make the argument unsigned.
2867 Value *ShVal = Op->getOperand(0);
2868 ShVal = InsertNewInstBefore(new ShiftInst(Instruction::LShr, ShVal,
2869 OpRHS, Op->getName()),
2870 TheAnd);
2871 Value *AndRHS2 = ConstantExpr::getCast(AndRHS, ShVal->getType());
2872 return BinaryOperator::createAnd(ShVal, AndRHS2, TheAnd.getName());
Chris Lattner7e794272004-09-24 15:21:34 +00002873 }
Chris Lattner2da29172003-09-19 19:05:02 +00002874 }
2875 break;
Chris Lattnerba1cb382003-09-19 17:17:26 +00002876 }
2877 return 0;
2878}
2879
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002880
Chris Lattner6862fbd2004-09-29 17:40:11 +00002881/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
2882/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
2883/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. IB is the location to
2884/// insert new instructions.
2885Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
2886 bool Inside, Instruction &IB) {
2887 assert(cast<ConstantBool>(ConstantExpr::getSetLE(Lo, Hi))->getValue() &&
2888 "Lo is not <= Hi in range emission code!");
2889 if (Inside) {
2890 if (Lo == Hi) // Trivially false.
2891 return new SetCondInst(Instruction::SetNE, V, V);
2892 if (cast<ConstantIntegral>(Lo)->isMinValue())
2893 return new SetCondInst(Instruction::SetLT, V, Hi);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002894
Chris Lattner6862fbd2004-09-29 17:40:11 +00002895 Constant *AddCST = ConstantExpr::getNeg(Lo);
2896 Instruction *Add = BinaryOperator::createAdd(V, AddCST,V->getName()+".off");
2897 InsertNewInstBefore(Add, IB);
2898 // Convert to unsigned for the comparison.
2899 const Type *UnsType = Add->getType()->getUnsignedVersion();
2900 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
2901 AddCST = ConstantExpr::getAdd(AddCST, Hi);
2902 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2903 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
2904 }
2905
2906 if (Lo == Hi) // Trivially true.
2907 return new SetCondInst(Instruction::SetEQ, V, V);
2908
2909 Hi = SubOne(cast<ConstantInt>(Hi));
Reid Spencere0fc4df2006-10-20 07:07:24 +00002910
2911 // V < 0 || V >= Hi ->'V > Hi-1'
2912 if (cast<ConstantIntegral>(Lo)->isMinValue())
Chris Lattner6862fbd2004-09-29 17:40:11 +00002913 return new SetCondInst(Instruction::SetGT, V, Hi);
2914
2915 // Emit X-Lo > Hi-Lo-1
2916 Constant *AddCST = ConstantExpr::getNeg(Lo);
2917 Instruction *Add = BinaryOperator::createAdd(V, AddCST, V->getName()+".off");
2918 InsertNewInstBefore(Add, IB);
2919 // Convert to unsigned for the comparison.
2920 const Type *UnsType = Add->getType()->getUnsignedVersion();
2921 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
2922 AddCST = ConstantExpr::getAdd(AddCST, Hi);
2923 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2924 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
2925}
2926
Chris Lattnerb4b25302005-09-18 07:22:02 +00002927// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
2928// any number of 0s on either side. The 1s are allowed to wrap from LSB to
2929// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
2930// not, since all 1s are not contiguous.
2931static bool isRunOfOnes(ConstantIntegral *Val, unsigned &MB, unsigned &ME) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002932 uint64_t V = Val->getZExtValue();
Chris Lattnerb4b25302005-09-18 07:22:02 +00002933 if (!isShiftedMask_64(V)) return false;
2934
2935 // look for the first zero bit after the run of ones
2936 MB = 64-CountLeadingZeros_64((V - 1) ^ V);
2937 // look for the first non-zero bit
2938 ME = 64-CountLeadingZeros_64(V);
2939 return true;
2940}
2941
2942
2943
2944/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
2945/// where isSub determines whether the operator is a sub. If we can fold one of
2946/// the following xforms:
Chris Lattneraf517572005-09-18 04:24:45 +00002947///
2948/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
2949/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
2950/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
2951///
2952/// return (A +/- B).
2953///
2954Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
2955 ConstantIntegral *Mask, bool isSub,
2956 Instruction &I) {
2957 Instruction *LHSI = dyn_cast<Instruction>(LHS);
2958 if (!LHSI || LHSI->getNumOperands() != 2 ||
2959 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
2960
2961 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
2962
2963 switch (LHSI->getOpcode()) {
2964 default: return 0;
2965 case Instruction::And:
Chris Lattnerb4b25302005-09-18 07:22:02 +00002966 if (ConstantExpr::getAnd(N, Mask) == Mask) {
2967 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Reid Spencere0fc4df2006-10-20 07:07:24 +00002968 if ((Mask->getZExtValue() & Mask->getZExtValue()+1) == 0)
Chris Lattnerb4b25302005-09-18 07:22:02 +00002969 break;
2970
2971 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
2972 // part, we don't need any explicit masks to take them out of A. If that
2973 // is all N is, ignore it.
2974 unsigned MB, ME;
2975 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Chris Lattnerc3ebf402006-02-07 07:27:52 +00002976 uint64_t Mask = RHS->getType()->getIntegralTypeMask();
2977 Mask >>= 64-MB+1;
2978 if (MaskedValueIsZero(RHS, Mask))
Chris Lattnerb4b25302005-09-18 07:22:02 +00002979 break;
2980 }
2981 }
Chris Lattneraf517572005-09-18 04:24:45 +00002982 return 0;
2983 case Instruction::Or:
2984 case Instruction::Xor:
Chris Lattnerb4b25302005-09-18 07:22:02 +00002985 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Reid Spencere0fc4df2006-10-20 07:07:24 +00002986 if ((Mask->getZExtValue() & Mask->getZExtValue()+1) == 0 &&
Chris Lattnerb4b25302005-09-18 07:22:02 +00002987 ConstantExpr::getAnd(N, Mask)->isNullValue())
Chris Lattneraf517572005-09-18 04:24:45 +00002988 break;
2989 return 0;
2990 }
2991
2992 Instruction *New;
2993 if (isSub)
2994 New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
2995 else
2996 New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
2997 return InsertNewInstBefore(New, I);
2998}
2999
Chris Lattner113f4f42002-06-25 16:13:24 +00003000Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003001 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00003002 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003003
Chris Lattner81a7a232004-10-16 18:11:37 +00003004 if (isa<UndefValue>(Op1)) // X & undef -> 0
3005 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3006
Chris Lattner86102b82005-01-01 16:22:27 +00003007 // and X, X = X
3008 if (Op0 == Op1)
Chris Lattnere6794492002-08-12 21:17:25 +00003009 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003010
Chris Lattner5b2edb12006-02-12 08:02:11 +00003011 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner5997cf92006-02-08 03:25:32 +00003012 // purpose is to compute bits we don't care about.
Chris Lattner0157e7f2006-02-11 09:31:47 +00003013 uint64_t KnownZero, KnownOne;
Chris Lattnerd70d9f52006-03-25 21:58:26 +00003014 if (!isa<PackedType>(I.getType()) &&
3015 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
Chris Lattner0157e7f2006-02-11 09:31:47 +00003016 KnownZero, KnownOne))
Chris Lattner5997cf92006-02-08 03:25:32 +00003017 return &I;
3018
Chris Lattner86102b82005-01-01 16:22:27 +00003019 if (ConstantIntegral *AndRHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00003020 uint64_t AndRHSMask = AndRHS->getZExtValue();
3021 uint64_t TypeMask = Op0->getType()->getIntegralTypeMask();
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00003022 uint64_t NotAndRHS = AndRHSMask^TypeMask;
Chris Lattner86102b82005-01-01 16:22:27 +00003023
Chris Lattnerba1cb382003-09-19 17:17:26 +00003024 // Optimize a variety of ((val OP C1) & C2) combinations...
3025 if (isa<BinaryOperator>(Op0) || isa<ShiftInst>(Op0)) {
3026 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner86102b82005-01-01 16:22:27 +00003027 Value *Op0LHS = Op0I->getOperand(0);
3028 Value *Op0RHS = Op0I->getOperand(1);
3029 switch (Op0I->getOpcode()) {
3030 case Instruction::Xor:
3031 case Instruction::Or:
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00003032 // If the mask is only needed on one incoming arm, push it up.
3033 if (Op0I->hasOneUse()) {
3034 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3035 // Not masking anything out for the LHS, move to RHS.
3036 Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
3037 Op0RHS->getName()+".masked");
3038 InsertNewInstBefore(NewRHS, I);
3039 return BinaryOperator::create(
3040 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003041 }
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003042 if (!isa<Constant>(Op0RHS) &&
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00003043 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3044 // Not masking anything out for the RHS, move to LHS.
3045 Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
3046 Op0LHS->getName()+".masked");
3047 InsertNewInstBefore(NewLHS, I);
3048 return BinaryOperator::create(
3049 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3050 }
3051 }
3052
Chris Lattner86102b82005-01-01 16:22:27 +00003053 break;
Chris Lattneraf517572005-09-18 04:24:45 +00003054 case Instruction::Add:
Chris Lattnerb4b25302005-09-18 07:22:02 +00003055 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3056 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3057 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3058 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
3059 return BinaryOperator::createAnd(V, AndRHS);
3060 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
3061 return BinaryOperator::createAnd(V, AndRHS); // Add commutes
Chris Lattneraf517572005-09-18 04:24:45 +00003062 break;
3063
3064 case Instruction::Sub:
Chris Lattnerb4b25302005-09-18 07:22:02 +00003065 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3066 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3067 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3068 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
3069 return BinaryOperator::createAnd(V, AndRHS);
Chris Lattneraf517572005-09-18 04:24:45 +00003070 break;
Chris Lattner86102b82005-01-01 16:22:27 +00003071 }
3072
Chris Lattner16464b32003-07-23 19:25:52 +00003073 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner86102b82005-01-01 16:22:27 +00003074 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerba1cb382003-09-19 17:17:26 +00003075 return Res;
Chris Lattner86102b82005-01-01 16:22:27 +00003076 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
Chris Lattner2c14cf72005-08-07 07:03:10 +00003077 // If this is an integer truncation or change from signed-to-unsigned, and
3078 // if the source is an and/or with immediate, transform it. This
3079 // frequently occurs for bitfield accesses.
3080 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003081 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
Chris Lattner2c14cf72005-08-07 07:03:10 +00003082 CastOp->getNumOperands() == 2)
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00003083 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1)))
Chris Lattner2c14cf72005-08-07 07:03:10 +00003084 if (CastOp->getOpcode() == Instruction::And) {
3085 // Change: and (cast (and X, C1) to T), C2
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003086 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
3087 // This will fold the two constants together, which may allow
3088 // other simplifications.
Chris Lattner2c14cf72005-08-07 07:03:10 +00003089 Instruction *NewCast =
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003090 CastInst::createInferredCast(CastOp->getOperand(0), I.getType(),
Chris Lattner2c14cf72005-08-07 07:03:10 +00003091 CastOp->getName()+".shrunk");
3092 NewCast = InsertNewInstBefore(NewCast, I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003093 // trunc_or_bitcast(C1)&C2
3094 Instruction::CastOps opc = (
3095 AndCI->getType()->getPrimitiveSizeInBits() ==
3096 I.getType()->getPrimitiveSizeInBits() ?
3097 Instruction::BitCast : Instruction::Trunc);
3098 Constant *C3 = ConstantExpr::getCast(opc, AndCI, I.getType());
3099 C3 = ConstantExpr::getAnd(C3, AndRHS);
Chris Lattner2c14cf72005-08-07 07:03:10 +00003100 return BinaryOperator::createAnd(NewCast, C3);
3101 } else if (CastOp->getOpcode() == Instruction::Or) {
3102 // Change: and (cast (or X, C1) to T), C2
3103 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003104 Constant *C3 = ConstantExpr::getCast(AndCI, I.getType());
Chris Lattner2c14cf72005-08-07 07:03:10 +00003105 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
3106 return ReplaceInstUsesWith(I, AndRHS);
3107 }
3108 }
Chris Lattner33217db2003-07-23 19:36:21 +00003109 }
Chris Lattner183b3362004-04-09 19:05:30 +00003110
3111 // Try to fold constant and into select arguments.
3112 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00003113 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00003114 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00003115 if (isa<PHINode>(Op0))
3116 if (Instruction *NV = FoldOpIntoPhi(I))
3117 return NV;
Chris Lattner49b47ae2003-07-23 17:57:01 +00003118 }
3119
Chris Lattnerbb74e222003-03-10 23:06:50 +00003120 Value *Op0NotVal = dyn_castNotVal(Op0);
3121 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00003122
Chris Lattner023a4832004-06-18 06:07:51 +00003123 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
3124 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3125
Misha Brukman9c003d82004-07-30 12:50:08 +00003126 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattnerbb74e222003-03-10 23:06:50 +00003127 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003128 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
3129 I.getName()+".demorgan");
Chris Lattner49b47ae2003-07-23 17:57:01 +00003130 InsertNewInstBefore(Or, I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00003131 return BinaryOperator::createNot(Or);
3132 }
Chris Lattner8b10ab32006-02-13 23:07:23 +00003133
3134 {
3135 Value *A = 0, *B = 0;
Chris Lattner8b10ab32006-02-13 23:07:23 +00003136 if (match(Op0, m_Or(m_Value(A), m_Value(B))))
3137 if (A == Op1 || B == Op1) // (A | ?) & A --> A
3138 return ReplaceInstUsesWith(I, Op1);
3139 if (match(Op1, m_Or(m_Value(A), m_Value(B))))
3140 if (A == Op0 || B == Op0) // A & (A | ?) --> A
3141 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerdcd07922006-04-01 08:03:55 +00003142
3143 if (Op0->hasOneUse() &&
3144 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3145 if (A == Op1) { // (A^B)&A -> A&(A^B)
3146 I.swapOperands(); // Simplify below
3147 std::swap(Op0, Op1);
3148 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
3149 cast<BinaryOperator>(Op0)->swapOperands();
3150 I.swapOperands(); // Simplify below
3151 std::swap(Op0, Op1);
3152 }
3153 }
3154 if (Op1->hasOneUse() &&
3155 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3156 if (B == Op0) { // B&(A^B) -> B&(B^A)
3157 cast<BinaryOperator>(Op1)->swapOperands();
3158 std::swap(A, B);
3159 }
3160 if (A == Op0) { // A&(A^B) -> A & ~B
3161 Instruction *NotB = BinaryOperator::createNot(B, "tmp");
3162 InsertNewInstBefore(NotB, I);
3163 return BinaryOperator::createAnd(A, NotB);
3164 }
3165 }
Chris Lattner8b10ab32006-02-13 23:07:23 +00003166 }
3167
Chris Lattner3082c5a2003-02-18 19:28:33 +00003168
Chris Lattner623826c2004-09-28 21:48:02 +00003169 if (SetCondInst *RHS = dyn_cast<SetCondInst>(Op1)) {
3170 // (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
Chris Lattner3ac7c262003-08-13 20:16:26 +00003171 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
3172 return R;
3173
Chris Lattner623826c2004-09-28 21:48:02 +00003174 Value *LHSVal, *RHSVal;
3175 ConstantInt *LHSCst, *RHSCst;
3176 Instruction::BinaryOps LHSCC, RHSCC;
3177 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3178 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3179 if (LHSVal == RHSVal && // Found (X setcc C1) & (X setcc C2)
3180 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
Misha Brukmanb1c93172005-04-21 23:48:37 +00003181 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
Chris Lattner623826c2004-09-28 21:48:02 +00003182 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
3183 // Ensure that the larger constant is on the RHS.
3184 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
3185 SetCondInst *LHS = cast<SetCondInst>(Op0);
3186 if (cast<ConstantBool>(Cmp)->getValue()) {
3187 std::swap(LHS, RHS);
3188 std::swap(LHSCst, RHSCst);
3189 std::swap(LHSCC, RHSCC);
3190 }
3191
3192 // At this point, we know we have have two setcc instructions
3193 // comparing a value against two constants and and'ing the result
3194 // together. Because of the above check, we know that we only have
3195 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
3196 // FoldSetCCLogical check above), that the two constants are not
3197 // equal.
3198 assert(LHSCst != RHSCst && "Compares not folded above?");
3199
3200 switch (LHSCC) {
3201 default: assert(0 && "Unknown integer condition code!");
3202 case Instruction::SetEQ:
3203 switch (RHSCC) {
3204 default: assert(0 && "Unknown integer condition code!");
3205 case Instruction::SetEQ: // (X == 13 & X == 15) -> false
3206 case Instruction::SetGT: // (X == 13 & X > 15) -> false
Chris Lattner6ab03f62006-09-28 23:35:22 +00003207 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattner623826c2004-09-28 21:48:02 +00003208 case Instruction::SetNE: // (X == 13 & X != 15) -> X == 13
3209 case Instruction::SetLT: // (X == 13 & X < 15) -> X == 13
3210 return ReplaceInstUsesWith(I, LHS);
3211 }
3212 case Instruction::SetNE:
3213 switch (RHSCC) {
3214 default: assert(0 && "Unknown integer condition code!");
3215 case Instruction::SetLT:
3216 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X < 14) -> X < 13
3217 return new SetCondInst(Instruction::SetLT, LHSVal, LHSCst);
3218 break; // (X != 13 & X < 15) -> no change
3219 case Instruction::SetEQ: // (X != 13 & X == 15) -> X == 15
3220 case Instruction::SetGT: // (X != 13 & X > 15) -> X > 15
3221 return ReplaceInstUsesWith(I, RHS);
3222 case Instruction::SetNE:
3223 if (LHSCst == SubOne(RHSCst)) {// (X != 13 & X != 14) -> X-13 >u 1
3224 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3225 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3226 LHSVal->getName()+".off");
3227 InsertNewInstBefore(Add, I);
3228 const Type *UnsType = Add->getType()->getUnsignedVersion();
3229 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
3230 AddCST = ConstantExpr::getSub(RHSCst, LHSCst);
3231 AddCST = ConstantExpr::getCast(AddCST, UnsType);
3232 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
3233 }
3234 break; // (X != 13 & X != 15) -> no change
3235 }
3236 break;
3237 case Instruction::SetLT:
3238 switch (RHSCC) {
3239 default: assert(0 && "Unknown integer condition code!");
3240 case Instruction::SetEQ: // (X < 13 & X == 15) -> false
3241 case Instruction::SetGT: // (X < 13 & X > 15) -> false
Chris Lattner6ab03f62006-09-28 23:35:22 +00003242 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattner623826c2004-09-28 21:48:02 +00003243 case Instruction::SetNE: // (X < 13 & X != 15) -> X < 13
3244 case Instruction::SetLT: // (X < 13 & X < 15) -> X < 13
3245 return ReplaceInstUsesWith(I, LHS);
3246 }
3247 case Instruction::SetGT:
3248 switch (RHSCC) {
3249 default: assert(0 && "Unknown integer condition code!");
3250 case Instruction::SetEQ: // (X > 13 & X == 15) -> X > 13
3251 return ReplaceInstUsesWith(I, LHS);
3252 case Instruction::SetGT: // (X > 13 & X > 15) -> X > 15
3253 return ReplaceInstUsesWith(I, RHS);
3254 case Instruction::SetNE:
3255 if (RHSCst == AddOne(LHSCst)) // (X > 13 & X != 14) -> X > 14
3256 return new SetCondInst(Instruction::SetGT, LHSVal, RHSCst);
3257 break; // (X > 13 & X != 15) -> no change
Chris Lattner6862fbd2004-09-29 17:40:11 +00003258 case Instruction::SetLT: // (X > 13 & X < 15) -> (X-14) <u 1
3259 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true, I);
Chris Lattner623826c2004-09-28 21:48:02 +00003260 }
3261 }
3262 }
3263 }
3264
Chris Lattner3af10532006-05-05 06:39:07 +00003265 // fold (and (cast A), (cast B)) -> (cast (and A, B))
Chris Lattnerf05d69a2006-11-14 07:46:50 +00003266 if (CastInst *Op1C = dyn_cast<CastInst>(Op1)) {
3267 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
3268 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattnere745c7d2006-05-05 20:51:30 +00003269 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegral() &&
Chris Lattner1d441ad2006-05-06 09:00:16 +00003270 // Only do this if the casts both really cause code to be generated.
3271 ValueRequiresCast(Op0C->getOperand(0), I.getType(), TD) &&
3272 ValueRequiresCast(Op1C->getOperand(0), I.getType(), TD)) {
Chris Lattner3af10532006-05-05 06:39:07 +00003273 Instruction *NewOp = BinaryOperator::createAnd(Op0C->getOperand(0),
3274 Op1C->getOperand(0),
3275 I.getName());
3276 InsertNewInstBefore(NewOp, I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003277 return CastInst::createInferredCast(NewOp, I.getType());
Chris Lattner3af10532006-05-05 06:39:07 +00003278 }
Chris Lattnerf05d69a2006-11-14 07:46:50 +00003279 }
3280 }
3281
3282 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
3283 if (ShiftInst *SI1 = dyn_cast<ShiftInst>(Op1)) {
3284 if (ShiftInst *SI0 = dyn_cast<ShiftInst>(Op0))
3285 if (SI0->getOpcode() == SI1->getOpcode() &&
3286 SI0->getOperand(1) == SI1->getOperand(1) &&
3287 (SI0->hasOneUse() || SI1->hasOneUse())) {
3288 Instruction *NewOp =
3289 InsertNewInstBefore(BinaryOperator::createAnd(SI0->getOperand(0),
3290 SI1->getOperand(0),
3291 SI0->getName()), I);
3292 return new ShiftInst(SI1->getOpcode(), NewOp, SI1->getOperand(1));
3293 }
Chris Lattner3af10532006-05-05 06:39:07 +00003294 }
3295
Chris Lattner113f4f42002-06-25 16:13:24 +00003296 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003297}
3298
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003299/// CollectBSwapParts - Look to see if the specified value defines a single byte
3300/// in the result. If it does, and if the specified byte hasn't been filled in
3301/// yet, fill it in and return false.
3302static bool CollectBSwapParts(Value *V, std::vector<Value*> &ByteValues) {
3303 Instruction *I = dyn_cast<Instruction>(V);
3304 if (I == 0) return true;
3305
3306 // If this is an or instruction, it is an inner node of the bswap.
3307 if (I->getOpcode() == Instruction::Or)
3308 return CollectBSwapParts(I->getOperand(0), ByteValues) ||
3309 CollectBSwapParts(I->getOperand(1), ByteValues);
3310
3311 // If this is a shift by a constant int, and it is "24", then its operand
3312 // defines a byte. We only handle unsigned types here.
3313 if (isa<ShiftInst>(I) && isa<ConstantInt>(I->getOperand(1))) {
3314 // Not shifting the entire input by N-1 bytes?
Reid Spencere0fc4df2006-10-20 07:07:24 +00003315 if (cast<ConstantInt>(I->getOperand(1))->getZExtValue() !=
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003316 8*(ByteValues.size()-1))
3317 return true;
3318
3319 unsigned DestNo;
3320 if (I->getOpcode() == Instruction::Shl) {
3321 // X << 24 defines the top byte with the lowest of the input bytes.
3322 DestNo = ByteValues.size()-1;
3323 } else {
3324 // X >>u 24 defines the low byte with the highest of the input bytes.
3325 DestNo = 0;
3326 }
3327
3328 // If the destination byte value is already defined, the values are or'd
3329 // together, which isn't a bswap (unless it's an or of the same bits).
3330 if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
3331 return true;
3332 ByteValues[DestNo] = I->getOperand(0);
3333 return false;
3334 }
3335
3336 // Otherwise, we can only handle and(shift X, imm), imm). Bail out of if we
3337 // don't have this.
3338 Value *Shift = 0, *ShiftLHS = 0;
3339 ConstantInt *AndAmt = 0, *ShiftAmt = 0;
3340 if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
3341 !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
3342 return true;
3343 Instruction *SI = cast<Instruction>(Shift);
3344
3345 // Make sure that the shift amount is by a multiple of 8 and isn't too big.
Reid Spencere0fc4df2006-10-20 07:07:24 +00003346 if (ShiftAmt->getZExtValue() & 7 ||
3347 ShiftAmt->getZExtValue() > 8*ByteValues.size())
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003348 return true;
3349
3350 // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
3351 unsigned DestByte;
3352 for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
Reid Spencere0fc4df2006-10-20 07:07:24 +00003353 if (AndAmt->getZExtValue() == uint64_t(0xFF) << 8*DestByte)
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003354 break;
3355 // Unknown mask for bswap.
3356 if (DestByte == ByteValues.size()) return true;
3357
Reid Spencere0fc4df2006-10-20 07:07:24 +00003358 unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003359 unsigned SrcByte;
3360 if (SI->getOpcode() == Instruction::Shl)
3361 SrcByte = DestByte - ShiftBytes;
3362 else
3363 SrcByte = DestByte + ShiftBytes;
3364
3365 // If the SrcByte isn't a bswapped value from the DestByte, reject it.
3366 if (SrcByte != ByteValues.size()-DestByte-1)
3367 return true;
3368
3369 // If the destination byte value is already defined, the values are or'd
3370 // together, which isn't a bswap (unless it's an or of the same bits).
3371 if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
3372 return true;
3373 ByteValues[DestByte] = SI->getOperand(0);
3374 return false;
3375}
3376
3377/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
3378/// If so, insert the new bswap intrinsic and return it.
3379Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
3380 // We can only handle bswap of unsigned integers, and cannot bswap one byte.
3381 if (!I.getType()->isUnsigned() || I.getType() == Type::UByteTy)
3382 return 0;
3383
3384 /// ByteValues - For each byte of the result, we keep track of which value
3385 /// defines each byte.
3386 std::vector<Value*> ByteValues;
3387 ByteValues.resize(I.getType()->getPrimitiveSize());
3388
3389 // Try to find all the pieces corresponding to the bswap.
3390 if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
3391 CollectBSwapParts(I.getOperand(1), ByteValues))
3392 return 0;
3393
3394 // Check to see if all of the bytes come from the same value.
3395 Value *V = ByteValues[0];
3396 if (V == 0) return 0; // Didn't find a byte? Must be zero.
3397
3398 // Check to make sure that all of the bytes come from the same value.
3399 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
3400 if (ByteValues[i] != V)
3401 return 0;
3402
3403 // If they do then *success* we can turn this into a bswap. Figure out what
3404 // bswap to make it into.
3405 Module *M = I.getParent()->getParent()->getParent();
Chris Lattner091b6ea2006-07-11 18:31:26 +00003406 const char *FnName = 0;
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003407 if (I.getType() == Type::UShortTy)
3408 FnName = "llvm.bswap.i16";
3409 else if (I.getType() == Type::UIntTy)
3410 FnName = "llvm.bswap.i32";
3411 else if (I.getType() == Type::ULongTy)
3412 FnName = "llvm.bswap.i64";
3413 else
3414 assert(0 && "Unknown integer type!");
3415 Function *F = M->getOrInsertFunction(FnName, I.getType(), I.getType(), NULL);
3416
3417 return new CallInst(F, V);
3418}
3419
3420
Chris Lattner113f4f42002-06-25 16:13:24 +00003421Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003422 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00003423 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003424
Chris Lattner81a7a232004-10-16 18:11:37 +00003425 if (isa<UndefValue>(Op1))
3426 return ReplaceInstUsesWith(I, // X | undef -> -1
3427 ConstantIntegral::getAllOnesValue(I.getType()));
3428
Chris Lattner5b2edb12006-02-12 08:02:11 +00003429 // or X, X = X
3430 if (Op0 == Op1)
Chris Lattnere6794492002-08-12 21:17:25 +00003431 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003432
Chris Lattner5b2edb12006-02-12 08:02:11 +00003433 // See if we can simplify any instructions used by the instruction whose sole
3434 // purpose is to compute bits we don't care about.
3435 uint64_t KnownZero, KnownOne;
Chris Lattnerd70d9f52006-03-25 21:58:26 +00003436 if (!isa<PackedType>(I.getType()) &&
3437 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
Chris Lattner5b2edb12006-02-12 08:02:11 +00003438 KnownZero, KnownOne))
3439 return &I;
3440
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003441 // or X, -1 == -1
Chris Lattner8f0d1562003-07-23 18:29:44 +00003442 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner330628a2006-01-06 17:59:59 +00003443 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00003444 // (X & C1) | C2 --> (X | C2) & (C1|C2)
3445 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Chris Lattnerb62f5082005-05-09 04:58:36 +00003446 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0->getName());
3447 Op0->setName("");
Chris Lattnerd4252a72004-07-30 07:50:03 +00003448 InsertNewInstBefore(Or, I);
3449 return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, C1));
3450 }
Chris Lattner8f0d1562003-07-23 18:29:44 +00003451
Chris Lattnerd4252a72004-07-30 07:50:03 +00003452 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
3453 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
3454 std::string Op0Name = Op0->getName(); Op0->setName("");
3455 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
3456 InsertNewInstBefore(Or, I);
3457 return BinaryOperator::createXor(Or,
3458 ConstantExpr::getAnd(C1, ConstantExpr::getNot(RHS)));
Chris Lattner8f0d1562003-07-23 18:29:44 +00003459 }
Chris Lattner183b3362004-04-09 19:05:30 +00003460
3461 // Try to fold constant and into select arguments.
3462 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00003463 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00003464 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00003465 if (isa<PHINode>(Op0))
3466 if (Instruction *NV = FoldOpIntoPhi(I))
3467 return NV;
Chris Lattner8f0d1562003-07-23 18:29:44 +00003468 }
3469
Chris Lattner330628a2006-01-06 17:59:59 +00003470 Value *A = 0, *B = 0;
3471 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattner4294cec2005-05-07 23:49:08 +00003472
3473 if (match(Op0, m_And(m_Value(A), m_Value(B))))
3474 if (A == Op1 || B == Op1) // (A & ?) | A --> A
3475 return ReplaceInstUsesWith(I, Op1);
3476 if (match(Op1, m_And(m_Value(A), m_Value(B))))
3477 if (A == Op0 || B == Op0) // A | (A & ?) --> A
3478 return ReplaceInstUsesWith(I, Op0);
3479
Chris Lattnerb7845d62006-07-10 20:25:24 +00003480 // (A | B) | C and A | (B | C) -> bswap if possible.
3481 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003482 if (match(Op0, m_Or(m_Value(), m_Value())) ||
Chris Lattnerb7845d62006-07-10 20:25:24 +00003483 match(Op1, m_Or(m_Value(), m_Value())) ||
3484 (match(Op0, m_Shift(m_Value(), m_Value())) &&
3485 match(Op1, m_Shift(m_Value(), m_Value())))) {
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003486 if (Instruction *BSwap = MatchBSwap(I))
3487 return BSwap;
3488 }
3489
Chris Lattnerb62f5082005-05-09 04:58:36 +00003490 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
3491 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003492 MaskedValueIsZero(Op1, C1->getZExtValue())) {
Chris Lattnerb62f5082005-05-09 04:58:36 +00003493 Instruction *NOr = BinaryOperator::createOr(A, Op1, Op0->getName());
3494 Op0->setName("");
3495 return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
3496 }
3497
3498 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
3499 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003500 MaskedValueIsZero(Op0, C1->getZExtValue())) {
Chris Lattnerb62f5082005-05-09 04:58:36 +00003501 Instruction *NOr = BinaryOperator::createOr(A, Op0, Op1->getName());
3502 Op0->setName("");
3503 return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
3504 }
3505
Chris Lattner15212982005-09-18 03:42:07 +00003506 // (A & C1)|(B & C2)
Chris Lattnerd4252a72004-07-30 07:50:03 +00003507 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattner15212982005-09-18 03:42:07 +00003508 match(Op1, m_And(m_Value(B), m_ConstantInt(C2)))) {
3509
3510 if (A == B) // (A & C1)|(A & C2) == A & (C1|C2)
3511 return BinaryOperator::createAnd(A, ConstantExpr::getOr(C1, C2));
3512
3513
Chris Lattner01f56c62005-09-18 06:02:59 +00003514 // If we have: ((V + N) & C1) | (V & C2)
3515 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
3516 // replace with V+N.
3517 if (C1 == ConstantExpr::getNot(C2)) {
Chris Lattner330628a2006-01-06 17:59:59 +00003518 Value *V1 = 0, *V2 = 0;
Reid Spencere0fc4df2006-10-20 07:07:24 +00003519 if ((C2->getZExtValue() & (C2->getZExtValue()+1)) == 0 && // C2 == 0+1+
Chris Lattner01f56c62005-09-18 06:02:59 +00003520 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
3521 // Add commutes, try both ways.
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003522 if (V1 == B && MaskedValueIsZero(V2, C2->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003523 return ReplaceInstUsesWith(I, A);
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003524 if (V2 == B && MaskedValueIsZero(V1, C2->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003525 return ReplaceInstUsesWith(I, A);
3526 }
3527 // Or commutes, try both ways.
Reid Spencere0fc4df2006-10-20 07:07:24 +00003528 if ((C1->getZExtValue() & (C1->getZExtValue()+1)) == 0 &&
Chris Lattner01f56c62005-09-18 06:02:59 +00003529 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
3530 // Add commutes, try both ways.
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003531 if (V1 == A && MaskedValueIsZero(V2, C1->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003532 return ReplaceInstUsesWith(I, B);
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003533 if (V2 == A && MaskedValueIsZero(V1, C1->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003534 return ReplaceInstUsesWith(I, B);
Chris Lattner15212982005-09-18 03:42:07 +00003535 }
3536 }
3537 }
Chris Lattnerf05d69a2006-11-14 07:46:50 +00003538
3539 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
3540 if (ShiftInst *SI1 = dyn_cast<ShiftInst>(Op1)) {
3541 if (ShiftInst *SI0 = dyn_cast<ShiftInst>(Op0))
3542 if (SI0->getOpcode() == SI1->getOpcode() &&
3543 SI0->getOperand(1) == SI1->getOperand(1) &&
3544 (SI0->hasOneUse() || SI1->hasOneUse())) {
3545 Instruction *NewOp =
3546 InsertNewInstBefore(BinaryOperator::createOr(SI0->getOperand(0),
3547 SI1->getOperand(0),
3548 SI0->getName()), I);
3549 return new ShiftInst(SI1->getOpcode(), NewOp, SI1->getOperand(1));
3550 }
3551 }
Chris Lattner812aab72003-08-12 19:11:07 +00003552
Chris Lattnerd4252a72004-07-30 07:50:03 +00003553 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
3554 if (A == Op1) // ~A | A == -1
Misha Brukmanb1c93172005-04-21 23:48:37 +00003555 return ReplaceInstUsesWith(I,
Chris Lattnerd4252a72004-07-30 07:50:03 +00003556 ConstantIntegral::getAllOnesValue(I.getType()));
3557 } else {
3558 A = 0;
3559 }
Chris Lattner4294cec2005-05-07 23:49:08 +00003560 // Note, A is still live here!
Chris Lattnerd4252a72004-07-30 07:50:03 +00003561 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
3562 if (Op0 == B)
Misha Brukmanb1c93172005-04-21 23:48:37 +00003563 return ReplaceInstUsesWith(I,
Chris Lattnerd4252a72004-07-30 07:50:03 +00003564 ConstantIntegral::getAllOnesValue(I.getType()));
Chris Lattner3e327a42003-03-10 23:13:59 +00003565
Misha Brukman9c003d82004-07-30 12:50:08 +00003566 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattnerd4252a72004-07-30 07:50:03 +00003567 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3568 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
3569 I.getName()+".demorgan"), I);
3570 return BinaryOperator::createNot(And);
3571 }
Chris Lattner3e327a42003-03-10 23:13:59 +00003572 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00003573
Chris Lattner3ac7c262003-08-13 20:16:26 +00003574 // (setcc1 A, B) | (setcc2 A, B) --> (setcc3 A, B)
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003575 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1))) {
Chris Lattner3ac7c262003-08-13 20:16:26 +00003576 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
3577 return R;
3578
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003579 Value *LHSVal, *RHSVal;
3580 ConstantInt *LHSCst, *RHSCst;
3581 Instruction::BinaryOps LHSCC, RHSCC;
3582 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3583 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3584 if (LHSVal == RHSVal && // Found (X setcc C1) | (X setcc C2)
3585 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
Misha Brukmanb1c93172005-04-21 23:48:37 +00003586 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003587 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
3588 // Ensure that the larger constant is on the RHS.
3589 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
3590 SetCondInst *LHS = cast<SetCondInst>(Op0);
3591 if (cast<ConstantBool>(Cmp)->getValue()) {
3592 std::swap(LHS, RHS);
3593 std::swap(LHSCst, RHSCst);
3594 std::swap(LHSCC, RHSCC);
3595 }
3596
3597 // At this point, we know we have have two setcc instructions
3598 // comparing a value against two constants and or'ing the result
3599 // together. Because of the above check, we know that we only have
3600 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
3601 // FoldSetCCLogical check above), that the two constants are not
3602 // equal.
3603 assert(LHSCst != RHSCst && "Compares not folded above?");
3604
3605 switch (LHSCC) {
3606 default: assert(0 && "Unknown integer condition code!");
3607 case Instruction::SetEQ:
3608 switch (RHSCC) {
3609 default: assert(0 && "Unknown integer condition code!");
3610 case Instruction::SetEQ:
3611 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
3612 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3613 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3614 LHSVal->getName()+".off");
3615 InsertNewInstBefore(Add, I);
3616 const Type *UnsType = Add->getType()->getUnsignedVersion();
3617 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
3618 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
3619 AddCST = ConstantExpr::getCast(AddCST, UnsType);
3620 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
3621 }
3622 break; // (X == 13 | X == 15) -> no change
3623
Chris Lattner5c219462005-04-19 06:04:18 +00003624 case Instruction::SetGT: // (X == 13 | X > 14) -> no change
3625 break;
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003626 case Instruction::SetNE: // (X == 13 | X != 15) -> X != 15
3627 case Instruction::SetLT: // (X == 13 | X < 15) -> X < 15
3628 return ReplaceInstUsesWith(I, RHS);
3629 }
3630 break;
3631 case Instruction::SetNE:
3632 switch (RHSCC) {
3633 default: assert(0 && "Unknown integer condition code!");
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003634 case Instruction::SetEQ: // (X != 13 | X == 15) -> X != 13
3635 case Instruction::SetGT: // (X != 13 | X > 15) -> X != 13
3636 return ReplaceInstUsesWith(I, LHS);
3637 case Instruction::SetNE: // (X != 13 | X != 15) -> true
Chris Lattner2ceb6ee2005-06-17 03:59:17 +00003638 case Instruction::SetLT: // (X != 13 | X < 15) -> true
Chris Lattner6ab03f62006-09-28 23:35:22 +00003639 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003640 }
3641 break;
3642 case Instruction::SetLT:
3643 switch (RHSCC) {
3644 default: assert(0 && "Unknown integer condition code!");
3645 case Instruction::SetEQ: // (X < 13 | X == 14) -> no change
3646 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00003647 case Instruction::SetGT: // (X < 13 | X > 15) -> (X-13) > 2
3648 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false, I);
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003649 case Instruction::SetNE: // (X < 13 | X != 15) -> X != 15
3650 case Instruction::SetLT: // (X < 13 | X < 15) -> X < 15
3651 return ReplaceInstUsesWith(I, RHS);
3652 }
3653 break;
3654 case Instruction::SetGT:
3655 switch (RHSCC) {
3656 default: assert(0 && "Unknown integer condition code!");
3657 case Instruction::SetEQ: // (X > 13 | X == 15) -> X > 13
3658 case Instruction::SetGT: // (X > 13 | X > 15) -> X > 13
3659 return ReplaceInstUsesWith(I, LHS);
3660 case Instruction::SetNE: // (X > 13 | X != 15) -> true
3661 case Instruction::SetLT: // (X > 13 | X < 15) -> true
Chris Lattner6ab03f62006-09-28 23:35:22 +00003662 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003663 }
3664 }
3665 }
3666 }
Chris Lattner3af10532006-05-05 06:39:07 +00003667
3668 // fold (or (cast A), (cast B)) -> (cast (or A, B))
3669 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattnere745c7d2006-05-05 20:51:30 +00003670 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner3af10532006-05-05 06:39:07 +00003671 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Chris Lattnere745c7d2006-05-05 20:51:30 +00003672 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegral() &&
Chris Lattner1d441ad2006-05-06 09:00:16 +00003673 // Only do this if the casts both really cause code to be generated.
3674 ValueRequiresCast(Op0C->getOperand(0), I.getType(), TD) &&
3675 ValueRequiresCast(Op1C->getOperand(0), I.getType(), TD)) {
Chris Lattner3af10532006-05-05 06:39:07 +00003676 Instruction *NewOp = BinaryOperator::createOr(Op0C->getOperand(0),
3677 Op1C->getOperand(0),
3678 I.getName());
3679 InsertNewInstBefore(NewOp, I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003680 return CastInst::createInferredCast(NewOp, I.getType());
Chris Lattner3af10532006-05-05 06:39:07 +00003681 }
3682 }
3683
Chris Lattner15212982005-09-18 03:42:07 +00003684
Chris Lattner113f4f42002-06-25 16:13:24 +00003685 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003686}
3687
Chris Lattnerc2076352004-02-16 01:20:27 +00003688// XorSelf - Implements: X ^ X --> 0
3689struct XorSelf {
3690 Value *RHS;
3691 XorSelf(Value *rhs) : RHS(rhs) {}
3692 bool shouldApply(Value *LHS) const { return LHS == RHS; }
3693 Instruction *apply(BinaryOperator &Xor) const {
3694 return &Xor;
3695 }
3696};
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003697
3698
Chris Lattner113f4f42002-06-25 16:13:24 +00003699Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003700 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00003701 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003702
Chris Lattner81a7a232004-10-16 18:11:37 +00003703 if (isa<UndefValue>(Op1))
3704 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
3705
Chris Lattnerc2076352004-02-16 01:20:27 +00003706 // xor X, X = 0, even if X is nested in a sequence of Xor's.
3707 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
3708 assert(Result == &I && "AssociativeOpt didn't work?");
Chris Lattnere6794492002-08-12 21:17:25 +00003709 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc2076352004-02-16 01:20:27 +00003710 }
Chris Lattner5b2edb12006-02-12 08:02:11 +00003711
3712 // See if we can simplify any instructions used by the instruction whose sole
3713 // purpose is to compute bits we don't care about.
3714 uint64_t KnownZero, KnownOne;
Chris Lattnerd70d9f52006-03-25 21:58:26 +00003715 if (!isa<PackedType>(I.getType()) &&
3716 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
Chris Lattner5b2edb12006-02-12 08:02:11 +00003717 KnownZero, KnownOne))
3718 return &I;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003719
Chris Lattner97638592003-07-23 21:37:07 +00003720 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner97638592003-07-23 21:37:07 +00003721 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerb8d6e402002-08-20 18:24:26 +00003722 // xor (setcc A, B), true = not (setcc A, B) = setncc A, B
Chris Lattner97638592003-07-23 21:37:07 +00003723 if (SetCondInst *SCI = dyn_cast<SetCondInst>(Op0I))
Chris Lattner6ab03f62006-09-28 23:35:22 +00003724 if (RHS == ConstantBool::getTrue() && SCI->hasOneUse())
Chris Lattnerb8d6e402002-08-20 18:24:26 +00003725 return new SetCondInst(SCI->getInverseCondition(),
3726 SCI->getOperand(0), SCI->getOperand(1));
Chris Lattnere5806662003-11-04 23:50:51 +00003727
Chris Lattner8f2f5982003-11-05 01:06:05 +00003728 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003729 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
3730 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003731 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
3732 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003733 ConstantInt::get(I.getType(), 1));
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003734 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003735 }
Chris Lattner023a4832004-06-18 06:07:51 +00003736
3737 // ~(~X & Y) --> (X | ~Y)
3738 if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
3739 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
3740 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
3741 Instruction *NotY =
Misha Brukmanb1c93172005-04-21 23:48:37 +00003742 BinaryOperator::createNot(Op0I->getOperand(1),
Chris Lattner023a4832004-06-18 06:07:51 +00003743 Op0I->getOperand(1)->getName()+".not");
3744 InsertNewInstBefore(NotY, I);
3745 return BinaryOperator::createOr(Op0NotVal, NotY);
3746 }
3747 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003748
Chris Lattner97638592003-07-23 21:37:07 +00003749 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner5b2edb12006-02-12 08:02:11 +00003750 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner0f68fa62003-11-04 23:37:10 +00003751 // ~(X-c) --> (-c-1)-X
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003752 if (RHS->isAllOnesValue()) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003753 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
3754 return BinaryOperator::createSub(
3755 ConstantExpr::getSub(NegOp0CI,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003756 ConstantInt::get(I.getType(), 1)),
Chris Lattner0f68fa62003-11-04 23:37:10 +00003757 Op0I->getOperand(0));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003758 }
Chris Lattnerf78df7c2006-02-26 19:57:54 +00003759 } else if (Op0I->getOpcode() == Instruction::Or) {
3760 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
3761 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getZExtValue())) {
3762 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
3763 // Anything in both C1 and C2 is known to be zero, remove it from
3764 // NewRHS.
3765 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
3766 NewRHS = ConstantExpr::getAnd(NewRHS,
3767 ConstantExpr::getNot(CommonBits));
3768 WorkList.push_back(Op0I);
3769 I.setOperand(0, Op0I->getOperand(0));
3770 I.setOperand(1, NewRHS);
3771 return &I;
3772 }
Chris Lattner97638592003-07-23 21:37:07 +00003773 }
Chris Lattnerb8d6e402002-08-20 18:24:26 +00003774 }
Chris Lattner183b3362004-04-09 19:05:30 +00003775
3776 // Try to fold constant and into select arguments.
3777 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00003778 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00003779 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00003780 if (isa<PHINode>(Op0))
3781 if (Instruction *NV = FoldOpIntoPhi(I))
3782 return NV;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003783 }
3784
Chris Lattnerbb74e222003-03-10 23:06:50 +00003785 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00003786 if (X == Op1)
3787 return ReplaceInstUsesWith(I,
3788 ConstantIntegral::getAllOnesValue(I.getType()));
3789
Chris Lattnerbb74e222003-03-10 23:06:50 +00003790 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00003791 if (X == Op0)
3792 return ReplaceInstUsesWith(I,
3793 ConstantIntegral::getAllOnesValue(I.getType()));
3794
Chris Lattnerdcd07922006-04-01 08:03:55 +00003795 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1))
Chris Lattnerb36d9082004-02-16 03:54:20 +00003796 if (Op1I->getOpcode() == Instruction::Or) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003797 if (Op1I->getOperand(0) == Op0) { // B^(B|A) == (A|B)^B
Chris Lattnerdcd07922006-04-01 08:03:55 +00003798 Op1I->swapOperands();
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003799 I.swapOperands();
3800 std::swap(Op0, Op1);
3801 } else if (Op1I->getOperand(1) == Op0) { // B^(A|B) == (A|B)^B
Chris Lattnerdcd07922006-04-01 08:03:55 +00003802 I.swapOperands(); // Simplified below.
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003803 std::swap(Op0, Op1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003804 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00003805 } else if (Op1I->getOpcode() == Instruction::Xor) {
3806 if (Op0 == Op1I->getOperand(0)) // A^(A^B) == B
3807 return ReplaceInstUsesWith(I, Op1I->getOperand(1));
3808 else if (Op0 == Op1I->getOperand(1)) // A^(B^A) == B
3809 return ReplaceInstUsesWith(I, Op1I->getOperand(0));
Chris Lattnerdcd07922006-04-01 08:03:55 +00003810 } else if (Op1I->getOpcode() == Instruction::And && Op1I->hasOneUse()) {
3811 if (Op1I->getOperand(0) == Op0) // A^(A&B) -> A^(B&A)
3812 Op1I->swapOperands();
3813 if (Op0 == Op1I->getOperand(1)) { // A^(B&A) -> (B&A)^A
3814 I.swapOperands(); // Simplified below.
3815 std::swap(Op0, Op1);
3816 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00003817 }
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003818
Chris Lattnerdcd07922006-04-01 08:03:55 +00003819 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00003820 if (Op0I->getOpcode() == Instruction::Or && Op0I->hasOneUse()) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003821 if (Op0I->getOperand(0) == Op1) // (B|A)^B == (A|B)^B
Chris Lattnerdcd07922006-04-01 08:03:55 +00003822 Op0I->swapOperands();
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003823 if (Op0I->getOperand(1) == Op1) { // (A|B)^B == A & ~B
Chris Lattnerdcd07922006-04-01 08:03:55 +00003824 Instruction *NotB = BinaryOperator::createNot(Op1, "tmp");
3825 InsertNewInstBefore(NotB, I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003826 return BinaryOperator::createAnd(Op0I->getOperand(0), NotB);
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003827 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00003828 } else if (Op0I->getOpcode() == Instruction::Xor) {
3829 if (Op1 == Op0I->getOperand(0)) // (A^B)^A == B
3830 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
3831 else if (Op1 == Op0I->getOperand(1)) // (B^A)^A == B
3832 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattnerdcd07922006-04-01 08:03:55 +00003833 } else if (Op0I->getOpcode() == Instruction::And && Op0I->hasOneUse()) {
3834 if (Op0I->getOperand(0) == Op1) // (A&B)^A -> (B&A)^A
3835 Op0I->swapOperands();
Chris Lattner6cf49142006-04-01 22:05:01 +00003836 if (Op0I->getOperand(1) == Op1 && // (B&A)^A == ~B & A
3837 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattnerdcd07922006-04-01 08:03:55 +00003838 Instruction *N = BinaryOperator::createNot(Op0I->getOperand(0), "tmp");
3839 InsertNewInstBefore(N, I);
3840 return BinaryOperator::createAnd(N, Op1);
3841 }
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003842 }
3843
Chris Lattner3ac7c262003-08-13 20:16:26 +00003844 // (setcc1 A, B) ^ (setcc2 A, B) --> (setcc3 A, B)
3845 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
3846 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
3847 return R;
3848
Chris Lattner3af10532006-05-05 06:39:07 +00003849 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
3850 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattnere745c7d2006-05-05 20:51:30 +00003851 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner3af10532006-05-05 06:39:07 +00003852 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Chris Lattnere745c7d2006-05-05 20:51:30 +00003853 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegral() &&
Chris Lattner1d441ad2006-05-06 09:00:16 +00003854 // Only do this if the casts both really cause code to be generated.
3855 ValueRequiresCast(Op0C->getOperand(0), I.getType(), TD) &&
3856 ValueRequiresCast(Op1C->getOperand(0), I.getType(), TD)) {
Chris Lattner3af10532006-05-05 06:39:07 +00003857 Instruction *NewOp = BinaryOperator::createXor(Op0C->getOperand(0),
3858 Op1C->getOperand(0),
3859 I.getName());
3860 InsertNewInstBefore(NewOp, I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003861 return CastInst::createInferredCast(NewOp, I.getType());
Chris Lattner3af10532006-05-05 06:39:07 +00003862 }
3863 }
Chris Lattnerf05d69a2006-11-14 07:46:50 +00003864
3865 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
3866 if (ShiftInst *SI1 = dyn_cast<ShiftInst>(Op1)) {
3867 if (ShiftInst *SI0 = dyn_cast<ShiftInst>(Op0))
3868 if (SI0->getOpcode() == SI1->getOpcode() &&
3869 SI0->getOperand(1) == SI1->getOperand(1) &&
3870 (SI0->hasOneUse() || SI1->hasOneUse())) {
3871 Instruction *NewOp =
3872 InsertNewInstBefore(BinaryOperator::createXor(SI0->getOperand(0),
3873 SI1->getOperand(0),
3874 SI0->getName()), I);
3875 return new ShiftInst(SI1->getOpcode(), NewOp, SI1->getOperand(1));
3876 }
3877 }
Chris Lattner3af10532006-05-05 06:39:07 +00003878
Chris Lattner113f4f42002-06-25 16:13:24 +00003879 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003880}
3881
Chris Lattner6862fbd2004-09-29 17:40:11 +00003882static bool isPositive(ConstantInt *C) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00003883 return C->getSExtValue() >= 0;
Chris Lattner6862fbd2004-09-29 17:40:11 +00003884}
3885
3886/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
3887/// overflowed for this type.
3888static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
3889 ConstantInt *In2) {
3890 Result = cast<ConstantInt>(ConstantExpr::getAdd(In1, In2));
3891
3892 if (In1->getType()->isUnsigned())
Reid Spencere0fc4df2006-10-20 07:07:24 +00003893 return cast<ConstantInt>(Result)->getZExtValue() <
3894 cast<ConstantInt>(In1)->getZExtValue();
Chris Lattner6862fbd2004-09-29 17:40:11 +00003895 if (isPositive(In1) != isPositive(In2))
3896 return false;
3897 if (isPositive(In1))
Reid Spencere0fc4df2006-10-20 07:07:24 +00003898 return cast<ConstantInt>(Result)->getSExtValue() <
3899 cast<ConstantInt>(In1)->getSExtValue();
3900 return cast<ConstantInt>(Result)->getSExtValue() >
3901 cast<ConstantInt>(In1)->getSExtValue();
Chris Lattner6862fbd2004-09-29 17:40:11 +00003902}
3903
Chris Lattner0798af32005-01-13 20:14:25 +00003904/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
3905/// code necessary to compute the offset from the base pointer (without adding
3906/// in the base pointer). Return the result as a signed integer of intptr size.
3907static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
3908 TargetData &TD = IC.getTargetData();
3909 gep_type_iterator GTI = gep_type_begin(GEP);
3910 const Type *UIntPtrTy = TD.getIntPtrType();
3911 const Type *SIntPtrTy = UIntPtrTy->getSignedVersion();
3912 Value *Result = Constant::getNullValue(SIntPtrTy);
3913
3914 // Build a mask for high order bits.
Chris Lattner77defba2006-02-07 07:00:41 +00003915 uint64_t PtrSizeMask = ~0ULL >> (64-TD.getPointerSize()*8);
Chris Lattner0798af32005-01-13 20:14:25 +00003916
Chris Lattner0798af32005-01-13 20:14:25 +00003917 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
3918 Value *Op = GEP->getOperand(i);
Chris Lattnerd35d2102005-01-13 23:26:48 +00003919 uint64_t Size = TD.getTypeSize(GTI.getIndexedType()) & PtrSizeMask;
Reid Spencere0fc4df2006-10-20 07:07:24 +00003920 Constant *Scale = ConstantExpr::getCast(ConstantInt::get(UIntPtrTy, Size),
Chris Lattner0798af32005-01-13 20:14:25 +00003921 SIntPtrTy);
3922 if (Constant *OpC = dyn_cast<Constant>(Op)) {
3923 if (!OpC->isNullValue()) {
Chris Lattner4cb9fa32005-01-13 20:40:58 +00003924 OpC = ConstantExpr::getCast(OpC, SIntPtrTy);
Chris Lattner0798af32005-01-13 20:14:25 +00003925 Scale = ConstantExpr::getMul(OpC, Scale);
3926 if (Constant *RC = dyn_cast<Constant>(Result))
3927 Result = ConstantExpr::getAdd(RC, Scale);
3928 else {
3929 // Emit an add instruction.
3930 Result = IC.InsertNewInstBefore(
3931 BinaryOperator::createAdd(Result, Scale,
3932 GEP->getName()+".offs"), I);
3933 }
3934 }
3935 } else {
Chris Lattner7aa41cf2005-01-14 17:17:59 +00003936 // Convert to correct type.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003937 Op = IC.InsertNewInstBefore(CastInst::createInferredCast(Op, SIntPtrTy,
Chris Lattner7aa41cf2005-01-14 17:17:59 +00003938 Op->getName()+".c"), I);
3939 if (Size != 1)
Chris Lattner4cb9fa32005-01-13 20:40:58 +00003940 // We'll let instcombine(mul) convert this to a shl if possible.
3941 Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
3942 GEP->getName()+".idx"), I);
Chris Lattner0798af32005-01-13 20:14:25 +00003943
3944 // Emit an add instruction.
Chris Lattner4cb9fa32005-01-13 20:40:58 +00003945 Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
Chris Lattner0798af32005-01-13 20:14:25 +00003946 GEP->getName()+".offs"), I);
3947 }
3948 }
3949 return Result;
3950}
3951
3952/// FoldGEPSetCC - Fold comparisons between a GEP instruction and something
3953/// else. At this point we know that the GEP is on the LHS of the comparison.
3954Instruction *InstCombiner::FoldGEPSetCC(User *GEPLHS, Value *RHS,
3955 Instruction::BinaryOps Cond,
3956 Instruction &I) {
3957 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattner81e84172005-01-13 22:25:21 +00003958
3959 if (CastInst *CI = dyn_cast<CastInst>(RHS))
3960 if (isa<PointerType>(CI->getOperand(0)->getType()))
3961 RHS = CI->getOperand(0);
3962
Chris Lattner0798af32005-01-13 20:14:25 +00003963 Value *PtrBase = GEPLHS->getOperand(0);
3964 if (PtrBase == RHS) {
3965 // As an optimization, we don't actually have to compute the actual value of
3966 // OFFSET if this is a seteq or setne comparison, just return whether each
3967 // index is zero or not.
Chris Lattner81e84172005-01-13 22:25:21 +00003968 if (Cond == Instruction::SetEQ || Cond == Instruction::SetNE) {
3969 Instruction *InVal = 0;
Chris Lattnercd517ff2005-01-28 19:32:01 +00003970 gep_type_iterator GTI = gep_type_begin(GEPLHS);
3971 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i, ++GTI) {
Chris Lattner81e84172005-01-13 22:25:21 +00003972 bool EmitIt = true;
3973 if (Constant *C = dyn_cast<Constant>(GEPLHS->getOperand(i))) {
3974 if (isa<UndefValue>(C)) // undef index -> undef.
3975 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
3976 if (C->isNullValue())
3977 EmitIt = false;
Chris Lattnercd517ff2005-01-28 19:32:01 +00003978 else if (TD->getTypeSize(GTI.getIndexedType()) == 0) {
3979 EmitIt = false; // This is indexing into a zero sized array?
Misha Brukmanb1c93172005-04-21 23:48:37 +00003980 } else if (isa<ConstantInt>(C))
Chris Lattner81e84172005-01-13 22:25:21 +00003981 return ReplaceInstUsesWith(I, // No comparison is needed here.
3982 ConstantBool::get(Cond == Instruction::SetNE));
3983 }
3984
3985 if (EmitIt) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00003986 Instruction *Comp =
Chris Lattner81e84172005-01-13 22:25:21 +00003987 new SetCondInst(Cond, GEPLHS->getOperand(i),
3988 Constant::getNullValue(GEPLHS->getOperand(i)->getType()));
3989 if (InVal == 0)
3990 InVal = Comp;
3991 else {
3992 InVal = InsertNewInstBefore(InVal, I);
3993 InsertNewInstBefore(Comp, I);
3994 if (Cond == Instruction::SetNE) // True if any are unequal
3995 InVal = BinaryOperator::createOr(InVal, Comp);
3996 else // True if all are equal
3997 InVal = BinaryOperator::createAnd(InVal, Comp);
3998 }
3999 }
4000 }
4001
4002 if (InVal)
4003 return InVal;
4004 else
4005 ReplaceInstUsesWith(I, // No comparison is needed here, all indexes = 0
4006 ConstantBool::get(Cond == Instruction::SetEQ));
4007 }
Chris Lattner0798af32005-01-13 20:14:25 +00004008
4009 // Only lower this if the setcc is the only user of the GEP or if we expect
4010 // the result to fold to a constant!
4011 if (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) {
4012 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
4013 Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
4014 return new SetCondInst(Cond, Offset,
4015 Constant::getNullValue(Offset->getType()));
4016 }
4017 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
Chris Lattnera21bf8d2005-04-25 20:17:30 +00004018 // If the base pointers are different, but the indices are the same, just
4019 // compare the base pointer.
4020 if (PtrBase != GEPRHS->getOperand(0)) {
4021 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00004022 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattnerbd43b9d2005-04-26 14:40:41 +00004023 GEPRHS->getOperand(0)->getType();
Chris Lattnera21bf8d2005-04-25 20:17:30 +00004024 if (IndicesTheSame)
4025 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4026 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4027 IndicesTheSame = false;
4028 break;
4029 }
4030
4031 // If all indices are the same, just compare the base pointers.
4032 if (IndicesTheSame)
4033 return new SetCondInst(Cond, GEPLHS->getOperand(0),
4034 GEPRHS->getOperand(0));
4035
4036 // Otherwise, the base pointers are different and the indices are
4037 // different, bail out.
Chris Lattner0798af32005-01-13 20:14:25 +00004038 return 0;
Chris Lattnera21bf8d2005-04-25 20:17:30 +00004039 }
Chris Lattner0798af32005-01-13 20:14:25 +00004040
Chris Lattner81e84172005-01-13 22:25:21 +00004041 // If one of the GEPs has all zero indices, recurse.
4042 bool AllZeros = true;
4043 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4044 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
4045 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
4046 AllZeros = false;
4047 break;
4048 }
4049 if (AllZeros)
4050 return FoldGEPSetCC(GEPRHS, GEPLHS->getOperand(0),
4051 SetCondInst::getSwappedCondition(Cond), I);
Chris Lattner4fa89822005-01-14 00:20:05 +00004052
4053 // If the other GEP has all zero indices, recurse.
Chris Lattner81e84172005-01-13 22:25:21 +00004054 AllZeros = true;
4055 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4056 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
4057 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
4058 AllZeros = false;
4059 break;
4060 }
4061 if (AllZeros)
4062 return FoldGEPSetCC(GEPLHS, GEPRHS->getOperand(0), Cond, I);
4063
Chris Lattner4fa89822005-01-14 00:20:05 +00004064 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
4065 // If the GEPs only differ by one index, compare it.
4066 unsigned NumDifferences = 0; // Keep track of # differences.
4067 unsigned DiffOperand = 0; // The operand that differs.
4068 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4069 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004070 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
4071 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattnerfc4429e2005-01-21 23:06:49 +00004072 // Irreconcilable differences.
Chris Lattner4fa89822005-01-14 00:20:05 +00004073 NumDifferences = 2;
4074 break;
4075 } else {
4076 if (NumDifferences++) break;
4077 DiffOperand = i;
4078 }
4079 }
4080
4081 if (NumDifferences == 0) // SAME GEP?
4082 return ReplaceInstUsesWith(I, // No comparison is needed here.
4083 ConstantBool::get(Cond == Instruction::SetEQ));
4084 else if (NumDifferences == 1) {
Chris Lattnerfc4429e2005-01-21 23:06:49 +00004085 Value *LHSV = GEPLHS->getOperand(DiffOperand);
4086 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Chris Lattner247aef82005-07-18 23:07:33 +00004087
4088 // Convert the operands to signed values to make sure to perform a
4089 // signed comparison.
4090 const Type *NewTy = LHSV->getType()->getSignedVersion();
4091 if (LHSV->getType() != NewTy)
Reid Spencer00c482b2006-10-26 19:19:06 +00004092 LHSV = InsertCastBefore(LHSV, NewTy, I);
Chris Lattner247aef82005-07-18 23:07:33 +00004093 if (RHSV->getType() != NewTy)
Reid Spencer00c482b2006-10-26 19:19:06 +00004094 RHSV = InsertCastBefore(RHSV, NewTy, I);
Chris Lattner247aef82005-07-18 23:07:33 +00004095 return new SetCondInst(Cond, LHSV, RHSV);
Chris Lattner4fa89822005-01-14 00:20:05 +00004096 }
4097 }
4098
Chris Lattner0798af32005-01-13 20:14:25 +00004099 // Only lower this if the setcc is the only user of the GEP or if we expect
4100 // the result to fold to a constant!
4101 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
4102 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
4103 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
4104 Value *L = EmitGEPOffset(GEPLHS, I, *this);
4105 Value *R = EmitGEPOffset(GEPRHS, I, *this);
4106 return new SetCondInst(Cond, L, R);
4107 }
4108 }
4109 return 0;
4110}
4111
4112
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004113Instruction *InstCombiner::visitSetCondInst(SetCondInst &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00004114 bool Changed = SimplifyCommutative(I);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004115 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4116 const Type *Ty = Op0->getType();
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004117
4118 // setcc X, X
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004119 if (Op0 == Op1)
4120 return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
Chris Lattner1fc23f32002-05-09 20:11:54 +00004121
Chris Lattner81a7a232004-10-16 18:11:37 +00004122 if (isa<UndefValue>(Op1)) // X setcc undef -> undef
4123 return ReplaceInstUsesWith(I, UndefValue::get(Type::BoolTy));
4124
Chris Lattner15ff1e12004-11-14 07:33:16 +00004125 // setcc <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
4126 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanb1c93172005-04-21 23:48:37 +00004127 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
4128 isa<ConstantPointerNull>(Op0)) &&
4129 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner15ff1e12004-11-14 07:33:16 +00004130 isa<ConstantPointerNull>(Op1)))
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004131 return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
4132
4133 // setcc's with boolean values can always be turned into bitwise operations
4134 if (Ty == Type::BoolTy) {
Chris Lattner4456da62004-08-11 00:50:51 +00004135 switch (I.getOpcode()) {
4136 default: assert(0 && "Invalid setcc instruction!");
4137 case Instruction::SetEQ: { // seteq bool %A, %B -> ~(A^B)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004138 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004139 InsertNewInstBefore(Xor, I);
Chris Lattner16930792003-11-03 04:25:02 +00004140 return BinaryOperator::createNot(Xor);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004141 }
Chris Lattner4456da62004-08-11 00:50:51 +00004142 case Instruction::SetNE:
4143 return BinaryOperator::createXor(Op0, Op1);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004144
Chris Lattner4456da62004-08-11 00:50:51 +00004145 case Instruction::SetGT:
4146 std::swap(Op0, Op1); // Change setgt -> setlt
4147 // FALL THROUGH
4148 case Instruction::SetLT: { // setlt bool A, B -> ~X & Y
4149 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4150 InsertNewInstBefore(Not, I);
4151 return BinaryOperator::createAnd(Not, Op1);
4152 }
4153 case Instruction::SetGE:
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004154 std::swap(Op0, Op1); // Change setge -> setle
Chris Lattner4456da62004-08-11 00:50:51 +00004155 // FALL THROUGH
4156 case Instruction::SetLE: { // setle bool %A, %B -> ~A | B
4157 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4158 InsertNewInstBefore(Not, I);
4159 return BinaryOperator::createOr(Not, Op1);
4160 }
4161 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004162 }
4163
Chris Lattner2dd01742004-06-09 04:24:29 +00004164 // See if we are doing a comparison between a constant and an instruction that
4165 // can be folded into the comparison.
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004166 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner6862fbd2004-09-29 17:40:11 +00004167 // Check to see if we are comparing against the minimum or maximum value...
4168 if (CI->isMinValue()) {
4169 if (I.getOpcode() == Instruction::SetLT) // A < MIN -> FALSE
Chris Lattner6ab03f62006-09-28 23:35:22 +00004170 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattner6862fbd2004-09-29 17:40:11 +00004171 if (I.getOpcode() == Instruction::SetGE) // A >= MIN -> TRUE
Chris Lattner6ab03f62006-09-28 23:35:22 +00004172 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
Chris Lattner6862fbd2004-09-29 17:40:11 +00004173 if (I.getOpcode() == Instruction::SetLE) // A <= MIN -> A == MIN
4174 return BinaryOperator::createSetEQ(Op0, Op1);
4175 if (I.getOpcode() == Instruction::SetGT) // A > MIN -> A != MIN
4176 return BinaryOperator::createSetNE(Op0, Op1);
4177
4178 } else if (CI->isMaxValue()) {
4179 if (I.getOpcode() == Instruction::SetGT) // A > MAX -> FALSE
Chris Lattner6ab03f62006-09-28 23:35:22 +00004180 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattner6862fbd2004-09-29 17:40:11 +00004181 if (I.getOpcode() == Instruction::SetLE) // A <= MAX -> TRUE
Chris Lattner6ab03f62006-09-28 23:35:22 +00004182 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
Chris Lattner6862fbd2004-09-29 17:40:11 +00004183 if (I.getOpcode() == Instruction::SetGE) // A >= MAX -> A == MAX
4184 return BinaryOperator::createSetEQ(Op0, Op1);
4185 if (I.getOpcode() == Instruction::SetLT) // A < MAX -> A != MAX
4186 return BinaryOperator::createSetNE(Op0, Op1);
4187
4188 // Comparing against a value really close to min or max?
4189 } else if (isMinValuePlusOne(CI)) {
4190 if (I.getOpcode() == Instruction::SetLT) // A < MIN+1 -> A == MIN
4191 return BinaryOperator::createSetEQ(Op0, SubOne(CI));
4192 if (I.getOpcode() == Instruction::SetGE) // A >= MIN-1 -> A != MIN
4193 return BinaryOperator::createSetNE(Op0, SubOne(CI));
4194
4195 } else if (isMaxValueMinusOne(CI)) {
4196 if (I.getOpcode() == Instruction::SetGT) // A > MAX-1 -> A == MAX
4197 return BinaryOperator::createSetEQ(Op0, AddOne(CI));
4198 if (I.getOpcode() == Instruction::SetLE) // A <= MAX-1 -> A != MAX
4199 return BinaryOperator::createSetNE(Op0, AddOne(CI));
4200 }
4201
4202 // If we still have a setle or setge instruction, turn it into the
4203 // appropriate setlt or setgt instruction. Since the border cases have
4204 // already been handled above, this requires little checking.
4205 //
4206 if (I.getOpcode() == Instruction::SetLE)
4207 return BinaryOperator::createSetLT(Op0, AddOne(CI));
4208 if (I.getOpcode() == Instruction::SetGE)
4209 return BinaryOperator::createSetGT(Op0, SubOne(CI));
4210
Chris Lattneree0f2802006-02-12 02:07:56 +00004211
4212 // See if we can fold the comparison based on bits known to be zero or one
4213 // in the input.
4214 uint64_t KnownZero, KnownOne;
4215 if (SimplifyDemandedBits(Op0, Ty->getIntegralTypeMask(),
4216 KnownZero, KnownOne, 0))
4217 return &I;
4218
4219 // Given the known and unknown bits, compute a range that the LHS could be
4220 // in.
4221 if (KnownOne | KnownZero) {
4222 if (Ty->isUnsigned()) { // Unsigned comparison.
4223 uint64_t Min, Max;
4224 uint64_t RHSVal = CI->getZExtValue();
4225 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne,
4226 Min, Max);
4227 switch (I.getOpcode()) { // LE/GE have been folded already.
4228 default: assert(0 && "Unknown setcc opcode!");
4229 case Instruction::SetEQ:
4230 if (Max < RHSVal || Min > RHSVal)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004231 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattneree0f2802006-02-12 02:07:56 +00004232 break;
4233 case Instruction::SetNE:
4234 if (Max < RHSVal || Min > RHSVal)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004235 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
Chris Lattneree0f2802006-02-12 02:07:56 +00004236 break;
4237 case Instruction::SetLT:
Chris Lattner6ab03f62006-09-28 23:35:22 +00004238 if (Max < RHSVal)
4239 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4240 if (Min > RHSVal)
4241 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattneree0f2802006-02-12 02:07:56 +00004242 break;
4243 case Instruction::SetGT:
Chris Lattner6ab03f62006-09-28 23:35:22 +00004244 if (Min > RHSVal)
4245 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4246 if (Max < RHSVal)
4247 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattneree0f2802006-02-12 02:07:56 +00004248 break;
4249 }
4250 } else { // Signed comparison.
4251 int64_t Min, Max;
4252 int64_t RHSVal = CI->getSExtValue();
4253 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne,
4254 Min, Max);
4255 switch (I.getOpcode()) { // LE/GE have been folded already.
4256 default: assert(0 && "Unknown setcc opcode!");
4257 case Instruction::SetEQ:
4258 if (Max < RHSVal || Min > RHSVal)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004259 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattneree0f2802006-02-12 02:07:56 +00004260 break;
4261 case Instruction::SetNE:
4262 if (Max < RHSVal || Min > RHSVal)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004263 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
Chris Lattneree0f2802006-02-12 02:07:56 +00004264 break;
4265 case Instruction::SetLT:
Chris Lattner6ab03f62006-09-28 23:35:22 +00004266 if (Max < RHSVal)
4267 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4268 if (Min > RHSVal)
4269 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattneree0f2802006-02-12 02:07:56 +00004270 break;
4271 case Instruction::SetGT:
Chris Lattner6ab03f62006-09-28 23:35:22 +00004272 if (Min > RHSVal)
4273 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4274 if (Max < RHSVal)
4275 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattneree0f2802006-02-12 02:07:56 +00004276 break;
4277 }
4278 }
4279 }
4280
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004281 // Since the RHS is a constantInt (CI), if the left hand side is an
4282 // instruction, see if that instruction also has constants so that the
4283 // instruction can be folded into the setcc
Chris Lattnere1e10e12004-05-25 06:32:08 +00004284 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004285 switch (LHSI->getOpcode()) {
4286 case Instruction::And:
4287 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
4288 LHSI->getOperand(0)->hasOneUse()) {
Chris Lattner4922a0e2006-09-18 05:27:43 +00004289 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
4290
4291 // If an operand is an AND of a truncating cast, we can widen the
4292 // and/compare to be the input width without changing the value
4293 // produced, eliminating a cast.
4294 if (CastInst *Cast = dyn_cast<CastInst>(LHSI->getOperand(0))) {
4295 // We can do this transformation if either the AND constant does not
4296 // have its sign bit set or if it is an equality comparison.
4297 // Extending a relational comparison when we're checking the sign
4298 // bit would not work.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00004299 if (Cast->hasOneUse() && isa<TruncInst>(Cast) &&
Chris Lattner4922a0e2006-09-18 05:27:43 +00004300 (I.isEquality() ||
4301 (AndCST->getZExtValue() == (uint64_t)AndCST->getSExtValue()) &&
4302 (CI->getZExtValue() == (uint64_t)CI->getSExtValue()))) {
4303 ConstantInt *NewCST;
4304 ConstantInt *NewCI;
4305 if (Cast->getOperand(0)->getType()->isSigned()) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00004306 NewCST = ConstantInt::get(Cast->getOperand(0)->getType(),
Chris Lattner4922a0e2006-09-18 05:27:43 +00004307 AndCST->getZExtValue());
Reid Spencere0fc4df2006-10-20 07:07:24 +00004308 NewCI = ConstantInt::get(Cast->getOperand(0)->getType(),
Chris Lattner4922a0e2006-09-18 05:27:43 +00004309 CI->getZExtValue());
4310 } else {
Reid Spencere0fc4df2006-10-20 07:07:24 +00004311 NewCST = ConstantInt::get(Cast->getOperand(0)->getType(),
Chris Lattner4922a0e2006-09-18 05:27:43 +00004312 AndCST->getZExtValue());
Reid Spencere0fc4df2006-10-20 07:07:24 +00004313 NewCI = ConstantInt::get(Cast->getOperand(0)->getType(),
Chris Lattner4922a0e2006-09-18 05:27:43 +00004314 CI->getZExtValue());
4315 }
4316 Instruction *NewAnd =
4317 BinaryOperator::createAnd(Cast->getOperand(0), NewCST,
4318 LHSI->getName());
4319 InsertNewInstBefore(NewAnd, I);
4320 return new SetCondInst(I.getOpcode(), NewAnd, NewCI);
4321 }
4322 }
4323
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004324 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
4325 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
4326 // happens a LOT in code produced by the C front-end, for bitfield
4327 // access.
4328 ShiftInst *Shift = dyn_cast<ShiftInst>(LHSI->getOperand(0));
Chris Lattneree0f2802006-02-12 02:07:56 +00004329
4330 // Check to see if there is a noop-cast between the shift and the and.
4331 if (!Shift) {
4332 if (CastInst *CI = dyn_cast<CastInst>(LHSI->getOperand(0)))
4333 if (CI->getOperand(0)->getType()->isIntegral() &&
4334 CI->getOperand(0)->getType()->getPrimitiveSizeInBits() ==
4335 CI->getType()->getPrimitiveSizeInBits())
4336 Shift = dyn_cast<ShiftInst>(CI->getOperand(0));
4337 }
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004338
Reid Spencere0fc4df2006-10-20 07:07:24 +00004339 ConstantInt *ShAmt;
4340 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
Chris Lattneree0f2802006-02-12 02:07:56 +00004341 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
4342 const Type *AndTy = AndCST->getType(); // Type of the and.
Misha Brukmanb1c93172005-04-21 23:48:37 +00004343
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004344 // We can fold this as long as we can't shift unknown bits
4345 // into the mask. This can only happen with signed shift
4346 // rights, as they sign-extend.
4347 if (ShAmt) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004348 bool CanFold = Shift->isLogicalShift();
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004349 if (!CanFold) {
4350 // To test for the bad case of the signed shr, see if any
4351 // of the bits shifted in could be tested after the mask.
Reid Spencere0fc4df2006-10-20 07:07:24 +00004352 int ShAmtVal = Ty->getPrimitiveSizeInBits()-ShAmt->getZExtValue();
Chris Lattnerc53cb9d2005-06-17 01:29:28 +00004353 if (ShAmtVal < 0) ShAmtVal = 0; // Out of range shift.
4354
Reid Spencere0fc4df2006-10-20 07:07:24 +00004355 Constant *OShAmt = ConstantInt::get(Type::UByteTy, ShAmtVal);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004356 Constant *ShVal =
Chris Lattneree0f2802006-02-12 02:07:56 +00004357 ConstantExpr::getShl(ConstantInt::getAllOnesValue(AndTy),
4358 OShAmt);
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004359 if (ConstantExpr::getAnd(ShVal, AndCST)->isNullValue())
4360 CanFold = true;
4361 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004362
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004363 if (CanFold) {
Chris Lattner6afc02f2004-09-28 17:54:07 +00004364 Constant *NewCst;
4365 if (Shift->getOpcode() == Instruction::Shl)
Reid Spencerfdff9382006-11-08 06:47:33 +00004366 NewCst = ConstantExpr::getLShr(CI, ShAmt);
Chris Lattner6afc02f2004-09-28 17:54:07 +00004367 else
4368 NewCst = ConstantExpr::getShl(CI, ShAmt);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004369
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004370 // Check to see if we are shifting out any of the bits being
4371 // compared.
4372 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != CI){
4373 // If we shifted bits out, the fold is not going to work out.
4374 // As a special case, check to see if this means that the
4375 // result is always true or false now.
4376 if (I.getOpcode() == Instruction::SetEQ)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004377 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004378 if (I.getOpcode() == Instruction::SetNE)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004379 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004380 } else {
4381 I.setOperand(1, NewCst);
Chris Lattner6afc02f2004-09-28 17:54:07 +00004382 Constant *NewAndCST;
4383 if (Shift->getOpcode() == Instruction::Shl)
Reid Spencerfdff9382006-11-08 06:47:33 +00004384 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
Chris Lattner6afc02f2004-09-28 17:54:07 +00004385 else
4386 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
4387 LHSI->setOperand(1, NewAndCST);
Chris Lattneree0f2802006-02-12 02:07:56 +00004388 if (AndTy == Ty)
4389 LHSI->setOperand(0, Shift->getOperand(0));
4390 else {
4391 Value *NewCast = InsertCastBefore(Shift->getOperand(0), AndTy,
4392 *Shift);
4393 LHSI->setOperand(0, NewCast);
4394 }
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004395 WorkList.push_back(Shift); // Shift is dead.
4396 AddUsesToWorkList(I);
4397 return &I;
Chris Lattner1638de42004-07-21 19:50:44 +00004398 }
4399 }
Chris Lattner35167c32004-06-09 07:59:58 +00004400 }
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004401
4402 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
4403 // preferable because it allows the C<<Y expression to be hoisted out
4404 // of a loop if Y is invariant and X is not.
4405 if (Shift && Shift->hasOneUse() && CI->isNullValue() &&
Chris Lattnerde077922006-09-18 18:27:05 +00004406 I.isEquality() && !Shift->isArithmeticShift() &&
4407 isa<Instruction>(Shift->getOperand(0))) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004408 // Compute C << Y.
4409 Value *NS;
Reid Spencerfdff9382006-11-08 06:47:33 +00004410 if (Shift->getOpcode() == Instruction::LShr) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004411 NS = new ShiftInst(Instruction::Shl, AndCST, Shift->getOperand(1),
4412 "tmp");
4413 } else {
4414 // Make sure we insert a logical shift.
Chris Lattner4922a0e2006-09-18 05:27:43 +00004415 Constant *NewAndCST = AndCST;
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004416 if (AndCST->getType()->isSigned())
Chris Lattner4922a0e2006-09-18 05:27:43 +00004417 NewAndCST = ConstantExpr::getCast(AndCST,
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004418 AndCST->getType()->getUnsignedVersion());
Reid Spencerfdff9382006-11-08 06:47:33 +00004419 NS = new ShiftInst(Instruction::LShr, NewAndCST,
Chris Lattner4922a0e2006-09-18 05:27:43 +00004420 Shift->getOperand(1), "tmp");
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004421 }
4422 InsertNewInstBefore(cast<Instruction>(NS), I);
4423
4424 // If C's sign doesn't agree with the and, insert a cast now.
4425 if (NS->getType() != LHSI->getType())
4426 NS = InsertCastBefore(NS, LHSI->getType(), I);
4427
4428 Value *ShiftOp = Shift->getOperand(0);
4429 if (ShiftOp->getType() != LHSI->getType())
4430 ShiftOp = InsertCastBefore(ShiftOp, LHSI->getType(), I);
4431
4432 // Compute X & (C << Y).
4433 Instruction *NewAnd =
4434 BinaryOperator::createAnd(ShiftOp, NS, LHSI->getName());
4435 InsertNewInstBefore(NewAnd, I);
4436
4437 I.setOperand(0, NewAnd);
4438 return &I;
4439 }
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004440 }
4441 break;
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004442
Chris Lattner272d5ca2004-09-28 18:22:15 +00004443 case Instruction::Shl: // (setcc (shl X, ShAmt), CI)
Reid Spencere0fc4df2006-10-20 07:07:24 +00004444 if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004445 if (I.isEquality()) {
Chris Lattner19b57f52005-06-15 20:53:31 +00004446 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
4447
4448 // Check that the shift amount is in range. If not, don't perform
4449 // undefined shifts. When the shift is visited it will be
4450 // simplified.
Reid Spencere0fc4df2006-10-20 07:07:24 +00004451 if (ShAmt->getZExtValue() >= TypeBits)
Chris Lattner19b57f52005-06-15 20:53:31 +00004452 break;
4453
Chris Lattner272d5ca2004-09-28 18:22:15 +00004454 // If we are comparing against bits always shifted out, the
4455 // comparison cannot succeed.
Misha Brukmanb1c93172005-04-21 23:48:37 +00004456 Constant *Comp =
Reid Spencerfdff9382006-11-08 06:47:33 +00004457 ConstantExpr::getShl(ConstantExpr::getLShr(CI, ShAmt), ShAmt);
Chris Lattner272d5ca2004-09-28 18:22:15 +00004458 if (Comp != CI) {// Comparing against a bit that we know is zero.
4459 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
4460 Constant *Cst = ConstantBool::get(IsSetNE);
4461 return ReplaceInstUsesWith(I, Cst);
4462 }
4463
4464 if (LHSI->hasOneUse()) {
4465 // Otherwise strength reduce the shift into an and.
Reid Spencere0fc4df2006-10-20 07:07:24 +00004466 unsigned ShAmtVal = (unsigned)ShAmt->getZExtValue();
Chris Lattner272d5ca2004-09-28 18:22:15 +00004467 uint64_t Val = (1ULL << (TypeBits-ShAmtVal))-1;
4468
4469 Constant *Mask;
4470 if (CI->getType()->isUnsigned()) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00004471 Mask = ConstantInt::get(CI->getType(), Val);
Chris Lattner272d5ca2004-09-28 18:22:15 +00004472 } else if (ShAmtVal != 0) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00004473 Mask = ConstantInt::get(CI->getType(), Val);
Chris Lattner272d5ca2004-09-28 18:22:15 +00004474 } else {
4475 Mask = ConstantInt::getAllOnesValue(CI->getType());
4476 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004477
Chris Lattner272d5ca2004-09-28 18:22:15 +00004478 Instruction *AndI =
4479 BinaryOperator::createAnd(LHSI->getOperand(0),
4480 Mask, LHSI->getName()+".mask");
4481 Value *And = InsertNewInstBefore(AndI, I);
4482 return new SetCondInst(I.getOpcode(), And,
Reid Spencerfdff9382006-11-08 06:47:33 +00004483 ConstantExpr::getLShr(CI, ShAmt));
Chris Lattner272d5ca2004-09-28 18:22:15 +00004484 }
4485 }
Chris Lattner272d5ca2004-09-28 18:22:15 +00004486 }
4487 break;
4488
Reid Spencerfdff9382006-11-08 06:47:33 +00004489 case Instruction::LShr: // (setcc (shr X, ShAmt), CI)
4490 case Instruction::AShr:
Reid Spencere0fc4df2006-10-20 07:07:24 +00004491 if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004492 if (I.isEquality()) {
Chris Lattner19b57f52005-06-15 20:53:31 +00004493 // Check that the shift amount is in range. If not, don't perform
4494 // undefined shifts. When the shift is visited it will be
4495 // simplified.
Chris Lattner104002b2005-06-16 01:52:07 +00004496 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
Reid Spencere0fc4df2006-10-20 07:07:24 +00004497 if (ShAmt->getZExtValue() >= TypeBits)
Chris Lattner19b57f52005-06-15 20:53:31 +00004498 break;
4499
Chris Lattner1023b872004-09-27 16:18:50 +00004500 // If we are comparing against bits always shifted out, the
4501 // comparison cannot succeed.
Reid Spencerfdff9382006-11-08 06:47:33 +00004502 Constant *Comp;
4503 if (CI->getType()->isUnsigned())
4504 Comp = ConstantExpr::getLShr(ConstantExpr::getShl(CI, ShAmt),
4505 ShAmt);
4506 else
4507 Comp = ConstantExpr::getAShr(ConstantExpr::getShl(CI, ShAmt),
4508 ShAmt);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004509
Chris Lattner1023b872004-09-27 16:18:50 +00004510 if (Comp != CI) {// Comparing against a bit that we know is zero.
4511 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
4512 Constant *Cst = ConstantBool::get(IsSetNE);
4513 return ReplaceInstUsesWith(I, Cst);
4514 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004515
Chris Lattner1023b872004-09-27 16:18:50 +00004516 if (LHSI->hasOneUse() || CI->isNullValue()) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00004517 unsigned ShAmtVal = (unsigned)ShAmt->getZExtValue();
Chris Lattner272d5ca2004-09-28 18:22:15 +00004518
Chris Lattner1023b872004-09-27 16:18:50 +00004519 // Otherwise strength reduce the shift into an and.
4520 uint64_t Val = ~0ULL; // All ones.
4521 Val <<= ShAmtVal; // Shift over to the right spot.
4522
4523 Constant *Mask;
4524 if (CI->getType()->isUnsigned()) {
Chris Lattner2f1457f2005-04-24 17:46:05 +00004525 Val &= ~0ULL >> (64-TypeBits);
Reid Spencere0fc4df2006-10-20 07:07:24 +00004526 Mask = ConstantInt::get(CI->getType(), Val);
Chris Lattner1023b872004-09-27 16:18:50 +00004527 } else {
Reid Spencere0fc4df2006-10-20 07:07:24 +00004528 Mask = ConstantInt::get(CI->getType(), Val);
Chris Lattner1023b872004-09-27 16:18:50 +00004529 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004530
Chris Lattner1023b872004-09-27 16:18:50 +00004531 Instruction *AndI =
4532 BinaryOperator::createAnd(LHSI->getOperand(0),
4533 Mask, LHSI->getName()+".mask");
4534 Value *And = InsertNewInstBefore(AndI, I);
4535 return new SetCondInst(I.getOpcode(), And,
4536 ConstantExpr::getShl(CI, ShAmt));
4537 }
Chris Lattner1023b872004-09-27 16:18:50 +00004538 }
4539 }
4540 break;
Chris Lattner7e794272004-09-24 15:21:34 +00004541
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004542 case Instruction::SDiv:
4543 case Instruction::UDiv:
4544 // Fold: setcc ([us]div X, C1), C2 -> range test
4545 // Fold this div into the comparison, producing a range check.
4546 // Determine, based on the divide type, what the range is being
4547 // checked. If there is an overflow on the low or high side, remember
4548 // it, otherwise compute the range [low, hi) bounding the new value.
4549 // See: InsertRangeTest above for the kinds of replacements possible.
Chris Lattner6862fbd2004-09-29 17:40:11 +00004550 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004551 // FIXME: If the operand types don't match the type of the divide
4552 // then don't attempt this transform. The code below doesn't have the
4553 // logic to deal with a signed divide and an unsigned compare (and
4554 // vice versa). This is because (x /s C1) <s C2 produces different
4555 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
4556 // (x /u C1) <u C2. Simply casting the operands and result won't
4557 // work. :( The if statement below tests that condition and bails
4558 // if it finds it.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00004559 const Type *DivRHSTy = DivRHS->getType();
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004560 unsigned DivOpCode = LHSI->getOpcode();
4561 if (I.isEquality() &&
4562 ((DivOpCode == Instruction::SDiv && DivRHSTy->isUnsigned()) ||
4563 (DivOpCode == Instruction::UDiv && DivRHSTy->isSigned())))
4564 break;
4565
4566 // Initialize the variables that will indicate the nature of the
4567 // range check.
4568 bool LoOverflow = false, HiOverflow = false;
Chris Lattner6862fbd2004-09-29 17:40:11 +00004569 ConstantInt *LoBound = 0, *HiBound = 0;
4570
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004571 // Compute Prod = CI * DivRHS. We are essentially solving an equation
4572 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
4573 // C2 (CI). By solving for X we can turn this into a range check
4574 // instead of computing a divide.
4575 ConstantInt *Prod =
4576 cast<ConstantInt>(ConstantExpr::getMul(CI, DivRHS));
Chris Lattner6862fbd2004-09-29 17:40:11 +00004577
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004578 // Determine if the product overflows by seeing if the product is
4579 // not equal to the divide. Make sure we do the same kind of divide
4580 // as in the LHS instruction that we're folding.
4581 bool ProdOV = !DivRHS->isNullValue() &&
4582 (DivOpCode == Instruction::SDiv ?
4583 ConstantExpr::getSDiv(Prod, DivRHS) :
4584 ConstantExpr::getUDiv(Prod, DivRHS)) != CI;
4585
4586 // Get the SetCC opcode
Chris Lattnera92af962004-10-11 19:40:04 +00004587 Instruction::BinaryOps Opcode = I.getOpcode();
4588
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004589 if (DivRHS->isNullValue()) {
4590 // Don't hack on divide by zeros!
4591 } else if (DivOpCode == Instruction::UDiv) { // udiv
Chris Lattner6862fbd2004-09-29 17:40:11 +00004592 LoBound = Prod;
4593 LoOverflow = ProdOV;
4594 HiOverflow = ProdOV || AddWithOverflow(HiBound, LoBound, DivRHS);
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004595 } else if (isPositive(DivRHS)) { // Divisor is > 0.
Chris Lattner6862fbd2004-09-29 17:40:11 +00004596 if (CI->isNullValue()) { // (X / pos) op 0
4597 // Can't overflow.
4598 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
4599 HiBound = DivRHS;
4600 } else if (isPositive(CI)) { // (X / pos) op pos
4601 LoBound = Prod;
4602 LoOverflow = ProdOV;
4603 HiOverflow = ProdOV || AddWithOverflow(HiBound, Prod, DivRHS);
4604 } else { // (X / pos) op neg
4605 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
4606 LoOverflow = AddWithOverflow(LoBound, Prod,
4607 cast<ConstantInt>(DivRHSH));
4608 HiBound = Prod;
4609 HiOverflow = ProdOV;
4610 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004611 } else { // Divisor is < 0.
Chris Lattner6862fbd2004-09-29 17:40:11 +00004612 if (CI->isNullValue()) { // (X / neg) op 0
4613 LoBound = AddOne(DivRHS);
4614 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner73bcba52005-06-17 02:05:55 +00004615 if (HiBound == DivRHS)
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004616 LoBound = 0; // - INTMIN = INTMIN
Chris Lattner6862fbd2004-09-29 17:40:11 +00004617 } else if (isPositive(CI)) { // (X / neg) op pos
4618 HiOverflow = LoOverflow = ProdOV;
4619 if (!LoOverflow)
4620 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS));
4621 HiBound = AddOne(Prod);
4622 } else { // (X / neg) op neg
4623 LoBound = Prod;
4624 LoOverflow = HiOverflow = ProdOV;
4625 HiBound = cast<ConstantInt>(ConstantExpr::getSub(Prod, DivRHS));
4626 }
Chris Lattner0b41e862004-10-08 19:15:44 +00004627
Chris Lattnera92af962004-10-11 19:40:04 +00004628 // Dividing by a negate swaps the condition.
4629 Opcode = SetCondInst::getSwappedCondition(Opcode);
Chris Lattner6862fbd2004-09-29 17:40:11 +00004630 }
4631
4632 if (LoBound) {
4633 Value *X = LHSI->getOperand(0);
Chris Lattnera92af962004-10-11 19:40:04 +00004634 switch (Opcode) {
Chris Lattner6862fbd2004-09-29 17:40:11 +00004635 default: assert(0 && "Unhandled setcc opcode!");
4636 case Instruction::SetEQ:
4637 if (LoOverflow && HiOverflow)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004638 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattner6862fbd2004-09-29 17:40:11 +00004639 else if (HiOverflow)
4640 return new SetCondInst(Instruction::SetGE, X, LoBound);
4641 else if (LoOverflow)
4642 return new SetCondInst(Instruction::SetLT, X, HiBound);
4643 else
4644 return InsertRangeTest(X, LoBound, HiBound, true, I);
4645 case Instruction::SetNE:
4646 if (LoOverflow && HiOverflow)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004647 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
Chris Lattner6862fbd2004-09-29 17:40:11 +00004648 else if (HiOverflow)
4649 return new SetCondInst(Instruction::SetLT, X, LoBound);
4650 else if (LoOverflow)
4651 return new SetCondInst(Instruction::SetGE, X, HiBound);
4652 else
4653 return InsertRangeTest(X, LoBound, HiBound, false, I);
4654 case Instruction::SetLT:
4655 if (LoOverflow)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004656 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattner6862fbd2004-09-29 17:40:11 +00004657 return new SetCondInst(Instruction::SetLT, X, LoBound);
4658 case Instruction::SetGT:
4659 if (HiOverflow)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004660 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattner6862fbd2004-09-29 17:40:11 +00004661 return new SetCondInst(Instruction::SetGE, X, HiBound);
4662 }
4663 }
4664 }
4665 break;
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004666 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004667
Chris Lattnera7942b72006-11-29 05:02:16 +00004668 // Simplify seteq and setne instructions with integer constant RHS.
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004669 if (I.isEquality()) {
Chris Lattnerd492a0b2003-07-23 17:02:11 +00004670 bool isSetNE = I.getOpcode() == Instruction::SetNE;
4671
Reid Spencere0fc4df2006-10-20 07:07:24 +00004672 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
4673 // the second operand is a constant, simplify a bit.
Chris Lattnerc992add2003-08-13 05:33:12 +00004674 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
4675 switch (BO->getOpcode()) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00004676 case Instruction::SRem:
4677 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
4678 if (CI->isNullValue() && isa<ConstantInt>(BO->getOperand(1)) &&
4679 BO->hasOneUse()) {
4680 int64_t V = cast<ConstantInt>(BO->getOperand(1))->getSExtValue();
4681 if (V > 1 && isPowerOf2_64(V)) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00004682 Value *NewRem = InsertNewInstBefore(BinaryOperator::createURem(
4683 BO->getOperand(0), BO->getOperand(1), BO->getName()), I);
Chris Lattner23b47b62004-07-06 07:38:18 +00004684 return BinaryOperator::create(I.getOpcode(), NewRem,
Reid Spencer7eb55b32006-11-02 01:53:59 +00004685 Constant::getNullValue(BO->getType()));
Chris Lattner23b47b62004-07-06 07:38:18 +00004686 }
Chris Lattner22d00a82005-08-02 19:16:58 +00004687 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004688 break;
Chris Lattnerc992add2003-08-13 05:33:12 +00004689 case Instruction::Add:
Chris Lattner6e079362004-06-27 22:51:36 +00004690 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
4691 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerb121ae12004-09-21 21:35:23 +00004692 if (BO->hasOneUse())
4693 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
4694 ConstantExpr::getSub(CI, BOp1C));
Chris Lattner6e079362004-06-27 22:51:36 +00004695 } else if (CI->isNullValue()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00004696 // Replace ((add A, B) != 0) with (A != -B) if A or B is
4697 // efficiently invertible, or if the add has just this one use.
4698 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004699
Chris Lattnerc992add2003-08-13 05:33:12 +00004700 if (Value *NegVal = dyn_castNegVal(BOp1))
4701 return new SetCondInst(I.getOpcode(), BOp0, NegVal);
4702 else if (Value *NegVal = dyn_castNegVal(BOp0))
4703 return new SetCondInst(I.getOpcode(), NegVal, BOp1);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00004704 else if (BO->hasOneUse()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00004705 Instruction *Neg = BinaryOperator::createNeg(BOp1, BO->getName());
4706 BO->setName("");
4707 InsertNewInstBefore(Neg, I);
4708 return new SetCondInst(I.getOpcode(), BOp0, Neg);
4709 }
4710 }
4711 break;
4712 case Instruction::Xor:
4713 // For the xor case, we can xor two constants together, eliminating
4714 // the explicit xor.
4715 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
4716 return BinaryOperator::create(I.getOpcode(), BO->getOperand(0),
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004717 ConstantExpr::getXor(CI, BOC));
Chris Lattnerc992add2003-08-13 05:33:12 +00004718
4719 // FALLTHROUGH
4720 case Instruction::Sub:
4721 // Replace (([sub|xor] A, B) != 0) with (A != B)
4722 if (CI->isNullValue())
4723 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
4724 BO->getOperand(1));
4725 break;
4726
4727 case Instruction::Or:
4728 // If bits are being or'd in that are not present in the constant we
4729 // are comparing against, then the comparison could never succeed!
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00004730 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Chris Lattnerc8e7e292004-06-10 02:12:35 +00004731 Constant *NotCI = ConstantExpr::getNot(CI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004732 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Chris Lattnerd492a0b2003-07-23 17:02:11 +00004733 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00004734 }
Chris Lattnerc992add2003-08-13 05:33:12 +00004735 break;
4736
4737 case Instruction::And:
4738 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerd492a0b2003-07-23 17:02:11 +00004739 // If bits are being compared against that are and'd out, then the
4740 // comparison can never succeed!
Chris Lattnerc8e7e292004-06-10 02:12:35 +00004741 if (!ConstantExpr::getAnd(CI,
4742 ConstantExpr::getNot(BOC))->isNullValue())
Chris Lattnerd492a0b2003-07-23 17:02:11 +00004743 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattnerc992add2003-08-13 05:33:12 +00004744
Chris Lattner35167c32004-06-09 07:59:58 +00004745 // If we have ((X & C) == C), turn it into ((X & C) != 0).
Chris Lattneree59d4b2004-06-10 02:33:20 +00004746 if (CI == BOC && isOneBitSet(CI))
Chris Lattner35167c32004-06-09 07:59:58 +00004747 return new SetCondInst(isSetNE ? Instruction::SetEQ :
4748 Instruction::SetNE, Op0,
4749 Constant::getNullValue(CI->getType()));
Chris Lattner35167c32004-06-09 07:59:58 +00004750
Chris Lattnerc992add2003-08-13 05:33:12 +00004751 // Replace (and X, (1 << size(X)-1) != 0) with x < 0, converting X
4752 // to be a signed value as appropriate.
4753 if (isSignBit(BOC)) {
4754 Value *X = BO->getOperand(0);
4755 // If 'X' is not signed, insert a cast now...
4756 if (!BOC->getType()->isSigned()) {
Chris Lattner97bfcea2004-06-17 18:16:02 +00004757 const Type *DestTy = BOC->getType()->getSignedVersion();
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004758 X = InsertCastBefore(X, DestTy, I);
Chris Lattnerc992add2003-08-13 05:33:12 +00004759 }
4760 return new SetCondInst(isSetNE ? Instruction::SetLT :
4761 Instruction::SetGE, X,
4762 Constant::getNullValue(X->getType()));
4763 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004764
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004765 // ((X & ~7) == 0) --> X < 8
Chris Lattner8fc5af42004-09-23 21:46:38 +00004766 if (CI->isNullValue() && isHighOnes(BOC)) {
4767 Value *X = BO->getOperand(0);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004768 Constant *NegX = ConstantExpr::getNeg(BOC);
Chris Lattner8fc5af42004-09-23 21:46:38 +00004769
4770 // If 'X' is signed, insert a cast now.
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004771 if (NegX->getType()->isSigned()) {
4772 const Type *DestTy = NegX->getType()->getUnsignedVersion();
4773 X = InsertCastBefore(X, DestTy, I);
4774 NegX = ConstantExpr::getCast(NegX, DestTy);
Chris Lattner8fc5af42004-09-23 21:46:38 +00004775 }
4776
4777 return new SetCondInst(isSetNE ? Instruction::SetGE :
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004778 Instruction::SetLT, X, NegX);
Chris Lattner8fc5af42004-09-23 21:46:38 +00004779 }
4780
Chris Lattnerd492a0b2003-07-23 17:02:11 +00004781 }
Chris Lattnerc992add2003-08-13 05:33:12 +00004782 default: break;
4783 }
Chris Lattnera7942b72006-11-29 05:02:16 +00004784 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Op0)) {
4785 // Handle set{eq|ne} <intrinsic>, intcst.
4786 switch (II->getIntrinsicID()) {
4787 default: break;
4788 case Intrinsic::bswap_i16: // seteq (bswap(x)), c -> seteq(x,bswap(c))
4789 WorkList.push_back(II); // Dead?
4790 I.setOperand(0, II->getOperand(1));
4791 I.setOperand(1, ConstantInt::get(Type::UShortTy,
4792 ByteSwap_16(CI->getZExtValue())));
4793 return &I;
4794 case Intrinsic::bswap_i32: // seteq (bswap(x)), c -> seteq(x,bswap(c))
4795 WorkList.push_back(II); // Dead?
4796 I.setOperand(0, II->getOperand(1));
4797 I.setOperand(1, ConstantInt::get(Type::UIntTy,
4798 ByteSwap_32(CI->getZExtValue())));
4799 return &I;
4800 case Intrinsic::bswap_i64: // seteq (bswap(x)), c -> seteq(x,bswap(c))
4801 WorkList.push_back(II); // Dead?
4802 I.setOperand(0, II->getOperand(1));
4803 I.setOperand(1, ConstantInt::get(Type::ULongTy,
4804 ByteSwap_64(CI->getZExtValue())));
4805 return &I;
4806 }
Chris Lattnerc992add2003-08-13 05:33:12 +00004807 }
Chris Lattner2b55ea32004-02-23 07:16:20 +00004808 } else { // Not a SetEQ/SetNE
Misha Brukmanb1c93172005-04-21 23:48:37 +00004809 // If the LHS is a cast from an integral value of the same size,
Chris Lattner2b55ea32004-02-23 07:16:20 +00004810 if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
4811 Value *CastOp = Cast->getOperand(0);
4812 const Type *SrcTy = CastOp->getType();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004813 unsigned SrcTySize = SrcTy->getPrimitiveSizeInBits();
Chris Lattner2b55ea32004-02-23 07:16:20 +00004814 if (SrcTy != Cast->getType() && SrcTy->isInteger() &&
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004815 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00004816 assert((SrcTy->isSigned() ^ Cast->getType()->isSigned()) &&
Chris Lattner2b55ea32004-02-23 07:16:20 +00004817 "Source and destination signednesses should differ!");
4818 if (Cast->getType()->isSigned()) {
4819 // If this is a signed comparison, check for comparisons in the
4820 // vicinity of zero.
4821 if (I.getOpcode() == Instruction::SetLT && CI->isNullValue())
4822 // X < 0 => x > 127
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004823 return BinaryOperator::createSetGT(CastOp,
Reid Spencere0fc4df2006-10-20 07:07:24 +00004824 ConstantInt::get(SrcTy, (1ULL << (SrcTySize-1))-1));
Chris Lattner2b55ea32004-02-23 07:16:20 +00004825 else if (I.getOpcode() == Instruction::SetGT &&
Reid Spencere0fc4df2006-10-20 07:07:24 +00004826 cast<ConstantInt>(CI)->getSExtValue() == -1)
Chris Lattner2b55ea32004-02-23 07:16:20 +00004827 // X > -1 => x < 128
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004828 return BinaryOperator::createSetLT(CastOp,
Reid Spencere0fc4df2006-10-20 07:07:24 +00004829 ConstantInt::get(SrcTy, 1ULL << (SrcTySize-1)));
Chris Lattner2b55ea32004-02-23 07:16:20 +00004830 } else {
Reid Spencere0fc4df2006-10-20 07:07:24 +00004831 ConstantInt *CUI = cast<ConstantInt>(CI);
Chris Lattner2b55ea32004-02-23 07:16:20 +00004832 if (I.getOpcode() == Instruction::SetLT &&
Reid Spencere0fc4df2006-10-20 07:07:24 +00004833 CUI->getZExtValue() == 1ULL << (SrcTySize-1))
Chris Lattner2b55ea32004-02-23 07:16:20 +00004834 // X < 128 => X > -1
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004835 return BinaryOperator::createSetGT(CastOp,
Reid Spencere0fc4df2006-10-20 07:07:24 +00004836 ConstantInt::get(SrcTy, -1));
Chris Lattner2b55ea32004-02-23 07:16:20 +00004837 else if (I.getOpcode() == Instruction::SetGT &&
Reid Spencere0fc4df2006-10-20 07:07:24 +00004838 CUI->getZExtValue() == (1ULL << (SrcTySize-1))-1)
Chris Lattner2b55ea32004-02-23 07:16:20 +00004839 // X > 127 => X < 0
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004840 return BinaryOperator::createSetLT(CastOp,
4841 Constant::getNullValue(SrcTy));
Chris Lattner2b55ea32004-02-23 07:16:20 +00004842 }
4843 }
4844 }
Chris Lattnere967b342003-06-04 05:10:11 +00004845 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004846 }
4847
Chris Lattner77c32c32005-04-23 15:31:55 +00004848 // Handle setcc with constant RHS's that can be integer, FP or pointer.
4849 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
4850 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4851 switch (LHSI->getOpcode()) {
Chris Lattnera816eee2005-05-01 04:42:15 +00004852 case Instruction::GetElementPtr:
4853 if (RHSC->isNullValue()) {
4854 // Transform setcc GEP P, int 0, int 0, int 0, null -> setcc P, null
4855 bool isAllZeros = true;
4856 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
4857 if (!isa<Constant>(LHSI->getOperand(i)) ||
4858 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
4859 isAllZeros = false;
4860 break;
4861 }
4862 if (isAllZeros)
4863 return new SetCondInst(I.getOpcode(), LHSI->getOperand(0),
4864 Constant::getNullValue(LHSI->getOperand(0)->getType()));
4865 }
4866 break;
4867
Chris Lattner77c32c32005-04-23 15:31:55 +00004868 case Instruction::PHI:
4869 if (Instruction *NV = FoldOpIntoPhi(I))
4870 return NV;
4871 break;
4872 case Instruction::Select:
4873 // If either operand of the select is a constant, we can fold the
4874 // comparison into the select arms, which will cause one to be
4875 // constant folded and the select turned into a bitwise or.
4876 Value *Op1 = 0, *Op2 = 0;
4877 if (LHSI->hasOneUse()) {
4878 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
4879 // Fold the known value into the constant operand.
4880 Op1 = ConstantExpr::get(I.getOpcode(), C, RHSC);
4881 // Insert a new SetCC of the other select operand.
4882 Op2 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
4883 LHSI->getOperand(2), RHSC,
4884 I.getName()), I);
4885 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
4886 // Fold the known value into the constant operand.
4887 Op2 = ConstantExpr::get(I.getOpcode(), C, RHSC);
4888 // Insert a new SetCC of the other select operand.
4889 Op1 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
4890 LHSI->getOperand(1), RHSC,
4891 I.getName()), I);
4892 }
4893 }
Jeff Cohen82639852005-04-23 21:38:35 +00004894
Chris Lattner77c32c32005-04-23 15:31:55 +00004895 if (Op1)
4896 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
4897 break;
4898 }
4899 }
4900
Chris Lattner0798af32005-01-13 20:14:25 +00004901 // If we can optimize a 'setcc GEP, P' or 'setcc P, GEP', do so now.
4902 if (User *GEP = dyn_castGetElementPtr(Op0))
4903 if (Instruction *NI = FoldGEPSetCC(GEP, Op1, I.getOpcode(), I))
4904 return NI;
4905 if (User *GEP = dyn_castGetElementPtr(Op1))
4906 if (Instruction *NI = FoldGEPSetCC(GEP, Op0,
4907 SetCondInst::getSwappedCondition(I.getOpcode()), I))
4908 return NI;
4909
Chris Lattner16930792003-11-03 04:25:02 +00004910 // Test to see if the operands of the setcc are casted versions of other
4911 // values. If the cast can be stripped off both arguments, we do so now.
Chris Lattner6444c372003-11-03 05:17:03 +00004912 if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
4913 Value *CastOp0 = CI->getOperand(0);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00004914 if (CI->isLosslessCast() && I.isEquality() &&
4915 (isa<Constant>(Op1) || isa<CastInst>(Op1))) {
Chris Lattner16930792003-11-03 04:25:02 +00004916 // We keep moving the cast from the left operand over to the right
4917 // operand, where it can often be eliminated completely.
Chris Lattner6444c372003-11-03 05:17:03 +00004918 Op0 = CastOp0;
Misha Brukmanb1c93172005-04-21 23:48:37 +00004919
Chris Lattner16930792003-11-03 04:25:02 +00004920 // If operand #1 is a cast instruction, see if we can eliminate it as
4921 // well.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00004922 if (CastInst *CI2 = dyn_cast<CastInst>(Op1)) {
4923 Value *CI2Op0 = CI2->getOperand(0);
4924 if (CI2Op0->getType()->canLosslesslyBitCastTo(Op0->getType()))
4925 Op1 = CI2Op0;
4926 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004927
Chris Lattner16930792003-11-03 04:25:02 +00004928 // If Op1 is a constant, we can fold the cast into the constant.
4929 if (Op1->getType() != Op0->getType())
4930 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
4931 Op1 = ConstantExpr::getCast(Op1C, Op0->getType());
4932 } else {
4933 // Otherwise, cast the RHS right before the setcc
Reid Spencer00c482b2006-10-26 19:19:06 +00004934 Op1 = InsertCastBefore(Op1, Op0->getType(), I);
Chris Lattner16930792003-11-03 04:25:02 +00004935 }
4936 return BinaryOperator::create(I.getOpcode(), Op0, Op1);
4937 }
4938
Chris Lattner6444c372003-11-03 05:17:03 +00004939 // Handle the special case of: setcc (cast bool to X), <cst>
4940 // This comes up when you have code like
4941 // int X = A < B;
4942 // if (X) ...
4943 // For generality, we handle any zero-extension of any operand comparison
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004944 // with a constant or another cast from the same type.
4945 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
4946 if (Instruction *R = visitSetCondInstWithCastAndCast(I))
4947 return R;
Chris Lattner6444c372003-11-03 05:17:03 +00004948 }
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00004949
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004950 if (I.isEquality()) {
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00004951 Value *A, *B;
4952 if (match(Op0, m_Xor(m_Value(A), m_Value(B))) &&
4953 (A == Op1 || B == Op1)) {
4954 // (A^B) == A -> B == 0
4955 Value *OtherVal = A == Op1 ? B : A;
4956 return BinaryOperator::create(I.getOpcode(), OtherVal,
4957 Constant::getNullValue(A->getType()));
4958 } else if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
4959 (A == Op0 || B == Op0)) {
4960 // A == (A^B) -> B == 0
4961 Value *OtherVal = A == Op0 ? B : A;
4962 return BinaryOperator::create(I.getOpcode(), OtherVal,
4963 Constant::getNullValue(A->getType()));
4964 } else if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
4965 // (A-B) == A -> B == 0
4966 return BinaryOperator::create(I.getOpcode(), B,
4967 Constant::getNullValue(B->getType()));
4968 } else if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
4969 // A == (A-B) -> B == 0
4970 return BinaryOperator::create(I.getOpcode(), B,
4971 Constant::getNullValue(B->getType()));
4972 }
Chris Lattnerd12a4bf2006-11-14 06:06:06 +00004973
4974 Value *C, *D;
4975 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
4976 if (Op0->hasOneUse() && Op1->hasOneUse() &&
4977 match(Op0, m_And(m_Value(A), m_Value(B))) &&
4978 match(Op1, m_And(m_Value(C), m_Value(D)))) {
4979 Value *X = 0, *Y = 0, *Z = 0;
4980
4981 if (A == C) {
4982 X = B; Y = D; Z = A;
4983 } else if (A == D) {
4984 X = B; Y = C; Z = A;
4985 } else if (B == C) {
4986 X = A; Y = D; Z = B;
4987 } else if (B == D) {
4988 X = A; Y = C; Z = B;
4989 }
4990
4991 if (X) { // Build (X^Y) & Z
4992 Op1 = InsertNewInstBefore(BinaryOperator::createXor(X, Y, "tmp"), I);
4993 Op1 = InsertNewInstBefore(BinaryOperator::createAnd(Op1, Z, "tmp"), I);
4994 I.setOperand(0, Op1);
4995 I.setOperand(1, Constant::getNullValue(Op1->getType()));
4996 return &I;
4997 }
4998 }
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00004999 }
Chris Lattner113f4f42002-06-25 16:13:24 +00005000 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005001}
5002
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005003// visitSetCondInstWithCastAndCast - Handle setcond (cast x to y), (cast/cst).
5004// We only handle extending casts so far.
5005//
5006Instruction *InstCombiner::visitSetCondInstWithCastAndCast(SetCondInst &SCI) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005007 const CastInst *LHSCI = cast<CastInst>(SCI.getOperand(0));
5008 Value *LHSCIOp = LHSCI->getOperand(0);
5009 const Type *SrcTy = LHSCIOp->getType();
5010 const Type *DestTy = SCI.getOperand(0)->getType();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005011 Value *RHSCIOp;
5012
5013 if (!DestTy->isIntegral() || !SrcTy->isIntegral())
Chris Lattner03f06f12005-01-17 03:20:02 +00005014 return 0;
5015
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005016 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
5017 unsigned DestBits = DestTy->getPrimitiveSizeInBits();
5018 if (SrcBits >= DestBits) return 0; // Only handle extending cast.
5019
5020 // Is this a sign or zero extension?
5021 bool isSignSrc = SrcTy->isSigned();
5022 bool isSignDest = DestTy->isSigned();
5023
5024 if (CastInst *CI = dyn_cast<CastInst>(SCI.getOperand(1))) {
5025 // Not an extension from the same type?
5026 RHSCIOp = CI->getOperand(0);
5027 if (RHSCIOp->getType() != LHSCIOp->getType()) return 0;
5028 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(SCI.getOperand(1))) {
5029 // Compute the constant that would happen if we truncated to SrcTy then
5030 // reextended to DestTy.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005031 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
5032 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005033
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005034 if (Res2 == CI) {
Devang Patelb42aef42006-10-19 18:54:08 +00005035 // Make sure that src sign and dest sign match. For example,
5036 //
5037 // %A = cast short %X to uint
5038 // %B = setgt uint %A, 1330
5039 //
Devang Patel88afd002006-10-19 19:21:36 +00005040 // It is incorrect to transform this into
Devang Patelb42aef42006-10-19 18:54:08 +00005041 //
5042 // %B = setgt short %X, 1330
5043 //
5044 // because %A may have negative value.
Devang Patel5d6df952006-10-19 20:59:13 +00005045 // However, it is OK if SrcTy is bool (See cast-set.ll testcase)
5046 // OR operation is EQ/NE.
5047 if (isSignSrc == isSignDest || SrcTy == Type::BoolTy || SCI.isEquality())
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005048 RHSCIOp = Res1;
Devang Patelb42aef42006-10-19 18:54:08 +00005049 else
5050 return 0;
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005051 } else {
5052 // If the value cannot be represented in the shorter type, we cannot emit
5053 // a simple comparison.
5054 if (SCI.getOpcode() == Instruction::SetEQ)
Chris Lattner6ab03f62006-09-28 23:35:22 +00005055 return ReplaceInstUsesWith(SCI, ConstantBool::getFalse());
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005056 if (SCI.getOpcode() == Instruction::SetNE)
Chris Lattner6ab03f62006-09-28 23:35:22 +00005057 return ReplaceInstUsesWith(SCI, ConstantBool::getTrue());
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005058
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005059 // Evaluate the comparison for LT.
5060 Value *Result;
5061 if (DestTy->isSigned()) {
5062 // We're performing a signed comparison.
5063 if (isSignSrc) {
5064 // Signed extend and signed comparison.
Reid Spencere0fc4df2006-10-20 07:07:24 +00005065 if (cast<ConstantInt>(CI)->getSExtValue() < 0)// X < (small) --> false
Chris Lattner6ab03f62006-09-28 23:35:22 +00005066 Result = ConstantBool::getFalse();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005067 else
Reid Spencere0fc4df2006-10-20 07:07:24 +00005068 Result = ConstantBool::getTrue(); // X < (large) --> true
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005069 } else {
5070 // Unsigned extend and signed comparison.
Reid Spencere0fc4df2006-10-20 07:07:24 +00005071 if (cast<ConstantInt>(CI)->getSExtValue() < 0)
Chris Lattner6ab03f62006-09-28 23:35:22 +00005072 Result = ConstantBool::getFalse();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005073 else
Chris Lattner6ab03f62006-09-28 23:35:22 +00005074 Result = ConstantBool::getTrue();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005075 }
5076 } else {
5077 // We're performing an unsigned comparison.
5078 if (!isSignSrc) {
5079 // Unsigned extend & compare -> always true.
Chris Lattner6ab03f62006-09-28 23:35:22 +00005080 Result = ConstantBool::getTrue();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005081 } else {
5082 // We're performing an unsigned comp with a sign extended value.
5083 // This is true if the input is >= 0. [aka >s -1]
5084 Constant *NegOne = ConstantIntegral::getAllOnesValue(SrcTy);
5085 Result = InsertNewInstBefore(BinaryOperator::createSetGT(LHSCIOp,
5086 NegOne, SCI.getName()), SCI);
5087 }
Reid Spencer279fa252004-11-28 21:31:15 +00005088 }
Chris Lattner03f06f12005-01-17 03:20:02 +00005089
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00005090 // Finally, return the value computed.
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005091 if (SCI.getOpcode() == Instruction::SetLT) {
5092 return ReplaceInstUsesWith(SCI, Result);
5093 } else {
5094 assert(SCI.getOpcode()==Instruction::SetGT &&"SetCC should be folded!");
5095 if (Constant *CI = dyn_cast<Constant>(Result))
5096 return ReplaceInstUsesWith(SCI, ConstantExpr::getNot(CI));
5097 else
5098 return BinaryOperator::createNot(Result);
5099 }
Chris Lattner03f06f12005-01-17 03:20:02 +00005100 }
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005101 } else {
5102 return 0;
Reid Spencer279fa252004-11-28 21:31:15 +00005103 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005104
Chris Lattner252a8452005-06-16 03:00:08 +00005105 // Okay, just insert a compare of the reduced operands now!
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005106 return BinaryOperator::create(SCI.getOpcode(), LHSCIOp, RHSCIOp);
5107}
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005108
Chris Lattnere8d6c602003-03-10 19:16:08 +00005109Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +00005110 assert(I.getOperand(1)->getType() == Type::UByteTy);
5111 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00005112 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005113
5114 // shl X, 0 == X and shr X, 0 == X
5115 // shl 0, X == 0 and shr 0, X == 0
5116 if (Op1 == Constant::getNullValue(Type::UByteTy) ||
Chris Lattnere6794492002-08-12 21:17:25 +00005117 Op0 == Constant::getNullValue(Op0->getType()))
5118 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf5b4ef72006-02-12 08:07:37 +00005119
Chris Lattner81a7a232004-10-16 18:11:37 +00005120 if (isa<UndefValue>(Op0)) { // undef >>s X -> undef
5121 if (!isLeftShift && I.getType()->isSigned())
Chris Lattner67f05452004-10-16 23:28:04 +00005122 return ReplaceInstUsesWith(I, Op0);
Chris Lattner81a7a232004-10-16 18:11:37 +00005123 else // undef << X -> 0 AND undef >>u X -> 0
5124 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5125 }
5126 if (isa<UndefValue>(Op1)) {
Chris Lattner18aa4d82005-07-20 18:49:28 +00005127 if (isLeftShift || I.getType()->isUnsigned())// X << undef, X >>u undef -> 0
Chris Lattner81a7a232004-10-16 18:11:37 +00005128 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5129 else
5130 return ReplaceInstUsesWith(I, Op0); // X >>s undef -> X
5131 }
5132
Chris Lattnerd4dee402006-11-10 23:38:52 +00005133 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
5134 if (I.getOpcode() == Instruction::AShr)
Reid Spencere0fc4df2006-10-20 07:07:24 +00005135 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Chris Lattnerd4dee402006-11-10 23:38:52 +00005136 if (CSI->isAllOnesValue())
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00005137 return ReplaceInstUsesWith(I, CSI);
5138
Chris Lattner183b3362004-04-09 19:05:30 +00005139 // Try to fold constant and into select arguments.
5140 if (isa<Constant>(Op0))
5141 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner86102b82005-01-01 16:22:27 +00005142 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00005143 return R;
5144
Chris Lattnerb18dbbf2005-05-08 17:34:56 +00005145 // See if we can turn a signed shr into an unsigned shr.
Chris Lattnerb3f24c92006-09-18 04:22:48 +00005146 if (I.isArithmeticShift()) {
Chris Lattnerc3ebf402006-02-07 07:27:52 +00005147 if (MaskedValueIsZero(Op0,
5148 1ULL << (I.getType()->getPrimitiveSizeInBits()-1))) {
Reid Spencerfdff9382006-11-08 06:47:33 +00005149 return new ShiftInst(Instruction::LShr, Op0, Op1, I.getName());
Chris Lattnerb18dbbf2005-05-08 17:34:56 +00005150 }
5151 }
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00005152
Reid Spencere0fc4df2006-10-20 07:07:24 +00005153 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
5154 if (CUI->getType()->isUnsigned())
5155 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
5156 return Res;
Chris Lattner14553932006-01-06 07:12:35 +00005157 return 0;
5158}
5159
Reid Spencere0fc4df2006-10-20 07:07:24 +00005160Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Chris Lattner14553932006-01-06 07:12:35 +00005161 ShiftInst &I) {
5162 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Reid Spencerfdff9382006-11-08 06:47:33 +00005163 bool isSignedShift = isLeftShift ? Op0->getType()->isSigned() :
5164 I.getOpcode() == Instruction::AShr;
Chris Lattnerb3309392006-01-06 07:22:22 +00005165 bool isUnsignedShift = !isSignedShift;
Chris Lattner14553932006-01-06 07:12:35 +00005166
Chris Lattnerf5b4ef72006-02-12 08:07:37 +00005167 // See if we can simplify any instructions used by the instruction whose sole
5168 // purpose is to compute bits we don't care about.
5169 uint64_t KnownZero, KnownOne;
5170 if (SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
5171 KnownZero, KnownOne))
5172 return &I;
5173
Chris Lattner14553932006-01-06 07:12:35 +00005174 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
5175 // of a signed value.
5176 //
5177 unsigned TypeBits = Op0->getType()->getPrimitiveSizeInBits();
Reid Spencere0fc4df2006-10-20 07:07:24 +00005178 if (Op1->getZExtValue() >= TypeBits) {
Chris Lattnerb3309392006-01-06 07:22:22 +00005179 if (isUnsignedShift || isLeftShift)
Chris Lattner14553932006-01-06 07:12:35 +00005180 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
5181 else {
Reid Spencere0fc4df2006-10-20 07:07:24 +00005182 I.setOperand(1, ConstantInt::get(Type::UByteTy, TypeBits-1));
Chris Lattner14553932006-01-06 07:12:35 +00005183 return &I;
Chris Lattnerf5ce2542004-02-23 20:30:06 +00005184 }
Chris Lattner14553932006-01-06 07:12:35 +00005185 }
5186
5187 // ((X*C1) << C2) == (X * (C1 << C2))
5188 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
5189 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
5190 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
5191 return BinaryOperator::createMul(BO->getOperand(0),
5192 ConstantExpr::getShl(BOOp, Op1));
5193
5194 // Try to fold constant and into select arguments.
5195 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5196 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5197 return R;
5198 if (isa<PHINode>(Op0))
5199 if (Instruction *NV = FoldOpIntoPhi(I))
5200 return NV;
5201
5202 if (Op0->hasOneUse()) {
Chris Lattner14553932006-01-06 07:12:35 +00005203 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
5204 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
5205 Value *V1, *V2;
5206 ConstantInt *CC;
5207 switch (Op0BO->getOpcode()) {
Chris Lattner27cb9db2005-09-18 05:12:10 +00005208 default: break;
5209 case Instruction::Add:
5210 case Instruction::And:
5211 case Instruction::Or:
5212 case Instruction::Xor:
5213 // These operators commute.
5214 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner797dee72005-09-18 06:30:59 +00005215 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
5216 match(Op0BO->getOperand(1),
Chris Lattner14553932006-01-06 07:12:35 +00005217 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Chris Lattner797dee72005-09-18 06:30:59 +00005218 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00005219 Op0BO->getOperand(0), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00005220 Op0BO->getName());
5221 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005222 Instruction *X =
5223 BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
5224 Op0BO->getOperand(1)->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00005225 InsertNewInstBefore(X, I); // (X + (Y << C))
5226 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
Chris Lattner14553932006-01-06 07:12:35 +00005227 C2 = ConstantExpr::getShl(C2, Op1);
Chris Lattner797dee72005-09-18 06:30:59 +00005228 return BinaryOperator::createAnd(X, C2);
5229 }
Chris Lattner14553932006-01-06 07:12:35 +00005230
Chris Lattner797dee72005-09-18 06:30:59 +00005231 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
5232 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
5233 match(Op0BO->getOperand(1),
5234 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner14553932006-01-06 07:12:35 +00005235 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005236 cast<BinaryOperator>(Op0BO->getOperand(1))->getOperand(0)->hasOneUse()) {
Chris Lattner797dee72005-09-18 06:30:59 +00005237 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00005238 Op0BO->getOperand(0), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00005239 Op0BO->getName());
5240 InsertNewInstBefore(YS, I); // (Y << C)
5241 Instruction *XM =
Chris Lattner14553932006-01-06 07:12:35 +00005242 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner797dee72005-09-18 06:30:59 +00005243 V1->getName()+".mask");
5244 InsertNewInstBefore(XM, I); // X & (CC << C)
5245
5246 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
5247 }
Chris Lattner14553932006-01-06 07:12:35 +00005248
Chris Lattner797dee72005-09-18 06:30:59 +00005249 // FALL THROUGH.
Chris Lattner27cb9db2005-09-18 05:12:10 +00005250 case Instruction::Sub:
5251 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner797dee72005-09-18 06:30:59 +00005252 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
5253 match(Op0BO->getOperand(0),
Chris Lattner14553932006-01-06 07:12:35 +00005254 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Chris Lattner797dee72005-09-18 06:30:59 +00005255 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00005256 Op0BO->getOperand(1), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00005257 Op0BO->getName());
5258 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005259 Instruction *X =
Chris Lattner1df0e982006-05-31 21:14:00 +00005260 BinaryOperator::create(Op0BO->getOpcode(), V1, YS,
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005261 Op0BO->getOperand(0)->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00005262 InsertNewInstBefore(X, I); // (X + (Y << C))
5263 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
Chris Lattner14553932006-01-06 07:12:35 +00005264 C2 = ConstantExpr::getShl(C2, Op1);
Chris Lattner797dee72005-09-18 06:30:59 +00005265 return BinaryOperator::createAnd(X, C2);
5266 }
Chris Lattner14553932006-01-06 07:12:35 +00005267
Chris Lattner1df0e982006-05-31 21:14:00 +00005268 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner797dee72005-09-18 06:30:59 +00005269 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
5270 match(Op0BO->getOperand(0),
5271 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner14553932006-01-06 07:12:35 +00005272 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005273 cast<BinaryOperator>(Op0BO->getOperand(0))
5274 ->getOperand(0)->hasOneUse()) {
Chris Lattner797dee72005-09-18 06:30:59 +00005275 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00005276 Op0BO->getOperand(1), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00005277 Op0BO->getName());
5278 InsertNewInstBefore(YS, I); // (Y << C)
5279 Instruction *XM =
Chris Lattner14553932006-01-06 07:12:35 +00005280 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner797dee72005-09-18 06:30:59 +00005281 V1->getName()+".mask");
5282 InsertNewInstBefore(XM, I); // X & (CC << C)
5283
Chris Lattner1df0e982006-05-31 21:14:00 +00005284 return BinaryOperator::create(Op0BO->getOpcode(), XM, YS);
Chris Lattner797dee72005-09-18 06:30:59 +00005285 }
Chris Lattner14553932006-01-06 07:12:35 +00005286
Chris Lattner27cb9db2005-09-18 05:12:10 +00005287 break;
Chris Lattner14553932006-01-06 07:12:35 +00005288 }
5289
5290
5291 // If the operand is an bitwise operator with a constant RHS, and the
5292 // shift is the only use, we can pull it out of the shift.
5293 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
5294 bool isValid = true; // Valid only for And, Or, Xor
5295 bool highBitSet = false; // Transform if high bit of constant set?
5296
5297 switch (Op0BO->getOpcode()) {
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00005298 default: isValid = false; break; // Do not perform transform!
Chris Lattner44bd3922004-10-08 03:46:20 +00005299 case Instruction::Add:
5300 isValid = isLeftShift;
5301 break;
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00005302 case Instruction::Or:
5303 case Instruction::Xor:
5304 highBitSet = false;
5305 break;
5306 case Instruction::And:
5307 highBitSet = true;
5308 break;
Chris Lattner14553932006-01-06 07:12:35 +00005309 }
5310
5311 // If this is a signed shift right, and the high bit is modified
5312 // by the logical operation, do not perform the transformation.
5313 // The highBitSet boolean indicates the value of the high bit of
5314 // the constant which would cause it to be modified for this
5315 // operation.
5316 //
Chris Lattnerb3309392006-01-06 07:22:22 +00005317 if (isValid && !isLeftShift && isSignedShift) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00005318 uint64_t Val = Op0C->getZExtValue();
Chris Lattner14553932006-01-06 07:12:35 +00005319 isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
5320 }
5321
5322 if (isValid) {
5323 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
5324
5325 Instruction *NewShift =
5326 new ShiftInst(I.getOpcode(), Op0BO->getOperand(0), Op1,
5327 Op0BO->getName());
5328 Op0BO->setName("");
5329 InsertNewInstBefore(NewShift, I);
5330
5331 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
5332 NewRHS);
5333 }
5334 }
5335 }
5336 }
5337
Chris Lattnereb372a02006-01-06 07:52:12 +00005338 // Find out if this is a shift of a shift by a constant.
5339 ShiftInst *ShiftOp = 0;
Chris Lattner14553932006-01-06 07:12:35 +00005340 if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0))
Chris Lattnereb372a02006-01-06 07:52:12 +00005341 ShiftOp = Op0SI;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005342 else if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
5343 // If this is a noop-integer cast of a shift instruction, use the shift.
5344 if (isa<ShiftInst>(CI->getOperand(0))) {
Chris Lattnereb372a02006-01-06 07:52:12 +00005345 ShiftOp = cast<ShiftInst>(CI->getOperand(0));
5346 }
5347 }
5348
Reid Spencere0fc4df2006-10-20 07:07:24 +00005349 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Chris Lattnereb372a02006-01-06 07:52:12 +00005350 // Find the operands and properties of the input shift. Note that the
5351 // signedness of the input shift may differ from the current shift if there
5352 // is a noop cast between the two.
5353 bool isShiftOfLeftShift = ShiftOp->getOpcode() == Instruction::Shl;
Reid Spencerfdff9382006-11-08 06:47:33 +00005354 bool isShiftOfSignedShift = isShiftOfLeftShift ?
5355 ShiftOp->getType()->isSigned() :
5356 ShiftOp->getOpcode() == Instruction::AShr;
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005357 bool isShiftOfUnsignedShift = !isShiftOfSignedShift;
Chris Lattnereb372a02006-01-06 07:52:12 +00005358
Reid Spencere0fc4df2006-10-20 07:07:24 +00005359 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Chris Lattnereb372a02006-01-06 07:52:12 +00005360
Reid Spencere0fc4df2006-10-20 07:07:24 +00005361 unsigned ShiftAmt1 = (unsigned)ShiftAmt1C->getZExtValue();
5362 unsigned ShiftAmt2 = (unsigned)Op1->getZExtValue();
Chris Lattnereb372a02006-01-06 07:52:12 +00005363
5364 // Check for (A << c1) << c2 and (A >> c1) >> c2.
5365 if (isLeftShift == isShiftOfLeftShift) {
5366 // Do not fold these shifts if the first one is signed and the second one
5367 // is unsigned and this is a right shift. Further, don't do any folding
5368 // on them.
5369 if (isShiftOfSignedShift && isUnsignedShift && !isLeftShift)
5370 return 0;
Chris Lattner14553932006-01-06 07:12:35 +00005371
Chris Lattnereb372a02006-01-06 07:52:12 +00005372 unsigned Amt = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
5373 if (Amt > Op0->getType()->getPrimitiveSizeInBits())
5374 Amt = Op0->getType()->getPrimitiveSizeInBits();
Chris Lattner14553932006-01-06 07:12:35 +00005375
Chris Lattnereb372a02006-01-06 07:52:12 +00005376 Value *Op = ShiftOp->getOperand(0);
5377 if (isShiftOfSignedShift != isSignedShift)
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005378 Op = InsertNewInstBefore(
5379 CastInst::createInferredCast(Op, I.getType(), "tmp"), I);
5380 ShiftInst *ShiftResult = new ShiftInst(I.getOpcode(), Op,
Reid Spencere0fc4df2006-10-20 07:07:24 +00005381 ConstantInt::get(Type::UByteTy, Amt));
Reid Spencerfdff9382006-11-08 06:47:33 +00005382 if (I.getType() == ShiftResult->getType())
5383 return ShiftResult;
5384 InsertNewInstBefore(ShiftResult, I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005385 return CastInst::create(Instruction::BitCast, ShiftResult, I.getType());
Chris Lattnereb372a02006-01-06 07:52:12 +00005386 }
5387
5388 // Check for (A << c1) >> c2 or (A >> c1) << c2. If we are dealing with
5389 // signed types, we can only support the (A >> c1) << c2 configuration,
5390 // because it can not turn an arbitrary bit of A into a sign bit.
5391 if (isUnsignedShift || isLeftShift) {
5392 // Calculate bitmask for what gets shifted off the edge.
5393 Constant *C = ConstantIntegral::getAllOnesValue(I.getType());
5394 if (isLeftShift)
5395 C = ConstantExpr::getShl(C, ShiftAmt1C);
5396 else
Reid Spencerfdff9382006-11-08 06:47:33 +00005397 C = ConstantExpr::getLShr(C, ShiftAmt1C);
Chris Lattnereb372a02006-01-06 07:52:12 +00005398
5399 Value *Op = ShiftOp->getOperand(0);
Reid Spencerfdff9382006-11-08 06:47:33 +00005400 if (Op->getType() != C->getType())
Reid Spencer00c482b2006-10-26 19:19:06 +00005401 Op = InsertCastBefore(Op, I.getType(), I);
Chris Lattnereb372a02006-01-06 07:52:12 +00005402
5403 Instruction *Mask =
5404 BinaryOperator::createAnd(Op, C, Op->getName()+".mask");
5405 InsertNewInstBefore(Mask, I);
5406
5407 // Figure out what flavor of shift we should use...
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005408 if (ShiftAmt1 == ShiftAmt2) {
Chris Lattnereb372a02006-01-06 07:52:12 +00005409 return ReplaceInstUsesWith(I, Mask); // (A << c) >> c === A & c2
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005410 } else if (ShiftAmt1 < ShiftAmt2) {
Chris Lattnereb372a02006-01-06 07:52:12 +00005411 return new ShiftInst(I.getOpcode(), Mask,
Reid Spencere0fc4df2006-10-20 07:07:24 +00005412 ConstantInt::get(Type::UByteTy, ShiftAmt2-ShiftAmt1));
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005413 } else if (isShiftOfUnsignedShift || isShiftOfLeftShift) {
5414 if (isShiftOfUnsignedShift && !isShiftOfLeftShift && isSignedShift) {
Reid Spencerfdff9382006-11-08 06:47:33 +00005415 return new ShiftInst(Instruction::LShr, Mask,
5416 ConstantInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005417 } else {
5418 return new ShiftInst(ShiftOp->getOpcode(), Mask,
Reid Spencere0fc4df2006-10-20 07:07:24 +00005419 ConstantInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005420 }
5421 } else {
5422 // (X >>s C1) << C2 where C1 > C2 === (X >>s (C1-C2)) & mask
Reid Spencer00c482b2006-10-26 19:19:06 +00005423 Op = InsertCastBefore(Mask, I.getType()->getSignedVersion(), I);
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005424 Instruction *Shift =
5425 new ShiftInst(ShiftOp->getOpcode(), Op,
Reid Spencere0fc4df2006-10-20 07:07:24 +00005426 ConstantInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005427 InsertNewInstBefore(Shift, I);
5428
5429 C = ConstantIntegral::getAllOnesValue(Shift->getType());
5430 C = ConstantExpr::getShl(C, Op1);
5431 Mask = BinaryOperator::createAnd(Shift, C, Op->getName()+".mask");
5432 InsertNewInstBefore(Mask, I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005433 return CastInst::create(Instruction::BitCast, Mask, I.getType());
Chris Lattnereb372a02006-01-06 07:52:12 +00005434 }
5435 } else {
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005436 // We can handle signed (X << C1) >>s C2 if it's a sign extend. In
Chris Lattnereb372a02006-01-06 07:52:12 +00005437 // this case, C1 == C2 and C1 is 8, 16, or 32.
5438 if (ShiftAmt1 == ShiftAmt2) {
5439 const Type *SExtType = 0;
Chris Lattner655d08f2006-04-28 22:21:41 +00005440 switch (Op0->getType()->getPrimitiveSizeInBits() - ShiftAmt1) {
Chris Lattnereb372a02006-01-06 07:52:12 +00005441 case 8 : SExtType = Type::SByteTy; break;
5442 case 16: SExtType = Type::ShortTy; break;
5443 case 32: SExtType = Type::IntTy; break;
5444 }
5445
5446 if (SExtType) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005447 Instruction *NewTrunc =
5448 new TruncInst(ShiftOp->getOperand(0), SExtType, "sext");
Chris Lattnereb372a02006-01-06 07:52:12 +00005449 InsertNewInstBefore(NewTrunc, I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005450 return new SExtInst(NewTrunc, I.getType());
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00005451 }
Chris Lattner27cb9db2005-09-18 05:12:10 +00005452 }
Chris Lattner86102b82005-01-01 16:22:27 +00005453 }
Chris Lattnereb372a02006-01-06 07:52:12 +00005454 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005455 return 0;
5456}
5457
Chris Lattner48a44f72002-05-02 17:06:02 +00005458
Chris Lattner8f663e82005-10-29 04:36:15 +00005459/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
5460/// expression. If so, decompose it, returning some value X, such that Val is
5461/// X*Scale+Offset.
5462///
5463static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
5464 unsigned &Offset) {
5465 assert(Val->getType() == Type::UIntTy && "Unexpected allocation size type!");
Reid Spencere0fc4df2006-10-20 07:07:24 +00005466 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
5467 if (CI->getType()->isUnsigned()) {
5468 Offset = CI->getZExtValue();
5469 Scale = 1;
5470 return ConstantInt::get(Type::UIntTy, 0);
5471 }
Chris Lattner8f663e82005-10-29 04:36:15 +00005472 } else if (Instruction *I = dyn_cast<Instruction>(Val)) {
5473 if (I->getNumOperands() == 2) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00005474 if (ConstantInt *CUI = dyn_cast<ConstantInt>(I->getOperand(1))) {
5475 if (CUI->getType()->isUnsigned()) {
5476 if (I->getOpcode() == Instruction::Shl) {
5477 // This is a value scaled by '1 << the shift amt'.
5478 Scale = 1U << CUI->getZExtValue();
5479 Offset = 0;
5480 return I->getOperand(0);
5481 } else if (I->getOpcode() == Instruction::Mul) {
5482 // This value is scaled by 'CUI'.
5483 Scale = CUI->getZExtValue();
5484 Offset = 0;
5485 return I->getOperand(0);
5486 } else if (I->getOpcode() == Instruction::Add) {
5487 // We have X+C. Check to see if we really have (X*C2)+C1,
5488 // where C1 is divisible by C2.
5489 unsigned SubScale;
5490 Value *SubVal =
5491 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
5492 Offset += CUI->getZExtValue();
5493 if (SubScale > 1 && (Offset % SubScale == 0)) {
5494 Scale = SubScale;
5495 return SubVal;
5496 }
Chris Lattner8f663e82005-10-29 04:36:15 +00005497 }
5498 }
5499 }
5500 }
5501 }
5502
5503 // Otherwise, we can't look past this.
5504 Scale = 1;
5505 Offset = 0;
5506 return Val;
5507}
5508
5509
Chris Lattner216be912005-10-24 06:03:58 +00005510/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
5511/// try to eliminate the cast by moving the type information into the alloc.
5512Instruction *InstCombiner::PromoteCastOfAllocation(CastInst &CI,
5513 AllocationInst &AI) {
5514 const PointerType *PTy = dyn_cast<PointerType>(CI.getType());
Chris Lattnerbb171802005-10-27 05:53:56 +00005515 if (!PTy) return 0; // Not casting the allocation to a pointer type.
Chris Lattner216be912005-10-24 06:03:58 +00005516
Chris Lattnerac87beb2005-10-24 06:22:12 +00005517 // Remove any uses of AI that are dead.
5518 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
5519 std::vector<Instruction*> DeadUsers;
5520 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
5521 Instruction *User = cast<Instruction>(*UI++);
5522 if (isInstructionTriviallyDead(User)) {
5523 while (UI != E && *UI == User)
5524 ++UI; // If this instruction uses AI more than once, don't break UI.
5525
5526 // Add operands to the worklist.
5527 AddUsesToWorkList(*User);
5528 ++NumDeadInst;
Bill Wendling5dbf43c2006-11-26 09:46:52 +00005529 DOUT << "IC: DCE: " << *User;
Chris Lattnerac87beb2005-10-24 06:22:12 +00005530
5531 User->eraseFromParent();
5532 removeFromWorkList(User);
5533 }
5534 }
5535
Chris Lattner216be912005-10-24 06:03:58 +00005536 // Get the type really allocated and the type casted to.
5537 const Type *AllocElTy = AI.getAllocatedType();
5538 const Type *CastElTy = PTy->getElementType();
5539 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner355ecc02005-10-24 06:26:18 +00005540
Chris Lattner7d190672006-10-01 19:40:58 +00005541 unsigned AllocElTyAlign = TD->getTypeAlignment(AllocElTy);
5542 unsigned CastElTyAlign = TD->getTypeAlignment(CastElTy);
Chris Lattner355ecc02005-10-24 06:26:18 +00005543 if (CastElTyAlign < AllocElTyAlign) return 0;
5544
Chris Lattner46705b22005-10-24 06:35:18 +00005545 // If the allocation has multiple uses, only promote it if we are strictly
5546 // increasing the alignment of the resultant allocation. If we keep it the
5547 // same, we open the door to infinite loops of various kinds.
5548 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
5549
Chris Lattner216be912005-10-24 06:03:58 +00005550 uint64_t AllocElTySize = TD->getTypeSize(AllocElTy);
5551 uint64_t CastElTySize = TD->getTypeSize(CastElTy);
Chris Lattnerbb171802005-10-27 05:53:56 +00005552 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner355ecc02005-10-24 06:26:18 +00005553
Chris Lattner8270c332005-10-29 03:19:53 +00005554 // See if we can satisfy the modulus by pulling a scale out of the array
5555 // size argument.
Chris Lattner8f663e82005-10-29 04:36:15 +00005556 unsigned ArraySizeScale, ArrayOffset;
5557 Value *NumElements = // See if the array size is a decomposable linear expr.
5558 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
5559
Chris Lattner8270c332005-10-29 03:19:53 +00005560 // If we can now satisfy the modulus, by using a non-1 scale, we really can
5561 // do the xform.
Chris Lattner8f663e82005-10-29 04:36:15 +00005562 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
5563 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattnerb3ecf962005-10-27 06:12:00 +00005564
Chris Lattner8270c332005-10-29 03:19:53 +00005565 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
5566 Value *Amt = 0;
5567 if (Scale == 1) {
5568 Amt = NumElements;
5569 } else {
Reid Spencere0fc4df2006-10-20 07:07:24 +00005570 // If the allocation size is constant, form a constant mul expression
5571 Amt = ConstantInt::get(Type::UIntTy, Scale);
5572 if (isa<ConstantInt>(NumElements) && NumElements->getType()->isUnsigned())
5573 Amt = ConstantExpr::getMul(
5574 cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
5575 // otherwise multiply the amount and the number of elements
Chris Lattner8270c332005-10-29 03:19:53 +00005576 else if (Scale != 1) {
5577 Instruction *Tmp = BinaryOperator::createMul(Amt, NumElements, "tmp");
5578 Amt = InsertNewInstBefore(Tmp, AI);
Chris Lattnerb3ecf962005-10-27 06:12:00 +00005579 }
Chris Lattnerbb171802005-10-27 05:53:56 +00005580 }
5581
Chris Lattner8f663e82005-10-29 04:36:15 +00005582 if (unsigned Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00005583 Value *Off = ConstantInt::get(Type::UIntTy, Offset);
Chris Lattner8f663e82005-10-29 04:36:15 +00005584 Instruction *Tmp = BinaryOperator::createAdd(Amt, Off, "tmp");
5585 Amt = InsertNewInstBefore(Tmp, AI);
5586 }
5587
Chris Lattner216be912005-10-24 06:03:58 +00005588 std::string Name = AI.getName(); AI.setName("");
5589 AllocationInst *New;
5590 if (isa<MallocInst>(AI))
Nate Begeman848622f2005-11-05 09:21:28 +00005591 New = new MallocInst(CastElTy, Amt, AI.getAlignment(), Name);
Chris Lattner216be912005-10-24 06:03:58 +00005592 else
Nate Begeman848622f2005-11-05 09:21:28 +00005593 New = new AllocaInst(CastElTy, Amt, AI.getAlignment(), Name);
Chris Lattner216be912005-10-24 06:03:58 +00005594 InsertNewInstBefore(New, AI);
Chris Lattner46705b22005-10-24 06:35:18 +00005595
5596 // If the allocation has multiple uses, insert a cast and change all things
5597 // that used it to use the new cast. This will also hack on CI, but it will
5598 // die soon.
5599 if (!AI.hasOneUse()) {
5600 AddUsesToWorkList(AI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005601 // New is the allocation instruction, pointer typed. AI is the original
5602 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
5603 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
Chris Lattner46705b22005-10-24 06:35:18 +00005604 InsertNewInstBefore(NewCast, AI);
5605 AI.replaceAllUsesWith(NewCast);
5606 }
Chris Lattner216be912005-10-24 06:03:58 +00005607 return ReplaceInstUsesWith(CI, New);
5608}
5609
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005610/// CanEvaluateInDifferentType - Return true if we can take the specified value
5611/// and return it without inserting any new casts. This is used by code that
5612/// tries to decide whether promoting or shrinking integer operations to wider
5613/// or smaller types will allow us to eliminate a truncate or extend.
5614static bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
5615 int &NumCastsRemoved) {
5616 if (isa<Constant>(V)) return true;
5617
5618 Instruction *I = dyn_cast<Instruction>(V);
5619 if (!I || !I->hasOneUse()) return false;
5620
5621 switch (I->getOpcode()) {
5622 case Instruction::And:
5623 case Instruction::Or:
5624 case Instruction::Xor:
5625 // These operators can all arbitrarily be extended or truncated.
5626 return CanEvaluateInDifferentType(I->getOperand(0), Ty, NumCastsRemoved) &&
5627 CanEvaluateInDifferentType(I->getOperand(1), Ty, NumCastsRemoved);
Chris Lattner960acb02006-11-29 07:18:39 +00005628 case Instruction::AShr:
5629 case Instruction::LShr:
5630 case Instruction::Shl:
5631 // If this is just a bitcast changing the sign of the operation, we can
5632 // convert if the operand can be converted.
5633 if (V->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
5634 return CanEvaluateInDifferentType(I->getOperand(0), Ty, NumCastsRemoved);
5635 break;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005636 case Instruction::Trunc:
5637 case Instruction::ZExt:
5638 case Instruction::SExt:
5639 case Instruction::BitCast:
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005640 // If this is a cast from the destination type, we can trivially eliminate
5641 // it, and this will remove a cast overall.
5642 if (I->getOperand(0)->getType() == Ty) {
Chris Lattner3fda3862006-06-28 17:34:50 +00005643 // If the first operand is itself a cast, and is eliminable, do not count
5644 // this as an eliminable cast. We would prefer to eliminate those two
5645 // casts first.
Reid Spencerde46e482006-11-02 20:25:50 +00005646 if (isa<CastInst>(I->getOperand(0)))
Chris Lattner3fda3862006-06-28 17:34:50 +00005647 return true;
5648
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005649 ++NumCastsRemoved;
5650 return true;
5651 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005652 break;
5653 default:
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005654 // TODO: Can handle more cases here.
5655 break;
5656 }
5657
5658 return false;
5659}
5660
5661/// EvaluateInDifferentType - Given an expression that
5662/// CanEvaluateInDifferentType returns true for, actually insert the code to
5663/// evaluate the expression.
5664Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty) {
5665 if (Constant *C = dyn_cast<Constant>(V))
5666 return ConstantExpr::getCast(C, Ty);
5667
5668 // Otherwise, it must be an instruction.
5669 Instruction *I = cast<Instruction>(V);
Chris Lattnerd0622b62006-05-20 23:14:03 +00005670 Instruction *Res = 0;
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005671 switch (I->getOpcode()) {
5672 case Instruction::And:
5673 case Instruction::Or:
5674 case Instruction::Xor: {
5675 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty);
5676 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty);
5677 Res = BinaryOperator::create((Instruction::BinaryOps)I->getOpcode(),
5678 LHS, RHS, I->getName());
5679 break;
5680 }
Chris Lattner960acb02006-11-29 07:18:39 +00005681 case Instruction::AShr:
5682 case Instruction::LShr:
5683 case Instruction::Shl: {
5684 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty);
5685 Res = new ShiftInst((Instruction::OtherOps)I->getOpcode(), LHS,
5686 I->getOperand(1), I->getName());
5687 break;
5688 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005689 case Instruction::Trunc:
5690 case Instruction::ZExt:
5691 case Instruction::SExt:
5692 case Instruction::BitCast:
5693 // If the source type of the cast is the type we're trying for then we can
5694 // just return the source. There's no need to insert it because its not new.
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005695 if (I->getOperand(0)->getType() == Ty)
5696 return I->getOperand(0);
5697
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005698 // Some other kind of cast, which shouldn't happen, so just ..
5699 // FALL THROUGH
5700 default:
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005701 // TODO: Can handle more cases here.
5702 assert(0 && "Unreachable!");
5703 break;
5704 }
5705
5706 return InsertNewInstBefore(Res, *I);
5707}
5708
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005709/// @brief Implement the transforms common to all CastInst visitors.
5710Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
Chris Lattner55d4bda2003-06-23 21:59:52 +00005711 Value *Src = CI.getOperand(0);
5712
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005713 // Casting undef to anything results in undef so might as just replace it and
5714 // get rid of the cast.
Chris Lattner81a7a232004-10-16 18:11:37 +00005715 if (isa<UndefValue>(Src)) // cast undef -> undef
5716 return ReplaceInstUsesWith(CI, UndefValue::get(CI.getType()));
5717
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005718 // Many cases of "cast of a cast" are eliminable. If its eliminable we just
5719 // eliminate it now.
Chris Lattner86102b82005-01-01 16:22:27 +00005720 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005721 if (Instruction::CastOps opc =
5722 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
5723 // The first cast (CSrc) is eliminable so we need to fix up or replace
5724 // the second cast (CI). CSrc will then have a good chance of being dead.
5725 return CastInst::create(opc, CSrc->getOperand(0), CI.getType());
Chris Lattner650b6da2002-08-02 20:00:25 +00005726 }
5727 }
Chris Lattner03841652004-05-25 04:29:21 +00005728
Chris Lattnerd0d51602003-06-21 23:12:02 +00005729 // If casting the result of a getelementptr instruction with no offset, turn
5730 // this into a cast of the original pointer!
5731 //
Chris Lattner55d4bda2003-06-23 21:59:52 +00005732 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattnerd0d51602003-06-21 23:12:02 +00005733 bool AllZeroOperands = true;
5734 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
5735 if (!isa<Constant>(GEP->getOperand(i)) ||
5736 !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
5737 AllZeroOperands = false;
5738 break;
5739 }
5740 if (AllZeroOperands) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005741 // Changing the cast operand is usually not a good idea but it is safe
5742 // here because the pointer operand is being replaced with another
5743 // pointer operand so the opcode doesn't need to change.
Chris Lattnerd0d51602003-06-21 23:12:02 +00005744 CI.setOperand(0, GEP->getOperand(0));
5745 return &CI;
5746 }
5747 }
Chris Lattnerec45a4c2006-11-21 17:05:13 +00005748
Chris Lattnerf4ad1652003-11-02 05:57:39 +00005749 // If we are casting a malloc or alloca to a pointer to a type of the same
5750 // size, rewrite the allocation instruction to allocate the "right" type.
Chris Lattnerf4ad1652003-11-02 05:57:39 +00005751 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
Chris Lattner216be912005-10-24 06:03:58 +00005752 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
5753 return V;
Chris Lattnerf4ad1652003-11-02 05:57:39 +00005754
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005755 // If we are casting a select then fold the cast into the select
Chris Lattner86102b82005-01-01 16:22:27 +00005756 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
5757 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
5758 return NV;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005759
5760 // If we are casting a PHI then fold the cast into the PHI
Chris Lattner6a4adcd2004-09-29 05:07:12 +00005761 if (isa<PHINode>(Src))
5762 if (Instruction *NV = FoldOpIntoPhi(CI))
5763 return NV;
Chris Lattnerb19a5c62006-04-12 18:09:35 +00005764
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005765 return 0;
5766}
5767
5768/// Only the TRUNC, ZEXT, SEXT, and BITCONVERT can have both operands as
5769/// integers. This function implements the common transforms for all those
5770/// cases.
5771/// @brief Implement the transforms common to CastInst with integer operands
5772Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
5773 if (Instruction *Result = commonCastTransforms(CI))
5774 return Result;
5775
5776 Value *Src = CI.getOperand(0);
5777 const Type *SrcTy = Src->getType();
5778 const Type *DestTy = CI.getType();
5779 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
5780 unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
5781
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005782 // See if we can simplify any instructions used by the LHS whose sole
5783 // purpose is to compute bits we don't care about.
5784 uint64_t KnownZero = 0, KnownOne = 0;
5785 if (SimplifyDemandedBits(&CI, DestTy->getIntegralTypeMask(),
5786 KnownZero, KnownOne))
5787 return &CI;
5788
5789 // If the source isn't an instruction or has more than one use then we
5790 // can't do anything more.
5791 if (!isa<Instruction>(Src) || !Src->hasOneUse())
5792 return 0;
5793
5794 // Attempt to propagate the cast into the instruction.
5795 Instruction *SrcI = cast<Instruction>(Src);
5796 int NumCastsRemoved = 0;
5797 if (CanEvaluateInDifferentType(SrcI, DestTy, NumCastsRemoved)) {
5798 // If this cast is a truncate, evaluting in a different type always
5799 // eliminates the cast, so it is always a win. If this is a noop-cast
5800 // this just removes a noop cast which isn't pointful, but simplifies
5801 // the code. If this is a zero-extension, we need to do an AND to
5802 // maintain the clear top-part of the computation, so we require that
5803 // the input have eliminated at least one cast. If this is a sign
5804 // extension, we insert two new casts (to do the extension) so we
5805 // require that two casts have been eliminated.
5806 bool DoXForm = CI.isNoopCast(TD->getIntPtrType());
5807 if (!DoXForm) {
5808 switch (CI.getOpcode()) {
5809 case Instruction::Trunc:
5810 DoXForm = true;
5811 break;
5812 case Instruction::ZExt:
5813 DoXForm = NumCastsRemoved >= 1;
5814 break;
5815 case Instruction::SExt:
5816 DoXForm = NumCastsRemoved >= 2;
5817 break;
5818 case Instruction::BitCast:
5819 DoXForm = false;
5820 break;
5821 default:
5822 // All the others use floating point so we shouldn't actually
5823 // get here because of the check above.
5824 assert(!"Unknown cast type .. unreachable");
5825 break;
5826 }
5827 }
5828
5829 if (DoXForm) {
5830 Value *Res = EvaluateInDifferentType(SrcI, DestTy);
5831 assert(Res->getType() == DestTy);
5832 switch (CI.getOpcode()) {
5833 default: assert(0 && "Unknown cast type!");
5834 case Instruction::Trunc:
5835 case Instruction::BitCast:
5836 // Just replace this cast with the result.
5837 return ReplaceInstUsesWith(CI, Res);
5838 case Instruction::ZExt: {
5839 // We need to emit an AND to clear the high bits.
5840 assert(SrcBitSize < DestBitSize && "Not a zext?");
5841 Constant *C =
5842 ConstantInt::get(Type::ULongTy, (1ULL << SrcBitSize)-1);
5843 if (DestBitSize < 64)
5844 C = ConstantExpr::getTrunc(C, DestTy);
5845 else {
5846 assert(DestBitSize == 64);
5847 C = ConstantExpr::getBitCast(C, DestTy);
5848 }
5849 return BinaryOperator::createAnd(Res, C);
5850 }
5851 case Instruction::SExt:
5852 // We need to emit a cast to truncate, then a cast to sext.
5853 return CastInst::create(Instruction::SExt,
5854 InsertCastBefore(Res, Src->getType(), CI), DestTy);
5855 }
5856 }
5857 }
5858
5859 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
5860 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
5861
5862 switch (SrcI->getOpcode()) {
5863 case Instruction::Add:
5864 case Instruction::Mul:
5865 case Instruction::And:
5866 case Instruction::Or:
5867 case Instruction::Xor:
5868 // If we are discarding information, or just changing the sign,
5869 // rewrite.
5870 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
5871 // Don't insert two casts if they cannot be eliminated. We allow
5872 // two casts to be inserted if the sizes are the same. This could
5873 // only be converting signedness, which is a noop.
5874 if (DestBitSize == SrcBitSize ||
5875 !ValueRequiresCast(Op1, DestTy,TD) ||
5876 !ValueRequiresCast(Op0, DestTy, TD)) {
5877 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
5878 Value *Op1c = InsertOperandCastBefore(Op1, DestTy, SrcI);
5879 return BinaryOperator::create(cast<BinaryOperator>(SrcI)
5880 ->getOpcode(), Op0c, Op1c);
5881 }
5882 }
5883
5884 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
5885 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
5886 SrcI->getOpcode() == Instruction::Xor &&
5887 Op1 == ConstantBool::getTrue() &&
5888 (!Op0->hasOneUse() || !isa<SetCondInst>(Op0))) {
5889 Value *New = InsertOperandCastBefore(Op0, DestTy, &CI);
5890 return BinaryOperator::createXor(New, ConstantInt::get(CI.getType(), 1));
5891 }
5892 break;
5893 case Instruction::SDiv:
5894 case Instruction::UDiv:
5895 case Instruction::SRem:
5896 case Instruction::URem:
5897 // If we are just changing the sign, rewrite.
5898 if (DestBitSize == SrcBitSize) {
5899 // Don't insert two casts if they cannot be eliminated. We allow
5900 // two casts to be inserted if the sizes are the same. This could
5901 // only be converting signedness, which is a noop.
5902 if (!ValueRequiresCast(Op1, DestTy,TD) ||
5903 !ValueRequiresCast(Op0, DestTy, TD)) {
5904 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
5905 Value *Op1c = InsertOperandCastBefore(Op1, DestTy, SrcI);
5906 return BinaryOperator::create(
5907 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
5908 }
5909 }
5910 break;
5911
5912 case Instruction::Shl:
5913 // Allow changing the sign of the source operand. Do not allow
5914 // changing the size of the shift, UNLESS the shift amount is a
5915 // constant. We must not change variable sized shifts to a smaller
5916 // size, because it is undefined to shift more bits out than exist
5917 // in the value.
5918 if (DestBitSize == SrcBitSize ||
5919 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
5920 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
5921 return new ShiftInst(Instruction::Shl, Op0c, Op1);
5922 }
5923 break;
5924 case Instruction::AShr:
5925 // If this is a signed shr, and if all bits shifted in are about to be
5926 // truncated off, turn it into an unsigned shr to allow greater
5927 // simplifications.
5928 if (DestBitSize < SrcBitSize &&
5929 isa<ConstantInt>(Op1)) {
5930 unsigned ShiftAmt = cast<ConstantInt>(Op1)->getZExtValue();
5931 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
5932 // Insert the new logical shift right.
5933 return new ShiftInst(Instruction::LShr, Op0, Op1);
5934 }
5935 }
5936 break;
5937
5938 case Instruction::SetEQ:
5939 case Instruction::SetNE:
5940 // If we are just checking for a seteq of a single bit and casting it
5941 // to an integer. If so, shift the bit to the appropriate place then
5942 // cast to integer to avoid the comparison.
5943 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
5944 uint64_t Op1CV = Op1C->getZExtValue();
5945 // cast (X == 0) to int --> X^1 iff X has only the low bit set.
5946 // cast (X == 0) to int --> (X>>1)^1 iff X has only the 2nd bit set.
5947 // cast (X == 1) to int --> X iff X has only the low bit set.
5948 // cast (X == 2) to int --> X>>1 iff X has only the 2nd bit set.
5949 // cast (X != 0) to int --> X iff X has only the low bit set.
5950 // cast (X != 0) to int --> X>>1 iff X has only the 2nd bit set.
5951 // cast (X != 1) to int --> X^1 iff X has only the low bit set.
5952 // cast (X != 2) to int --> (X>>1)^1 iff X has only the 2nd bit set.
5953 if (Op1CV == 0 || isPowerOf2_64(Op1CV)) {
5954 // If Op1C some other power of two, convert:
5955 uint64_t KnownZero, KnownOne;
5956 uint64_t TypeMask = Op1->getType()->getIntegralTypeMask();
5957 ComputeMaskedBits(Op0, TypeMask, KnownZero, KnownOne);
5958
5959 if (isPowerOf2_64(KnownZero^TypeMask)) { // Exactly 1 possible 1?
5960 bool isSetNE = SrcI->getOpcode() == Instruction::SetNE;
5961 if (Op1CV && (Op1CV != (KnownZero^TypeMask))) {
5962 // (X&4) == 2 --> false
5963 // (X&4) != 2 --> true
5964 Constant *Res = ConstantBool::get(isSetNE);
5965 Res = ConstantExpr::getZeroExtend(Res, CI.getType());
5966 return ReplaceInstUsesWith(CI, Res);
5967 }
5968
5969 unsigned ShiftAmt = Log2_64(KnownZero^TypeMask);
5970 Value *In = Op0;
5971 if (ShiftAmt) {
5972 // Perform a logical shr by shiftamt.
5973 // Insert the shift to put the result in the low bit.
5974 In = InsertNewInstBefore(
5975 new ShiftInst(Instruction::LShr, In,
5976 ConstantInt::get(Type::UByteTy, ShiftAmt),
5977 In->getName()+".lobit"), CI);
5978 }
5979
5980 if ((Op1CV != 0) == isSetNE) { // Toggle the low bit.
5981 Constant *One = ConstantInt::get(In->getType(), 1);
5982 In = BinaryOperator::createXor(In, One, "tmp");
5983 InsertNewInstBefore(cast<Instruction>(In), CI);
5984 }
5985
5986 if (CI.getType() == In->getType())
5987 return ReplaceInstUsesWith(CI, In);
5988 else
5989 return CastInst::createInferredCast(In, CI.getType());
5990 }
5991 }
5992 }
5993 break;
5994 }
5995 return 0;
5996}
5997
5998Instruction *InstCombiner::visitTrunc(CastInst &CI) {
Chris Lattnerd747f012006-11-29 07:04:07 +00005999 if (Instruction *Result = commonIntCastTransforms(CI))
6000 return Result;
6001
6002 Value *Src = CI.getOperand(0);
6003 const Type *Ty = CI.getType();
6004 unsigned DestBitWidth = Ty->getPrimitiveSizeInBits();
6005
6006 if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
6007 switch (SrcI->getOpcode()) {
6008 default: break;
6009 case Instruction::LShr:
6010 // We can shrink lshr to something smaller if we know the bits shifted in
6011 // are already zeros.
6012 if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
6013 unsigned ShAmt = ShAmtV->getZExtValue();
6014
6015 // Get a mask for the bits shifting in.
6016 uint64_t Mask = (~0ULL >> (64-ShAmt)) << DestBitWidth;
6017 if (SrcI->hasOneUse() && MaskedValueIsZero(SrcI->getOperand(0), Mask)) {
6018 if (ShAmt >= DestBitWidth) // All zeros.
6019 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
6020
6021 // Okay, we can shrink this. Truncate the input, then return a new
6022 // shift.
6023 Value *V = InsertCastBefore(SrcI->getOperand(0), Ty, CI);
6024 return new ShiftInst(Instruction::LShr, V, SrcI->getOperand(1));
6025 }
Chris Lattnerc209b582006-12-05 01:26:29 +00006026 } else { // This is a variable shr.
6027
6028 // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'. This is
6029 // more LLVM instructions, but allows '1 << Y' to be hoisted if
6030 // loop-invariant and CSE'd.
6031 if (CI.getType() == Type::BoolTy && SrcI->hasOneUse()) {
6032 Value *One = ConstantInt::get(SrcI->getType(), 1);
6033
6034 Value *V = InsertNewInstBefore(new ShiftInst(Instruction::Shl, One,
6035 SrcI->getOperand(1),
6036 "tmp"), CI);
6037 V = InsertNewInstBefore(BinaryOperator::createAnd(V,
6038 SrcI->getOperand(0),
6039 "tmp"), CI);
6040 Value *Zero = Constant::getNullValue(V->getType());
6041 return BinaryOperator::createSetNE(V, Zero);
6042 }
Chris Lattnerd747f012006-11-29 07:04:07 +00006043 }
6044 break;
6045 }
6046 }
6047
6048 return 0;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006049}
6050
6051Instruction *InstCombiner::visitZExt(CastInst &CI) {
6052 // If one of the common conversion will work ..
6053 if (Instruction *Result = commonIntCastTransforms(CI))
6054 return Result;
6055
6056 Value *Src = CI.getOperand(0);
6057
6058 // If this is a cast of a cast
6059 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
6060 // If the operand of the ZEXT is a TRUNC then we are dealing with integral
6061 // types and we can convert this to a logical AND if the sizes are just
6062 // right. This will be much cheaper than the pair of casts.
6063 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
6064 // types and if the sizes are just right we can convert this into a logical
6065 // 'and' which will be much cheaper than the pair of casts.
6066 if (isa<TruncInst>(CSrc)) {
6067 // Get the sizes of the types involved
6068 Value *A = CSrc->getOperand(0);
6069 unsigned SrcSize = A->getType()->getPrimitiveSizeInBits();
6070 unsigned MidSize = CSrc->getType()->getPrimitiveSizeInBits();
6071 unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
6072 // If we're actually extending zero bits and the trunc is a no-op
6073 if (MidSize < DstSize && SrcSize == DstSize) {
6074 // Replace both of the casts with an And of the type mask.
6075 uint64_t AndValue = CSrc->getType()->getIntegralTypeMask();
6076 Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
6077 Instruction *And =
6078 BinaryOperator::createAnd(CSrc->getOperand(0), AndConst);
6079 // Unfortunately, if the type changed, we need to cast it back.
6080 if (And->getType() != CI.getType()) {
6081 And->setName(CSrc->getName()+".mask");
6082 InsertNewInstBefore(And, CI);
6083 And = CastInst::createInferredCast(And, CI.getType());
6084 }
6085 return And;
6086 }
6087 }
6088 }
6089
6090 return 0;
6091}
6092
6093Instruction *InstCombiner::visitSExt(CastInst &CI) {
6094 return commonIntCastTransforms(CI);
6095}
6096
6097Instruction *InstCombiner::visitFPTrunc(CastInst &CI) {
6098 return commonCastTransforms(CI);
6099}
6100
6101Instruction *InstCombiner::visitFPExt(CastInst &CI) {
6102 return commonCastTransforms(CI);
6103}
6104
6105Instruction *InstCombiner::visitFPToUI(CastInst &CI) {
Reid Spencerad05ee92006-11-30 23:13:36 +00006106 return commonCastTransforms(CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006107}
6108
6109Instruction *InstCombiner::visitFPToSI(CastInst &CI) {
Reid Spencerad05ee92006-11-30 23:13:36 +00006110 return commonCastTransforms(CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006111}
6112
6113Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
6114 return commonCastTransforms(CI);
6115}
6116
6117Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
6118 return commonCastTransforms(CI);
6119}
6120
6121Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
Reid Spencerad05ee92006-11-30 23:13:36 +00006122 return commonCastTransforms(CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006123}
6124
6125Instruction *InstCombiner::visitIntToPtr(CastInst &CI) {
6126 return commonCastTransforms(CI);
6127}
6128
6129Instruction *InstCombiner::visitBitCast(CastInst &CI) {
6130
6131 // If the operands are integer typed then apply the integer transforms,
6132 // otherwise just apply the common ones.
6133 Value *Src = CI.getOperand(0);
6134 const Type *SrcTy = Src->getType();
6135 const Type *DestTy = CI.getType();
6136
6137 if (SrcTy->isInteger() && DestTy->isInteger()) {
6138 if (Instruction *Result = commonIntCastTransforms(CI))
6139 return Result;
6140 } else {
6141 if (Instruction *Result = commonCastTransforms(CI))
6142 return Result;
6143 }
6144
6145
6146 // Get rid of casts from one type to the same type. These are useless and can
6147 // be replaced by the operand.
6148 if (DestTy == Src->getType())
6149 return ReplaceInstUsesWith(CI, Src);
6150
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006151 // If the source and destination are pointers, and this cast is equivalent to
6152 // a getelementptr X, 0, 0, 0... turn it into the appropriate getelementptr.
6153 // This can enhance SROA and other transforms that want type-safe pointers.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006154 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
6155 if (const PointerType *SrcPTy = dyn_cast<PointerType>(SrcTy)) {
6156 const Type *DstElTy = DstPTy->getElementType();
6157 const Type *SrcElTy = SrcPTy->getElementType();
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006158
6159 Constant *ZeroUInt = Constant::getNullValue(Type::UIntTy);
6160 unsigned NumZeros = 0;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006161 while (SrcElTy != DstElTy &&
6162 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
6163 SrcElTy->getNumContainedTypes() /* not "{}" */) {
6164 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006165 ++NumZeros;
6166 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00006167
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006168 // If we found a path from the src to dest, create the getelementptr now.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006169 if (SrcElTy == DstElTy) {
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006170 std::vector<Value*> Idxs(NumZeros+1, ZeroUInt);
6171 return new GetElementPtrInst(Src, Idxs);
6172 }
6173 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006174 }
Chris Lattnerdfae8be2003-07-24 17:35:25 +00006175
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006176 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
6177 if (SVI->hasOneUse()) {
6178 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
6179 // a bitconvert to a vector with the same # elts.
6180 if (isa<PackedType>(DestTy) &&
6181 cast<PackedType>(DestTy)->getNumElements() ==
6182 SVI->getType()->getNumElements()) {
6183 CastInst *Tmp;
6184 // If either of the operands is a cast from CI.getType(), then
6185 // evaluating the shuffle in the casted destination's type will allow
6186 // us to eliminate at least one cast.
6187 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
6188 Tmp->getOperand(0)->getType() == DestTy) ||
6189 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
6190 Tmp->getOperand(0)->getType() == DestTy)) {
6191 Value *LHS = InsertOperandCastBefore(SVI->getOperand(0), DestTy, &CI);
6192 Value *RHS = InsertOperandCastBefore(SVI->getOperand(1), DestTy, &CI);
6193 // Return a new shuffle vector. Use the same element ID's, as we
6194 // know the vector types match #elts.
6195 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner99155be2006-05-25 23:24:33 +00006196 }
6197 }
6198 }
6199 }
Chris Lattner260ab202002-04-18 17:39:14 +00006200 return 0;
Chris Lattnerca081252001-12-14 16:52:21 +00006201}
6202
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006203/// GetSelectFoldableOperands - We want to turn code that looks like this:
6204/// %C = or %A, %B
6205/// %D = select %cond, %C, %A
6206/// into:
6207/// %C = select %cond, %B, 0
6208/// %D = or %A, %C
6209///
6210/// Assuming that the specified instruction is an operand to the select, return
6211/// a bitmask indicating which operands of this instruction are foldable if they
6212/// equal the other incoming value of the select.
6213///
6214static unsigned GetSelectFoldableOperands(Instruction *I) {
6215 switch (I->getOpcode()) {
6216 case Instruction::Add:
6217 case Instruction::Mul:
6218 case Instruction::And:
6219 case Instruction::Or:
6220 case Instruction::Xor:
6221 return 3; // Can fold through either operand.
6222 case Instruction::Sub: // Can only fold on the amount subtracted.
6223 case Instruction::Shl: // Can only fold on the shift amount.
Reid Spencerfdff9382006-11-08 06:47:33 +00006224 case Instruction::LShr:
6225 case Instruction::AShr:
Misha Brukmanb1c93172005-04-21 23:48:37 +00006226 return 1;
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006227 default:
6228 return 0; // Cannot fold
6229 }
6230}
6231
6232/// GetSelectFoldableConstant - For the same transformation as the previous
6233/// function, return the identity constant that goes into the select.
6234static Constant *GetSelectFoldableConstant(Instruction *I) {
6235 switch (I->getOpcode()) {
6236 default: assert(0 && "This cannot happen!"); abort();
6237 case Instruction::Add:
6238 case Instruction::Sub:
6239 case Instruction::Or:
6240 case Instruction::Xor:
6241 return Constant::getNullValue(I->getType());
6242 case Instruction::Shl:
Reid Spencerfdff9382006-11-08 06:47:33 +00006243 case Instruction::LShr:
6244 case Instruction::AShr:
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006245 return Constant::getNullValue(Type::UByteTy);
6246 case Instruction::And:
6247 return ConstantInt::getAllOnesValue(I->getType());
6248 case Instruction::Mul:
6249 return ConstantInt::get(I->getType(), 1);
6250 }
6251}
6252
Chris Lattner411336f2005-01-19 21:50:18 +00006253/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
6254/// have the same opcode and only one use each. Try to simplify this.
6255Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
6256 Instruction *FI) {
6257 if (TI->getNumOperands() == 1) {
6258 // If this is a non-volatile load or a cast from the same type,
6259 // merge.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006260 if (TI->isCast()) {
Chris Lattner411336f2005-01-19 21:50:18 +00006261 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
6262 return 0;
6263 } else {
6264 return 0; // unknown unary op.
6265 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00006266
Chris Lattner411336f2005-01-19 21:50:18 +00006267 // Fold this by inserting a select from the input values.
6268 SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
6269 FI->getOperand(0), SI.getName()+".v");
6270 InsertNewInstBefore(NewSI, SI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006271 return CastInst::create(Instruction::CastOps(TI->getOpcode()), NewSI,
6272 TI->getType());
Chris Lattner411336f2005-01-19 21:50:18 +00006273 }
6274
6275 // Only handle binary operators here.
6276 if (!isa<ShiftInst>(TI) && !isa<BinaryOperator>(TI))
6277 return 0;
6278
6279 // Figure out if the operations have any operands in common.
6280 Value *MatchOp, *OtherOpT, *OtherOpF;
6281 bool MatchIsOpZero;
6282 if (TI->getOperand(0) == FI->getOperand(0)) {
6283 MatchOp = TI->getOperand(0);
6284 OtherOpT = TI->getOperand(1);
6285 OtherOpF = FI->getOperand(1);
6286 MatchIsOpZero = true;
6287 } else if (TI->getOperand(1) == FI->getOperand(1)) {
6288 MatchOp = TI->getOperand(1);
6289 OtherOpT = TI->getOperand(0);
6290 OtherOpF = FI->getOperand(0);
6291 MatchIsOpZero = false;
6292 } else if (!TI->isCommutative()) {
6293 return 0;
6294 } else if (TI->getOperand(0) == FI->getOperand(1)) {
6295 MatchOp = TI->getOperand(0);
6296 OtherOpT = TI->getOperand(1);
6297 OtherOpF = FI->getOperand(0);
6298 MatchIsOpZero = true;
6299 } else if (TI->getOperand(1) == FI->getOperand(0)) {
6300 MatchOp = TI->getOperand(1);
6301 OtherOpT = TI->getOperand(0);
6302 OtherOpF = FI->getOperand(1);
6303 MatchIsOpZero = true;
6304 } else {
6305 return 0;
6306 }
6307
6308 // If we reach here, they do have operations in common.
6309 SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
6310 OtherOpF, SI.getName()+".v");
6311 InsertNewInstBefore(NewSI, SI);
6312
6313 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
6314 if (MatchIsOpZero)
6315 return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
6316 else
6317 return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
6318 } else {
6319 if (MatchIsOpZero)
6320 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), MatchOp, NewSI);
6321 else
6322 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), NewSI, MatchOp);
6323 }
6324}
6325
Chris Lattnerb909e8b2004-03-12 05:52:32 +00006326Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattner533bc492004-03-30 19:37:13 +00006327 Value *CondVal = SI.getCondition();
6328 Value *TrueVal = SI.getTrueValue();
6329 Value *FalseVal = SI.getFalseValue();
6330
6331 // select true, X, Y -> X
6332 // select false, X, Y -> Y
6333 if (ConstantBool *C = dyn_cast<ConstantBool>(CondVal))
Chris Lattner6ab03f62006-09-28 23:35:22 +00006334 return ReplaceInstUsesWith(SI, C->getValue() ? TrueVal : FalseVal);
Chris Lattner533bc492004-03-30 19:37:13 +00006335
6336 // select C, X, X -> X
6337 if (TrueVal == FalseVal)
6338 return ReplaceInstUsesWith(SI, TrueVal);
6339
Chris Lattner81a7a232004-10-16 18:11:37 +00006340 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
6341 return ReplaceInstUsesWith(SI, FalseVal);
6342 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
6343 return ReplaceInstUsesWith(SI, TrueVal);
6344 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
6345 if (isa<Constant>(TrueVal))
6346 return ReplaceInstUsesWith(SI, TrueVal);
6347 else
6348 return ReplaceInstUsesWith(SI, FalseVal);
6349 }
6350
Chris Lattner1c631e82004-04-08 04:43:23 +00006351 if (SI.getType() == Type::BoolTy)
6352 if (ConstantBool *C = dyn_cast<ConstantBool>(TrueVal)) {
Chris Lattner6ab03f62006-09-28 23:35:22 +00006353 if (C->getValue()) {
Chris Lattner1c631e82004-04-08 04:43:23 +00006354 // Change: A = select B, true, C --> A = or B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00006355 return BinaryOperator::createOr(CondVal, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00006356 } else {
6357 // Change: A = select B, false, C --> A = and !B, C
6358 Value *NotCond =
6359 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
6360 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00006361 return BinaryOperator::createAnd(NotCond, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00006362 }
6363 } else if (ConstantBool *C = dyn_cast<ConstantBool>(FalseVal)) {
Chris Lattner6ab03f62006-09-28 23:35:22 +00006364 if (C->getValue() == false) {
Chris Lattner1c631e82004-04-08 04:43:23 +00006365 // Change: A = select B, C, false --> A = and B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00006366 return BinaryOperator::createAnd(CondVal, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00006367 } else {
6368 // Change: A = select B, C, true --> A = or !B, C
6369 Value *NotCond =
6370 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
6371 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00006372 return BinaryOperator::createOr(NotCond, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00006373 }
6374 }
6375
Chris Lattner183b3362004-04-09 19:05:30 +00006376 // Selecting between two integer constants?
6377 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
6378 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
6379 // select C, 1, 0 -> cast C to int
Reid Spencere0fc4df2006-10-20 07:07:24 +00006380 if (FalseValC->isNullValue() && TrueValC->getZExtValue() == 1) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006381 return CastInst::create(Instruction::ZExt, CondVal, SI.getType());
Reid Spencere0fc4df2006-10-20 07:07:24 +00006382 } else if (TrueValC->isNullValue() && FalseValC->getZExtValue() == 1) {
Chris Lattner183b3362004-04-09 19:05:30 +00006383 // select C, 0, 1 -> cast !C to int
6384 Value *NotCond =
6385 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
Chris Lattnercf7baf32004-04-09 18:19:44 +00006386 "not."+CondVal->getName()), SI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006387 return CastInst::create(Instruction::ZExt, NotCond, SI.getType());
Chris Lattnercf7baf32004-04-09 18:19:44 +00006388 }
Chris Lattner35167c32004-06-09 07:59:58 +00006389
Chris Lattner380c7e92006-09-20 04:44:59 +00006390 if (SetCondInst *IC = dyn_cast<SetCondInst>(SI.getCondition())) {
6391
6392 // (x <s 0) ? -1 : 0 -> sra x, 31
6393 // (x >u 2147483647) ? -1 : 0 -> sra x, 31
6394 if (TrueValC->isAllOnesValue() && FalseValC->isNullValue())
6395 if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
6396 bool CanXForm = false;
6397 if (CmpCst->getType()->isSigned())
6398 CanXForm = CmpCst->isNullValue() &&
6399 IC->getOpcode() == Instruction::SetLT;
6400 else {
6401 unsigned Bits = CmpCst->getType()->getPrimitiveSizeInBits();
Reid Spencere0fc4df2006-10-20 07:07:24 +00006402 CanXForm = (CmpCst->getZExtValue() == ~0ULL >> (64-Bits+1)) &&
Chris Lattner380c7e92006-09-20 04:44:59 +00006403 IC->getOpcode() == Instruction::SetGT;
6404 }
6405
6406 if (CanXForm) {
6407 // The comparison constant and the result are not neccessarily the
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006408 // same width. Make an all-ones value by inserting a AShr.
Chris Lattner380c7e92006-09-20 04:44:59 +00006409 Value *X = IC->getOperand(0);
Chris Lattner380c7e92006-09-20 04:44:59 +00006410 unsigned Bits = X->getType()->getPrimitiveSizeInBits();
Reid Spencere0fc4df2006-10-20 07:07:24 +00006411 Constant *ShAmt = ConstantInt::get(Type::UByteTy, Bits-1);
Reid Spencerfdff9382006-11-08 06:47:33 +00006412 Instruction *SRA = new ShiftInst(Instruction::AShr, X,
Chris Lattner380c7e92006-09-20 04:44:59 +00006413 ShAmt, "ones");
6414 InsertNewInstBefore(SRA, SI);
6415
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006416 // Finally, convert to the type of the select RHS. We figure out
6417 // if this requires a SExt, Trunc or BitCast based on the sizes.
6418 Instruction::CastOps opc = Instruction::BitCast;
6419 unsigned SRASize = SRA->getType()->getPrimitiveSizeInBits();
6420 unsigned SISize = SI.getType()->getPrimitiveSizeInBits();
6421 if (SRASize < SISize)
6422 opc = Instruction::SExt;
6423 else if (SRASize > SISize)
6424 opc = Instruction::Trunc;
6425 return CastInst::create(opc, SRA, SI.getType());
Chris Lattner380c7e92006-09-20 04:44:59 +00006426 }
6427 }
6428
6429
6430 // If one of the constants is zero (we know they can't both be) and we
6431 // have a setcc instruction with zero, and we have an 'and' with the
6432 // non-constant value, eliminate this whole mess. This corresponds to
6433 // cases like this: ((X & 27) ? 27 : 0)
6434 if (TrueValC->isNullValue() || FalseValC->isNullValue())
Chris Lattnerb3f24c92006-09-18 04:22:48 +00006435 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner35167c32004-06-09 07:59:58 +00006436 cast<Constant>(IC->getOperand(1))->isNullValue())
6437 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
6438 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00006439 isa<ConstantInt>(ICA->getOperand(1)) &&
6440 (ICA->getOperand(1) == TrueValC ||
6441 ICA->getOperand(1) == FalseValC) &&
Chris Lattner35167c32004-06-09 07:59:58 +00006442 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
6443 // Okay, now we know that everything is set up, we just don't
6444 // know whether we have a setne or seteq and whether the true or
6445 // false val is the zero.
6446 bool ShouldNotVal = !TrueValC->isNullValue();
6447 ShouldNotVal ^= IC->getOpcode() == Instruction::SetNE;
6448 Value *V = ICA;
6449 if (ShouldNotVal)
6450 V = InsertNewInstBefore(BinaryOperator::create(
6451 Instruction::Xor, V, ICA->getOperand(1)), SI);
6452 return ReplaceInstUsesWith(SI, V);
6453 }
Chris Lattner380c7e92006-09-20 04:44:59 +00006454 }
Chris Lattner533bc492004-03-30 19:37:13 +00006455 }
Chris Lattner623fba12004-04-10 22:21:27 +00006456
6457 // See if we are selecting two values based on a comparison of the two values.
6458 if (SetCondInst *SCI = dyn_cast<SetCondInst>(CondVal)) {
6459 if (SCI->getOperand(0) == TrueVal && SCI->getOperand(1) == FalseVal) {
6460 // Transform (X == Y) ? X : Y -> Y
6461 if (SCI->getOpcode() == Instruction::SetEQ)
6462 return ReplaceInstUsesWith(SI, FalseVal);
6463 // Transform (X != Y) ? X : Y -> X
6464 if (SCI->getOpcode() == Instruction::SetNE)
6465 return ReplaceInstUsesWith(SI, TrueVal);
6466 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6467
6468 } else if (SCI->getOperand(0) == FalseVal && SCI->getOperand(1) == TrueVal){
6469 // Transform (X == Y) ? Y : X -> X
6470 if (SCI->getOpcode() == Instruction::SetEQ)
Chris Lattner24cf0202004-04-11 01:39:19 +00006471 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattner623fba12004-04-10 22:21:27 +00006472 // Transform (X != Y) ? Y : X -> Y
6473 if (SCI->getOpcode() == Instruction::SetNE)
Chris Lattner24cf0202004-04-11 01:39:19 +00006474 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattner623fba12004-04-10 22:21:27 +00006475 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6476 }
6477 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00006478
Chris Lattnera04c9042005-01-13 22:52:24 +00006479 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
6480 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
6481 if (TI->hasOneUse() && FI->hasOneUse()) {
Chris Lattnera04c9042005-01-13 22:52:24 +00006482 Instruction *AddOp = 0, *SubOp = 0;
6483
Chris Lattner411336f2005-01-19 21:50:18 +00006484 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
6485 if (TI->getOpcode() == FI->getOpcode())
6486 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
6487 return IV;
6488
6489 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
6490 // even legal for FP.
Chris Lattnera04c9042005-01-13 22:52:24 +00006491 if (TI->getOpcode() == Instruction::Sub &&
6492 FI->getOpcode() == Instruction::Add) {
6493 AddOp = FI; SubOp = TI;
6494 } else if (FI->getOpcode() == Instruction::Sub &&
6495 TI->getOpcode() == Instruction::Add) {
6496 AddOp = TI; SubOp = FI;
6497 }
6498
6499 if (AddOp) {
6500 Value *OtherAddOp = 0;
6501 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
6502 OtherAddOp = AddOp->getOperand(1);
6503 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
6504 OtherAddOp = AddOp->getOperand(0);
6505 }
6506
6507 if (OtherAddOp) {
Chris Lattnerb580d262006-02-24 18:05:58 +00006508 // So at this point we know we have (Y -> OtherAddOp):
6509 // select C, (add X, Y), (sub X, Z)
6510 Value *NegVal; // Compute -Z
6511 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
6512 NegVal = ConstantExpr::getNeg(C);
6513 } else {
6514 NegVal = InsertNewInstBefore(
6515 BinaryOperator::createNeg(SubOp->getOperand(1), "tmp"), SI);
Chris Lattnera04c9042005-01-13 22:52:24 +00006516 }
Chris Lattnerb580d262006-02-24 18:05:58 +00006517
6518 Value *NewTrueOp = OtherAddOp;
6519 Value *NewFalseOp = NegVal;
6520 if (AddOp != TI)
6521 std::swap(NewTrueOp, NewFalseOp);
6522 Instruction *NewSel =
6523 new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
6524
6525 NewSel = InsertNewInstBefore(NewSel, SI);
6526 return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
Chris Lattnera04c9042005-01-13 22:52:24 +00006527 }
6528 }
6529 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00006530
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006531 // See if we can fold the select into one of our operands.
6532 if (SI.getType()->isInteger()) {
6533 // See the comment above GetSelectFoldableOperands for a description of the
6534 // transformation we are doing here.
6535 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
6536 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
6537 !isa<Constant>(FalseVal))
6538 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
6539 unsigned OpToFold = 0;
6540 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
6541 OpToFold = 1;
6542 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
6543 OpToFold = 2;
6544 }
6545
6546 if (OpToFold) {
6547 Constant *C = GetSelectFoldableConstant(TVI);
6548 std::string Name = TVI->getName(); TVI->setName("");
6549 Instruction *NewSel =
6550 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C,
6551 Name);
6552 InsertNewInstBefore(NewSel, SI);
6553 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
6554 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
6555 else if (ShiftInst *SI = dyn_cast<ShiftInst>(TVI))
6556 return new ShiftInst(SI->getOpcode(), FalseVal, NewSel);
6557 else {
6558 assert(0 && "Unknown instruction!!");
6559 }
6560 }
6561 }
Chris Lattner6862fbd2004-09-29 17:40:11 +00006562
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006563 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
6564 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
6565 !isa<Constant>(TrueVal))
6566 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
6567 unsigned OpToFold = 0;
6568 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
6569 OpToFold = 1;
6570 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
6571 OpToFold = 2;
6572 }
6573
6574 if (OpToFold) {
6575 Constant *C = GetSelectFoldableConstant(FVI);
6576 std::string Name = FVI->getName(); FVI->setName("");
6577 Instruction *NewSel =
6578 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold),
6579 Name);
6580 InsertNewInstBefore(NewSel, SI);
6581 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
6582 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
6583 else if (ShiftInst *SI = dyn_cast<ShiftInst>(FVI))
6584 return new ShiftInst(SI->getOpcode(), TrueVal, NewSel);
6585 else {
6586 assert(0 && "Unknown instruction!!");
6587 }
6588 }
6589 }
6590 }
Chris Lattnerd6f636a2005-04-24 07:30:14 +00006591
6592 if (BinaryOperator::isNot(CondVal)) {
6593 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
6594 SI.setOperand(1, FalseVal);
6595 SI.setOperand(2, TrueVal);
6596 return &SI;
6597 }
6598
Chris Lattnerb909e8b2004-03-12 05:52:32 +00006599 return 0;
6600}
6601
Chris Lattner82f2ef22006-03-06 20:18:44 +00006602/// GetKnownAlignment - If the specified pointer has an alignment that we can
6603/// determine, return it, otherwise return 0.
6604static unsigned GetKnownAlignment(Value *V, TargetData *TD) {
6605 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
6606 unsigned Align = GV->getAlignment();
6607 if (Align == 0 && TD)
6608 Align = TD->getTypeAlignment(GV->getType()->getElementType());
6609 return Align;
6610 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
6611 unsigned Align = AI->getAlignment();
6612 if (Align == 0 && TD) {
6613 if (isa<AllocaInst>(AI))
6614 Align = TD->getTypeAlignment(AI->getType()->getElementType());
6615 else if (isa<MallocInst>(AI)) {
6616 // Malloc returns maximally aligned memory.
6617 Align = TD->getTypeAlignment(AI->getType()->getElementType());
6618 Align = std::max(Align, (unsigned)TD->getTypeAlignment(Type::DoubleTy));
6619 Align = std::max(Align, (unsigned)TD->getTypeAlignment(Type::LongTy));
6620 }
6621 }
6622 return Align;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006623 } else if (isa<BitCastInst>(V) ||
Chris Lattner53ef5a02006-03-07 01:28:57 +00006624 (isa<ConstantExpr>(V) &&
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006625 cast<ConstantExpr>(V)->getOpcode() == Instruction::BitCast)) {
Chris Lattner53ef5a02006-03-07 01:28:57 +00006626 User *CI = cast<User>(V);
Chris Lattner82f2ef22006-03-06 20:18:44 +00006627 if (isa<PointerType>(CI->getOperand(0)->getType()))
6628 return GetKnownAlignment(CI->getOperand(0), TD);
6629 return 0;
Chris Lattner53ef5a02006-03-07 01:28:57 +00006630 } else if (isa<GetElementPtrInst>(V) ||
6631 (isa<ConstantExpr>(V) &&
6632 cast<ConstantExpr>(V)->getOpcode()==Instruction::GetElementPtr)) {
6633 User *GEPI = cast<User>(V);
Chris Lattner82f2ef22006-03-06 20:18:44 +00006634 unsigned BaseAlignment = GetKnownAlignment(GEPI->getOperand(0), TD);
6635 if (BaseAlignment == 0) return 0;
6636
6637 // If all indexes are zero, it is just the alignment of the base pointer.
6638 bool AllZeroOperands = true;
6639 for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
6640 if (!isa<Constant>(GEPI->getOperand(i)) ||
6641 !cast<Constant>(GEPI->getOperand(i))->isNullValue()) {
6642 AllZeroOperands = false;
6643 break;
6644 }
6645 if (AllZeroOperands)
6646 return BaseAlignment;
6647
6648 // Otherwise, if the base alignment is >= the alignment we expect for the
6649 // base pointer type, then we know that the resultant pointer is aligned at
6650 // least as much as its type requires.
6651 if (!TD) return 0;
6652
6653 const Type *BasePtrTy = GEPI->getOperand(0)->getType();
6654 if (TD->getTypeAlignment(cast<PointerType>(BasePtrTy)->getElementType())
Chris Lattner53ef5a02006-03-07 01:28:57 +00006655 <= BaseAlignment) {
6656 const Type *GEPTy = GEPI->getType();
6657 return TD->getTypeAlignment(cast<PointerType>(GEPTy)->getElementType());
6658 }
Chris Lattner82f2ef22006-03-06 20:18:44 +00006659 return 0;
6660 }
6661 return 0;
6662}
6663
Chris Lattnerb909e8b2004-03-12 05:52:32 +00006664
Chris Lattnerc66b2232006-01-13 20:11:04 +00006665/// visitCallInst - CallInst simplification. This mostly only handles folding
6666/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
6667/// the heavy lifting.
6668///
Chris Lattner970c33a2003-06-19 17:00:31 +00006669Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattnerc66b2232006-01-13 20:11:04 +00006670 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
6671 if (!II) return visitCallSite(&CI);
6672
Chris Lattner51ea1272004-02-28 05:22:00 +00006673 // Intrinsics cannot occur in an invoke, so handle them here instead of in
6674 // visitCallSite.
Chris Lattnerc66b2232006-01-13 20:11:04 +00006675 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner00648e12004-10-12 04:52:52 +00006676 bool Changed = false;
6677
6678 // memmove/cpy/set of zero bytes is a noop.
6679 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
6680 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
6681
Chris Lattner00648e12004-10-12 04:52:52 +00006682 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencere0fc4df2006-10-20 07:07:24 +00006683 if (CI->getZExtValue() == 1) {
Chris Lattner00648e12004-10-12 04:52:52 +00006684 // Replace the instruction with just byte operations. We would
6685 // transform other cases to loads/stores, but we don't know if
6686 // alignment is sufficient.
6687 }
Chris Lattner51ea1272004-02-28 05:22:00 +00006688 }
6689
Chris Lattner00648e12004-10-12 04:52:52 +00006690 // If we have a memmove and the source operation is a constant global,
6691 // then the source and dest pointers can't alias, so we can change this
6692 // into a call to memcpy.
Chris Lattner82f2ef22006-03-06 20:18:44 +00006693 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(II)) {
Chris Lattner00648e12004-10-12 04:52:52 +00006694 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
6695 if (GVSrc->isConstant()) {
6696 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner681ef2f2006-03-03 01:34:17 +00006697 const char *Name;
Andrew Lenharth0ebb0b02006-11-03 22:45:50 +00006698 if (CI.getCalledFunction()->getFunctionType()->getParamType(2) ==
Chris Lattner681ef2f2006-03-03 01:34:17 +00006699 Type::UIntTy)
6700 Name = "llvm.memcpy.i32";
6701 else
6702 Name = "llvm.memcpy.i64";
6703 Function *MemCpy = M->getOrInsertFunction(Name,
Chris Lattner00648e12004-10-12 04:52:52 +00006704 CI.getCalledFunction()->getFunctionType());
6705 CI.setOperand(0, MemCpy);
6706 Changed = true;
6707 }
Chris Lattner82f2ef22006-03-06 20:18:44 +00006708 }
Chris Lattner00648e12004-10-12 04:52:52 +00006709
Chris Lattner82f2ef22006-03-06 20:18:44 +00006710 // If we can determine a pointer alignment that is bigger than currently
6711 // set, update the alignment.
6712 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
6713 unsigned Alignment1 = GetKnownAlignment(MI->getOperand(1), TD);
6714 unsigned Alignment2 = GetKnownAlignment(MI->getOperand(2), TD);
6715 unsigned Align = std::min(Alignment1, Alignment2);
Reid Spencere0fc4df2006-10-20 07:07:24 +00006716 if (MI->getAlignment()->getZExtValue() < Align) {
6717 MI->setAlignment(ConstantInt::get(Type::UIntTy, Align));
Chris Lattner82f2ef22006-03-06 20:18:44 +00006718 Changed = true;
6719 }
6720 } else if (isa<MemSetInst>(MI)) {
6721 unsigned Alignment = GetKnownAlignment(MI->getDest(), TD);
Reid Spencere0fc4df2006-10-20 07:07:24 +00006722 if (MI->getAlignment()->getZExtValue() < Alignment) {
6723 MI->setAlignment(ConstantInt::get(Type::UIntTy, Alignment));
Chris Lattner82f2ef22006-03-06 20:18:44 +00006724 Changed = true;
6725 }
6726 }
6727
Chris Lattnerc66b2232006-01-13 20:11:04 +00006728 if (Changed) return II;
Chris Lattner503221f2006-01-13 21:28:09 +00006729 } else {
6730 switch (II->getIntrinsicID()) {
6731 default: break;
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00006732 case Intrinsic::ppc_altivec_lvx:
6733 case Intrinsic::ppc_altivec_lvxl:
Chris Lattner36dd7c92006-04-17 22:26:56 +00006734 case Intrinsic::x86_sse_loadu_ps:
6735 case Intrinsic::x86_sse2_loadu_pd:
6736 case Intrinsic::x86_sse2_loadu_dq:
6737 // Turn PPC lvx -> load if the pointer is known aligned.
6738 // Turn X86 loadups -> load if the pointer is known aligned.
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00006739 if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
Chris Lattnere79d2492006-04-06 19:19:17 +00006740 Value *Ptr = InsertCastBefore(II->getOperand(1),
6741 PointerType::get(II->getType()), CI);
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00006742 return new LoadInst(Ptr);
6743 }
6744 break;
6745 case Intrinsic::ppc_altivec_stvx:
6746 case Intrinsic::ppc_altivec_stvxl:
6747 // Turn stvx -> store if the pointer is known aligned.
6748 if (GetKnownAlignment(II->getOperand(2), TD) >= 16) {
Chris Lattnere79d2492006-04-06 19:19:17 +00006749 const Type *OpPtrTy = PointerType::get(II->getOperand(1)->getType());
6750 Value *Ptr = InsertCastBefore(II->getOperand(2), OpPtrTy, CI);
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00006751 return new StoreInst(II->getOperand(1), Ptr);
6752 }
6753 break;
Chris Lattner36dd7c92006-04-17 22:26:56 +00006754 case Intrinsic::x86_sse_storeu_ps:
6755 case Intrinsic::x86_sse2_storeu_pd:
6756 case Intrinsic::x86_sse2_storeu_dq:
6757 case Intrinsic::x86_sse2_storel_dq:
6758 // Turn X86 storeu -> store if the pointer is known aligned.
6759 if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
6760 const Type *OpPtrTy = PointerType::get(II->getOperand(2)->getType());
6761 Value *Ptr = InsertCastBefore(II->getOperand(1), OpPtrTy, CI);
6762 return new StoreInst(II->getOperand(2), Ptr);
6763 }
6764 break;
Chris Lattner2deeaea2006-10-05 06:55:50 +00006765
6766 case Intrinsic::x86_sse_cvttss2si: {
6767 // These intrinsics only demands the 0th element of its input vector. If
6768 // we can simplify the input based on that, do so now.
6769 uint64_t UndefElts;
6770 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1,
6771 UndefElts)) {
6772 II->setOperand(1, V);
6773 return II;
6774 }
6775 break;
6776 }
6777
Chris Lattnere79d2492006-04-06 19:19:17 +00006778 case Intrinsic::ppc_altivec_vperm:
6779 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
6780 if (ConstantPacked *Mask = dyn_cast<ConstantPacked>(II->getOperand(3))) {
6781 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
6782
6783 // Check that all of the elements are integer constants or undefs.
6784 bool AllEltsOk = true;
6785 for (unsigned i = 0; i != 16; ++i) {
6786 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
6787 !isa<UndefValue>(Mask->getOperand(i))) {
6788 AllEltsOk = false;
6789 break;
6790 }
6791 }
6792
6793 if (AllEltsOk) {
6794 // Cast the input vectors to byte vectors.
6795 Value *Op0 = InsertCastBefore(II->getOperand(1), Mask->getType(), CI);
6796 Value *Op1 = InsertCastBefore(II->getOperand(2), Mask->getType(), CI);
6797 Value *Result = UndefValue::get(Op0->getType());
6798
6799 // Only extract each element once.
6800 Value *ExtractedElts[32];
6801 memset(ExtractedElts, 0, sizeof(ExtractedElts));
6802
6803 for (unsigned i = 0; i != 16; ++i) {
6804 if (isa<UndefValue>(Mask->getOperand(i)))
6805 continue;
Reid Spencere0fc4df2006-10-20 07:07:24 +00006806 unsigned Idx =cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
Chris Lattnere79d2492006-04-06 19:19:17 +00006807 Idx &= 31; // Match the hardware behavior.
6808
6809 if (ExtractedElts[Idx] == 0) {
6810 Instruction *Elt =
Chris Lattner2deeaea2006-10-05 06:55:50 +00006811 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
Chris Lattnere79d2492006-04-06 19:19:17 +00006812 InsertNewInstBefore(Elt, CI);
6813 ExtractedElts[Idx] = Elt;
6814 }
6815
6816 // Insert this value into the result vector.
Chris Lattner2deeaea2006-10-05 06:55:50 +00006817 Result = new InsertElementInst(Result, ExtractedElts[Idx], i,"tmp");
Chris Lattnere79d2492006-04-06 19:19:17 +00006818 InsertNewInstBefore(cast<Instruction>(Result), CI);
6819 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006820 return CastInst::create(Instruction::BitCast, Result, CI.getType());
Chris Lattnere79d2492006-04-06 19:19:17 +00006821 }
6822 }
6823 break;
6824
Chris Lattner503221f2006-01-13 21:28:09 +00006825 case Intrinsic::stackrestore: {
6826 // If the save is right next to the restore, remove the restore. This can
6827 // happen when variable allocas are DCE'd.
6828 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
6829 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
6830 BasicBlock::iterator BI = SS;
6831 if (&*++BI == II)
6832 return EraseInstFromFunction(CI);
6833 }
6834 }
6835
6836 // If the stack restore is in a return/unwind block and if there are no
6837 // allocas or calls between the restore and the return, nuke the restore.
6838 TerminatorInst *TI = II->getParent()->getTerminator();
6839 if (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)) {
6840 BasicBlock::iterator BI = II;
6841 bool CannotRemove = false;
6842 for (++BI; &*BI != TI; ++BI) {
6843 if (isa<AllocaInst>(BI) ||
6844 (isa<CallInst>(BI) && !isa<IntrinsicInst>(BI))) {
6845 CannotRemove = true;
6846 break;
6847 }
6848 }
6849 if (!CannotRemove)
6850 return EraseInstFromFunction(CI);
6851 }
6852 break;
6853 }
6854 }
Chris Lattner00648e12004-10-12 04:52:52 +00006855 }
6856
Chris Lattnerc66b2232006-01-13 20:11:04 +00006857 return visitCallSite(II);
Chris Lattner970c33a2003-06-19 17:00:31 +00006858}
6859
6860// InvokeInst simplification
6861//
6862Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattneraec3d942003-10-07 22:32:43 +00006863 return visitCallSite(&II);
Chris Lattner970c33a2003-06-19 17:00:31 +00006864}
6865
Chris Lattneraec3d942003-10-07 22:32:43 +00006866// visitCallSite - Improvements for call and invoke instructions.
6867//
6868Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner75b4d1d2003-10-07 22:54:13 +00006869 bool Changed = false;
6870
6871 // If the callee is a constexpr cast of a function, attempt to move the cast
6872 // to the arguments of the call/invoke.
Chris Lattneraec3d942003-10-07 22:32:43 +00006873 if (transformConstExprCastCall(CS)) return 0;
6874
Chris Lattner75b4d1d2003-10-07 22:54:13 +00006875 Value *Callee = CS.getCalledValue();
Chris Lattner81a7a232004-10-16 18:11:37 +00006876
Chris Lattner61d9d812005-05-13 07:09:09 +00006877 if (Function *CalleeF = dyn_cast<Function>(Callee))
6878 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
6879 Instruction *OldCall = CS.getInstruction();
6880 // If the call and callee calling conventions don't match, this call must
6881 // be unreachable, as the call is undefined.
Chris Lattner6ab03f62006-09-28 23:35:22 +00006882 new StoreInst(ConstantBool::getTrue(),
Chris Lattner61d9d812005-05-13 07:09:09 +00006883 UndefValue::get(PointerType::get(Type::BoolTy)), OldCall);
6884 if (!OldCall->use_empty())
6885 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
6886 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
6887 return EraseInstFromFunction(*OldCall);
6888 return 0;
6889 }
6890
Chris Lattner8ba9ec92004-10-18 02:59:09 +00006891 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
6892 // This instruction is not reachable, just remove it. We insert a store to
6893 // undef so that we know that this code is not reachable, despite the fact
6894 // that we can't modify the CFG here.
Chris Lattner6ab03f62006-09-28 23:35:22 +00006895 new StoreInst(ConstantBool::getTrue(),
Chris Lattner8ba9ec92004-10-18 02:59:09 +00006896 UndefValue::get(PointerType::get(Type::BoolTy)),
6897 CS.getInstruction());
6898
6899 if (!CS.getInstruction()->use_empty())
6900 CS.getInstruction()->
6901 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
6902
6903 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
6904 // Don't break the CFG, insert a dummy cond branch.
6905 new BranchInst(II->getNormalDest(), II->getUnwindDest(),
Chris Lattner6ab03f62006-09-28 23:35:22 +00006906 ConstantBool::getTrue(), II);
Chris Lattner81a7a232004-10-16 18:11:37 +00006907 }
Chris Lattner8ba9ec92004-10-18 02:59:09 +00006908 return EraseInstFromFunction(*CS.getInstruction());
6909 }
Chris Lattner81a7a232004-10-16 18:11:37 +00006910
Chris Lattner75b4d1d2003-10-07 22:54:13 +00006911 const PointerType *PTy = cast<PointerType>(Callee->getType());
6912 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
6913 if (FTy->isVarArg()) {
6914 // See if we can optimize any arguments passed through the varargs area of
6915 // the call.
6916 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
6917 E = CS.arg_end(); I != E; ++I)
6918 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
6919 // If this cast does not effect the value passed through the varargs
6920 // area, we can eliminate the use of the cast.
6921 Value *Op = CI->getOperand(0);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006922 if (CI->isLosslessCast()) {
Chris Lattner75b4d1d2003-10-07 22:54:13 +00006923 *I = Op;
6924 Changed = true;
6925 }
6926 }
6927 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00006928
Chris Lattner75b4d1d2003-10-07 22:54:13 +00006929 return Changed ? CS.getInstruction() : 0;
Chris Lattneraec3d942003-10-07 22:32:43 +00006930}
6931
Chris Lattner970c33a2003-06-19 17:00:31 +00006932// transformConstExprCastCall - If the callee is a constexpr cast of a function,
6933// attempt to move the cast to the arguments of the call/invoke.
6934//
6935bool InstCombiner::transformConstExprCastCall(CallSite CS) {
6936 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
6937 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006938 if (CE->getOpcode() != Instruction::BitCast ||
6939 !isa<Function>(CE->getOperand(0)))
Chris Lattner970c33a2003-06-19 17:00:31 +00006940 return false;
Reid Spencer87436872004-07-18 00:38:32 +00006941 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner970c33a2003-06-19 17:00:31 +00006942 Instruction *Caller = CS.getInstruction();
6943
6944 // Okay, this is a cast from a function to a different type. Unless doing so
6945 // would cause a type conversion of one of our arguments, change this call to
6946 // be a direct call with arguments casted to the appropriate types.
6947 //
6948 const FunctionType *FT = Callee->getFunctionType();
6949 const Type *OldRetTy = Caller->getType();
6950
Chris Lattner1f7942f2004-01-14 06:06:08 +00006951 // Check to see if we are changing the return type...
6952 if (OldRetTy != FT->getReturnType()) {
6953 if (Callee->isExternal() &&
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006954 !Caller->use_empty() &&
6955 !(OldRetTy->canLosslesslyBitCastTo(FT->getReturnType()) ||
Andrew Lenharth61eae292006-04-20 14:56:47 +00006956 (isa<PointerType>(FT->getReturnType()) &&
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006957 TD->getIntPtrType()->canLosslesslyBitCastTo(OldRetTy)))
6958 )
Chris Lattner1f7942f2004-01-14 06:06:08 +00006959 return false; // Cannot transform this return value...
6960
6961 // If the callsite is an invoke instruction, and the return value is used by
6962 // a PHI node in a successor, we cannot change the return type of the call
6963 // because there is no place to put the cast instruction (without breaking
6964 // the critical edge). Bail out in this case.
6965 if (!Caller->use_empty())
6966 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
6967 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
6968 UI != E; ++UI)
6969 if (PHINode *PN = dyn_cast<PHINode>(*UI))
6970 if (PN->getParent() == II->getNormalDest() ||
Chris Lattnerfae8ab32004-02-08 21:44:31 +00006971 PN->getParent() == II->getUnwindDest())
Chris Lattner1f7942f2004-01-14 06:06:08 +00006972 return false;
6973 }
Chris Lattner970c33a2003-06-19 17:00:31 +00006974
6975 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
6976 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanb1c93172005-04-21 23:48:37 +00006977
Chris Lattner970c33a2003-06-19 17:00:31 +00006978 CallSite::arg_iterator AI = CS.arg_begin();
6979 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
6980 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthebfa24e2006-06-28 01:01:52 +00006981 const Type *ActTy = (*AI)->getType();
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006982 ConstantInt *c = dyn_cast<ConstantInt>(*AI);
Andrew Lenharthebfa24e2006-06-28 01:01:52 +00006983 //Either we can cast directly, or we can upconvert the argument
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006984 bool isConvertible = ActTy->canLosslesslyBitCastTo(ParamTy) ||
Andrew Lenharthebfa24e2006-06-28 01:01:52 +00006985 (ParamTy->isIntegral() && ActTy->isIntegral() &&
6986 ParamTy->isSigned() == ActTy->isSigned() &&
6987 ParamTy->getPrimitiveSize() >= ActTy->getPrimitiveSize()) ||
6988 (c && ParamTy->getPrimitiveSize() >= ActTy->getPrimitiveSize() &&
Reid Spencere0fc4df2006-10-20 07:07:24 +00006989 c->getSExtValue() > 0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00006990 if (Callee->isExternal() && !isConvertible) return false;
Chris Lattner970c33a2003-06-19 17:00:31 +00006991 }
6992
6993 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
6994 Callee->isExternal())
6995 return false; // Do not delete arguments unless we have a function body...
6996
6997 // Okay, we decided that this is a safe thing to do: go ahead and start
6998 // inserting cast instructions as necessary...
6999 std::vector<Value*> Args;
7000 Args.reserve(NumActualArgs);
7001
7002 AI = CS.arg_begin();
7003 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
7004 const Type *ParamTy = FT->getParamType(i);
7005 if ((*AI)->getType() == ParamTy) {
7006 Args.push_back(*AI);
7007 } else {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007008 CastInst *NewCast = CastInst::createInferredCast(*AI, ParamTy, "tmp");
7009 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
Chris Lattner970c33a2003-06-19 17:00:31 +00007010 }
7011 }
7012
7013 // If the function takes more arguments than the call was taking, add them
7014 // now...
7015 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
7016 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
7017
7018 // If we are removing arguments to the function, emit an obnoxious warning...
7019 if (FT->getNumParams() < NumActualArgs)
7020 if (!FT->isVarArg()) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +00007021 llvm_cerr << "WARNING: While resolving call to function '"
Chris Lattner970c33a2003-06-19 17:00:31 +00007022 << Callee->getName() << "' arguments were dropped!\n";
7023 } else {
7024 // Add all of the arguments in their promoted form to the arg list...
7025 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
7026 const Type *PTy = getPromotedType((*AI)->getType());
7027 if (PTy != (*AI)->getType()) {
7028 // Must promote to pass through va_arg area!
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007029 Instruction *Cast = CastInst::createInferredCast(*AI, PTy, "tmp");
Chris Lattner970c33a2003-06-19 17:00:31 +00007030 InsertNewInstBefore(Cast, *Caller);
7031 Args.push_back(Cast);
7032 } else {
7033 Args.push_back(*AI);
7034 }
7035 }
7036 }
7037
7038 if (FT->getReturnType() == Type::VoidTy)
7039 Caller->setName(""); // Void type should not have a name...
7040
7041 Instruction *NC;
7042 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Chris Lattnerfae8ab32004-02-08 21:44:31 +00007043 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
Chris Lattner970c33a2003-06-19 17:00:31 +00007044 Args, Caller->getName(), Caller);
Chris Lattner05c703e2005-05-14 12:25:32 +00007045 cast<InvokeInst>(II)->setCallingConv(II->getCallingConv());
Chris Lattner970c33a2003-06-19 17:00:31 +00007046 } else {
7047 NC = new CallInst(Callee, Args, Caller->getName(), Caller);
Chris Lattner6aacb0f2005-05-06 06:48:21 +00007048 if (cast<CallInst>(Caller)->isTailCall())
7049 cast<CallInst>(NC)->setTailCall();
Chris Lattner05c703e2005-05-14 12:25:32 +00007050 cast<CallInst>(NC)->setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Chris Lattner970c33a2003-06-19 17:00:31 +00007051 }
7052
7053 // Insert a cast of the return type as necessary...
7054 Value *NV = NC;
7055 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
7056 if (NV->getType() != Type::VoidTy) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007057 NV = NC = CastInst::createInferredCast(NC, Caller->getType(), "tmp");
Chris Lattner686767f2003-10-30 00:46:41 +00007058
7059 // If this is an invoke instruction, we should insert it after the first
7060 // non-phi, instruction in the normal successor block.
7061 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
7062 BasicBlock::iterator I = II->getNormalDest()->begin();
7063 while (isa<PHINode>(I)) ++I;
7064 InsertNewInstBefore(NC, *I);
7065 } else {
7066 // Otherwise, it's a call, just insert cast right after the call instr
7067 InsertNewInstBefore(NC, *Caller);
7068 }
Chris Lattner51ea1272004-02-28 05:22:00 +00007069 AddUsersToWorkList(*Caller);
Chris Lattner970c33a2003-06-19 17:00:31 +00007070 } else {
Chris Lattnere29d6342004-10-17 21:22:38 +00007071 NV = UndefValue::get(Caller->getType());
Chris Lattner970c33a2003-06-19 17:00:31 +00007072 }
7073 }
7074
7075 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
7076 Caller->replaceAllUsesWith(NV);
7077 Caller->getParent()->getInstList().erase(Caller);
7078 removeFromWorkList(Caller);
7079 return true;
7080}
7081
Chris Lattnercadac0c2006-11-01 04:51:18 +00007082/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
7083/// and if a/b/c/d and the add's all have a single use, turn this into two phi's
7084/// and a single binop.
7085Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
7086 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Chris Lattnereebea432006-11-01 07:43:41 +00007087 assert(isa<BinaryOperator>(FirstInst) || isa<ShiftInst>(FirstInst) ||
7088 isa<GetElementPtrInst>(FirstInst));
Chris Lattnercadac0c2006-11-01 04:51:18 +00007089 unsigned Opc = FirstInst->getOpcode();
Chris Lattnercd62f112006-11-08 19:29:23 +00007090 Value *LHSVal = FirstInst->getOperand(0);
7091 Value *RHSVal = FirstInst->getOperand(1);
7092
7093 const Type *LHSType = LHSVal->getType();
7094 const Type *RHSType = RHSVal->getType();
Chris Lattnercadac0c2006-11-01 04:51:18 +00007095
7096 // Scan to see if all operands are the same opcode, all have one use, and all
7097 // kill their operands (i.e. the operands have one use).
Chris Lattnerdc826fc2006-11-01 04:55:47 +00007098 for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
Chris Lattnercadac0c2006-11-01 04:51:18 +00007099 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Chris Lattnerdc826fc2006-11-01 04:55:47 +00007100 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
7101 // Verify type of the LHS matches so we don't fold setcc's of different
Chris Lattnereebea432006-11-01 07:43:41 +00007102 // types or GEP's with different index types.
7103 I->getOperand(0)->getType() != LHSType ||
7104 I->getOperand(1)->getType() != RHSType)
Chris Lattnercadac0c2006-11-01 04:51:18 +00007105 return 0;
Chris Lattnercd62f112006-11-08 19:29:23 +00007106
7107 // Keep track of which operand needs a phi node.
7108 if (I->getOperand(0) != LHSVal) LHSVal = 0;
7109 if (I->getOperand(1) != RHSVal) RHSVal = 0;
Chris Lattnercadac0c2006-11-01 04:51:18 +00007110 }
7111
Chris Lattner4f218d52006-11-08 19:42:28 +00007112 // Otherwise, this is safe to transform, determine if it is profitable.
7113
7114 // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
7115 // Indexes are often folded into load/store instructions, so we don't want to
7116 // hide them behind a phi.
7117 if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
7118 return 0;
7119
Chris Lattnercadac0c2006-11-01 04:51:18 +00007120 Value *InLHS = FirstInst->getOperand(0);
Chris Lattnercadac0c2006-11-01 04:51:18 +00007121 Value *InRHS = FirstInst->getOperand(1);
Chris Lattner4f218d52006-11-08 19:42:28 +00007122 PHINode *NewLHS = 0, *NewRHS = 0;
Chris Lattnercd62f112006-11-08 19:29:23 +00007123 if (LHSVal == 0) {
7124 NewLHS = new PHINode(LHSType, FirstInst->getOperand(0)->getName()+".pn");
7125 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
7126 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
Chris Lattnereebea432006-11-01 07:43:41 +00007127 InsertNewInstBefore(NewLHS, PN);
7128 LHSVal = NewLHS;
7129 }
Chris Lattnercd62f112006-11-08 19:29:23 +00007130
7131 if (RHSVal == 0) {
7132 NewRHS = new PHINode(RHSType, FirstInst->getOperand(1)->getName()+".pn");
7133 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
7134 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
Chris Lattnereebea432006-11-01 07:43:41 +00007135 InsertNewInstBefore(NewRHS, PN);
7136 RHSVal = NewRHS;
7137 }
7138
Chris Lattnercd62f112006-11-08 19:29:23 +00007139 // Add all operands to the new PHIs.
7140 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7141 if (NewLHS) {
7142 Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
7143 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
7144 }
7145 if (NewRHS) {
7146 Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
7147 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
7148 }
7149 }
7150
Chris Lattnercadac0c2006-11-01 04:51:18 +00007151 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattnereebea432006-11-01 07:43:41 +00007152 return BinaryOperator::create(BinOp->getOpcode(), LHSVal, RHSVal);
7153 else if (ShiftInst *SI = dyn_cast<ShiftInst>(FirstInst))
7154 return new ShiftInst(SI->getOpcode(), LHSVal, RHSVal);
7155 else {
7156 assert(isa<GetElementPtrInst>(FirstInst));
7157 return new GetElementPtrInst(LHSVal, RHSVal);
7158 }
Chris Lattnercadac0c2006-11-01 04:51:18 +00007159}
7160
Chris Lattner14f82c72006-11-01 07:13:54 +00007161/// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
7162/// of the block that defines it. This means that it must be obvious the value
7163/// of the load is not changed from the point of the load to the end of the
7164/// block it is in.
7165static bool isSafeToSinkLoad(LoadInst *L) {
7166 BasicBlock::iterator BBI = L, E = L->getParent()->end();
7167
7168 for (++BBI; BBI != E; ++BBI)
7169 if (BBI->mayWriteToMemory())
7170 return false;
7171 return true;
7172}
7173
Chris Lattner970c33a2003-06-19 17:00:31 +00007174
Chris Lattner7515cab2004-11-14 19:13:23 +00007175// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
7176// operator and they all are only used by the PHI, PHI together their
7177// inputs, and do the operation once, to the result of the PHI.
7178Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
7179 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
7180
7181 // Scan the instruction, looking for input operations that can be folded away.
7182 // If all input operands to the phi are the same instruction (e.g. a cast from
7183 // the same type or "+42") we can pull the operation through the PHI, reducing
7184 // code size and simplifying code.
7185 Constant *ConstantOp = 0;
7186 const Type *CastSrcTy = 0;
Chris Lattner14f82c72006-11-01 07:13:54 +00007187 bool isVolatile = false;
Chris Lattner7515cab2004-11-14 19:13:23 +00007188 if (isa<CastInst>(FirstInst)) {
7189 CastSrcTy = FirstInst->getOperand(0)->getType();
7190 } else if (isa<BinaryOperator>(FirstInst) || isa<ShiftInst>(FirstInst)) {
Chris Lattnercadac0c2006-11-01 04:51:18 +00007191 // Can fold binop or shift here if the RHS is a constant, otherwise call
7192 // FoldPHIArgBinOpIntoPHI.
Chris Lattner7515cab2004-11-14 19:13:23 +00007193 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Chris Lattnercadac0c2006-11-01 04:51:18 +00007194 if (ConstantOp == 0)
7195 return FoldPHIArgBinOpIntoPHI(PN);
Chris Lattner14f82c72006-11-01 07:13:54 +00007196 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
7197 isVolatile = LI->isVolatile();
7198 // We can't sink the load if the loaded value could be modified between the
7199 // load and the PHI.
7200 if (LI->getParent() != PN.getIncomingBlock(0) ||
7201 !isSafeToSinkLoad(LI))
7202 return 0;
Chris Lattnereebea432006-11-01 07:43:41 +00007203 } else if (isa<GetElementPtrInst>(FirstInst)) {
Chris Lattner4f218d52006-11-08 19:42:28 +00007204 if (FirstInst->getNumOperands() == 2)
Chris Lattnereebea432006-11-01 07:43:41 +00007205 return FoldPHIArgBinOpIntoPHI(PN);
7206 // Can't handle general GEPs yet.
7207 return 0;
Chris Lattner7515cab2004-11-14 19:13:23 +00007208 } else {
7209 return 0; // Cannot fold this operation.
7210 }
7211
7212 // Check to see if all arguments are the same operation.
7213 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7214 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
7215 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
7216 if (!I->hasOneUse() || I->getOpcode() != FirstInst->getOpcode())
7217 return 0;
7218 if (CastSrcTy) {
7219 if (I->getOperand(0)->getType() != CastSrcTy)
7220 return 0; // Cast operation must match.
Chris Lattner14f82c72006-11-01 07:13:54 +00007221 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
7222 // We can't sink the load if the loaded value could be modified between the
7223 // load and the PHI.
7224 if (LI->isVolatile() != isVolatile ||
7225 LI->getParent() != PN.getIncomingBlock(i) ||
7226 !isSafeToSinkLoad(LI))
7227 return 0;
Chris Lattner7515cab2004-11-14 19:13:23 +00007228 } else if (I->getOperand(1) != ConstantOp) {
7229 return 0;
7230 }
7231 }
7232
7233 // Okay, they are all the same operation. Create a new PHI node of the
7234 // correct type, and PHI together all of the LHS's of the instructions.
7235 PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
7236 PN.getName()+".in");
Chris Lattnerd8e20182005-01-29 00:39:08 +00007237 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattner46dd5a62004-11-14 19:29:34 +00007238
7239 Value *InVal = FirstInst->getOperand(0);
7240 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattner7515cab2004-11-14 19:13:23 +00007241
7242 // Add all operands to the new PHI.
Chris Lattner46dd5a62004-11-14 19:29:34 +00007243 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7244 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
7245 if (NewInVal != InVal)
7246 InVal = 0;
7247 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
7248 }
7249
7250 Value *PhiVal;
7251 if (InVal) {
7252 // The new PHI unions all of the same values together. This is really
7253 // common, so we handle it intelligently here for compile-time speed.
7254 PhiVal = InVal;
7255 delete NewPN;
7256 } else {
7257 InsertNewInstBefore(NewPN, PN);
7258 PhiVal = NewPN;
7259 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00007260
Chris Lattner7515cab2004-11-14 19:13:23 +00007261 // Insert and return the new operation.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007262 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
7263 return CastInst::create(FirstCI->getOpcode(), PhiVal, PN.getType());
Reid Spencerde46e482006-11-02 20:25:50 +00007264 else if (isa<LoadInst>(FirstInst))
Chris Lattner14f82c72006-11-01 07:13:54 +00007265 return new LoadInst(PhiVal, "", isVolatile);
Chris Lattner7515cab2004-11-14 19:13:23 +00007266 else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattner46dd5a62004-11-14 19:29:34 +00007267 return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattner7515cab2004-11-14 19:13:23 +00007268 else
7269 return new ShiftInst(cast<ShiftInst>(FirstInst)->getOpcode(),
Chris Lattner46dd5a62004-11-14 19:29:34 +00007270 PhiVal, ConstantOp);
Chris Lattner7515cab2004-11-14 19:13:23 +00007271}
Chris Lattner48a44f72002-05-02 17:06:02 +00007272
Chris Lattner71536432005-01-17 05:10:15 +00007273/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
7274/// that is dead.
7275static bool DeadPHICycle(PHINode *PN, std::set<PHINode*> &PotentiallyDeadPHIs) {
7276 if (PN->use_empty()) return true;
7277 if (!PN->hasOneUse()) return false;
7278
7279 // Remember this node, and if we find the cycle, return.
7280 if (!PotentiallyDeadPHIs.insert(PN).second)
7281 return true;
7282
7283 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
7284 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanb1c93172005-04-21 23:48:37 +00007285
Chris Lattner71536432005-01-17 05:10:15 +00007286 return false;
7287}
7288
Chris Lattnerbbbdd852002-05-06 18:06:38 +00007289// PHINode simplification
7290//
Chris Lattner113f4f42002-06-25 16:13:24 +00007291Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonbbf89902006-07-10 22:15:25 +00007292 // If LCSSA is around, don't mess with Phi nodes
7293 if (mustPreserveAnalysisID(LCSSAID)) return 0;
Owen Andersona6968f82006-07-10 19:03:49 +00007294
Owen Andersonae8aa642006-07-10 22:03:18 +00007295 if (Value *V = PN.hasConstantValue())
7296 return ReplaceInstUsesWith(PN, V);
7297
Owen Andersonae8aa642006-07-10 22:03:18 +00007298 // If all PHI operands are the same operation, pull them through the PHI,
7299 // reducing code size.
7300 if (isa<Instruction>(PN.getIncomingValue(0)) &&
7301 PN.getIncomingValue(0)->hasOneUse())
7302 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
7303 return Result;
7304
7305 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
7306 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
7307 // PHI)... break the cycle.
7308 if (PN.hasOneUse())
7309 if (PHINode *PU = dyn_cast<PHINode>(PN.use_back())) {
7310 std::set<PHINode*> PotentiallyDeadPHIs;
7311 PotentiallyDeadPHIs.insert(&PN);
7312 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
7313 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
7314 }
7315
Chris Lattner91daeb52003-12-19 05:58:40 +00007316 return 0;
Chris Lattnerbbbdd852002-05-06 18:06:38 +00007317}
7318
Chris Lattner69193f92004-04-05 01:30:19 +00007319static Value *InsertSignExtendToPtrTy(Value *V, const Type *DTy,
7320 Instruction *InsertPoint,
7321 InstCombiner *IC) {
7322 unsigned PS = IC->getTargetData().getPointerSize();
7323 const Type *VTy = V->getType();
Chris Lattner69193f92004-04-05 01:30:19 +00007324 if (!VTy->isSigned() && VTy->getPrimitiveSize() < PS)
7325 // We must insert a cast to ensure we sign-extend.
Reid Spencer00c482b2006-10-26 19:19:06 +00007326 V = IC->InsertCastBefore(V, VTy->getSignedVersion(), *InsertPoint);
7327 return IC->InsertCastBefore(V, DTy, *InsertPoint);
Chris Lattner69193f92004-04-05 01:30:19 +00007328}
7329
Chris Lattner48a44f72002-05-02 17:06:02 +00007330
Chris Lattner113f4f42002-06-25 16:13:24 +00007331Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner5f667a62004-05-07 22:09:22 +00007332 Value *PtrOp = GEP.getOperand(0);
Chris Lattner471bd762003-05-22 19:07:21 +00007333 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
Chris Lattner113f4f42002-06-25 16:13:24 +00007334 // If so, eliminate the noop.
Chris Lattner8d0bacb2004-02-22 05:25:17 +00007335 if (GEP.getNumOperands() == 1)
Chris Lattner5f667a62004-05-07 22:09:22 +00007336 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner8d0bacb2004-02-22 05:25:17 +00007337
Chris Lattner81a7a232004-10-16 18:11:37 +00007338 if (isa<UndefValue>(GEP.getOperand(0)))
7339 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
7340
Chris Lattner8d0bacb2004-02-22 05:25:17 +00007341 bool HasZeroPointerIndex = false;
7342 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
7343 HasZeroPointerIndex = C->isNullValue();
7344
7345 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner5f667a62004-05-07 22:09:22 +00007346 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner48a44f72002-05-02 17:06:02 +00007347
Chris Lattner69193f92004-04-05 01:30:19 +00007348 // Eliminate unneeded casts for indices.
7349 bool MadeChange = false;
Chris Lattner2b2412d2004-04-07 18:38:20 +00007350 gep_type_iterator GTI = gep_type_begin(GEP);
7351 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI)
7352 if (isa<SequentialType>(*GTI)) {
7353 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
7354 Value *Src = CI->getOperand(0);
7355 const Type *SrcTy = Src->getType();
7356 const Type *DestTy = CI->getType();
7357 if (Src->getType()->isInteger()) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00007358 if (SrcTy->getPrimitiveSizeInBits() ==
7359 DestTy->getPrimitiveSizeInBits()) {
Chris Lattner2b2412d2004-04-07 18:38:20 +00007360 // We can always eliminate a cast from ulong or long to the other.
7361 // We can always eliminate a cast from uint to int or the other on
7362 // 32-bit pointer platforms.
Chris Lattnerd1f46d32005-04-24 06:59:08 +00007363 if (DestTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()){
Chris Lattner2b2412d2004-04-07 18:38:20 +00007364 MadeChange = true;
7365 GEP.setOperand(i, Src);
7366 }
7367 } else if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
7368 SrcTy->getPrimitiveSize() == 4) {
7369 // We can always eliminate a cast from int to [u]long. We can
7370 // eliminate a cast from uint to [u]long iff the target is a 32-bit
7371 // pointer target.
Misha Brukmanb1c93172005-04-21 23:48:37 +00007372 if (SrcTy->isSigned() ||
Chris Lattnerd1f46d32005-04-24 06:59:08 +00007373 SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
Chris Lattner2b2412d2004-04-07 18:38:20 +00007374 MadeChange = true;
7375 GEP.setOperand(i, Src);
7376 }
Chris Lattner69193f92004-04-05 01:30:19 +00007377 }
7378 }
7379 }
Chris Lattner2b2412d2004-04-07 18:38:20 +00007380 // If we are using a wider index than needed for this platform, shrink it
7381 // to what we need. If the incoming value needs a cast instruction,
7382 // insert it. This explicit cast can make subsequent optimizations more
7383 // obvious.
7384 Value *Op = GEP.getOperand(i);
7385 if (Op->getType()->getPrimitiveSize() > TD->getPointerSize())
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00007386 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner44d0b952004-07-20 01:48:15 +00007387 GEP.setOperand(i, ConstantExpr::getCast(C,
7388 TD->getIntPtrType()->getSignedVersion()));
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00007389 MadeChange = true;
7390 } else {
Reid Spencer00c482b2006-10-26 19:19:06 +00007391 Op = InsertCastBefore(Op, TD->getIntPtrType(), GEP);
Chris Lattner2b2412d2004-04-07 18:38:20 +00007392 GEP.setOperand(i, Op);
7393 MadeChange = true;
7394 }
Chris Lattner44d0b952004-07-20 01:48:15 +00007395
7396 // If this is a constant idx, make sure to canonicalize it to be a signed
7397 // operand, otherwise CSE and other optimizations are pessimized.
Reid Spencere0fc4df2006-10-20 07:07:24 +00007398 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op))
7399 if (CUI->getType()->isUnsigned()) {
7400 GEP.setOperand(i,
7401 ConstantExpr::getCast(CUI, CUI->getType()->getSignedVersion()));
7402 MadeChange = true;
7403 }
Chris Lattner69193f92004-04-05 01:30:19 +00007404 }
7405 if (MadeChange) return &GEP;
7406
Chris Lattnerae7a0d32002-08-02 19:29:35 +00007407 // Combine Indices - If the source pointer to this getelementptr instruction
7408 // is a getelementptr instruction, combine the indices of the two
7409 // getelementptr instructions into a single instruction.
7410 //
Chris Lattner57c67b02004-03-25 22:59:29 +00007411 std::vector<Value*> SrcGEPOperands;
Chris Lattner0798af32005-01-13 20:14:25 +00007412 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattner57c67b02004-03-25 22:59:29 +00007413 SrcGEPOperands.assign(Src->op_begin(), Src->op_end());
Chris Lattner57c67b02004-03-25 22:59:29 +00007414
7415 if (!SrcGEPOperands.empty()) {
Chris Lattner5f667a62004-05-07 22:09:22 +00007416 // Note that if our source is a gep chain itself that we wait for that
7417 // chain to be resolved before we perform this transformation. This
7418 // avoids us creating a TON of code in some cases.
7419 //
7420 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
7421 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
7422 return 0; // Wait until our source is folded to completion.
7423
Chris Lattnerae7a0d32002-08-02 19:29:35 +00007424 std::vector<Value *> Indices;
Chris Lattner5f667a62004-05-07 22:09:22 +00007425
7426 // Find out whether the last index in the source GEP is a sequential idx.
7427 bool EndsWithSequential = false;
7428 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
7429 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattner8ec5f882004-05-08 22:41:42 +00007430 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00007431
Chris Lattnerae7a0d32002-08-02 19:29:35 +00007432 // Can we combine the two pointer arithmetics offsets?
Chris Lattner5f667a62004-05-07 22:09:22 +00007433 if (EndsWithSequential) {
Chris Lattner235af562003-03-05 22:33:14 +00007434 // Replace: gep (gep %P, long B), long A, ...
7435 // With: T = long A+B; gep %P, T, ...
7436 //
Chris Lattner5f667a62004-05-07 22:09:22 +00007437 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner69193f92004-04-05 01:30:19 +00007438 if (SO1 == Constant::getNullValue(SO1->getType())) {
7439 Sum = GO1;
7440 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
7441 Sum = SO1;
7442 } else {
7443 // If they aren't the same type, convert both to an integer of the
7444 // target's pointer size.
7445 if (SO1->getType() != GO1->getType()) {
7446 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
7447 SO1 = ConstantExpr::getCast(SO1C, GO1->getType());
7448 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
7449 GO1 = ConstantExpr::getCast(GO1C, SO1->getType());
7450 } else {
7451 unsigned PS = TD->getPointerSize();
Chris Lattner69193f92004-04-05 01:30:19 +00007452 if (SO1->getType()->getPrimitiveSize() == PS) {
7453 // Convert GO1 to SO1's type.
7454 GO1 = InsertSignExtendToPtrTy(GO1, SO1->getType(), &GEP, this);
7455
7456 } else if (GO1->getType()->getPrimitiveSize() == PS) {
7457 // Convert SO1 to GO1's type.
7458 SO1 = InsertSignExtendToPtrTy(SO1, GO1->getType(), &GEP, this);
7459 } else {
7460 const Type *PT = TD->getIntPtrType();
7461 SO1 = InsertSignExtendToPtrTy(SO1, PT, &GEP, this);
7462 GO1 = InsertSignExtendToPtrTy(GO1, PT, &GEP, this);
7463 }
7464 }
7465 }
Chris Lattner5f667a62004-05-07 22:09:22 +00007466 if (isa<Constant>(SO1) && isa<Constant>(GO1))
7467 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
7468 else {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00007469 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
7470 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner5f667a62004-05-07 22:09:22 +00007471 }
Chris Lattner69193f92004-04-05 01:30:19 +00007472 }
Chris Lattner5f667a62004-05-07 22:09:22 +00007473
7474 // Recycle the GEP we already have if possible.
7475 if (SrcGEPOperands.size() == 2) {
7476 GEP.setOperand(0, SrcGEPOperands[0]);
7477 GEP.setOperand(1, Sum);
7478 return &GEP;
7479 } else {
7480 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
7481 SrcGEPOperands.end()-1);
7482 Indices.push_back(Sum);
7483 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
7484 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00007485 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner69193f92004-04-05 01:30:19 +00007486 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00007487 SrcGEPOperands.size() != 1) {
Chris Lattnerae7a0d32002-08-02 19:29:35 +00007488 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattner57c67b02004-03-25 22:59:29 +00007489 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
7490 SrcGEPOperands.end());
Chris Lattnerae7a0d32002-08-02 19:29:35 +00007491 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
7492 }
7493
7494 if (!Indices.empty())
Chris Lattner57c67b02004-03-25 22:59:29 +00007495 return new GetElementPtrInst(SrcGEPOperands[0], Indices, GEP.getName());
Chris Lattnerc59af1d2002-08-17 22:21:59 +00007496
Chris Lattner5f667a62004-05-07 22:09:22 +00007497 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattnerc59af1d2002-08-17 22:21:59 +00007498 // GEP of global variable. If all of the indices for this GEP are
7499 // constants, we can promote this to a constexpr instead of an instruction.
7500
7501 // Scan for nonconstants...
7502 std::vector<Constant*> Indices;
7503 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
7504 for (; I != E && isa<Constant>(*I); ++I)
7505 Indices.push_back(cast<Constant>(*I));
7506
7507 if (I == E) { // If they are all constants...
Chris Lattnerf3edc492004-07-18 18:59:44 +00007508 Constant *CE = ConstantExpr::getGetElementPtr(GV, Indices);
Chris Lattnerc59af1d2002-08-17 22:21:59 +00007509
7510 // Replace all uses of the GEP with the new constexpr...
7511 return ReplaceInstUsesWith(GEP, CE);
7512 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007513 } else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast?
Chris Lattner567b81f2005-09-13 00:40:14 +00007514 if (!isa<PointerType>(X->getType())) {
7515 // Not interesting. Source pointer must be a cast from pointer.
7516 } else if (HasZeroPointerIndex) {
7517 // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
7518 // into : GEP [10 x ubyte]* X, long 0, ...
7519 //
7520 // This occurs when the program declares an array extern like "int X[];"
7521 //
7522 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
7523 const PointerType *XTy = cast<PointerType>(X->getType());
7524 if (const ArrayType *XATy =
7525 dyn_cast<ArrayType>(XTy->getElementType()))
7526 if (const ArrayType *CATy =
7527 dyn_cast<ArrayType>(CPTy->getElementType()))
7528 if (CATy->getElementType() == XATy->getElementType()) {
7529 // At this point, we know that the cast source type is a pointer
7530 // to an array of the same type as the destination pointer
7531 // array. Because the array type is never stepped over (there
7532 // is a leading zero) we can fold the cast into this GEP.
7533 GEP.setOperand(0, X);
7534 return &GEP;
7535 }
7536 } else if (GEP.getNumOperands() == 2) {
7537 // Transform things like:
Chris Lattner2a893292005-09-13 18:36:04 +00007538 // %t = getelementptr ubyte* cast ([2 x int]* %str to uint*), uint %V
7539 // into: %t1 = getelementptr [2 x int*]* %str, int 0, uint %V; cast
Chris Lattner567b81f2005-09-13 00:40:14 +00007540 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
7541 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
7542 if (isa<ArrayType>(SrcElTy) &&
7543 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
7544 TD->getTypeSize(ResElTy)) {
7545 Value *V = InsertNewInstBefore(
7546 new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
7547 GEP.getOperand(1), GEP.getName()), GEP);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007548 // V and GEP are both pointer types --> BitCast
7549 return new BitCastInst(V, GEP.getType());
Chris Lattner8d0bacb2004-02-22 05:25:17 +00007550 }
Chris Lattner2a893292005-09-13 18:36:04 +00007551
7552 // Transform things like:
7553 // getelementptr sbyte* cast ([100 x double]* X to sbyte*), int %tmp
7554 // (where tmp = 8*tmp2) into:
7555 // getelementptr [100 x double]* %arr, int 0, int %tmp.2
7556
7557 if (isa<ArrayType>(SrcElTy) &&
7558 (ResElTy == Type::SByteTy || ResElTy == Type::UByteTy)) {
7559 uint64_t ArrayEltSize =
7560 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType());
7561
7562 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
7563 // allow either a mul, shift, or constant here.
7564 Value *NewIdx = 0;
7565 ConstantInt *Scale = 0;
7566 if (ArrayEltSize == 1) {
7567 NewIdx = GEP.getOperand(1);
7568 Scale = ConstantInt::get(NewIdx->getType(), 1);
7569 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Chris Lattnera393e4d2005-09-14 17:32:56 +00007570 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner2a893292005-09-13 18:36:04 +00007571 Scale = CI;
7572 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
7573 if (Inst->getOpcode() == Instruction::Shl &&
7574 isa<ConstantInt>(Inst->getOperand(1))) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00007575 unsigned ShAmt =
7576 cast<ConstantInt>(Inst->getOperand(1))->getZExtValue();
Chris Lattner2a893292005-09-13 18:36:04 +00007577 if (Inst->getType()->isSigned())
Reid Spencere0fc4df2006-10-20 07:07:24 +00007578 Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmt);
Chris Lattner2a893292005-09-13 18:36:04 +00007579 else
Reid Spencere0fc4df2006-10-20 07:07:24 +00007580 Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmt);
Chris Lattner2a893292005-09-13 18:36:04 +00007581 NewIdx = Inst->getOperand(0);
7582 } else if (Inst->getOpcode() == Instruction::Mul &&
7583 isa<ConstantInt>(Inst->getOperand(1))) {
7584 Scale = cast<ConstantInt>(Inst->getOperand(1));
7585 NewIdx = Inst->getOperand(0);
7586 }
7587 }
7588
7589 // If the index will be to exactly the right offset with the scale taken
7590 // out, perform the transformation.
Reid Spencere0fc4df2006-10-20 07:07:24 +00007591 if (Scale && Scale->getZExtValue() % ArrayEltSize == 0) {
Reid Spencerde46e482006-11-02 20:25:50 +00007592 if (isa<ConstantInt>(Scale))
Reid Spencere0fc4df2006-10-20 07:07:24 +00007593 Scale = ConstantInt::get(Scale->getType(),
7594 Scale->getZExtValue() / ArrayEltSize);
7595 if (Scale->getZExtValue() != 1) {
Chris Lattner2a893292005-09-13 18:36:04 +00007596 Constant *C = ConstantExpr::getCast(Scale, NewIdx->getType());
7597 Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
7598 NewIdx = InsertNewInstBefore(Sc, GEP);
7599 }
7600
7601 // Insert the new GEP instruction.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007602 Instruction *NewGEP =
Chris Lattner2a893292005-09-13 18:36:04 +00007603 new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
7604 NewIdx, GEP.getName());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007605 NewGEP = InsertNewInstBefore(NewGEP, GEP);
7606 // The NewGEP must be pointer typed, so must the old one -> BitCast
7607 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner2a893292005-09-13 18:36:04 +00007608 }
7609 }
Chris Lattner8d0bacb2004-02-22 05:25:17 +00007610 }
Chris Lattnerca081252001-12-14 16:52:21 +00007611 }
7612
Chris Lattnerca081252001-12-14 16:52:21 +00007613 return 0;
7614}
7615
Chris Lattner1085bdf2002-11-04 16:18:53 +00007616Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
7617 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
7618 if (AI.isArrayAllocation()) // Check C != 1
Reid Spencere0fc4df2006-10-20 07:07:24 +00007619 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
7620 const Type *NewTy =
7621 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Chris Lattnera2620ac2002-11-09 00:49:43 +00007622 AllocationInst *New = 0;
Chris Lattner1085bdf2002-11-04 16:18:53 +00007623
7624 // Create and insert the replacement instruction...
7625 if (isa<MallocInst>(AI))
Nate Begeman848622f2005-11-05 09:21:28 +00007626 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00007627 else {
7628 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Nate Begeman848622f2005-11-05 09:21:28 +00007629 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00007630 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00007631
7632 InsertNewInstBefore(New, AI);
Misha Brukmanb1c93172005-04-21 23:48:37 +00007633
Chris Lattner1085bdf2002-11-04 16:18:53 +00007634 // Scan to the end of the allocation instructions, to skip over a block of
7635 // allocas if possible...
7636 //
7637 BasicBlock::iterator It = New;
7638 while (isa<AllocationInst>(*It)) ++It;
7639
7640 // Now that I is pointing to the first non-allocation-inst in the block,
7641 // insert our getelementptr instruction...
7642 //
Chris Lattner809dfac2005-05-04 19:10:26 +00007643 Value *NullIdx = Constant::getNullValue(Type::IntTy);
7644 Value *V = new GetElementPtrInst(New, NullIdx, NullIdx,
7645 New->getName()+".sub", It);
Chris Lattner1085bdf2002-11-04 16:18:53 +00007646
7647 // Now make everything use the getelementptr instead of the original
7648 // allocation.
Chris Lattnerabb77c92004-03-19 06:08:10 +00007649 return ReplaceInstUsesWith(AI, V);
Chris Lattner81a7a232004-10-16 18:11:37 +00007650 } else if (isa<UndefValue>(AI.getArraySize())) {
7651 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner1085bdf2002-11-04 16:18:53 +00007652 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00007653
7654 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
7655 // Note that we only do this for alloca's, because malloc should allocate and
7656 // return a unique pointer, even for a zero byte allocation.
Misha Brukmanb1c93172005-04-21 23:48:37 +00007657 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
Chris Lattner49df6ce2004-07-02 22:55:47 +00007658 TD->getTypeSize(AI.getAllocatedType()) == 0)
Chris Lattnerabb77c92004-03-19 06:08:10 +00007659 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
7660
Chris Lattner1085bdf2002-11-04 16:18:53 +00007661 return 0;
7662}
7663
Chris Lattner8427bff2003-12-07 01:24:23 +00007664Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
7665 Value *Op = FI.getOperand(0);
7666
7667 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
7668 if (CastInst *CI = dyn_cast<CastInst>(Op))
7669 if (isa<PointerType>(CI->getOperand(0)->getType())) {
7670 FI.setOperand(0, CI->getOperand(0));
7671 return &FI;
7672 }
7673
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007674 // free undef -> unreachable.
7675 if (isa<UndefValue>(Op)) {
7676 // Insert a new store to null because we cannot modify the CFG here.
Chris Lattner6ab03f62006-09-28 23:35:22 +00007677 new StoreInst(ConstantBool::getTrue(),
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007678 UndefValue::get(PointerType::get(Type::BoolTy)), &FI);
7679 return EraseInstFromFunction(FI);
7680 }
7681
Chris Lattnerf3a36602004-02-28 04:57:37 +00007682 // If we have 'free null' delete the instruction. This can happen in stl code
7683 // when lots of inlining happens.
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007684 if (isa<ConstantPointerNull>(Op))
Chris Lattner51ea1272004-02-28 05:22:00 +00007685 return EraseInstFromFunction(FI);
Chris Lattnerf3a36602004-02-28 04:57:37 +00007686
Chris Lattner8427bff2003-12-07 01:24:23 +00007687 return 0;
7688}
7689
7690
Chris Lattner72684fe2005-01-31 05:51:45 +00007691/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Chris Lattner35e24772004-07-13 01:49:43 +00007692static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
7693 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00007694 Value *CastOp = CI->getOperand(0);
Chris Lattner35e24772004-07-13 01:49:43 +00007695
7696 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00007697 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Chris Lattner35e24772004-07-13 01:49:43 +00007698 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00007699
Chris Lattnerebca4762006-04-02 05:37:12 +00007700 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
7701 isa<PackedType>(DestPTy)) {
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00007702 // If the source is an array, the code below will not succeed. Check to
7703 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
7704 // constants.
7705 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
7706 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
7707 if (ASrcTy->getNumElements() != 0) {
7708 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
7709 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
7710 SrcTy = cast<PointerType>(CastOp->getType());
7711 SrcPTy = SrcTy->getElementType();
7712 }
7713
Chris Lattnerebca4762006-04-02 05:37:12 +00007714 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
7715 isa<PackedType>(SrcPTy)) &&
Chris Lattnerecfa9b52005-03-29 06:37:47 +00007716 // Do not allow turning this into a load of an integer, which is then
7717 // casted to a pointer, this pessimizes pointer analysis a lot.
7718 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00007719 IC.getTargetData().getTypeSize(SrcPTy) ==
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00007720 IC.getTargetData().getTypeSize(DestPTy)) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00007721
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00007722 // Okay, we are casting from one integer or pointer type to another of
7723 // the same size. Instead of casting the pointer before the load, cast
7724 // the result of the loaded value.
7725 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
7726 CI->getName(),
7727 LI.isVolatile()),LI);
7728 // Now cast the result of the load.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007729 return CastInst::createInferredCast(NewLoad, LI.getType());
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00007730 }
Chris Lattner35e24772004-07-13 01:49:43 +00007731 }
7732 }
7733 return 0;
7734}
7735
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00007736/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattnere6f13092004-09-19 19:18:10 +00007737/// from this value cannot trap. If it is not obviously safe to load from the
7738/// specified pointer, we do a quick local scan of the basic block containing
7739/// ScanFrom, to determine if the address is already accessed.
7740static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
7741 // If it is an alloca or global variable, it is always safe to load from.
7742 if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
7743
7744 // Otherwise, be a little bit agressive by scanning the local block where we
7745 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00007746 // from/to. If so, the previous load or store would have already trapped,
7747 // so there is no harm doing an extra load (also, CSE will later eliminate
7748 // the load entirely).
Chris Lattnere6f13092004-09-19 19:18:10 +00007749 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
7750
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00007751 while (BBI != E) {
Chris Lattnere6f13092004-09-19 19:18:10 +00007752 --BBI;
7753
7754 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
7755 if (LI->getOperand(0) == V) return true;
7756 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
7757 if (SI->getOperand(1) == V) return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +00007758
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00007759 }
Chris Lattnere6f13092004-09-19 19:18:10 +00007760 return false;
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00007761}
7762
Chris Lattner0f1d8a32003-06-26 05:06:25 +00007763Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
7764 Value *Op = LI.getOperand(0);
Chris Lattner7e8af382004-01-12 04:13:56 +00007765
Chris Lattnera9d84e32005-05-01 04:24:53 +00007766 // load (cast X) --> cast (load X) iff safe
Reid Spencerde46e482006-11-02 20:25:50 +00007767 if (isa<CastInst>(Op))
Chris Lattnera9d84e32005-05-01 04:24:53 +00007768 if (Instruction *Res = InstCombineLoadCast(*this, LI))
7769 return Res;
7770
7771 // None of the following transforms are legal for volatile loads.
7772 if (LI.isVolatile()) return 0;
Chris Lattnerb990f7d2005-09-12 22:00:15 +00007773
Chris Lattnerb990f7d2005-09-12 22:00:15 +00007774 if (&LI.getParent()->front() != &LI) {
7775 BasicBlock::iterator BBI = &LI; --BBI;
Chris Lattnere0bfdf12005-09-12 22:21:03 +00007776 // If the instruction immediately before this is a store to the same
7777 // address, do a simple form of store->load forwarding.
Chris Lattnerb990f7d2005-09-12 22:00:15 +00007778 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
7779 if (SI->getOperand(1) == LI.getOperand(0))
7780 return ReplaceInstUsesWith(LI, SI->getOperand(0));
Chris Lattnere0bfdf12005-09-12 22:21:03 +00007781 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
7782 if (LIB->getOperand(0) == LI.getOperand(0))
7783 return ReplaceInstUsesWith(LI, LIB);
Chris Lattnerb990f7d2005-09-12 22:00:15 +00007784 }
Chris Lattnera9d84e32005-05-01 04:24:53 +00007785
7786 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op))
7787 if (isa<ConstantPointerNull>(GEPI->getOperand(0)) ||
7788 isa<UndefValue>(GEPI->getOperand(0))) {
7789 // Insert a new store to null instruction before the load to indicate
7790 // that this code is not reachable. We do this instead of inserting
7791 // an unreachable instruction directly because we cannot modify the
7792 // CFG.
7793 new StoreInst(UndefValue::get(LI.getType()),
7794 Constant::getNullValue(Op->getType()), &LI);
7795 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
7796 }
7797
Chris Lattner81a7a232004-10-16 18:11:37 +00007798 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattnera9d84e32005-05-01 04:24:53 +00007799 // load null/undef -> undef
7800 if ((C->isNullValue() || isa<UndefValue>(C))) {
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007801 // Insert a new store to null instruction before the load to indicate that
7802 // this code is not reachable. We do this instead of inserting an
7803 // unreachable instruction directly because we cannot modify the CFG.
Chris Lattnera9d84e32005-05-01 04:24:53 +00007804 new StoreInst(UndefValue::get(LI.getType()),
7805 Constant::getNullValue(Op->getType()), &LI);
Chris Lattner81a7a232004-10-16 18:11:37 +00007806 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007807 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00007808
Chris Lattner81a7a232004-10-16 18:11:37 +00007809 // Instcombine load (constant global) into the value loaded.
7810 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
7811 if (GV->isConstant() && !GV->isExternal())
7812 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanb1c93172005-04-21 23:48:37 +00007813
Chris Lattner81a7a232004-10-16 18:11:37 +00007814 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
7815 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
7816 if (CE->getOpcode() == Instruction::GetElementPtr) {
7817 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
7818 if (GV->isConstant() && !GV->isExternal())
Chris Lattner0b011ec2005-09-26 05:28:06 +00007819 if (Constant *V =
7820 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
Chris Lattner81a7a232004-10-16 18:11:37 +00007821 return ReplaceInstUsesWith(LI, V);
Chris Lattnera9d84e32005-05-01 04:24:53 +00007822 if (CE->getOperand(0)->isNullValue()) {
7823 // Insert a new store to null instruction before the load to indicate
7824 // that this code is not reachable. We do this instead of inserting
7825 // an unreachable instruction directly because we cannot modify the
7826 // CFG.
7827 new StoreInst(UndefValue::get(LI.getType()),
7828 Constant::getNullValue(Op->getType()), &LI);
7829 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
7830 }
7831
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007832 } else if (CE->isCast()) {
Chris Lattner81a7a232004-10-16 18:11:37 +00007833 if (Instruction *Res = InstCombineLoadCast(*this, LI))
7834 return Res;
7835 }
7836 }
Chris Lattnere228ee52004-04-08 20:39:49 +00007837
Chris Lattnera9d84e32005-05-01 04:24:53 +00007838 if (Op->hasOneUse()) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00007839 // Change select and PHI nodes to select values instead of addresses: this
7840 // helps alias analysis out a lot, allows many others simplifications, and
7841 // exposes redundancy in the code.
7842 //
7843 // Note that we cannot do the transformation unless we know that the
7844 // introduced loads cannot trap! Something like this is valid as long as
7845 // the condition is always false: load (select bool %C, int* null, int* %G),
7846 // but it would not be valid if we transformed it to load from null
7847 // unconditionally.
7848 //
7849 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
7850 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattnere6f13092004-09-19 19:18:10 +00007851 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
7852 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00007853 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner42618552004-09-20 10:15:10 +00007854 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00007855 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner42618552004-09-20 10:15:10 +00007856 SI->getOperand(2)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00007857 return new SelectInst(SI->getCondition(), V1, V2);
7858 }
7859
Chris Lattnerbdcf41a2004-09-23 15:46:00 +00007860 // load (select (cond, null, P)) -> load P
7861 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
7862 if (C->isNullValue()) {
7863 LI.setOperand(0, SI->getOperand(2));
7864 return &LI;
7865 }
7866
7867 // load (select (cond, P, null)) -> load P
7868 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
7869 if (C->isNullValue()) {
7870 LI.setOperand(0, SI->getOperand(1));
7871 return &LI;
7872 }
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00007873 }
7874 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00007875 return 0;
7876}
7877
Chris Lattner72684fe2005-01-31 05:51:45 +00007878/// InstCombineStoreToCast - Fold 'store V, (cast P)' -> store (cast V), P'
7879/// when possible.
7880static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
7881 User *CI = cast<User>(SI.getOperand(1));
7882 Value *CastOp = CI->getOperand(0);
7883
7884 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
7885 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
7886 const Type *SrcPTy = SrcTy->getElementType();
7887
7888 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
7889 // If the source is an array, the code below will not succeed. Check to
7890 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
7891 // constants.
7892 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
7893 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
7894 if (ASrcTy->getNumElements() != 0) {
7895 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
7896 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
7897 SrcTy = cast<PointerType>(CastOp->getType());
7898 SrcPTy = SrcTy->getElementType();
7899 }
7900
7901 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00007902 IC.getTargetData().getTypeSize(SrcPTy) ==
Chris Lattner72684fe2005-01-31 05:51:45 +00007903 IC.getTargetData().getTypeSize(DestPTy)) {
7904
7905 // Okay, we are casting from one integer or pointer type to another of
7906 // the same size. Instead of casting the pointer before the store, cast
7907 // the value to be stored.
7908 Value *NewCast;
7909 if (Constant *C = dyn_cast<Constant>(SI.getOperand(0)))
7910 NewCast = ConstantExpr::getCast(C, SrcPTy);
7911 else
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007912 NewCast = IC.InsertNewInstBefore(
7913 CastInst::createInferredCast(SI.getOperand(0), SrcPTy,
7914 SI.getOperand(0)->getName()+".c"), SI);
Chris Lattner72684fe2005-01-31 05:51:45 +00007915
7916 return new StoreInst(NewCast, CastOp);
7917 }
7918 }
7919 }
7920 return 0;
7921}
7922
Chris Lattner31f486c2005-01-31 05:36:43 +00007923Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
7924 Value *Val = SI.getOperand(0);
7925 Value *Ptr = SI.getOperand(1);
7926
7927 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner5997cf92006-02-08 03:25:32 +00007928 EraseInstFromFunction(SI);
Chris Lattner31f486c2005-01-31 05:36:43 +00007929 ++NumCombined;
7930 return 0;
7931 }
7932
Chris Lattner5997cf92006-02-08 03:25:32 +00007933 // Do really simple DSE, to catch cases where there are several consequtive
7934 // stores to the same location, separated by a few arithmetic operations. This
7935 // situation often occurs with bitfield accesses.
7936 BasicBlock::iterator BBI = &SI;
7937 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
7938 --ScanInsts) {
7939 --BBI;
7940
7941 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
7942 // Prev store isn't volatile, and stores to the same location?
7943 if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
7944 ++NumDeadStore;
7945 ++BBI;
7946 EraseInstFromFunction(*PrevSI);
7947 continue;
7948 }
7949 break;
7950 }
7951
Chris Lattnerdab43b22006-05-26 19:19:20 +00007952 // If this is a load, we have to stop. However, if the loaded value is from
7953 // the pointer we're loading and is producing the pointer we're storing,
7954 // then *this* store is dead (X = load P; store X -> P).
7955 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
7956 if (LI == Val && LI->getOperand(0) == Ptr) {
7957 EraseInstFromFunction(SI);
7958 ++NumCombined;
7959 return 0;
7960 }
7961 // Otherwise, this is a load from some other location. Stores before it
7962 // may not be dead.
7963 break;
7964 }
7965
Chris Lattner5997cf92006-02-08 03:25:32 +00007966 // Don't skip over loads or things that can modify memory.
Chris Lattnerdab43b22006-05-26 19:19:20 +00007967 if (BBI->mayWriteToMemory())
Chris Lattner5997cf92006-02-08 03:25:32 +00007968 break;
7969 }
7970
7971
7972 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner31f486c2005-01-31 05:36:43 +00007973
7974 // store X, null -> turns into 'unreachable' in SimplifyCFG
7975 if (isa<ConstantPointerNull>(Ptr)) {
7976 if (!isa<UndefValue>(Val)) {
7977 SI.setOperand(0, UndefValue::get(Val->getType()));
7978 if (Instruction *U = dyn_cast<Instruction>(Val))
7979 WorkList.push_back(U); // Dropped a use.
7980 ++NumCombined;
7981 }
7982 return 0; // Do not modify these!
7983 }
7984
7985 // store undef, Ptr -> noop
7986 if (isa<UndefValue>(Val)) {
Chris Lattner5997cf92006-02-08 03:25:32 +00007987 EraseInstFromFunction(SI);
Chris Lattner31f486c2005-01-31 05:36:43 +00007988 ++NumCombined;
7989 return 0;
7990 }
7991
Chris Lattner72684fe2005-01-31 05:51:45 +00007992 // If the pointer destination is a cast, see if we can fold the cast into the
7993 // source instead.
Reid Spencerde46e482006-11-02 20:25:50 +00007994 if (isa<CastInst>(Ptr))
Chris Lattner72684fe2005-01-31 05:51:45 +00007995 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
7996 return Res;
7997 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007998 if (CE->isCast())
Chris Lattner72684fe2005-01-31 05:51:45 +00007999 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
8000 return Res;
8001
Chris Lattner219175c2005-09-12 23:23:25 +00008002
8003 // If this store is the last instruction in the basic block, and if the block
8004 // ends with an unconditional branch, try to move it to the successor block.
Chris Lattner5997cf92006-02-08 03:25:32 +00008005 BBI = &SI; ++BBI;
Chris Lattner219175c2005-09-12 23:23:25 +00008006 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
8007 if (BI->isUnconditional()) {
8008 // Check to see if the successor block has exactly two incoming edges. If
8009 // so, see if the other predecessor contains a store to the same location.
8010 // if so, insert a PHI node (if needed) and move the stores down.
8011 BasicBlock *Dest = BI->getSuccessor(0);
8012
8013 pred_iterator PI = pred_begin(Dest);
8014 BasicBlock *Other = 0;
8015 if (*PI != BI->getParent())
8016 Other = *PI;
8017 ++PI;
8018 if (PI != pred_end(Dest)) {
8019 if (*PI != BI->getParent())
8020 if (Other)
8021 Other = 0;
8022 else
8023 Other = *PI;
8024 if (++PI != pred_end(Dest))
8025 Other = 0;
8026 }
8027 if (Other) { // If only one other pred...
8028 BBI = Other->getTerminator();
8029 // Make sure this other block ends in an unconditional branch and that
8030 // there is an instruction before the branch.
8031 if (isa<BranchInst>(BBI) && cast<BranchInst>(BBI)->isUnconditional() &&
8032 BBI != Other->begin()) {
8033 --BBI;
8034 StoreInst *OtherStore = dyn_cast<StoreInst>(BBI);
8035
8036 // If this instruction is a store to the same location.
8037 if (OtherStore && OtherStore->getOperand(1) == SI.getOperand(1)) {
8038 // Okay, we know we can perform this transformation. Insert a PHI
8039 // node now if we need it.
8040 Value *MergedVal = OtherStore->getOperand(0);
8041 if (MergedVal != SI.getOperand(0)) {
8042 PHINode *PN = new PHINode(MergedVal->getType(), "storemerge");
8043 PN->reserveOperandSpace(2);
8044 PN->addIncoming(SI.getOperand(0), SI.getParent());
8045 PN->addIncoming(OtherStore->getOperand(0), Other);
8046 MergedVal = InsertNewInstBefore(PN, Dest->front());
8047 }
8048
8049 // Advance to a place where it is safe to insert the new store and
8050 // insert it.
8051 BBI = Dest->begin();
8052 while (isa<PHINode>(BBI)) ++BBI;
8053 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
8054 OtherStore->isVolatile()), *BBI);
8055
8056 // Nuke the old stores.
Chris Lattner5997cf92006-02-08 03:25:32 +00008057 EraseInstFromFunction(SI);
8058 EraseInstFromFunction(*OtherStore);
Chris Lattner219175c2005-09-12 23:23:25 +00008059 ++NumCombined;
8060 return 0;
8061 }
8062 }
8063 }
8064 }
8065
Chris Lattner31f486c2005-01-31 05:36:43 +00008066 return 0;
8067}
8068
8069
Chris Lattner9eef8a72003-06-04 04:46:00 +00008070Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
8071 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4fdd96c2005-06-18 17:37:34 +00008072 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00008073 BasicBlock *TrueDest;
8074 BasicBlock *FalseDest;
8075 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
8076 !isa<Constant>(X)) {
8077 // Swap Destinations and condition...
8078 BI.setCondition(X);
8079 BI.setSuccessor(0, FalseDest);
8080 BI.setSuccessor(1, TrueDest);
8081 return &BI;
8082 }
8083
8084 // Cannonicalize setne -> seteq
8085 Instruction::BinaryOps Op; Value *Y;
8086 if (match(&BI, m_Br(m_SetCond(Op, m_Value(X), m_Value(Y)),
8087 TrueDest, FalseDest)))
8088 if ((Op == Instruction::SetNE || Op == Instruction::SetLE ||
8089 Op == Instruction::SetGE) && BI.getCondition()->hasOneUse()) {
8090 SetCondInst *I = cast<SetCondInst>(BI.getCondition());
8091 std::string Name = I->getName(); I->setName("");
8092 Instruction::BinaryOps NewOpcode = SetCondInst::getInverseCondition(Op);
8093 Value *NewSCC = BinaryOperator::create(NewOpcode, X, Y, Name, I);
Chris Lattnere967b342003-06-04 05:10:11 +00008094 // Swap Destinations and condition...
Chris Lattnerd4252a72004-07-30 07:50:03 +00008095 BI.setCondition(NewSCC);
Chris Lattnere967b342003-06-04 05:10:11 +00008096 BI.setSuccessor(0, FalseDest);
8097 BI.setSuccessor(1, TrueDest);
Chris Lattnerd4252a72004-07-30 07:50:03 +00008098 removeFromWorkList(I);
8099 I->getParent()->getInstList().erase(I);
8100 WorkList.push_back(cast<Instruction>(NewSCC));
Chris Lattnere967b342003-06-04 05:10:11 +00008101 return &BI;
8102 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00008103
Chris Lattner9eef8a72003-06-04 04:46:00 +00008104 return 0;
8105}
Chris Lattner1085bdf2002-11-04 16:18:53 +00008106
Chris Lattner4c9c20a2004-07-03 00:26:11 +00008107Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
8108 Value *Cond = SI.getCondition();
8109 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
8110 if (I->getOpcode() == Instruction::Add)
8111 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
8112 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
8113 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattner81a7a232004-10-16 18:11:37 +00008114 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner4c9c20a2004-07-03 00:26:11 +00008115 AddRHS));
8116 SI.setOperand(0, I->getOperand(0));
8117 WorkList.push_back(I);
8118 return &SI;
8119 }
8120 }
8121 return 0;
8122}
8123
Chris Lattner6bc98652006-03-05 00:22:33 +00008124/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
8125/// is to leave as a vector operation.
8126static bool CheapToScalarize(Value *V, bool isConstant) {
8127 if (isa<ConstantAggregateZero>(V))
8128 return true;
8129 if (ConstantPacked *C = dyn_cast<ConstantPacked>(V)) {
8130 if (isConstant) return true;
8131 // If all elts are the same, we can extract.
8132 Constant *Op0 = C->getOperand(0);
8133 for (unsigned i = 1; i < C->getNumOperands(); ++i)
8134 if (C->getOperand(i) != Op0)
8135 return false;
8136 return true;
8137 }
8138 Instruction *I = dyn_cast<Instruction>(V);
8139 if (!I) return false;
8140
8141 // Insert element gets simplified to the inserted element or is deleted if
8142 // this is constant idx extract element and its a constant idx insertelt.
8143 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
8144 isa<ConstantInt>(I->getOperand(2)))
8145 return true;
8146 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
8147 return true;
8148 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
8149 if (BO->hasOneUse() &&
8150 (CheapToScalarize(BO->getOperand(0), isConstant) ||
8151 CheapToScalarize(BO->getOperand(1), isConstant)))
8152 return true;
8153
8154 return false;
8155}
8156
Chris Lattner12249be2006-05-25 23:48:38 +00008157/// getShuffleMask - Read and decode a shufflevector mask. It turns undef
8158/// elements into values that are larger than the #elts in the input.
8159static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
8160 unsigned NElts = SVI->getType()->getNumElements();
8161 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
8162 return std::vector<unsigned>(NElts, 0);
8163 if (isa<UndefValue>(SVI->getOperand(2)))
8164 return std::vector<unsigned>(NElts, 2*NElts);
8165
8166 std::vector<unsigned> Result;
8167 const ConstantPacked *CP = cast<ConstantPacked>(SVI->getOperand(2));
8168 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
8169 if (isa<UndefValue>(CP->getOperand(i)))
8170 Result.push_back(NElts*2); // undef -> 8
8171 else
Reid Spencere0fc4df2006-10-20 07:07:24 +00008172 Result.push_back(cast<ConstantInt>(CP->getOperand(i))->getZExtValue());
Chris Lattner12249be2006-05-25 23:48:38 +00008173 return Result;
8174}
8175
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008176/// FindScalarElement - Given a vector and an element number, see if the scalar
8177/// value is already around as a register, for example if it were inserted then
8178/// extracted from the vector.
8179static Value *FindScalarElement(Value *V, unsigned EltNo) {
8180 assert(isa<PackedType>(V->getType()) && "Not looking at a vector?");
8181 const PackedType *PTy = cast<PackedType>(V->getType());
Chris Lattner2d37f922006-04-10 23:06:36 +00008182 unsigned Width = PTy->getNumElements();
8183 if (EltNo >= Width) // Out of range access.
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008184 return UndefValue::get(PTy->getElementType());
8185
8186 if (isa<UndefValue>(V))
8187 return UndefValue::get(PTy->getElementType());
8188 else if (isa<ConstantAggregateZero>(V))
8189 return Constant::getNullValue(PTy->getElementType());
8190 else if (ConstantPacked *CP = dyn_cast<ConstantPacked>(V))
8191 return CP->getOperand(EltNo);
8192 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
8193 // If this is an insert to a variable element, we don't know what it is.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008194 if (!isa<ConstantInt>(III->getOperand(2)))
8195 return 0;
8196 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008197
8198 // If this is an insert to the element we are looking for, return the
8199 // inserted value.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008200 if (EltNo == IIElt)
8201 return III->getOperand(1);
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008202
8203 // Otherwise, the insertelement doesn't modify the value, recurse on its
8204 // vector input.
8205 return FindScalarElement(III->getOperand(0), EltNo);
Chris Lattner2d37f922006-04-10 23:06:36 +00008206 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Chris Lattner12249be2006-05-25 23:48:38 +00008207 unsigned InEl = getShuffleMask(SVI)[EltNo];
8208 if (InEl < Width)
8209 return FindScalarElement(SVI->getOperand(0), InEl);
8210 else if (InEl < Width*2)
8211 return FindScalarElement(SVI->getOperand(1), InEl - Width);
8212 else
8213 return UndefValue::get(PTy->getElementType());
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008214 }
8215
8216 // Otherwise, we don't know.
8217 return 0;
8218}
8219
Robert Bocchinoa8352962006-01-13 22:48:06 +00008220Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008221
Chris Lattner92346c32006-03-31 18:25:14 +00008222 // If packed val is undef, replace extract with scalar undef.
8223 if (isa<UndefValue>(EI.getOperand(0)))
8224 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
8225
8226 // If packed val is constant 0, replace extract with scalar 0.
8227 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
8228 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
8229
Robert Bocchinoa8352962006-01-13 22:48:06 +00008230 if (ConstantPacked *C = dyn_cast<ConstantPacked>(EI.getOperand(0))) {
8231 // If packed val is constant with uniform operands, replace EI
8232 // with that operand
Chris Lattner6bc98652006-03-05 00:22:33 +00008233 Constant *op0 = C->getOperand(0);
Robert Bocchinoa8352962006-01-13 22:48:06 +00008234 for (unsigned i = 1; i < C->getNumOperands(); ++i)
Chris Lattner6bc98652006-03-05 00:22:33 +00008235 if (C->getOperand(i) != op0) {
8236 op0 = 0;
8237 break;
8238 }
8239 if (op0)
8240 return ReplaceInstUsesWith(EI, op0);
Robert Bocchinoa8352962006-01-13 22:48:06 +00008241 }
Chris Lattner6bc98652006-03-05 00:22:33 +00008242
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008243 // If extracting a specified index from the vector, see if we can recursively
8244 // find a previously computed scalar that was inserted into the vector.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008245 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Chris Lattner2deeaea2006-10-05 06:55:50 +00008246 // This instruction only demands the single element from the input vector.
8247 // If the input vector has a single use, simplify it based on this use
8248 // property.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008249 uint64_t IndexVal = IdxC->getZExtValue();
Chris Lattner2deeaea2006-10-05 06:55:50 +00008250 if (EI.getOperand(0)->hasOneUse()) {
8251 uint64_t UndefElts;
8252 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Reid Spencere0fc4df2006-10-20 07:07:24 +00008253 1 << IndexVal,
Chris Lattner2deeaea2006-10-05 06:55:50 +00008254 UndefElts)) {
8255 EI.setOperand(0, V);
8256 return &EI;
8257 }
8258 }
8259
Reid Spencere0fc4df2006-10-20 07:07:24 +00008260 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008261 return ReplaceInstUsesWith(EI, Elt);
Chris Lattner2d37f922006-04-10 23:06:36 +00008262 }
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008263
Chris Lattner83f65782006-05-25 22:53:38 +00008264 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Robert Bocchinoa8352962006-01-13 22:48:06 +00008265 if (I->hasOneUse()) {
8266 // Push extractelement into predecessor operation if legal and
8267 // profitable to do so
8268 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Chris Lattner6bc98652006-03-05 00:22:33 +00008269 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
8270 if (CheapToScalarize(BO, isConstantElt)) {
8271 ExtractElementInst *newEI0 =
8272 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
8273 EI.getName()+".lhs");
8274 ExtractElementInst *newEI1 =
8275 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
8276 EI.getName()+".rhs");
8277 InsertNewInstBefore(newEI0, EI);
8278 InsertNewInstBefore(newEI1, EI);
8279 return BinaryOperator::create(BO->getOpcode(), newEI0, newEI1);
8280 }
Reid Spencerde46e482006-11-02 20:25:50 +00008281 } else if (isa<LoadInst>(I)) {
Robert Bocchinoa8352962006-01-13 22:48:06 +00008282 Value *Ptr = InsertCastBefore(I->getOperand(0),
8283 PointerType::get(EI.getType()), EI);
8284 GetElementPtrInst *GEP =
Reid Spencera736fdf2006-11-29 01:11:01 +00008285 new GetElementPtrInst(Ptr, EI.getOperand(1), I->getName() + ".gep");
Robert Bocchinoa8352962006-01-13 22:48:06 +00008286 InsertNewInstBefore(GEP, EI);
8287 return new LoadInst(GEP);
Chris Lattner83f65782006-05-25 22:53:38 +00008288 }
8289 }
8290 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
8291 // Extracting the inserted element?
8292 if (IE->getOperand(2) == EI.getOperand(1))
8293 return ReplaceInstUsesWith(EI, IE->getOperand(1));
8294 // If the inserted and extracted elements are constants, they must not
8295 // be the same value, extract from the pre-inserted value instead.
8296 if (isa<Constant>(IE->getOperand(2)) &&
8297 isa<Constant>(EI.getOperand(1))) {
8298 AddUsesToWorkList(EI);
8299 EI.setOperand(0, IE->getOperand(0));
8300 return &EI;
8301 }
8302 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
8303 // If this is extracting an element from a shufflevector, figure out where
8304 // it came from and extract from the appropriate input element instead.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008305 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
8306 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
Chris Lattner12249be2006-05-25 23:48:38 +00008307 Value *Src;
8308 if (SrcIdx < SVI->getType()->getNumElements())
8309 Src = SVI->getOperand(0);
8310 else if (SrcIdx < SVI->getType()->getNumElements()*2) {
8311 SrcIdx -= SVI->getType()->getNumElements();
8312 Src = SVI->getOperand(1);
8313 } else {
8314 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattner612fa8e2006-03-30 22:02:40 +00008315 }
Chris Lattner2deeaea2006-10-05 06:55:50 +00008316 return new ExtractElementInst(Src, SrcIdx);
Robert Bocchinoa8352962006-01-13 22:48:06 +00008317 }
8318 }
Chris Lattner83f65782006-05-25 22:53:38 +00008319 }
Robert Bocchinoa8352962006-01-13 22:48:06 +00008320 return 0;
8321}
8322
Chris Lattner90951862006-04-16 00:51:47 +00008323/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
8324/// elements from either LHS or RHS, return the shuffle mask and true.
8325/// Otherwise, return false.
8326static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
8327 std::vector<Constant*> &Mask) {
8328 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
8329 "Invalid CollectSingleShuffleElements");
8330 unsigned NumElts = cast<PackedType>(V->getType())->getNumElements();
8331
8332 if (isa<UndefValue>(V)) {
8333 Mask.assign(NumElts, UndefValue::get(Type::UIntTy));
8334 return true;
8335 } else if (V == LHS) {
8336 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencere0fc4df2006-10-20 07:07:24 +00008337 Mask.push_back(ConstantInt::get(Type::UIntTy, i));
Chris Lattner90951862006-04-16 00:51:47 +00008338 return true;
8339 } else if (V == RHS) {
8340 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencere0fc4df2006-10-20 07:07:24 +00008341 Mask.push_back(ConstantInt::get(Type::UIntTy, i+NumElts));
Chris Lattner90951862006-04-16 00:51:47 +00008342 return true;
8343 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
8344 // If this is an insert of an extract from some other vector, include it.
8345 Value *VecOp = IEI->getOperand(0);
8346 Value *ScalarOp = IEI->getOperand(1);
8347 Value *IdxOp = IEI->getOperand(2);
8348
Chris Lattnerb6cb64b2006-04-27 21:14:21 +00008349 if (!isa<ConstantInt>(IdxOp))
8350 return false;
Reid Spencere0fc4df2006-10-20 07:07:24 +00008351 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerb6cb64b2006-04-27 21:14:21 +00008352
8353 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
8354 // Okay, we can handle this if the vector we are insertinting into is
8355 // transitively ok.
8356 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
8357 // If so, update the mask to reflect the inserted undef.
8358 Mask[InsertedIdx] = UndefValue::get(Type::UIntTy);
8359 return true;
8360 }
8361 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
8362 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner90951862006-04-16 00:51:47 +00008363 EI->getOperand(0)->getType() == V->getType()) {
8364 unsigned ExtractedIdx =
Reid Spencere0fc4df2006-10-20 07:07:24 +00008365 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattner90951862006-04-16 00:51:47 +00008366
8367 // This must be extracting from either LHS or RHS.
8368 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
8369 // Okay, we can handle this if the vector we are insertinting into is
8370 // transitively ok.
8371 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
8372 // If so, update the mask to reflect the inserted value.
8373 if (EI->getOperand(0) == LHS) {
8374 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencere0fc4df2006-10-20 07:07:24 +00008375 ConstantInt::get(Type::UIntTy, ExtractedIdx);
Chris Lattner90951862006-04-16 00:51:47 +00008376 } else {
8377 assert(EI->getOperand(0) == RHS);
8378 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencere0fc4df2006-10-20 07:07:24 +00008379 ConstantInt::get(Type::UIntTy, ExtractedIdx+NumElts);
Chris Lattner90951862006-04-16 00:51:47 +00008380
8381 }
8382 return true;
8383 }
8384 }
8385 }
8386 }
8387 }
8388 // TODO: Handle shufflevector here!
8389
8390 return false;
8391}
8392
8393/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
8394/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
8395/// that computes V and the LHS value of the shuffle.
Chris Lattner39fac442006-04-15 01:39:45 +00008396static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Chris Lattner90951862006-04-16 00:51:47 +00008397 Value *&RHS) {
8398 assert(isa<PackedType>(V->getType()) &&
8399 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattner39fac442006-04-15 01:39:45 +00008400 "Invalid shuffle!");
8401 unsigned NumElts = cast<PackedType>(V->getType())->getNumElements();
8402
8403 if (isa<UndefValue>(V)) {
8404 Mask.assign(NumElts, UndefValue::get(Type::UIntTy));
8405 return V;
8406 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00008407 Mask.assign(NumElts, ConstantInt::get(Type::UIntTy, 0));
Chris Lattner39fac442006-04-15 01:39:45 +00008408 return V;
8409 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
8410 // If this is an insert of an extract from some other vector, include it.
8411 Value *VecOp = IEI->getOperand(0);
8412 Value *ScalarOp = IEI->getOperand(1);
8413 Value *IdxOp = IEI->getOperand(2);
8414
8415 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
8416 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
8417 EI->getOperand(0)->getType() == V->getType()) {
8418 unsigned ExtractedIdx =
Reid Spencere0fc4df2006-10-20 07:07:24 +00008419 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
8420 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattner39fac442006-04-15 01:39:45 +00008421
8422 // Either the extracted from or inserted into vector must be RHSVec,
8423 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner90951862006-04-16 00:51:47 +00008424 if (EI->getOperand(0) == RHS || RHS == 0) {
8425 RHS = EI->getOperand(0);
8426 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
Chris Lattner39fac442006-04-15 01:39:45 +00008427 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencere0fc4df2006-10-20 07:07:24 +00008428 ConstantInt::get(Type::UIntTy, NumElts+ExtractedIdx);
Chris Lattner39fac442006-04-15 01:39:45 +00008429 return V;
8430 }
8431
Chris Lattner90951862006-04-16 00:51:47 +00008432 if (VecOp == RHS) {
8433 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
Chris Lattner39fac442006-04-15 01:39:45 +00008434 // Everything but the extracted element is replaced with the RHS.
8435 for (unsigned i = 0; i != NumElts; ++i) {
8436 if (i != InsertedIdx)
Reid Spencere0fc4df2006-10-20 07:07:24 +00008437 Mask[i] = ConstantInt::get(Type::UIntTy, NumElts+i);
Chris Lattner39fac442006-04-15 01:39:45 +00008438 }
8439 return V;
8440 }
Chris Lattner90951862006-04-16 00:51:47 +00008441
8442 // If this insertelement is a chain that comes from exactly these two
8443 // vectors, return the vector and the effective shuffle.
8444 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
8445 return EI->getOperand(0);
8446
Chris Lattner39fac442006-04-15 01:39:45 +00008447 }
8448 }
8449 }
Chris Lattner90951862006-04-16 00:51:47 +00008450 // TODO: Handle shufflevector here!
Chris Lattner39fac442006-04-15 01:39:45 +00008451
8452 // Otherwise, can't do anything fancy. Return an identity vector.
8453 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencere0fc4df2006-10-20 07:07:24 +00008454 Mask.push_back(ConstantInt::get(Type::UIntTy, i));
Chris Lattner39fac442006-04-15 01:39:45 +00008455 return V;
8456}
8457
8458Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
8459 Value *VecOp = IE.getOperand(0);
8460 Value *ScalarOp = IE.getOperand(1);
8461 Value *IdxOp = IE.getOperand(2);
8462
8463 // If the inserted element was extracted from some other vector, and if the
8464 // indexes are constant, try to turn this into a shufflevector operation.
8465 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
8466 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
8467 EI->getOperand(0)->getType() == IE.getType()) {
8468 unsigned NumVectorElts = IE.getType()->getNumElements();
Reid Spencere0fc4df2006-10-20 07:07:24 +00008469 unsigned ExtractedIdx=cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
8470 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattner39fac442006-04-15 01:39:45 +00008471
8472 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
8473 return ReplaceInstUsesWith(IE, VecOp);
8474
8475 if (InsertedIdx >= NumVectorElts) // Out of range insert.
8476 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
8477
8478 // If we are extracting a value from a vector, then inserting it right
8479 // back into the same place, just use the input vector.
8480 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
8481 return ReplaceInstUsesWith(IE, VecOp);
8482
8483 // We could theoretically do this for ANY input. However, doing so could
8484 // turn chains of insertelement instructions into a chain of shufflevector
8485 // instructions, and right now we do not merge shufflevectors. As such,
8486 // only do this in a situation where it is clear that there is benefit.
8487 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
8488 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
8489 // the values of VecOp, except then one read from EIOp0.
8490 // Build a new shuffle mask.
8491 std::vector<Constant*> Mask;
8492 if (isa<UndefValue>(VecOp))
8493 Mask.assign(NumVectorElts, UndefValue::get(Type::UIntTy));
8494 else {
8495 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
Reid Spencere0fc4df2006-10-20 07:07:24 +00008496 Mask.assign(NumVectorElts, ConstantInt::get(Type::UIntTy,
Chris Lattner39fac442006-04-15 01:39:45 +00008497 NumVectorElts));
8498 }
Reid Spencere0fc4df2006-10-20 07:07:24 +00008499 Mask[InsertedIdx] = ConstantInt::get(Type::UIntTy, ExtractedIdx);
Chris Lattner39fac442006-04-15 01:39:45 +00008500 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
8501 ConstantPacked::get(Mask));
8502 }
8503
8504 // If this insertelement isn't used by some other insertelement, turn it
8505 // (and any insertelements it points to), into one big shuffle.
8506 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
8507 std::vector<Constant*> Mask;
Chris Lattner90951862006-04-16 00:51:47 +00008508 Value *RHS = 0;
8509 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
8510 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
8511 // We now have a shuffle of LHS, RHS, Mask.
8512 return new ShuffleVectorInst(LHS, RHS, ConstantPacked::get(Mask));
Chris Lattner39fac442006-04-15 01:39:45 +00008513 }
8514 }
8515 }
8516
8517 return 0;
8518}
8519
8520
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008521Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
8522 Value *LHS = SVI.getOperand(0);
8523 Value *RHS = SVI.getOperand(1);
Chris Lattner12249be2006-05-25 23:48:38 +00008524 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008525
8526 bool MadeChange = false;
8527
Chris Lattner2deeaea2006-10-05 06:55:50 +00008528 // Undefined shuffle mask -> undefined value.
Chris Lattner12249be2006-05-25 23:48:38 +00008529 if (isa<UndefValue>(SVI.getOperand(2)))
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008530 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
8531
Chris Lattner39fac442006-04-15 01:39:45 +00008532 // TODO: If we have shuffle(x, undef, mask) and any elements of mask refer to
8533 // the undef, change them to undefs.
8534
Chris Lattner12249be2006-05-25 23:48:38 +00008535 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
8536 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
8537 if (LHS == RHS || isa<UndefValue>(LHS)) {
8538 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008539 // shuffle(undef,undef,mask) -> undef.
8540 return ReplaceInstUsesWith(SVI, LHS);
8541 }
8542
Chris Lattner12249be2006-05-25 23:48:38 +00008543 // Remap any references to RHS to use LHS.
8544 std::vector<Constant*> Elts;
8545 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner0e477162006-05-26 00:29:06 +00008546 if (Mask[i] >= 2*e)
Chris Lattner12249be2006-05-25 23:48:38 +00008547 Elts.push_back(UndefValue::get(Type::UIntTy));
Chris Lattner0e477162006-05-26 00:29:06 +00008548 else {
8549 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
8550 (Mask[i] < e && isa<UndefValue>(LHS)))
8551 Mask[i] = 2*e; // Turn into undef.
8552 else
8553 Mask[i] &= (e-1); // Force to LHS.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008554 Elts.push_back(ConstantInt::get(Type::UIntTy, Mask[i]));
Chris Lattner0e477162006-05-26 00:29:06 +00008555 }
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008556 }
Chris Lattner12249be2006-05-25 23:48:38 +00008557 SVI.setOperand(0, SVI.getOperand(1));
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008558 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Chris Lattner12249be2006-05-25 23:48:38 +00008559 SVI.setOperand(2, ConstantPacked::get(Elts));
Chris Lattner0e477162006-05-26 00:29:06 +00008560 LHS = SVI.getOperand(0);
8561 RHS = SVI.getOperand(1);
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008562 MadeChange = true;
8563 }
8564
Chris Lattner0e477162006-05-26 00:29:06 +00008565 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner12249be2006-05-25 23:48:38 +00008566 bool isLHSID = true, isRHSID = true;
Chris Lattner34cebe72006-04-16 00:03:56 +00008567
Chris Lattner12249be2006-05-25 23:48:38 +00008568 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
8569 if (Mask[i] >= e*2) continue; // Ignore undef values.
8570 // Is this an identity shuffle of the LHS value?
8571 isLHSID &= (Mask[i] == i);
8572
8573 // Is this an identity shuffle of the RHS value?
8574 isRHSID &= (Mask[i]-e == i);
Chris Lattner34cebe72006-04-16 00:03:56 +00008575 }
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008576
Chris Lattner12249be2006-05-25 23:48:38 +00008577 // Eliminate identity shuffles.
8578 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
8579 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008580
Chris Lattner0e477162006-05-26 00:29:06 +00008581 // If the LHS is a shufflevector itself, see if we can combine it with this
8582 // one without producing an unusual shuffle. Here we are really conservative:
8583 // we are absolutely afraid of producing a shuffle mask not in the input
8584 // program, because the code gen may not be smart enough to turn a merged
8585 // shuffle into two specific shuffles: it may produce worse code. As such,
8586 // we only merge two shuffles if the result is one of the two input shuffle
8587 // masks. In this case, merging the shuffles just removes one instruction,
8588 // which we know is safe. This is good for things like turning:
8589 // (splat(splat)) -> splat.
8590 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
8591 if (isa<UndefValue>(RHS)) {
8592 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
8593
8594 std::vector<unsigned> NewMask;
8595 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
8596 if (Mask[i] >= 2*e)
8597 NewMask.push_back(2*e);
8598 else
8599 NewMask.push_back(LHSMask[Mask[i]]);
8600
8601 // If the result mask is equal to the src shuffle or this shuffle mask, do
8602 // the replacement.
8603 if (NewMask == LHSMask || NewMask == Mask) {
8604 std::vector<Constant*> Elts;
8605 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
8606 if (NewMask[i] >= e*2) {
8607 Elts.push_back(UndefValue::get(Type::UIntTy));
8608 } else {
Reid Spencere0fc4df2006-10-20 07:07:24 +00008609 Elts.push_back(ConstantInt::get(Type::UIntTy, NewMask[i]));
Chris Lattner0e477162006-05-26 00:29:06 +00008610 }
8611 }
8612 return new ShuffleVectorInst(LHSSVI->getOperand(0),
8613 LHSSVI->getOperand(1),
8614 ConstantPacked::get(Elts));
8615 }
8616 }
8617 }
8618
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008619 return MadeChange ? &SVI : 0;
8620}
8621
8622
Robert Bocchinoa8352962006-01-13 22:48:06 +00008623
Chris Lattner99f48c62002-09-02 04:59:56 +00008624void InstCombiner::removeFromWorkList(Instruction *I) {
8625 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
8626 WorkList.end());
8627}
8628
Chris Lattner39c98bb2004-12-08 23:43:58 +00008629
8630/// TryToSinkInstruction - Try to move the specified instruction from its
8631/// current block into the beginning of DestBlock, which can only happen if it's
8632/// safe to move the instruction past all of the instructions between it and the
8633/// end of its block.
8634static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
8635 assert(I->hasOneUse() && "Invariants didn't hold!");
8636
Chris Lattnerc4f67e62005-10-27 17:13:11 +00008637 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
8638 if (isa<PHINode>(I) || I->mayWriteToMemory()) return false;
Misha Brukmanb1c93172005-04-21 23:48:37 +00008639
Chris Lattner39c98bb2004-12-08 23:43:58 +00008640 // Do not sink alloca instructions out of the entry block.
8641 if (isa<AllocaInst>(I) && I->getParent() == &DestBlock->getParent()->front())
8642 return false;
8643
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00008644 // We can only sink load instructions if there is nothing between the load and
8645 // the end of block that could change the value.
8646 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00008647 for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
8648 Scan != E; ++Scan)
8649 if (Scan->mayWriteToMemory())
8650 return false;
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00008651 }
Chris Lattner39c98bb2004-12-08 23:43:58 +00008652
8653 BasicBlock::iterator InsertPos = DestBlock->begin();
8654 while (isa<PHINode>(InsertPos)) ++InsertPos;
8655
Chris Lattner9f269e42005-08-08 19:11:57 +00008656 I->moveBefore(InsertPos);
Chris Lattner39c98bb2004-12-08 23:43:58 +00008657 ++NumSunkInst;
8658 return true;
8659}
8660
Chris Lattner1443bc52006-05-11 17:11:52 +00008661/// OptimizeConstantExpr - Given a constant expression and target data layout
8662/// information, symbolically evaluation the constant expr to something simpler
8663/// if possible.
8664static Constant *OptimizeConstantExpr(ConstantExpr *CE, const TargetData *TD) {
8665 if (!TD) return CE;
8666
8667 Constant *Ptr = CE->getOperand(0);
8668 if (CE->getOpcode() == Instruction::GetElementPtr && Ptr->isNullValue() &&
8669 cast<PointerType>(Ptr->getType())->getElementType()->isSized()) {
8670 // If this is a constant expr gep that is effectively computing an
8671 // "offsetof", fold it into 'cast int Size to T*' instead of 'gep 0, 0, 12'
8672 bool isFoldableGEP = true;
8673 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
8674 if (!isa<ConstantInt>(CE->getOperand(i)))
8675 isFoldableGEP = false;
8676 if (isFoldableGEP) {
8677 std::vector<Value*> Ops(CE->op_begin()+1, CE->op_end());
8678 uint64_t Offset = TD->getIndexedOffset(Ptr->getType(), Ops);
Reid Spencere0fc4df2006-10-20 07:07:24 +00008679 Constant *C = ConstantInt::get(Type::ULongTy, Offset);
Chris Lattner1443bc52006-05-11 17:11:52 +00008680 C = ConstantExpr::getCast(C, TD->getIntPtrType());
8681 return ConstantExpr::getCast(C, CE->getType());
8682 }
8683 }
8684
8685 return CE;
8686}
8687
Chris Lattnera36ee4e2006-05-10 19:00:36 +00008688
8689/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
8690/// all reachable code to the worklist.
8691///
8692/// This has a couple of tricks to make the code faster and more powerful. In
8693/// particular, we constant fold and DCE instructions as we go, to avoid adding
8694/// them to the worklist (this significantly speeds up instcombine on code where
8695/// many instructions are dead or constant). Additionally, if we find a branch
8696/// whose condition is a known constant, we only visit the reachable successors.
8697///
8698static void AddReachableCodeToWorklist(BasicBlock *BB,
8699 std::set<BasicBlock*> &Visited,
Chris Lattner1443bc52006-05-11 17:11:52 +00008700 std::vector<Instruction*> &WorkList,
8701 const TargetData *TD) {
Chris Lattnera36ee4e2006-05-10 19:00:36 +00008702 // We have now visited this block! If we've already been here, bail out.
8703 if (!Visited.insert(BB).second) return;
8704
8705 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
8706 Instruction *Inst = BBI++;
8707
8708 // DCE instruction if trivially dead.
8709 if (isInstructionTriviallyDead(Inst)) {
8710 ++NumDeadInst;
Bill Wendling5dbf43c2006-11-26 09:46:52 +00008711 DOUT << "IC: DCE: " << *Inst;
Chris Lattnera36ee4e2006-05-10 19:00:36 +00008712 Inst->eraseFromParent();
8713 continue;
8714 }
8715
8716 // ConstantProp instruction if trivially constant.
8717 if (Constant *C = ConstantFoldInstruction(Inst)) {
Chris Lattner1443bc52006-05-11 17:11:52 +00008718 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
8719 C = OptimizeConstantExpr(CE, TD);
Bill Wendling5dbf43c2006-11-26 09:46:52 +00008720 DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
Chris Lattnera36ee4e2006-05-10 19:00:36 +00008721 Inst->replaceAllUsesWith(C);
8722 ++NumConstProp;
8723 Inst->eraseFromParent();
8724 continue;
8725 }
8726
8727 WorkList.push_back(Inst);
8728 }
8729
8730 // Recursively visit successors. If this is a branch or switch on a constant,
8731 // only visit the reachable successor.
8732 TerminatorInst *TI = BB->getTerminator();
8733 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
8734 if (BI->isConditional() && isa<ConstantBool>(BI->getCondition())) {
8735 bool CondVal = cast<ConstantBool>(BI->getCondition())->getValue();
Chris Lattner1443bc52006-05-11 17:11:52 +00008736 AddReachableCodeToWorklist(BI->getSuccessor(!CondVal), Visited, WorkList,
8737 TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00008738 return;
8739 }
8740 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
8741 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
8742 // See if this is an explicit destination.
8743 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
8744 if (SI->getCaseValue(i) == Cond) {
Chris Lattner1443bc52006-05-11 17:11:52 +00008745 AddReachableCodeToWorklist(SI->getSuccessor(i), Visited, WorkList,TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00008746 return;
8747 }
8748
8749 // Otherwise it is the default destination.
Chris Lattner1443bc52006-05-11 17:11:52 +00008750 AddReachableCodeToWorklist(SI->getSuccessor(0), Visited, WorkList, TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00008751 return;
8752 }
8753 }
8754
8755 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
Chris Lattner1443bc52006-05-11 17:11:52 +00008756 AddReachableCodeToWorklist(TI->getSuccessor(i), Visited, WorkList, TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00008757}
8758
Chris Lattner113f4f42002-06-25 16:13:24 +00008759bool InstCombiner::runOnFunction(Function &F) {
Chris Lattner260ab202002-04-18 17:39:14 +00008760 bool Changed = false;
Chris Lattnerf4ad1652003-11-02 05:57:39 +00008761 TD = &getAnalysis<TargetData>();
Chris Lattnerca081252001-12-14 16:52:21 +00008762
Chris Lattner4ed40f72005-07-07 20:40:38 +00008763 {
Chris Lattnera36ee4e2006-05-10 19:00:36 +00008764 // Do a depth-first traversal of the function, populate the worklist with
8765 // the reachable instructions. Ignore blocks that are not reachable. Keep
8766 // track of which blocks we visit.
Chris Lattner4ed40f72005-07-07 20:40:38 +00008767 std::set<BasicBlock*> Visited;
Chris Lattner1443bc52006-05-11 17:11:52 +00008768 AddReachableCodeToWorklist(F.begin(), Visited, WorkList, TD);
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00008769
Chris Lattner4ed40f72005-07-07 20:40:38 +00008770 // Do a quick scan over the function. If we find any blocks that are
8771 // unreachable, remove any instructions inside of them. This prevents
8772 // the instcombine code from having to deal with some bad special cases.
8773 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
8774 if (!Visited.count(BB)) {
8775 Instruction *Term = BB->getTerminator();
8776 while (Term != BB->begin()) { // Remove instrs bottom-up
8777 BasicBlock::iterator I = Term; --I;
Chris Lattner2d3a7a62004-04-27 15:13:33 +00008778
Bill Wendling5dbf43c2006-11-26 09:46:52 +00008779 DOUT << "IC: DCE: " << *I;
Chris Lattner4ed40f72005-07-07 20:40:38 +00008780 ++NumDeadInst;
8781
8782 if (!I->use_empty())
8783 I->replaceAllUsesWith(UndefValue::get(I->getType()));
8784 I->eraseFromParent();
8785 }
8786 }
8787 }
Chris Lattnerca081252001-12-14 16:52:21 +00008788
8789 while (!WorkList.empty()) {
8790 Instruction *I = WorkList.back(); // Get an instruction from the worklist
8791 WorkList.pop_back();
8792
Chris Lattner1443bc52006-05-11 17:11:52 +00008793 // Check to see if we can DCE the instruction.
Chris Lattner99f48c62002-09-02 04:59:56 +00008794 if (isInstructionTriviallyDead(I)) {
Chris Lattner1443bc52006-05-11 17:11:52 +00008795 // Add operands to the worklist.
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00008796 if (I->getNumOperands() < 4)
Chris Lattner51ea1272004-02-28 05:22:00 +00008797 AddUsesToWorkList(*I);
Chris Lattner99f48c62002-09-02 04:59:56 +00008798 ++NumDeadInst;
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00008799
Bill Wendling5dbf43c2006-11-26 09:46:52 +00008800 DOUT << "IC: DCE: " << *I;
Chris Lattnercd517ff2005-01-28 19:32:01 +00008801
8802 I->eraseFromParent();
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00008803 removeFromWorkList(I);
8804 continue;
8805 }
Chris Lattner99f48c62002-09-02 04:59:56 +00008806
Chris Lattner1443bc52006-05-11 17:11:52 +00008807 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattner99f48c62002-09-02 04:59:56 +00008808 if (Constant *C = ConstantFoldInstruction(I)) {
Chris Lattner1443bc52006-05-11 17:11:52 +00008809 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
8810 C = OptimizeConstantExpr(CE, TD);
Bill Wendling5dbf43c2006-11-26 09:46:52 +00008811 DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
Chris Lattnercd517ff2005-01-28 19:32:01 +00008812
Chris Lattner1443bc52006-05-11 17:11:52 +00008813 // Add operands to the worklist.
Chris Lattner51ea1272004-02-28 05:22:00 +00008814 AddUsesToWorkList(*I);
Chris Lattnerc6509f42002-12-05 22:41:53 +00008815 ReplaceInstUsesWith(*I, C);
8816
Chris Lattner99f48c62002-09-02 04:59:56 +00008817 ++NumConstProp;
Chris Lattnera36ee4e2006-05-10 19:00:36 +00008818 I->eraseFromParent();
Chris Lattner800aaaf2003-10-07 15:17:02 +00008819 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00008820 continue;
Chris Lattner99f48c62002-09-02 04:59:56 +00008821 }
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00008822
Chris Lattner39c98bb2004-12-08 23:43:58 +00008823 // See if we can trivially sink this instruction to a successor basic block.
8824 if (I->hasOneUse()) {
8825 BasicBlock *BB = I->getParent();
8826 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
8827 if (UserParent != BB) {
8828 bool UserIsSuccessor = false;
8829 // See if the user is one of our successors.
8830 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
8831 if (*SI == UserParent) {
8832 UserIsSuccessor = true;
8833 break;
8834 }
8835
8836 // If the user is one of our immediate successors, and if that successor
8837 // only has us as a predecessors (we'd have to split the critical edge
8838 // otherwise), we can keep going.
8839 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
8840 next(pred_begin(UserParent)) == pred_end(UserParent))
8841 // Okay, the CFG is simple enough, try to sink this instruction.
8842 Changed |= TryToSinkInstruction(I, UserParent);
8843 }
8844 }
8845
Chris Lattnerca081252001-12-14 16:52:21 +00008846 // Now that we have an instruction, try combining it to simplify it...
Chris Lattnerae7a0d32002-08-02 19:29:35 +00008847 if (Instruction *Result = visit(*I)) {
Chris Lattner0b18c1d2002-05-10 15:38:35 +00008848 ++NumCombined;
Chris Lattner260ab202002-04-18 17:39:14 +00008849 // Should we replace the old instruction with a new one?
Chris Lattner053c0932002-05-14 15:24:07 +00008850 if (Result != I) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +00008851 DOUT << "IC: Old = " << *I
8852 << " New = " << *Result;
Chris Lattner7d2a5392004-03-13 23:54:27 +00008853
Chris Lattner396dbfe2004-06-09 05:08:07 +00008854 // Everything uses the new instruction now.
8855 I->replaceAllUsesWith(Result);
8856
8857 // Push the new instruction and any users onto the worklist.
8858 WorkList.push_back(Result);
8859 AddUsersToWorkList(*Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00008860
8861 // Move the name to the new instruction first...
8862 std::string OldName = I->getName(); I->setName("");
Chris Lattner950fc782003-10-07 22:58:41 +00008863 Result->setName(OldName);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00008864
8865 // Insert the new instruction into the basic block...
8866 BasicBlock *InstParent = I->getParent();
Chris Lattner7515cab2004-11-14 19:13:23 +00008867 BasicBlock::iterator InsertPos = I;
8868
8869 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
8870 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
8871 ++InsertPos;
8872
8873 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00008874
Chris Lattner63d75af2004-05-01 23:27:23 +00008875 // Make sure that we reprocess all operands now that we reduced their
8876 // use counts.
Chris Lattnerb643a9e2004-05-01 23:19:52 +00008877 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
8878 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
8879 WorkList.push_back(OpI);
8880
Chris Lattner396dbfe2004-06-09 05:08:07 +00008881 // Instructions can end up on the worklist more than once. Make sure
8882 // we do not process an instruction that has been deleted.
8883 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00008884
8885 // Erase the old instruction.
8886 InstParent->getInstList().erase(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00008887 } else {
Bill Wendling5dbf43c2006-11-26 09:46:52 +00008888 DOUT << "IC: MOD = " << *I;
Chris Lattner7d2a5392004-03-13 23:54:27 +00008889
Chris Lattnerae7a0d32002-08-02 19:29:35 +00008890 // If the instruction was modified, it's possible that it is now dead.
8891 // if so, remove it.
Chris Lattner63d75af2004-05-01 23:27:23 +00008892 if (isInstructionTriviallyDead(I)) {
8893 // Make sure we process all operands now that we are reducing their
8894 // use counts.
8895 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
8896 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
8897 WorkList.push_back(OpI);
Misha Brukmanb1c93172005-04-21 23:48:37 +00008898
Chris Lattner63d75af2004-05-01 23:27:23 +00008899 // Instructions may end up in the worklist more than once. Erase all
Robert Bocchinoa8352962006-01-13 22:48:06 +00008900 // occurrences of this instruction.
Chris Lattner99f48c62002-09-02 04:59:56 +00008901 removeFromWorkList(I);
Chris Lattner31f486c2005-01-31 05:36:43 +00008902 I->eraseFromParent();
Chris Lattner396dbfe2004-06-09 05:08:07 +00008903 } else {
8904 WorkList.push_back(Result);
8905 AddUsersToWorkList(*Result);
Chris Lattnerae7a0d32002-08-02 19:29:35 +00008906 }
Chris Lattner053c0932002-05-14 15:24:07 +00008907 }
Chris Lattner260ab202002-04-18 17:39:14 +00008908 Changed = true;
Chris Lattnerca081252001-12-14 16:52:21 +00008909 }
8910 }
8911
Chris Lattner260ab202002-04-18 17:39:14 +00008912 return Changed;
Chris Lattner04805fa2002-02-26 21:46:54 +00008913}
8914
Brian Gaeke38b79e82004-07-27 17:43:21 +00008915FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattner260ab202002-04-18 17:39:14 +00008916 return new InstCombiner();
Chris Lattner04805fa2002-02-26 21:46:54 +00008917}
Brian Gaeke960707c2003-11-11 22:41:34 +00008918