blob: 43cf48ae1324bd5a86634910ba650c5245e04ba8 [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 Lattner700b8732006-12-06 17:46:33 +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");
62 Statistic NumDeadStore("instcombine", "Number of dead stores eliminated");
63 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.
Reid Spencer13bc5d72006-12-12 09:18:51 +0000208 Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
209 Instruction &Pos) {
Chris Lattner7e794272004-09-24 15:21:34 +0000210 if (V->getType() == Ty) return V;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000211
Chris Lattnere79d2492006-04-06 19:19:17 +0000212 if (Constant *CV = dyn_cast<Constant>(V))
Reid Spencer13bc5d72006-12-12 09:18:51 +0000213 return ConstantExpr::getCast(opc, CV, Ty);
Chris Lattnere79d2492006-04-06 19:19:17 +0000214
Reid Spencer13bc5d72006-12-12 09:18:51 +0000215 Instruction *C = CastInst::create(opc, V, Ty, V->getName(), &Pos);
Chris Lattner7e794272004-09-24 15:21:34 +0000216 WorkList.push_back(C);
217 return C;
218 }
219
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000220 // ReplaceInstUsesWith - This method is to be used when an instruction is
221 // found to be dead, replacable with another preexisting expression. Here
222 // we add all uses of I to the worklist, replace all uses of I with the new
223 // value, then return I, so that the inst combiner will know that I was
224 // modified.
225 //
226 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattner51ea1272004-02-28 05:22:00 +0000227 AddUsersToWorkList(I); // Add all modified instrs to worklist
Chris Lattner8953b902004-04-05 02:10:19 +0000228 if (&I != V) {
229 I.replaceAllUsesWith(V);
230 return &I;
231 } else {
232 // If we are replacing the instruction with itself, this must be in a
233 // segment of unreachable code, so just clobber the instruction.
Chris Lattner8ba9ec92004-10-18 02:59:09 +0000234 I.replaceAllUsesWith(UndefValue::get(I.getType()));
Chris Lattner8953b902004-04-05 02:10:19 +0000235 return &I;
236 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000237 }
Chris Lattner51ea1272004-02-28 05:22:00 +0000238
Chris Lattner2590e512006-02-07 06:56:34 +0000239 // UpdateValueUsesWith - This method is to be used when an value is
240 // found to be replacable with another preexisting expression or was
241 // updated. Here we add all uses of I to the worklist, replace all uses of
242 // I with the new value (unless the instruction was just updated), then
243 // return true, so that the inst combiner will know that I was modified.
244 //
245 bool UpdateValueUsesWith(Value *Old, Value *New) {
246 AddUsersToWorkList(*Old); // Add all modified instrs to worklist
247 if (Old != New)
248 Old->replaceAllUsesWith(New);
249 if (Instruction *I = dyn_cast<Instruction>(Old))
250 WorkList.push_back(I);
Chris Lattner5b2edb12006-02-12 08:02:11 +0000251 if (Instruction *I = dyn_cast<Instruction>(New))
252 WorkList.push_back(I);
Chris Lattner2590e512006-02-07 06:56:34 +0000253 return true;
254 }
255
Chris Lattner51ea1272004-02-28 05:22:00 +0000256 // EraseInstFromFunction - When dealing with an instruction that has side
257 // effects or produces a void value, we can't rely on DCE to delete the
258 // instruction. Instead, visit methods should return the value returned by
259 // this function.
260 Instruction *EraseInstFromFunction(Instruction &I) {
261 assert(I.use_empty() && "Cannot erase instruction that is used!");
262 AddUsesToWorkList(I);
263 removeFromWorkList(&I);
Chris Lattner95307542004-11-18 21:41:39 +0000264 I.eraseFromParent();
Chris Lattner51ea1272004-02-28 05:22:00 +0000265 return 0; // Don't do anything with FI
266 }
267
Chris Lattner3ac7c262003-08-13 20:16:26 +0000268 private:
Chris Lattnerdfae8be2003-07-24 17:35:25 +0000269 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
270 /// InsertBefore instruction. This is specialized a bit to avoid inserting
271 /// casts that are known to not do anything...
272 ///
Reid Spencer13bc5d72006-12-12 09:18:51 +0000273 Value *InsertOperandCastBefore(Instruction::CastOps opcode,
274 Value *V, const Type *DestTy,
Chris Lattnerdfae8be2003-07-24 17:35:25 +0000275 Instruction *InsertBefore);
276
Chris Lattner7fb29e12003-03-11 00:12:48 +0000277 // SimplifyCommutative - This performs a few simplifications for commutative
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000278 // operators.
Chris Lattner7fb29e12003-03-11 00:12:48 +0000279 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerba1cb382003-09-19 17:17:26 +0000280
Chris Lattner0157e7f2006-02-11 09:31:47 +0000281 bool SimplifyDemandedBits(Value *V, uint64_t Mask,
282 uint64_t &KnownZero, uint64_t &KnownOne,
283 unsigned Depth = 0);
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000284
Chris Lattner2deeaea2006-10-05 06:55:50 +0000285 Value *SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
286 uint64_t &UndefElts, unsigned Depth = 0);
287
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000288 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
289 // PHI node as operand #0, see if we can fold the instruction into the PHI
290 // (which is only possible if all operands to the PHI are constants).
291 Instruction *FoldOpIntoPhi(Instruction &I);
292
Chris Lattner7515cab2004-11-14 19:13:23 +0000293 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
294 // operator and they all are only used by the PHI, PHI together their
295 // inputs, and do the operation once, to the result of the PHI.
296 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
Chris Lattnercadac0c2006-11-01 04:51:18 +0000297 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
298
299
Chris Lattnerba1cb382003-09-19 17:17:26 +0000300 Instruction *OptAndOp(Instruction *Op, ConstantIntegral *OpRHS,
301 ConstantIntegral *AndRHS, BinaryOperator &TheAnd);
Chris Lattneraf517572005-09-18 04:24:45 +0000302
303 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantIntegral *Mask,
304 bool isSub, Instruction &I);
Chris Lattner6862fbd2004-09-29 17:40:11 +0000305 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
306 bool Inside, Instruction &IB);
Chris Lattner216be912005-10-24 06:03:58 +0000307 Instruction *PromoteCastOfAllocation(CastInst &CI, AllocationInst &AI);
Chris Lattnerc482a9e2006-06-15 19:07:26 +0000308 Instruction *MatchBSwap(BinaryOperator &I);
309
Chris Lattner1ebbe6a2006-05-13 02:06:03 +0000310 Value *EvaluateInDifferentType(Value *V, const Type *Ty);
Chris Lattner260ab202002-04-18 17:39:14 +0000311 };
Chris Lattnerb28b6802002-07-23 18:06:35 +0000312
Chris Lattnerc2d3d312006-08-27 22:42:52 +0000313 RegisterPass<InstCombiner> X("instcombine", "Combine redundant instructions");
Chris Lattner260ab202002-04-18 17:39:14 +0000314}
315
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000316// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattner81a7a232004-10-16 18:11:37 +0000317// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000318static unsigned getComplexity(Value *V) {
319 if (isa<Instruction>(V)) {
320 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
Chris Lattner81a7a232004-10-16 18:11:37 +0000321 return 3;
322 return 4;
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000323 }
Chris Lattner81a7a232004-10-16 18:11:37 +0000324 if (isa<Argument>(V)) return 3;
325 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000326}
Chris Lattner260ab202002-04-18 17:39:14 +0000327
Chris Lattner7fb29e12003-03-11 00:12:48 +0000328// isOnlyUse - Return true if this instruction will be deleted if we stop using
329// it.
330static bool isOnlyUse(Value *V) {
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000331 return V->hasOneUse() || isa<Constant>(V);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000332}
333
Chris Lattnere79e8542004-02-23 06:38:22 +0000334// getPromotedType - Return the specified type promoted as it would be to pass
335// though a va_arg area...
336static const Type *getPromotedType(const Type *Ty) {
Chris Lattner97bfcea2004-06-17 18:16:02 +0000337 switch (Ty->getTypeID()) {
Chris Lattnere79e8542004-02-23 06:38:22 +0000338 case Type::SByteTyID:
339 case Type::ShortTyID: return Type::IntTy;
340 case Type::UByteTyID:
341 case Type::UShortTyID: return Type::UIntTy;
342 case Type::FloatTyID: return Type::DoubleTy;
343 default: return Ty;
344 }
345}
346
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000347/// getBitCastOperand - If the specified operand is a CastInst or a constant
348/// expression bitcast, return the operand value, otherwise return null.
349static Value *getBitCastOperand(Value *V) {
350 if (BitCastInst *I = dyn_cast<BitCastInst>(V))
Chris Lattner567b81f2005-09-13 00:40:14 +0000351 return I->getOperand(0);
352 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000353 if (CE->getOpcode() == Instruction::BitCast)
Chris Lattner567b81f2005-09-13 00:40:14 +0000354 return CE->getOperand(0);
355 return 0;
356}
357
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000358/// This function is a wrapper around CastInst::isEliminableCastPair. It
359/// simply extracts arguments and returns what that function returns.
360/// @Determine if it is valid to eliminate a Convert pair
361static Instruction::CastOps
362isEliminableCastPair(
363 const CastInst *CI, ///< The first cast instruction
364 unsigned opcode, ///< The opcode of the second cast instruction
365 const Type *DstTy, ///< The target type for the second cast instruction
366 TargetData *TD ///< The target data for pointer size
367) {
368
369 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
370 const Type *MidTy = CI->getType(); // B from above
Chris Lattner1d441ad2006-05-06 09:00:16 +0000371
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000372 // Get the opcodes of the two Cast instructions
373 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
374 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
Chris Lattner1d441ad2006-05-06 09:00:16 +0000375
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000376 return Instruction::CastOps(
377 CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
378 DstTy, TD->getIntPtrType()));
Chris Lattner1d441ad2006-05-06 09:00:16 +0000379}
380
381/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
382/// in any code being generated. It does not require codegen if V is simple
383/// enough or if the cast can be folded into other casts.
384static bool ValueRequiresCast(const Value *V, const Type *Ty, TargetData *TD) {
385 if (V->getType() == Ty || isa<Constant>(V)) return false;
386
387 // If this is a noop cast, it isn't real codegen.
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000388 if (V->getType()->canLosslesslyBitCastTo(Ty))
Chris Lattner1d441ad2006-05-06 09:00:16 +0000389 return false;
390
Chris Lattner99155be2006-05-25 23:24:33 +0000391 // If this is another cast that can be eliminated, it isn't codegen either.
Chris Lattner1d441ad2006-05-06 09:00:16 +0000392 if (const CastInst *CI = dyn_cast<CastInst>(V))
Reid Spencer14fbdd52006-12-04 02:48:01 +0000393 if (isEliminableCastPair(CI, CastInst::getCastOpcode(
394 V, V->getType()->isSigned(), Ty, Ty->isSigned()), Ty, TD))
Chris Lattner1d441ad2006-05-06 09:00:16 +0000395 return false;
396 return true;
397}
398
399/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
400/// InsertBefore instruction. This is specialized a bit to avoid inserting
401/// casts that are known to not do anything...
402///
Reid Spencer13bc5d72006-12-12 09:18:51 +0000403Value *InstCombiner::InsertOperandCastBefore(Instruction::CastOps opcode,
404 Value *V, const Type *DestTy,
Chris Lattner1d441ad2006-05-06 09:00:16 +0000405 Instruction *InsertBefore) {
406 if (V->getType() == DestTy) return V;
407 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencer13bc5d72006-12-12 09:18:51 +0000408 return ConstantExpr::getCast(opcode, C, DestTy);
Chris Lattner1d441ad2006-05-06 09:00:16 +0000409
Reid Spencer13bc5d72006-12-12 09:18:51 +0000410 return InsertCastBefore(opcode, V, DestTy, *InsertBefore);
Chris Lattner1d441ad2006-05-06 09:00:16 +0000411}
412
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000413// SimplifyCommutative - This performs a few simplifications for commutative
414// operators:
Chris Lattner260ab202002-04-18 17:39:14 +0000415//
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000416// 1. Order operands such that they are listed from right (least complex) to
417// left (most complex). This puts constants before unary operators before
418// binary operators.
419//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000420// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
421// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000422//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000423bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000424 bool Changed = false;
425 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
426 Changed = !I.swapOperands();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000427
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000428 if (!I.isAssociative()) return Changed;
429 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattner7fb29e12003-03-11 00:12:48 +0000430 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
431 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
432 if (isa<Constant>(I.getOperand(1))) {
Chris Lattner34428442003-05-27 16:40:51 +0000433 Constant *Folded = ConstantExpr::get(I.getOpcode(),
434 cast<Constant>(I.getOperand(1)),
435 cast<Constant>(Op->getOperand(1)));
Chris Lattner7fb29e12003-03-11 00:12:48 +0000436 I.setOperand(0, Op->getOperand(0));
437 I.setOperand(1, Folded);
438 return true;
439 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
440 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
441 isOnlyUse(Op) && isOnlyUse(Op1)) {
442 Constant *C1 = cast<Constant>(Op->getOperand(1));
443 Constant *C2 = cast<Constant>(Op1->getOperand(1));
444
445 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner34428442003-05-27 16:40:51 +0000446 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000447 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
448 Op1->getOperand(0),
449 Op1->getName(), &I);
450 WorkList.push_back(New);
451 I.setOperand(0, New);
452 I.setOperand(1, Folded);
453 return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000454 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000455 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000456 return Changed;
Chris Lattner260ab202002-04-18 17:39:14 +0000457}
Chris Lattnerca081252001-12-14 16:52:21 +0000458
Chris Lattnerbb74e222003-03-10 23:06:50 +0000459// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
460// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattner9fa53de2002-05-06 16:49:18 +0000461//
Chris Lattnerbb74e222003-03-10 23:06:50 +0000462static inline Value *dyn_castNegVal(Value *V) {
463 if (BinaryOperator::isNeg(V))
Chris Lattnerd6f636a2005-04-24 07:30:14 +0000464 return BinaryOperator::getNegArgument(V);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000465
Chris Lattner9ad0d552004-12-14 20:08:06 +0000466 // Constants can be considered to be negated values if they can be folded.
467 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
468 return ConstantExpr::getNeg(C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000469 return 0;
Chris Lattner9fa53de2002-05-06 16:49:18 +0000470}
471
Chris Lattnerbb74e222003-03-10 23:06:50 +0000472static inline Value *dyn_castNotVal(Value *V) {
473 if (BinaryOperator::isNot(V))
Chris Lattnerd6f636a2005-04-24 07:30:14 +0000474 return BinaryOperator::getNotArgument(V);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000475
476 // Constants can be considered to be not'ed values...
Chris Lattnerdd65d862003-04-30 22:34:06 +0000477 if (ConstantIntegral *C = dyn_cast<ConstantIntegral>(V))
Chris Lattnerc8e7e292004-06-10 02:12:35 +0000478 return ConstantExpr::getNot(C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000479 return 0;
480}
481
Chris Lattner7fb29e12003-03-11 00:12:48 +0000482// dyn_castFoldableMul - If this value is a multiply that can be folded into
483// other computations (because it has a constant operand), return the
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000484// non-constant operand of the multiply, and set CST to point to the multiplier.
485// Otherwise, return null.
Chris Lattner7fb29e12003-03-11 00:12:48 +0000486//
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000487static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000488 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000489 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattner7fb29e12003-03-11 00:12:48 +0000490 if (I->getOpcode() == Instruction::Mul)
Chris Lattner970136362004-11-15 05:54:07 +0000491 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattner7fb29e12003-03-11 00:12:48 +0000492 return I->getOperand(0);
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000493 if (I->getOpcode() == Instruction::Shl)
Chris Lattner970136362004-11-15 05:54:07 +0000494 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000495 // The multiplier is really 1 << CST.
496 Constant *One = ConstantInt::get(V->getType(), 1);
497 CST = cast<ConstantInt>(ConstantExpr::getShl(One, CST));
498 return I->getOperand(0);
499 }
500 }
Chris Lattner7fb29e12003-03-11 00:12:48 +0000501 return 0;
Chris Lattner3082c5a2003-02-18 19:28:33 +0000502}
Chris Lattner31ae8632002-08-14 17:51:49 +0000503
Chris Lattner0798af32005-01-13 20:14:25 +0000504/// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
505/// expression, return it.
506static User *dyn_castGetElementPtr(Value *V) {
507 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
508 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
509 if (CE->getOpcode() == Instruction::GetElementPtr)
510 return cast<User>(V);
511 return false;
512}
513
Chris Lattner623826c2004-09-28 21:48:02 +0000514// AddOne, SubOne - Add or subtract a constant one from an integer constant...
Chris Lattner6862fbd2004-09-29 17:40:11 +0000515static ConstantInt *AddOne(ConstantInt *C) {
516 return cast<ConstantInt>(ConstantExpr::getAdd(C,
517 ConstantInt::get(C->getType(), 1)));
Chris Lattner623826c2004-09-28 21:48:02 +0000518}
Chris Lattner6862fbd2004-09-29 17:40:11 +0000519static ConstantInt *SubOne(ConstantInt *C) {
520 return cast<ConstantInt>(ConstantExpr::getSub(C,
521 ConstantInt::get(C->getType(), 1)));
Chris Lattner623826c2004-09-28 21:48:02 +0000522}
523
Chris Lattner0157e7f2006-02-11 09:31:47 +0000524/// GetConstantInType - Return a ConstantInt with the specified type and value.
525///
Chris Lattneree0f2802006-02-12 02:07:56 +0000526static ConstantIntegral *GetConstantInType(const Type *Ty, uint64_t Val) {
Reid Spencere0fc4df2006-10-20 07:07:24 +0000527 if (Ty->isUnsigned())
528 return ConstantInt::get(Ty, Val);
Chris Lattneree0f2802006-02-12 02:07:56 +0000529 else if (Ty->getTypeID() == Type::BoolTyID)
530 return ConstantBool::get(Val);
Chris Lattner0157e7f2006-02-11 09:31:47 +0000531 int64_t SVal = Val;
532 SVal <<= 64-Ty->getPrimitiveSizeInBits();
533 SVal >>= 64-Ty->getPrimitiveSizeInBits();
Reid Spencere0fc4df2006-10-20 07:07:24 +0000534 return ConstantInt::get(Ty, SVal);
Chris Lattner0157e7f2006-02-11 09:31:47 +0000535}
536
537
Chris Lattner4534dd592006-02-09 07:38:58 +0000538/// ComputeMaskedBits - Determine which of the bits specified in Mask are
539/// known to be either zero or one and return them in the KnownZero/KnownOne
540/// bitsets. This code only analyzes bits in Mask, in order to short-circuit
541/// processing.
542static void ComputeMaskedBits(Value *V, uint64_t Mask, uint64_t &KnownZero,
543 uint64_t &KnownOne, unsigned Depth = 0) {
Chris Lattner0b3557f2005-09-24 23:43:33 +0000544 // Note, we cannot consider 'undef' to be "IsZero" here. The problem is that
545 // we cannot optimize based on the assumption that it is zero without changing
Chris Lattnerc3ebf402006-02-07 07:27:52 +0000546 // it to be an explicit zero. If we don't change it to zero, other code could
Chris Lattner0b3557f2005-09-24 23:43:33 +0000547 // optimized based on the contradictory assumption that it is non-zero.
548 // Because instcombine aggressively folds operations with undef args anyway,
549 // this won't lose us code quality.
Chris Lattner4534dd592006-02-09 07:38:58 +0000550 if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(V)) {
551 // We know all of the bits for a constant!
Chris Lattner0157e7f2006-02-11 09:31:47 +0000552 KnownOne = CI->getZExtValue() & Mask;
Chris Lattner4534dd592006-02-09 07:38:58 +0000553 KnownZero = ~KnownOne & Mask;
554 return;
555 }
556
557 KnownZero = KnownOne = 0; // Don't know anything.
Chris Lattner92a68652006-02-07 08:05:22 +0000558 if (Depth == 6 || Mask == 0)
Chris Lattner4534dd592006-02-09 07:38:58 +0000559 return; // Limit search depth.
560
561 uint64_t KnownZero2, KnownOne2;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000562 Instruction *I = dyn_cast<Instruction>(V);
563 if (!I) return;
564
Chris Lattnerfb296922006-05-04 17:33:35 +0000565 Mask &= V->getType()->getIntegralTypeMask();
566
Chris Lattner0157e7f2006-02-11 09:31:47 +0000567 switch (I->getOpcode()) {
568 case Instruction::And:
569 // If either the LHS or the RHS are Zero, the result is zero.
570 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
571 Mask &= ~KnownZero;
572 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
573 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
574 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
575
576 // Output known-1 bits are only known if set in both the LHS & RHS.
577 KnownOne &= KnownOne2;
578 // Output known-0 are known to be clear if zero in either the LHS | RHS.
579 KnownZero |= KnownZero2;
580 return;
581 case Instruction::Or:
582 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
583 Mask &= ~KnownOne;
584 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
585 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
586 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
587
588 // Output known-0 bits are only known if clear in both the LHS & RHS.
589 KnownZero &= KnownZero2;
590 // Output known-1 are known to be set if set in either the LHS | RHS.
591 KnownOne |= KnownOne2;
592 return;
593 case Instruction::Xor: {
594 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
595 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
596 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
597 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
598
599 // Output known-0 bits are known if clear or set in both the LHS & RHS.
600 uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
601 // Output known-1 are known to be set if set in only one of the LHS, RHS.
602 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
603 KnownZero = KnownZeroOut;
604 return;
605 }
606 case Instruction::Select:
607 ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
608 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
609 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
610 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
611
612 // Only known if known in both the LHS and RHS.
613 KnownOne &= KnownOne2;
614 KnownZero &= KnownZero2;
615 return;
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000616 case Instruction::FPTrunc:
617 case Instruction::FPExt:
618 case Instruction::FPToUI:
619 case Instruction::FPToSI:
620 case Instruction::SIToFP:
621 case Instruction::PtrToInt:
622 case Instruction::UIToFP:
623 case Instruction::IntToPtr:
624 return; // Can't work with floating point or pointers
625 case Instruction::Trunc:
626 // All these have integer operands
627 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
628 return;
629 case Instruction::BitCast: {
Chris Lattner0157e7f2006-02-11 09:31:47 +0000630 const Type *SrcTy = I->getOperand(0)->getType();
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000631 if (SrcTy->isIntegral()) {
Chris Lattner0157e7f2006-02-11 09:31:47 +0000632 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
Chris Lattner4534dd592006-02-09 07:38:58 +0000633 return;
634 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000635 break;
636 }
637 case Instruction::ZExt: {
638 // Compute the bits in the result that are not present in the input.
639 const Type *SrcTy = I->getOperand(0)->getType();
Chris Lattner0157e7f2006-02-11 09:31:47 +0000640 uint64_t NotIn = ~SrcTy->getIntegralTypeMask();
641 uint64_t NewBits = I->getType()->getIntegralTypeMask() & NotIn;
Chris Lattner62010c42005-10-09 06:36:35 +0000642
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000643 Mask &= SrcTy->getIntegralTypeMask();
644 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
645 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
646 // The top bits are known to be zero.
647 KnownZero |= NewBits;
648 return;
649 }
650 case Instruction::SExt: {
651 // Compute the bits in the result that are not present in the input.
652 const Type *SrcTy = I->getOperand(0)->getType();
653 uint64_t NotIn = ~SrcTy->getIntegralTypeMask();
654 uint64_t NewBits = I->getType()->getIntegralTypeMask() & NotIn;
655
656 Mask &= SrcTy->getIntegralTypeMask();
657 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
658 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattner92a68652006-02-07 08:05:22 +0000659
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000660 // If the sign bit of the input is known set or clear, then we know the
661 // top bits of the result.
662 uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
663 if (KnownZero & InSignBit) { // Input sign bit known zero
664 KnownZero |= NewBits;
665 KnownOne &= ~NewBits;
666 } else if (KnownOne & InSignBit) { // Input sign bit known set
667 KnownOne |= NewBits;
668 KnownZero &= ~NewBits;
669 } else { // Input sign bit unknown
670 KnownZero &= ~NewBits;
671 KnownOne &= ~NewBits;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000672 }
673 return;
674 }
675 case Instruction::Shl:
676 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
Reid Spencere0fc4df2006-10-20 07:07:24 +0000677 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
678 uint64_t ShiftAmt = SA->getZExtValue();
679 Mask >>= ShiftAmt;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000680 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
681 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Reid Spencere0fc4df2006-10-20 07:07:24 +0000682 KnownZero <<= ShiftAmt;
683 KnownOne <<= ShiftAmt;
684 KnownZero |= (1ULL << ShiftAmt)-1; // low bits known zero.
Chris Lattner0157e7f2006-02-11 09:31:47 +0000685 return;
686 }
687 break;
Reid Spencerfdff9382006-11-08 06:47:33 +0000688 case Instruction::LShr:
Chris Lattner0157e7f2006-02-11 09:31:47 +0000689 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
Reid Spencere0fc4df2006-10-20 07:07:24 +0000690 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Chris Lattner0157e7f2006-02-11 09:31:47 +0000691 // Compute the new bits that are at the top now.
Reid Spencere0fc4df2006-10-20 07:07:24 +0000692 uint64_t ShiftAmt = SA->getZExtValue();
693 uint64_t HighBits = (1ULL << ShiftAmt)-1;
694 HighBits <<= I->getType()->getPrimitiveSizeInBits()-ShiftAmt;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000695
Reid Spencerfdff9382006-11-08 06:47:33 +0000696 // Unsigned shift right.
697 Mask <<= ShiftAmt;
698 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
699 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
700 KnownZero >>= ShiftAmt;
701 KnownOne >>= ShiftAmt;
702 KnownZero |= HighBits; // high bits known zero.
703 return;
704 }
705 break;
706 case Instruction::AShr:
707 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
708 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
709 // Compute the new bits that are at the top now.
710 uint64_t ShiftAmt = SA->getZExtValue();
711 uint64_t HighBits = (1ULL << ShiftAmt)-1;
712 HighBits <<= I->getType()->getPrimitiveSizeInBits()-ShiftAmt;
713
714 // Signed shift right.
715 Mask <<= ShiftAmt;
716 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
717 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
718 KnownZero >>= ShiftAmt;
719 KnownOne >>= ShiftAmt;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000720
Reid Spencerfdff9382006-11-08 06:47:33 +0000721 // Handle the sign bits.
722 uint64_t SignBit = 1ULL << (I->getType()->getPrimitiveSizeInBits()-1);
723 SignBit >>= ShiftAmt; // Adjust to where it is now in the mask.
Chris Lattner0157e7f2006-02-11 09:31:47 +0000724
Reid Spencerfdff9382006-11-08 06:47:33 +0000725 if (KnownZero & SignBit) { // New bits are known zero.
726 KnownZero |= HighBits;
727 } else if (KnownOne & SignBit) { // New bits are known one.
728 KnownOne |= HighBits;
Chris Lattner4534dd592006-02-09 07:38:58 +0000729 }
730 return;
Chris Lattner62010c42005-10-09 06:36:35 +0000731 }
Chris Lattner0157e7f2006-02-11 09:31:47 +0000732 break;
Chris Lattner0b3557f2005-09-24 23:43:33 +0000733 }
Chris Lattner92a68652006-02-07 08:05:22 +0000734}
735
736/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
737/// this predicate to simplify operations downstream. Mask is known to be zero
738/// for bits that V cannot have.
739static bool MaskedValueIsZero(Value *V, uint64_t Mask, unsigned Depth = 0) {
Chris Lattner4534dd592006-02-09 07:38:58 +0000740 uint64_t KnownZero, KnownOne;
741 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
742 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
743 return (KnownZero & Mask) == Mask;
Chris Lattner0b3557f2005-09-24 23:43:33 +0000744}
745
Chris Lattner0157e7f2006-02-11 09:31:47 +0000746/// ShrinkDemandedConstant - Check to see if the specified operand of the
747/// specified instruction is a constant integer. If so, check to see if there
748/// are any bits set in the constant that are not demanded. If so, shrink the
749/// constant and return true.
750static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
751 uint64_t Demanded) {
752 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
753 if (!OpC) return false;
754
755 // If there are no bits set that aren't demanded, nothing to do.
756 if ((~Demanded & OpC->getZExtValue()) == 0)
757 return false;
758
759 // This is producing any bits that are not needed, shrink the RHS.
760 uint64_t Val = Demanded & OpC->getZExtValue();
761 I->setOperand(OpNo, GetConstantInType(OpC->getType(), Val));
762 return true;
763}
764
Chris Lattneree0f2802006-02-12 02:07:56 +0000765// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
766// set of known zero and one bits, compute the maximum and minimum values that
767// could have the specified known zero and known one bits, returning them in
768// min/max.
769static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
770 uint64_t KnownZero,
771 uint64_t KnownOne,
772 int64_t &Min, int64_t &Max) {
773 uint64_t TypeBits = Ty->getIntegralTypeMask();
774 uint64_t UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
775
776 uint64_t SignBit = 1ULL << (Ty->getPrimitiveSizeInBits()-1);
777
778 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
779 // bit if it is unknown.
780 Min = KnownOne;
781 Max = KnownOne|UnknownBits;
782
783 if (SignBit & UnknownBits) { // Sign bit is unknown
784 Min |= SignBit;
785 Max &= ~SignBit;
786 }
787
788 // Sign extend the min/max values.
789 int ShAmt = 64-Ty->getPrimitiveSizeInBits();
790 Min = (Min << ShAmt) >> ShAmt;
791 Max = (Max << ShAmt) >> ShAmt;
792}
793
794// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
795// a set of known zero and one bits, compute the maximum and minimum values that
796// could have the specified known zero and known one bits, returning them in
797// min/max.
798static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
799 uint64_t KnownZero,
800 uint64_t KnownOne,
801 uint64_t &Min,
802 uint64_t &Max) {
803 uint64_t TypeBits = Ty->getIntegralTypeMask();
804 uint64_t UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
805
806 // The minimum value is when the unknown bits are all zeros.
807 Min = KnownOne;
808 // The maximum value is when the unknown bits are all ones.
809 Max = KnownOne|UnknownBits;
810}
Chris Lattner0157e7f2006-02-11 09:31:47 +0000811
812
813/// SimplifyDemandedBits - Look at V. At this point, we know that only the
814/// DemandedMask bits of the result of V are ever used downstream. If we can
815/// use this information to simplify V, do so and return true. Otherwise,
816/// analyze the expression and return a mask of KnownOne and KnownZero bits for
817/// the expression (used to simplify the caller). The KnownZero/One bits may
818/// only be accurate for those bits in the DemandedMask.
819bool InstCombiner::SimplifyDemandedBits(Value *V, uint64_t DemandedMask,
820 uint64_t &KnownZero, uint64_t &KnownOne,
Chris Lattner2590e512006-02-07 06:56:34 +0000821 unsigned Depth) {
Chris Lattner0157e7f2006-02-11 09:31:47 +0000822 if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(V)) {
823 // We know all of the bits for a constant!
824 KnownOne = CI->getZExtValue() & DemandedMask;
825 KnownZero = ~KnownOne & DemandedMask;
826 return false;
827 }
828
829 KnownZero = KnownOne = 0;
Chris Lattner2590e512006-02-07 06:56:34 +0000830 if (!V->hasOneUse()) { // Other users may use these bits.
Chris Lattner0157e7f2006-02-11 09:31:47 +0000831 if (Depth != 0) { // Not at the root.
832 // Just compute the KnownZero/KnownOne bits to simplify things downstream.
833 ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
Chris Lattner2590e512006-02-07 06:56:34 +0000834 return false;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000835 }
Chris Lattner2590e512006-02-07 06:56:34 +0000836 // If this is the root being simplified, allow it to have multiple uses,
Chris Lattner0157e7f2006-02-11 09:31:47 +0000837 // just set the DemandedMask to all bits.
838 DemandedMask = V->getType()->getIntegralTypeMask();
839 } else if (DemandedMask == 0) { // Not demanding any bits from V.
Chris Lattner92a68652006-02-07 08:05:22 +0000840 if (V != UndefValue::get(V->getType()))
841 return UpdateValueUsesWith(V, UndefValue::get(V->getType()));
842 return false;
Chris Lattner2590e512006-02-07 06:56:34 +0000843 } else if (Depth == 6) { // Limit search depth.
844 return false;
845 }
846
847 Instruction *I = dyn_cast<Instruction>(V);
848 if (!I) return false; // Only analyze instructions.
849
Chris Lattnerfb296922006-05-04 17:33:35 +0000850 DemandedMask &= V->getType()->getIntegralTypeMask();
851
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000852 uint64_t KnownZero2 = 0, KnownOne2 = 0;
Chris Lattner2590e512006-02-07 06:56:34 +0000853 switch (I->getOpcode()) {
854 default: break;
855 case Instruction::And:
Chris Lattner0157e7f2006-02-11 09:31:47 +0000856 // If either the LHS or the RHS are Zero, the result is zero.
857 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
858 KnownZero, KnownOne, Depth+1))
859 return true;
860 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
861
862 // If something is known zero on the RHS, the bits aren't demanded on the
863 // LHS.
864 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownZero,
865 KnownZero2, KnownOne2, Depth+1))
866 return true;
867 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
868
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000869 // If all of the demanded bits are known 1 on one side, return the other.
Chris Lattner0157e7f2006-02-11 09:31:47 +0000870 // These bits cannot contribute to the result of the 'and'.
871 if ((DemandedMask & ~KnownZero2 & KnownOne) == (DemandedMask & ~KnownZero2))
872 return UpdateValueUsesWith(I, I->getOperand(0));
873 if ((DemandedMask & ~KnownZero & KnownOne2) == (DemandedMask & ~KnownZero))
874 return UpdateValueUsesWith(I, I->getOperand(1));
Chris Lattner5b2edb12006-02-12 08:02:11 +0000875
876 // If all of the demanded bits in the inputs are known zeros, return zero.
877 if ((DemandedMask & (KnownZero|KnownZero2)) == DemandedMask)
878 return UpdateValueUsesWith(I, Constant::getNullValue(I->getType()));
879
Chris Lattner0157e7f2006-02-11 09:31:47 +0000880 // If the RHS is a constant, see if we can simplify it.
Chris Lattner5b2edb12006-02-12 08:02:11 +0000881 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~KnownZero2))
Chris Lattner0157e7f2006-02-11 09:31:47 +0000882 return UpdateValueUsesWith(I, I);
883
884 // Output known-1 bits are only known if set in both the LHS & RHS.
885 KnownOne &= KnownOne2;
886 // Output known-0 are known to be clear if zero in either the LHS | RHS.
887 KnownZero |= KnownZero2;
888 break;
889 case Instruction::Or:
890 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
891 KnownZero, KnownOne, Depth+1))
892 return true;
893 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
894 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownOne,
895 KnownZero2, KnownOne2, Depth+1))
896 return true;
897 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
898
899 // If all of the demanded bits are known zero on one side, return the other.
900 // These bits cannot contribute to the result of the 'or'.
Jeff Cohen0add83e2006-02-18 03:20:33 +0000901 if ((DemandedMask & ~KnownOne2 & KnownZero) == (DemandedMask & ~KnownOne2))
Chris Lattner0157e7f2006-02-11 09:31:47 +0000902 return UpdateValueUsesWith(I, I->getOperand(0));
Jeff Cohen0add83e2006-02-18 03:20:33 +0000903 if ((DemandedMask & ~KnownOne & KnownZero2) == (DemandedMask & ~KnownOne))
Chris Lattner0157e7f2006-02-11 09:31:47 +0000904 return UpdateValueUsesWith(I, I->getOperand(1));
Chris Lattner5b2edb12006-02-12 08:02:11 +0000905
906 // If all of the potentially set bits on one side are known to be set on
907 // the other side, just use the 'other' side.
908 if ((DemandedMask & (~KnownZero) & KnownOne2) ==
909 (DemandedMask & (~KnownZero)))
910 return UpdateValueUsesWith(I, I->getOperand(0));
Nate Begeman8a77efe2006-02-16 21:11:51 +0000911 if ((DemandedMask & (~KnownZero2) & KnownOne) ==
912 (DemandedMask & (~KnownZero2)))
913 return UpdateValueUsesWith(I, I->getOperand(1));
Chris Lattner0157e7f2006-02-11 09:31:47 +0000914
915 // If the RHS is a constant, see if we can simplify it.
916 if (ShrinkDemandedConstant(I, 1, DemandedMask))
917 return UpdateValueUsesWith(I, I);
918
919 // Output known-0 bits are only known if clear in both the LHS & RHS.
920 KnownZero &= KnownZero2;
921 // Output known-1 are known to be set if set in either the LHS | RHS.
922 KnownOne |= KnownOne2;
923 break;
924 case Instruction::Xor: {
925 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
926 KnownZero, KnownOne, Depth+1))
927 return true;
928 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
929 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
930 KnownZero2, KnownOne2, Depth+1))
931 return true;
932 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
933
934 // If all of the demanded bits are known zero on one side, return the other.
935 // These bits cannot contribute to the result of the 'xor'.
936 if ((DemandedMask & KnownZero) == DemandedMask)
937 return UpdateValueUsesWith(I, I->getOperand(0));
938 if ((DemandedMask & KnownZero2) == DemandedMask)
939 return UpdateValueUsesWith(I, I->getOperand(1));
940
941 // Output known-0 bits are known if clear or set in both the LHS & RHS.
942 uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
943 // Output known-1 are known to be set if set in only one of the LHS, RHS.
944 uint64_t KnownOneOut = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
945
Chris Lattner8e9a7b72006-11-27 19:55:07 +0000946 // If all of the demanded bits are known to be zero on one side or the
947 // other, turn this into an *inclusive* or.
Chris Lattner5b2edb12006-02-12 08:02:11 +0000948 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattner8e9a7b72006-11-27 19:55:07 +0000949 if ((DemandedMask & ~KnownZero & ~KnownZero2) == 0) {
950 Instruction *Or =
951 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
952 I->getName());
953 InsertNewInstBefore(Or, *I);
954 return UpdateValueUsesWith(I, Or);
Chris Lattner2590e512006-02-07 06:56:34 +0000955 }
Chris Lattner0157e7f2006-02-11 09:31:47 +0000956
Chris Lattner5b2edb12006-02-12 08:02:11 +0000957 // If all of the demanded bits on one side are known, and all of the set
958 // bits on that side are also known to be set on the other side, turn this
959 // into an AND, as we know the bits will be cleared.
960 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
961 if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask) { // all known
962 if ((KnownOne & KnownOne2) == KnownOne) {
963 Constant *AndC = GetConstantInType(I->getType(),
964 ~KnownOne & DemandedMask);
965 Instruction *And =
966 BinaryOperator::createAnd(I->getOperand(0), AndC, "tmp");
967 InsertNewInstBefore(And, *I);
968 return UpdateValueUsesWith(I, And);
969 }
970 }
971
Chris Lattner0157e7f2006-02-11 09:31:47 +0000972 // If the RHS is a constant, see if we can simplify it.
973 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
974 if (ShrinkDemandedConstant(I, 1, DemandedMask))
975 return UpdateValueUsesWith(I, I);
976
977 KnownZero = KnownZeroOut;
978 KnownOne = KnownOneOut;
979 break;
980 }
981 case Instruction::Select:
982 if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
983 KnownZero, KnownOne, Depth+1))
984 return true;
985 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
986 KnownZero2, KnownOne2, Depth+1))
987 return true;
988 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
989 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
990
991 // If the operands are constants, see if we can simplify them.
992 if (ShrinkDemandedConstant(I, 1, DemandedMask))
993 return UpdateValueUsesWith(I, I);
994 if (ShrinkDemandedConstant(I, 2, DemandedMask))
995 return UpdateValueUsesWith(I, I);
996
997 // Only known if known in both the LHS and RHS.
998 KnownOne &= KnownOne2;
999 KnownZero &= KnownZero2;
1000 break;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001001 case Instruction::Trunc:
1002 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1003 KnownZero, KnownOne, Depth+1))
1004 return true;
1005 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1006 break;
1007 case Instruction::BitCast:
1008 if (!I->getOperand(0)->getType()->isIntegral())
1009 return false;
Chris Lattner850465d2006-09-16 03:14:10 +00001010
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001011 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1012 KnownZero, KnownOne, Depth+1))
1013 return true;
1014 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1015 break;
1016 case Instruction::ZExt: {
1017 // Compute the bits in the result that are not present in the input.
1018 const Type *SrcTy = I->getOperand(0)->getType();
Chris Lattner0157e7f2006-02-11 09:31:47 +00001019 uint64_t NotIn = ~SrcTy->getIntegralTypeMask();
1020 uint64_t NewBits = I->getType()->getIntegralTypeMask() & NotIn;
1021
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001022 DemandedMask &= SrcTy->getIntegralTypeMask();
1023 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1024 KnownZero, KnownOne, Depth+1))
1025 return true;
1026 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1027 // The top bits are known to be zero.
1028 KnownZero |= NewBits;
1029 break;
1030 }
1031 case Instruction::SExt: {
1032 // Compute the bits in the result that are not present in the input.
1033 const Type *SrcTy = I->getOperand(0)->getType();
1034 uint64_t NotIn = ~SrcTy->getIntegralTypeMask();
1035 uint64_t NewBits = I->getType()->getIntegralTypeMask() & NotIn;
1036
1037 // Get the sign bit for the source type
1038 uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
1039 int64_t InputDemandedBits = DemandedMask & SrcTy->getIntegralTypeMask();
Chris Lattner7d852282006-02-13 22:41:07 +00001040
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001041 // If any of the sign extended bits are demanded, we know that the sign
1042 // bit is demanded.
1043 if (NewBits & DemandedMask)
1044 InputDemandedBits |= InSignBit;
Chris Lattner7d852282006-02-13 22:41:07 +00001045
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001046 if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
1047 KnownZero, KnownOne, Depth+1))
1048 return true;
1049 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattner0157e7f2006-02-11 09:31:47 +00001050
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001051 // If the sign bit of the input is known set or clear, then we know the
1052 // top bits of the result.
Chris Lattner2590e512006-02-07 06:56:34 +00001053
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001054 // If the input sign bit is known zero, or if the NewBits are not demanded
1055 // convert this into a zero extension.
1056 if ((KnownZero & InSignBit) || (NewBits & ~DemandedMask) == NewBits) {
1057 // Convert to ZExt cast
1058 CastInst *NewCast = CastInst::create(
1059 Instruction::ZExt, I->getOperand(0), I->getType(), I->getName(), I);
1060 return UpdateValueUsesWith(I, NewCast);
1061 } else if (KnownOne & InSignBit) { // Input sign bit known set
1062 KnownOne |= NewBits;
1063 KnownZero &= ~NewBits;
1064 } else { // Input sign bit unknown
1065 KnownZero &= ~NewBits;
1066 KnownOne &= ~NewBits;
Chris Lattner2590e512006-02-07 06:56:34 +00001067 }
Chris Lattner0157e7f2006-02-11 09:31:47 +00001068 break;
Chris Lattner2590e512006-02-07 06:56:34 +00001069 }
Chris Lattner6e2c15c2006-11-09 05:12:27 +00001070 case Instruction::Add:
1071 // If there is a constant on the RHS, there are a variety of xformations
1072 // we can do.
1073 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1074 // If null, this should be simplified elsewhere. Some of the xforms here
1075 // won't work if the RHS is zero.
1076 if (RHS->isNullValue())
1077 break;
1078
1079 // Figure out what the input bits are. If the top bits of the and result
1080 // are not demanded, then the add doesn't demand them from its input
1081 // either.
1082
1083 // Shift the demanded mask up so that it's at the top of the uint64_t.
1084 unsigned BitWidth = I->getType()->getPrimitiveSizeInBits();
1085 unsigned NLZ = CountLeadingZeros_64(DemandedMask << (64-BitWidth));
1086
1087 // If the top bit of the output is demanded, demand everything from the
1088 // input. Otherwise, we demand all the input bits except NLZ top bits.
1089 uint64_t InDemandedBits = ~0ULL >> 64-BitWidth+NLZ;
1090
1091 // Find information about known zero/one bits in the input.
1092 if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits,
1093 KnownZero2, KnownOne2, Depth+1))
1094 return true;
1095
1096 // If the RHS of the add has bits set that can't affect the input, reduce
1097 // the constant.
1098 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1099 return UpdateValueUsesWith(I, I);
1100
1101 // Avoid excess work.
1102 if (KnownZero2 == 0 && KnownOne2 == 0)
1103 break;
1104
1105 // Turn it into OR if input bits are zero.
1106 if ((KnownZero2 & RHS->getZExtValue()) == RHS->getZExtValue()) {
1107 Instruction *Or =
1108 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1109 I->getName());
1110 InsertNewInstBefore(Or, *I);
1111 return UpdateValueUsesWith(I, Or);
1112 }
1113
1114 // We can say something about the output known-zero and known-one bits,
1115 // depending on potential carries from the input constant and the
1116 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1117 // bits set and the RHS constant is 0x01001, then we know we have a known
1118 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1119
1120 // To compute this, we first compute the potential carry bits. These are
1121 // the bits which may be modified. I'm not aware of a better way to do
1122 // this scan.
1123 uint64_t RHSVal = RHS->getZExtValue();
1124
1125 bool CarryIn = false;
1126 uint64_t CarryBits = 0;
1127 uint64_t CurBit = 1;
1128 for (unsigned i = 0; i != BitWidth; ++i, CurBit <<= 1) {
1129 // Record the current carry in.
1130 if (CarryIn) CarryBits |= CurBit;
1131
1132 bool CarryOut;
1133
1134 // This bit has a carry out unless it is "zero + zero" or
1135 // "zero + anything" with no carry in.
1136 if ((KnownZero2 & CurBit) && ((RHSVal & CurBit) == 0)) {
1137 CarryOut = false; // 0 + 0 has no carry out, even with carry in.
1138 } else if (!CarryIn &&
1139 ((KnownZero2 & CurBit) || ((RHSVal & CurBit) == 0))) {
1140 CarryOut = false; // 0 + anything has no carry out if no carry in.
1141 } else {
1142 // Otherwise, we have to assume we have a carry out.
1143 CarryOut = true;
1144 }
1145
1146 // This stage's carry out becomes the next stage's carry-in.
1147 CarryIn = CarryOut;
1148 }
1149
1150 // Now that we know which bits have carries, compute the known-1/0 sets.
1151
1152 // Bits are known one if they are known zero in one operand and one in the
1153 // other, and there is no input carry.
1154 KnownOne = ((KnownZero2 & RHSVal) | (KnownOne2 & ~RHSVal)) & ~CarryBits;
1155
1156 // Bits are known zero if they are known zero in both operands and there
1157 // is no input carry.
1158 KnownZero = KnownZero2 & ~RHSVal & ~CarryBits;
1159 }
1160 break;
Chris Lattner2590e512006-02-07 06:56:34 +00001161 case Instruction::Shl:
Reid Spencere0fc4df2006-10-20 07:07:24 +00001162 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1163 uint64_t ShiftAmt = SA->getZExtValue();
1164 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask >> ShiftAmt,
Chris Lattner0157e7f2006-02-11 09:31:47 +00001165 KnownZero, KnownOne, Depth+1))
1166 return true;
1167 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Reid Spencere0fc4df2006-10-20 07:07:24 +00001168 KnownZero <<= ShiftAmt;
1169 KnownOne <<= ShiftAmt;
1170 KnownZero |= (1ULL << ShiftAmt) - 1; // low bits known zero.
Chris Lattner0157e7f2006-02-11 09:31:47 +00001171 }
Chris Lattner2590e512006-02-07 06:56:34 +00001172 break;
Reid Spencerfdff9382006-11-08 06:47:33 +00001173 case Instruction::LShr:
1174 // For a logical shift right
1175 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1176 unsigned ShiftAmt = SA->getZExtValue();
1177
1178 // Compute the new bits that are at the top now.
1179 uint64_t HighBits = (1ULL << ShiftAmt)-1;
1180 HighBits <<= I->getType()->getPrimitiveSizeInBits() - ShiftAmt;
1181 uint64_t TypeMask = I->getType()->getIntegralTypeMask();
1182 // Unsigned shift right.
1183 if (SimplifyDemandedBits(I->getOperand(0),
1184 (DemandedMask << ShiftAmt) & TypeMask,
1185 KnownZero, KnownOne, Depth+1))
1186 return true;
1187 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1188 KnownZero &= TypeMask;
1189 KnownOne &= TypeMask;
1190 KnownZero >>= ShiftAmt;
1191 KnownOne >>= ShiftAmt;
1192 KnownZero |= HighBits; // high bits known zero.
1193 }
1194 break;
1195 case Instruction::AShr:
Chris Lattner420c4bc2006-09-18 04:31:40 +00001196 // If this is an arithmetic shift right and only the low-bit is set, we can
1197 // always convert this into a logical shr, even if the shift amount is
1198 // variable. The low bit of the shift cannot be an input sign bit unless
1199 // the shift amount is >= the size of the datatype, which is undefined.
Reid Spencerfdff9382006-11-08 06:47:33 +00001200 if (DemandedMask == 1) {
1201 // Perform the logical shift right.
1202 Value *NewVal = new ShiftInst(Instruction::LShr, I->getOperand(0),
1203 I->getOperand(1), I->getName());
Reid Spencer00c482b2006-10-26 19:19:06 +00001204 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
Chris Lattner420c4bc2006-09-18 04:31:40 +00001205 return UpdateValueUsesWith(I, NewVal);
1206 }
1207
Reid Spencere0fc4df2006-10-20 07:07:24 +00001208 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1209 unsigned ShiftAmt = SA->getZExtValue();
Chris Lattner0157e7f2006-02-11 09:31:47 +00001210
1211 // Compute the new bits that are at the top now.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001212 uint64_t HighBits = (1ULL << ShiftAmt)-1;
1213 HighBits <<= I->getType()->getPrimitiveSizeInBits() - ShiftAmt;
Chris Lattner68e74752006-02-13 06:09:08 +00001214 uint64_t TypeMask = I->getType()->getIntegralTypeMask();
Reid Spencerfdff9382006-11-08 06:47:33 +00001215 // Signed shift right.
1216 if (SimplifyDemandedBits(I->getOperand(0),
1217 (DemandedMask << ShiftAmt) & TypeMask,
1218 KnownZero, KnownOne, Depth+1))
1219 return true;
1220 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1221 KnownZero &= TypeMask;
1222 KnownOne &= TypeMask;
1223 KnownZero >>= ShiftAmt;
1224 KnownOne >>= ShiftAmt;
Chris Lattner0157e7f2006-02-11 09:31:47 +00001225
Reid Spencerfdff9382006-11-08 06:47:33 +00001226 // Handle the sign bits.
1227 uint64_t SignBit = 1ULL << (I->getType()->getPrimitiveSizeInBits()-1);
1228 SignBit >>= ShiftAmt; // Adjust to where it is now in the mask.
Chris Lattner0157e7f2006-02-11 09:31:47 +00001229
Reid Spencerfdff9382006-11-08 06:47:33 +00001230 // If the input sign bit is known to be zero, or if none of the top bits
1231 // are demanded, turn this into an unsigned shift right.
1232 if ((KnownZero & SignBit) || (HighBits & ~DemandedMask) == HighBits) {
1233 // Perform the logical shift right.
1234 Value *NewVal = new ShiftInst(Instruction::LShr, I->getOperand(0),
1235 SA, I->getName());
1236 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1237 return UpdateValueUsesWith(I, NewVal);
1238 } else if (KnownOne & SignBit) { // New bits are known one.
1239 KnownOne |= HighBits;
Chris Lattner2590e512006-02-07 06:56:34 +00001240 }
Chris Lattner0157e7f2006-02-11 09:31:47 +00001241 }
Chris Lattner2590e512006-02-07 06:56:34 +00001242 break;
1243 }
Chris Lattner0157e7f2006-02-11 09:31:47 +00001244
1245 // If the client is only demanding bits that we know, return the known
1246 // constant.
1247 if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask)
1248 return UpdateValueUsesWith(I, GetConstantInType(I->getType(), KnownOne));
Chris Lattner2590e512006-02-07 06:56:34 +00001249 return false;
1250}
1251
Chris Lattner2deeaea2006-10-05 06:55:50 +00001252
1253/// SimplifyDemandedVectorElts - The specified value producecs a vector with
1254/// 64 or fewer elements. DemandedElts contains the set of elements that are
1255/// actually used by the caller. This method analyzes which elements of the
1256/// operand are undef and returns that information in UndefElts.
1257///
1258/// If the information about demanded elements can be used to simplify the
1259/// operation, the operation is simplified, then the resultant value is
1260/// returned. This returns null if no change was made.
1261Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1262 uint64_t &UndefElts,
1263 unsigned Depth) {
1264 unsigned VWidth = cast<PackedType>(V->getType())->getNumElements();
1265 assert(VWidth <= 64 && "Vector too wide to analyze!");
1266 uint64_t EltMask = ~0ULL >> (64-VWidth);
1267 assert(DemandedElts != EltMask && (DemandedElts & ~EltMask) == 0 &&
1268 "Invalid DemandedElts!");
1269
1270 if (isa<UndefValue>(V)) {
1271 // If the entire vector is undefined, just return this info.
1272 UndefElts = EltMask;
1273 return 0;
1274 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1275 UndefElts = EltMask;
1276 return UndefValue::get(V->getType());
1277 }
1278
1279 UndefElts = 0;
1280 if (ConstantPacked *CP = dyn_cast<ConstantPacked>(V)) {
1281 const Type *EltTy = cast<PackedType>(V->getType())->getElementType();
1282 Constant *Undef = UndefValue::get(EltTy);
1283
1284 std::vector<Constant*> Elts;
1285 for (unsigned i = 0; i != VWidth; ++i)
1286 if (!(DemandedElts & (1ULL << i))) { // If not demanded, set to undef.
1287 Elts.push_back(Undef);
1288 UndefElts |= (1ULL << i);
1289 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1290 Elts.push_back(Undef);
1291 UndefElts |= (1ULL << i);
1292 } else { // Otherwise, defined.
1293 Elts.push_back(CP->getOperand(i));
1294 }
1295
1296 // If we changed the constant, return it.
1297 Constant *NewCP = ConstantPacked::get(Elts);
1298 return NewCP != CP ? NewCP : 0;
1299 } else if (isa<ConstantAggregateZero>(V)) {
1300 // Simplify the CAZ to a ConstantPacked where the non-demanded elements are
1301 // set to undef.
1302 const Type *EltTy = cast<PackedType>(V->getType())->getElementType();
1303 Constant *Zero = Constant::getNullValue(EltTy);
1304 Constant *Undef = UndefValue::get(EltTy);
1305 std::vector<Constant*> Elts;
1306 for (unsigned i = 0; i != VWidth; ++i)
1307 Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1308 UndefElts = DemandedElts ^ EltMask;
1309 return ConstantPacked::get(Elts);
1310 }
1311
1312 if (!V->hasOneUse()) { // Other users may use these bits.
1313 if (Depth != 0) { // Not at the root.
1314 // TODO: Just compute the UndefElts information recursively.
1315 return false;
1316 }
1317 return false;
1318 } else if (Depth == 10) { // Limit search depth.
1319 return false;
1320 }
1321
1322 Instruction *I = dyn_cast<Instruction>(V);
1323 if (!I) return false; // Only analyze instructions.
1324
1325 bool MadeChange = false;
1326 uint64_t UndefElts2;
1327 Value *TmpV;
1328 switch (I->getOpcode()) {
1329 default: break;
1330
1331 case Instruction::InsertElement: {
1332 // If this is a variable index, we don't know which element it overwrites.
1333 // demand exactly the same input as we produce.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001334 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
Chris Lattner2deeaea2006-10-05 06:55:50 +00001335 if (Idx == 0) {
1336 // Note that we can't propagate undef elt info, because we don't know
1337 // which elt is getting updated.
1338 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1339 UndefElts2, Depth+1);
1340 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1341 break;
1342 }
1343
1344 // If this is inserting an element that isn't demanded, remove this
1345 // insertelement.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001346 unsigned IdxNo = Idx->getZExtValue();
Chris Lattner2deeaea2006-10-05 06:55:50 +00001347 if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1348 return AddSoonDeadInstToWorklist(*I, 0);
1349
1350 // Otherwise, the element inserted overwrites whatever was there, so the
1351 // input demanded set is simpler than the output set.
1352 TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1353 DemandedElts & ~(1ULL << IdxNo),
1354 UndefElts, Depth+1);
1355 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1356
1357 // The inserted element is defined.
1358 UndefElts |= 1ULL << IdxNo;
1359 break;
1360 }
1361
1362 case Instruction::And:
1363 case Instruction::Or:
1364 case Instruction::Xor:
1365 case Instruction::Add:
1366 case Instruction::Sub:
1367 case Instruction::Mul:
1368 // div/rem demand all inputs, because they don't want divide by zero.
1369 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1370 UndefElts, Depth+1);
1371 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1372 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1373 UndefElts2, Depth+1);
1374 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1375
1376 // Output elements are undefined if both are undefined. Consider things
1377 // like undef&0. The result is known zero, not undef.
1378 UndefElts &= UndefElts2;
1379 break;
1380
1381 case Instruction::Call: {
1382 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1383 if (!II) break;
1384 switch (II->getIntrinsicID()) {
1385 default: break;
1386
1387 // Binary vector operations that work column-wise. A dest element is a
1388 // function of the corresponding input elements from the two inputs.
1389 case Intrinsic::x86_sse_sub_ss:
1390 case Intrinsic::x86_sse_mul_ss:
1391 case Intrinsic::x86_sse_min_ss:
1392 case Intrinsic::x86_sse_max_ss:
1393 case Intrinsic::x86_sse2_sub_sd:
1394 case Intrinsic::x86_sse2_mul_sd:
1395 case Intrinsic::x86_sse2_min_sd:
1396 case Intrinsic::x86_sse2_max_sd:
1397 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1398 UndefElts, Depth+1);
1399 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1400 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1401 UndefElts2, Depth+1);
1402 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1403
1404 // If only the low elt is demanded and this is a scalarizable intrinsic,
1405 // scalarize it now.
1406 if (DemandedElts == 1) {
1407 switch (II->getIntrinsicID()) {
1408 default: break;
1409 case Intrinsic::x86_sse_sub_ss:
1410 case Intrinsic::x86_sse_mul_ss:
1411 case Intrinsic::x86_sse2_sub_sd:
1412 case Intrinsic::x86_sse2_mul_sd:
1413 // TODO: Lower MIN/MAX/ABS/etc
1414 Value *LHS = II->getOperand(1);
1415 Value *RHS = II->getOperand(2);
1416 // Extract the element as scalars.
1417 LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1418 RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1419
1420 switch (II->getIntrinsicID()) {
1421 default: assert(0 && "Case stmts out of sync!");
1422 case Intrinsic::x86_sse_sub_ss:
1423 case Intrinsic::x86_sse2_sub_sd:
1424 TmpV = InsertNewInstBefore(BinaryOperator::createSub(LHS, RHS,
1425 II->getName()), *II);
1426 break;
1427 case Intrinsic::x86_sse_mul_ss:
1428 case Intrinsic::x86_sse2_mul_sd:
1429 TmpV = InsertNewInstBefore(BinaryOperator::createMul(LHS, RHS,
1430 II->getName()), *II);
1431 break;
1432 }
1433
1434 Instruction *New =
1435 new InsertElementInst(UndefValue::get(II->getType()), TmpV, 0U,
1436 II->getName());
1437 InsertNewInstBefore(New, *II);
1438 AddSoonDeadInstToWorklist(*II, 0);
1439 return New;
1440 }
1441 }
1442
1443 // Output elements are undefined if both are undefined. Consider things
1444 // like undef&0. The result is known zero, not undef.
1445 UndefElts &= UndefElts2;
1446 break;
1447 }
1448 break;
1449 }
1450 }
1451 return MadeChange ? I : 0;
1452}
1453
Chris Lattner623826c2004-09-28 21:48:02 +00001454// isTrueWhenEqual - Return true if the specified setcondinst instruction is
1455// true when both operands are equal...
1456//
1457static bool isTrueWhenEqual(Instruction &I) {
1458 return I.getOpcode() == Instruction::SetEQ ||
1459 I.getOpcode() == Instruction::SetGE ||
1460 I.getOpcode() == Instruction::SetLE;
1461}
Chris Lattnerb8b97502003-08-13 19:01:45 +00001462
1463/// AssociativeOpt - Perform an optimization on an associative operator. This
1464/// function is designed to check a chain of associative operators for a
1465/// potential to apply a certain optimization. Since the optimization may be
1466/// applicable if the expression was reassociated, this checks the chain, then
1467/// reassociates the expression as necessary to expose the optimization
1468/// opportunity. This makes use of a special Functor, which must define
1469/// 'shouldApply' and 'apply' methods.
1470///
1471template<typename Functor>
1472Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1473 unsigned Opcode = Root.getOpcode();
1474 Value *LHS = Root.getOperand(0);
1475
1476 // Quick check, see if the immediate LHS matches...
1477 if (F.shouldApply(LHS))
1478 return F.apply(Root);
1479
1480 // Otherwise, if the LHS is not of the same opcode as the root, return.
1481 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001482 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattnerb8b97502003-08-13 19:01:45 +00001483 // Should we apply this transform to the RHS?
1484 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1485
1486 // If not to the RHS, check to see if we should apply to the LHS...
1487 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1488 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1489 ShouldApply = true;
1490 }
1491
1492 // If the functor wants to apply the optimization to the RHS of LHSI,
1493 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1494 if (ShouldApply) {
1495 BasicBlock *BB = Root.getParent();
Misha Brukmanb1c93172005-04-21 23:48:37 +00001496
Chris Lattnerb8b97502003-08-13 19:01:45 +00001497 // Now all of the instructions are in the current basic block, go ahead
1498 // and perform the reassociation.
1499 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1500
1501 // First move the selected RHS to the LHS of the root...
1502 Root.setOperand(0, LHSI->getOperand(1));
1503
1504 // Make what used to be the LHS of the root be the user of the root...
1505 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner284d3b02004-04-16 18:08:07 +00001506 if (&Root == TmpLHSI) {
Chris Lattner8953b902004-04-05 02:10:19 +00001507 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1508 return 0;
1509 }
Chris Lattner284d3b02004-04-16 18:08:07 +00001510 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattnerb8b97502003-08-13 19:01:45 +00001511 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner284d3b02004-04-16 18:08:07 +00001512 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
1513 BasicBlock::iterator ARI = &Root; ++ARI;
1514 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
1515 ARI = Root;
Chris Lattnerb8b97502003-08-13 19:01:45 +00001516
1517 // Now propagate the ExtraOperand down the chain of instructions until we
1518 // get to LHSI.
1519 while (TmpLHSI != LHSI) {
1520 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner284d3b02004-04-16 18:08:07 +00001521 // Move the instruction to immediately before the chain we are
1522 // constructing to avoid breaking dominance properties.
1523 NextLHSI->getParent()->getInstList().remove(NextLHSI);
1524 BB->getInstList().insert(ARI, NextLHSI);
1525 ARI = NextLHSI;
1526
Chris Lattnerb8b97502003-08-13 19:01:45 +00001527 Value *NextOp = NextLHSI->getOperand(1);
1528 NextLHSI->setOperand(1, ExtraOperand);
1529 TmpLHSI = NextLHSI;
1530 ExtraOperand = NextOp;
1531 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001532
Chris Lattnerb8b97502003-08-13 19:01:45 +00001533 // Now that the instructions are reassociated, have the functor perform
1534 // the transformation...
1535 return F.apply(Root);
1536 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001537
Chris Lattnerb8b97502003-08-13 19:01:45 +00001538 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1539 }
1540 return 0;
1541}
1542
1543
1544// AddRHS - Implements: X + X --> X << 1
1545struct AddRHS {
1546 Value *RHS;
1547 AddRHS(Value *rhs) : RHS(rhs) {}
1548 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1549 Instruction *apply(BinaryOperator &Add) const {
1550 return new ShiftInst(Instruction::Shl, Add.getOperand(0),
1551 ConstantInt::get(Type::UByteTy, 1));
1552 }
1553};
1554
1555// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1556// iff C1&C2 == 0
1557struct AddMaskingAnd {
1558 Constant *C2;
1559 AddMaskingAnd(Constant *c) : C2(c) {}
1560 bool shouldApply(Value *LHS) const {
Chris Lattnerd4252a72004-07-30 07:50:03 +00001561 ConstantInt *C1;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001562 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Chris Lattnerd4252a72004-07-30 07:50:03 +00001563 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattnerb8b97502003-08-13 19:01:45 +00001564 }
1565 Instruction *apply(BinaryOperator &Add) const {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001566 return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattnerb8b97502003-08-13 19:01:45 +00001567 }
1568};
1569
Chris Lattner86102b82005-01-01 16:22:27 +00001570static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner183b3362004-04-09 19:05:30 +00001571 InstCombiner *IC) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001572 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
Chris Lattner86102b82005-01-01 16:22:27 +00001573 if (Constant *SOC = dyn_cast<Constant>(SO))
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001574 return ConstantExpr::getCast(CI->getOpcode(), SOC, I.getType());
Misha Brukmanb1c93172005-04-21 23:48:37 +00001575
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001576 return IC->InsertNewInstBefore(CastInst::create(
1577 CI->getOpcode(), SO, I.getType(), SO->getName() + ".cast"), I);
Chris Lattner86102b82005-01-01 16:22:27 +00001578 }
1579
Chris Lattner183b3362004-04-09 19:05:30 +00001580 // Figure out if the constant is the left or the right argument.
Chris Lattner86102b82005-01-01 16:22:27 +00001581 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1582 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattnerb8b97502003-08-13 19:01:45 +00001583
Chris Lattner183b3362004-04-09 19:05:30 +00001584 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1585 if (ConstIsRHS)
Chris Lattner86102b82005-01-01 16:22:27 +00001586 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1587 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner183b3362004-04-09 19:05:30 +00001588 }
1589
1590 Value *Op0 = SO, *Op1 = ConstOperand;
1591 if (!ConstIsRHS)
1592 std::swap(Op0, Op1);
1593 Instruction *New;
Chris Lattner86102b82005-01-01 16:22:27 +00001594 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1595 New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
1596 else if (ShiftInst *SI = dyn_cast<ShiftInst>(&I))
1597 New = new ShiftInst(SI->getOpcode(), Op0, Op1, SO->getName()+".sh");
Chris Lattnerf9d96652004-04-10 19:15:56 +00001598 else {
Chris Lattner183b3362004-04-09 19:05:30 +00001599 assert(0 && "Unknown binary instruction type!");
Chris Lattnerf9d96652004-04-10 19:15:56 +00001600 abort();
1601 }
Chris Lattner86102b82005-01-01 16:22:27 +00001602 return IC->InsertNewInstBefore(New, I);
1603}
1604
1605// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1606// constant as the other operand, try to fold the binary operator into the
1607// select arguments. This also works for Cast instructions, which obviously do
1608// not have a second operand.
1609static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1610 InstCombiner *IC) {
1611 // Don't modify shared select instructions
1612 if (!SI->hasOneUse()) return 0;
1613 Value *TV = SI->getOperand(1);
1614 Value *FV = SI->getOperand(2);
1615
1616 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner374e6592005-04-21 05:43:13 +00001617 // Bool selects with constant operands can be folded to logical ops.
1618 if (SI->getType() == Type::BoolTy) return 0;
1619
Chris Lattner86102b82005-01-01 16:22:27 +00001620 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1621 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1622
1623 return new SelectInst(SI->getCondition(), SelectTrueVal,
1624 SelectFalseVal);
1625 }
1626 return 0;
Chris Lattner183b3362004-04-09 19:05:30 +00001627}
1628
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001629
1630/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1631/// node as operand #0, see if we can fold the instruction into the PHI (which
1632/// is only possible if all operands to the PHI are constants).
1633Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1634 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattner7515cab2004-11-14 19:13:23 +00001635 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner04689872006-09-09 22:02:56 +00001636 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001637
Chris Lattner04689872006-09-09 22:02:56 +00001638 // Check to see if all of the operands of the PHI are constants. If there is
1639 // one non-constant value, remember the BB it is. If there is more than one
1640 // bail out.
1641 BasicBlock *NonConstBB = 0;
1642 for (unsigned i = 0; i != NumPHIValues; ++i)
1643 if (!isa<Constant>(PN->getIncomingValue(i))) {
1644 if (NonConstBB) return 0; // More than one non-const value.
1645 NonConstBB = PN->getIncomingBlock(i);
1646
1647 // If the incoming non-constant value is in I's block, we have an infinite
1648 // loop.
1649 if (NonConstBB == I.getParent())
1650 return 0;
1651 }
1652
1653 // If there is exactly one non-constant value, we can insert a copy of the
1654 // operation in that block. However, if this is a critical edge, we would be
1655 // inserting the computation one some other paths (e.g. inside a loop). Only
1656 // do this if the pred block is unconditionally branching into the phi block.
1657 if (NonConstBB) {
1658 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1659 if (!BI || !BI->isUnconditional()) return 0;
1660 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001661
1662 // Okay, we can do the transformation: create the new PHI node.
1663 PHINode *NewPN = new PHINode(I.getType(), I.getName());
1664 I.setName("");
Chris Lattnerd8e20182005-01-29 00:39:08 +00001665 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001666 InsertNewInstBefore(NewPN, *PN);
1667
1668 // Next, add all of the operands to the PHI.
1669 if (I.getNumOperands() == 2) {
1670 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattner7515cab2004-11-14 19:13:23 +00001671 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner04689872006-09-09 22:02:56 +00001672 Value *InV;
1673 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1674 InV = ConstantExpr::get(I.getOpcode(), InC, C);
1675 } else {
1676 assert(PN->getIncomingBlock(i) == NonConstBB);
1677 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1678 InV = BinaryOperator::create(BO->getOpcode(),
1679 PN->getIncomingValue(i), C, "phitmp",
1680 NonConstBB->getTerminator());
1681 else if (ShiftInst *SI = dyn_cast<ShiftInst>(&I))
1682 InV = new ShiftInst(SI->getOpcode(),
1683 PN->getIncomingValue(i), C, "phitmp",
1684 NonConstBB->getTerminator());
1685 else
1686 assert(0 && "Unknown binop!");
1687
1688 WorkList.push_back(cast<Instruction>(InV));
1689 }
1690 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001691 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001692 } else {
1693 CastInst *CI = cast<CastInst>(&I);
1694 const Type *RetTy = CI->getType();
Chris Lattner7515cab2004-11-14 19:13:23 +00001695 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner04689872006-09-09 22:02:56 +00001696 Value *InV;
1697 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001698 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Chris Lattner04689872006-09-09 22:02:56 +00001699 } else {
1700 assert(PN->getIncomingBlock(i) == NonConstBB);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001701 InV = CastInst::create(CI->getOpcode(), PN->getIncomingValue(i),
1702 I.getType(), "phitmp",
1703 NonConstBB->getTerminator());
Chris Lattner04689872006-09-09 22:02:56 +00001704 WorkList.push_back(cast<Instruction>(InV));
1705 }
1706 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001707 }
1708 }
1709 return ReplaceInstUsesWith(I, NewPN);
1710}
1711
Chris Lattner113f4f42002-06-25 16:13:24 +00001712Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001713 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00001714 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattner9fa53de2002-05-06 16:49:18 +00001715
Chris Lattnercf4a9962004-04-10 22:01:55 +00001716 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattner81a7a232004-10-16 18:11:37 +00001717 // X + undef -> undef
1718 if (isa<UndefValue>(RHS))
1719 return ReplaceInstUsesWith(I, RHS);
1720
Chris Lattnercf4a9962004-04-10 22:01:55 +00001721 // X + 0 --> X
Chris Lattner7a002fe2006-12-02 00:13:08 +00001722 if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
Chris Lattner7fde91e2005-10-17 17:56:38 +00001723 if (RHSC->isNullValue())
1724 return ReplaceInstUsesWith(I, LHS);
Chris Lattnerda1b1522005-10-17 20:18:38 +00001725 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
1726 if (CFP->isExactlyValue(-0.0))
1727 return ReplaceInstUsesWith(I, LHS);
Chris Lattner7fde91e2005-10-17 17:56:38 +00001728 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001729
Chris Lattnercf4a9962004-04-10 22:01:55 +00001730 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattner6e2c15c2006-11-09 05:12:27 +00001731 // X + (signbit) --> X ^ signbit
Chris Lattner92a68652006-02-07 08:05:22 +00001732 uint64_t Val = CI->getZExtValue();
Chris Lattner77defba2006-02-07 07:00:41 +00001733 if (Val == (1ULL << (CI->getType()->getPrimitiveSizeInBits()-1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001734 return BinaryOperator::createXor(LHS, RHS);
Chris Lattner6e2c15c2006-11-09 05:12:27 +00001735
1736 // See if SimplifyDemandedBits can simplify this. This handles stuff like
1737 // (X & 254)+1 -> (X&254)|1
1738 uint64_t KnownZero, KnownOne;
1739 if (!isa<PackedType>(I.getType()) &&
1740 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
1741 KnownZero, KnownOne))
1742 return &I;
Chris Lattnercf4a9962004-04-10 22:01:55 +00001743 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001744
1745 if (isa<PHINode>(LHS))
1746 if (Instruction *NV = FoldOpIntoPhi(I))
1747 return NV;
Chris Lattner0b3557f2005-09-24 23:43:33 +00001748
Chris Lattner330628a2006-01-06 17:59:59 +00001749 ConstantInt *XorRHS = 0;
1750 Value *XorLHS = 0;
Chris Lattner0b3557f2005-09-24 23:43:33 +00001751 if (match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
1752 unsigned TySizeBits = I.getType()->getPrimitiveSizeInBits();
1753 int64_t RHSSExt = cast<ConstantInt>(RHSC)->getSExtValue();
1754 uint64_t RHSZExt = cast<ConstantInt>(RHSC)->getZExtValue();
1755
1756 uint64_t C0080Val = 1ULL << 31;
1757 int64_t CFF80Val = -C0080Val;
1758 unsigned Size = 32;
1759 do {
1760 if (TySizeBits > Size) {
1761 bool Found = false;
1762 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
1763 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
1764 if (RHSSExt == CFF80Val) {
1765 if (XorRHS->getZExtValue() == C0080Val)
1766 Found = true;
1767 } else if (RHSZExt == C0080Val) {
1768 if (XorRHS->getSExtValue() == CFF80Val)
1769 Found = true;
1770 }
1771 if (Found) {
1772 // This is a sign extend if the top bits are known zero.
Chris Lattner4534dd592006-02-09 07:38:58 +00001773 uint64_t Mask = ~0ULL;
Chris Lattnerc3ebf402006-02-07 07:27:52 +00001774 Mask <<= 64-(TySizeBits-Size);
Chris Lattner4534dd592006-02-09 07:38:58 +00001775 Mask &= XorLHS->getType()->getIntegralTypeMask();
Chris Lattnerc3ebf402006-02-07 07:27:52 +00001776 if (!MaskedValueIsZero(XorLHS, Mask))
Chris Lattner0b3557f2005-09-24 23:43:33 +00001777 Size = 0; // Not a sign ext, but can't be any others either.
1778 goto FoundSExt;
1779 }
1780 }
1781 Size >>= 1;
1782 C0080Val >>= Size;
1783 CFF80Val >>= Size;
1784 } while (Size >= 8);
1785
1786FoundSExt:
1787 const Type *MiddleType = 0;
1788 switch (Size) {
1789 default: break;
1790 case 32: MiddleType = Type::IntTy; break;
1791 case 16: MiddleType = Type::ShortTy; break;
1792 case 8: MiddleType = Type::SByteTy; break;
1793 }
1794 if (MiddleType) {
Reid Spencerbb65ebf2006-12-12 23:36:14 +00001795 Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
Chris Lattner0b3557f2005-09-24 23:43:33 +00001796 InsertNewInstBefore(NewTrunc, I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001797 return new SExtInst(NewTrunc, I.getType());
Chris Lattner0b3557f2005-09-24 23:43:33 +00001798 }
1799 }
Chris Lattnercf4a9962004-04-10 22:01:55 +00001800 }
Chris Lattner9fa53de2002-05-06 16:49:18 +00001801
Chris Lattnerb8b97502003-08-13 19:01:45 +00001802 // X + X --> X << 1
Robert Bocchino7b5b86c2004-07-27 21:02:21 +00001803 if (I.getType()->isInteger()) {
Chris Lattnerb8b97502003-08-13 19:01:45 +00001804 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Chris Lattner47060462005-04-07 17:14:51 +00001805
1806 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
1807 if (RHSI->getOpcode() == Instruction::Sub)
1808 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
1809 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
1810 }
1811 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
1812 if (LHSI->getOpcode() == Instruction::Sub)
1813 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
1814 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
1815 }
Robert Bocchino7b5b86c2004-07-27 21:02:21 +00001816 }
Chris Lattnerede3fe02003-08-13 04:18:28 +00001817
Chris Lattner147e9752002-05-08 22:46:53 +00001818 // -A + B --> B - A
Chris Lattnerbb74e222003-03-10 23:06:50 +00001819 if (Value *V = dyn_castNegVal(LHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001820 return BinaryOperator::createSub(RHS, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +00001821
1822 // A + -B --> A - B
Chris Lattnerbb74e222003-03-10 23:06:50 +00001823 if (!isa<Constant>(RHS))
1824 if (Value *V = dyn_castNegVal(RHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001825 return BinaryOperator::createSub(LHS, V);
Chris Lattner260ab202002-04-18 17:39:14 +00001826
Misha Brukmanb1c93172005-04-21 23:48:37 +00001827
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001828 ConstantInt *C2;
1829 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
1830 if (X == RHS) // X*C + X --> X * (C+1)
1831 return BinaryOperator::createMul(RHS, AddOne(C2));
1832
1833 // X*C1 + X*C2 --> X * (C1+C2)
1834 ConstantInt *C1;
1835 if (X == dyn_castFoldableMul(RHS, C1))
1836 return BinaryOperator::createMul(X, ConstantExpr::getAdd(C1, C2));
Chris Lattner57c8d992003-02-18 19:57:07 +00001837 }
1838
1839 // X + X*C --> X * (C+1)
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001840 if (dyn_castFoldableMul(RHS, C2) == LHS)
1841 return BinaryOperator::createMul(LHS, AddOne(C2));
1842
Chris Lattner57c8d992003-02-18 19:57:07 +00001843
Chris Lattnerb8b97502003-08-13 19:01:45 +00001844 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattnerd4252a72004-07-30 07:50:03 +00001845 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattnerb8b97502003-08-13 19:01:45 +00001846 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2))) return R;
Chris Lattner7fb29e12003-03-11 00:12:48 +00001847
Chris Lattnerb9cde762003-10-02 15:11:26 +00001848 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner330628a2006-01-06 17:59:59 +00001849 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00001850 if (match(LHS, m_Not(m_Value(X)))) { // ~X + C --> (C-1) - X
1851 Constant *C= ConstantExpr::getSub(CRHS, ConstantInt::get(I.getType(), 1));
1852 return BinaryOperator::createSub(C, X);
Chris Lattnerb9cde762003-10-02 15:11:26 +00001853 }
Chris Lattnerd4252a72004-07-30 07:50:03 +00001854
Chris Lattnerbff91d92004-10-08 05:07:56 +00001855 // (X & FF00) + xx00 -> (X+xx00) & FF00
1856 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
1857 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
1858 if (Anded == CRHS) {
1859 // See if all bits from the first bit set in the Add RHS up are included
1860 // in the mask. First, get the rightmost bit.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001861 uint64_t AddRHSV = CRHS->getZExtValue();
Chris Lattnerbff91d92004-10-08 05:07:56 +00001862
1863 // Form a mask of all bits from the lowest bit added through the top.
1864 uint64_t AddRHSHighBits = ~((AddRHSV & -AddRHSV)-1);
Chris Lattner77defba2006-02-07 07:00:41 +00001865 AddRHSHighBits &= C2->getType()->getIntegralTypeMask();
Chris Lattnerbff91d92004-10-08 05:07:56 +00001866
1867 // See if the and mask includes all of these bits.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001868 uint64_t AddRHSHighBitsAnd = AddRHSHighBits & C2->getZExtValue();
Misha Brukmanb1c93172005-04-21 23:48:37 +00001869
Chris Lattnerbff91d92004-10-08 05:07:56 +00001870 if (AddRHSHighBits == AddRHSHighBitsAnd) {
1871 // Okay, the xform is safe. Insert the new add pronto.
1872 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
1873 LHS->getName()), I);
1874 return BinaryOperator::createAnd(NewAdd, C2);
1875 }
1876 }
1877 }
1878
Chris Lattnerd4252a72004-07-30 07:50:03 +00001879 // Try to fold constant add into select arguments.
1880 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner86102b82005-01-01 16:22:27 +00001881 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattnerd4252a72004-07-30 07:50:03 +00001882 return R;
Chris Lattnerb9cde762003-10-02 15:11:26 +00001883 }
1884
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001885 // add (cast *A to intptrtype) B ->
1886 // cast (GEP (cast *A to sbyte*) B) ->
1887 // intptrtype
Andrew Lenharth4f339be2006-09-19 18:24:51 +00001888 {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001889 CastInst *CI = dyn_cast<CastInst>(LHS);
1890 Value *Other = RHS;
Andrew Lenharth4f339be2006-09-19 18:24:51 +00001891 if (!CI) {
1892 CI = dyn_cast<CastInst>(RHS);
1893 Other = LHS;
1894 }
Andrew Lenharth44cb67a2006-09-20 15:37:57 +00001895 if (CI && CI->getType()->isSized() &&
1896 (CI->getType()->getPrimitiveSize() ==
1897 TD->getIntPtrType()->getPrimitiveSize())
1898 && isa<PointerType>(CI->getOperand(0)->getType())) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00001899 Value *I2 = InsertCastBefore(Instruction::BitCast, CI->getOperand(0),
Andrew Lenharth44cb67a2006-09-20 15:37:57 +00001900 PointerType::get(Type::SByteTy), I);
1901 I2 = InsertNewInstBefore(new GetElementPtrInst(I2, Other, "ctg2"), I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001902 return new PtrToIntInst(I2, CI->getType());
Andrew Lenharth4f339be2006-09-19 18:24:51 +00001903 }
1904 }
1905
Chris Lattner113f4f42002-06-25 16:13:24 +00001906 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +00001907}
1908
Chris Lattnerbdb0ce02003-07-22 21:46:59 +00001909// isSignBit - Return true if the value represented by the constant only has the
1910// highest order bit set.
1911static bool isSignBit(ConstantInt *CI) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001912 unsigned NumBits = CI->getType()->getPrimitiveSizeInBits();
Reid Spencere0fc4df2006-10-20 07:07:24 +00001913 return (CI->getZExtValue() & (~0ULL >> (64-NumBits))) == (1ULL << (NumBits-1));
Chris Lattnerbdb0ce02003-07-22 21:46:59 +00001914}
1915
Chris Lattner022167f2004-03-13 00:11:49 +00001916/// RemoveNoopCast - Strip off nonconverting casts from the value.
1917///
1918static Value *RemoveNoopCast(Value *V) {
1919 if (CastInst *CI = dyn_cast<CastInst>(V)) {
1920 const Type *CTy = CI->getType();
1921 const Type *OpTy = CI->getOperand(0)->getType();
1922 if (CTy->isInteger() && OpTy->isInteger()) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001923 if (CTy->getPrimitiveSizeInBits() == OpTy->getPrimitiveSizeInBits())
Chris Lattner022167f2004-03-13 00:11:49 +00001924 return RemoveNoopCast(CI->getOperand(0));
1925 } else if (isa<PointerType>(CTy) && isa<PointerType>(OpTy))
1926 return RemoveNoopCast(CI->getOperand(0));
1927 }
1928 return V;
1929}
1930
Chris Lattner113f4f42002-06-25 16:13:24 +00001931Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +00001932 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001933
Chris Lattnere6794492002-08-12 21:17:25 +00001934 if (Op0 == Op1) // sub X, X -> 0
1935 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner260ab202002-04-18 17:39:14 +00001936
Chris Lattnere6794492002-08-12 21:17:25 +00001937 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattnerbb74e222003-03-10 23:06:50 +00001938 if (Value *V = dyn_castNegVal(Op1))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001939 return BinaryOperator::createAdd(Op0, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +00001940
Chris Lattner81a7a232004-10-16 18:11:37 +00001941 if (isa<UndefValue>(Op0))
1942 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
1943 if (isa<UndefValue>(Op1))
1944 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
1945
Chris Lattner8f2f5982003-11-05 01:06:05 +00001946 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
1947 // Replace (-1 - A) with (~A)...
Chris Lattner3082c5a2003-02-18 19:28:33 +00001948 if (C->isAllOnesValue())
1949 return BinaryOperator::createNot(Op1);
Chris Lattnerad3c4952002-05-09 01:29:19 +00001950
Chris Lattner8f2f5982003-11-05 01:06:05 +00001951 // C - ~X == X + (1+C)
Reid Spencer4fdd96c2005-06-18 17:37:34 +00001952 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00001953 if (match(Op1, m_Not(m_Value(X))))
1954 return BinaryOperator::createAdd(X,
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001955 ConstantExpr::getAdd(C, ConstantInt::get(I.getType(), 1)));
Chris Lattner92295c52004-03-12 23:53:13 +00001956 // -((uint)X >> 31) -> ((int)X >> 31)
1957 // -((int)X >> 31) -> ((uint)X >> 31)
Chris Lattner022167f2004-03-13 00:11:49 +00001958 if (C->isNullValue()) {
1959 Value *NoopCastedRHS = RemoveNoopCast(Op1);
1960 if (ShiftInst *SI = dyn_cast<ShiftInst>(NoopCastedRHS))
Reid Spencerfdff9382006-11-08 06:47:33 +00001961 if (SI->getOpcode() == Instruction::LShr) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00001962 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
Chris Lattner92295c52004-03-12 23:53:13 +00001963 // Check to see if we are shifting out everything but the sign bit.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001964 if (CU->getZExtValue() ==
1965 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerfdff9382006-11-08 06:47:33 +00001966 // Ok, the transformation is safe. Insert AShr.
1967 return new ShiftInst(Instruction::AShr, SI->getOperand(0),
1968 CU, SI->getName());
Chris Lattner92295c52004-03-12 23:53:13 +00001969 }
1970 }
Reid Spencerfdff9382006-11-08 06:47:33 +00001971 }
1972 else if (SI->getOpcode() == Instruction::AShr) {
1973 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
1974 // Check to see if we are shifting out everything but the sign bit.
1975 if (CU->getZExtValue() ==
1976 SI->getType()->getPrimitiveSizeInBits()-1) {
1977 // Ok, the transformation is safe. Insert LShr.
1978 return new ShiftInst(Instruction::LShr, SI->getOperand(0),
1979 CU, SI->getName());
1980 }
1981 }
1982 }
Chris Lattner022167f2004-03-13 00:11:49 +00001983 }
Chris Lattner183b3362004-04-09 19:05:30 +00001984
1985 // Try to fold constant sub into select arguments.
1986 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner86102b82005-01-01 16:22:27 +00001987 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00001988 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001989
1990 if (isa<PHINode>(Op0))
1991 if (Instruction *NV = FoldOpIntoPhi(I))
1992 return NV;
Chris Lattner8f2f5982003-11-05 01:06:05 +00001993 }
1994
Chris Lattnera9be4492005-04-07 16:15:25 +00001995 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
1996 if (Op1I->getOpcode() == Instruction::Add &&
Chris Lattner7a002fe2006-12-02 00:13:08 +00001997 !Op0->getType()->isFPOrFPVector()) {
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00001998 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Chris Lattnera9be4492005-04-07 16:15:25 +00001999 return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00002000 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Chris Lattnera9be4492005-04-07 16:15:25 +00002001 return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00002002 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2003 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2004 // C1-(X+C2) --> (C1-C2)-X
2005 return BinaryOperator::createSub(ConstantExpr::getSub(CI1, CI2),
2006 Op1I->getOperand(0));
2007 }
Chris Lattnera9be4492005-04-07 16:15:25 +00002008 }
2009
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002010 if (Op1I->hasOneUse()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00002011 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2012 // is not used by anyone else...
2013 //
Chris Lattnerc2f0aa52004-02-02 20:09:56 +00002014 if (Op1I->getOpcode() == Instruction::Sub &&
Chris Lattner7a002fe2006-12-02 00:13:08 +00002015 !Op1I->getType()->isFPOrFPVector()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00002016 // Swap the two operands of the subexpr...
2017 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2018 Op1I->setOperand(0, IIOp1);
2019 Op1I->setOperand(1, IIOp0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002020
Chris Lattner3082c5a2003-02-18 19:28:33 +00002021 // Create the new top level add instruction...
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002022 return BinaryOperator::createAdd(Op0, Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002023 }
2024
2025 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2026 //
2027 if (Op1I->getOpcode() == Instruction::And &&
2028 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2029 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2030
Chris Lattner396dbfe2004-06-09 05:08:07 +00002031 Value *NewNot =
2032 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002033 return BinaryOperator::createAnd(Op0, NewNot);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002034 }
Chris Lattner57c8d992003-02-18 19:57:07 +00002035
Reid Spencer3c514952006-10-16 23:08:08 +00002036 // 0 - (X sdiv C) -> (X sdiv -C)
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002037 if (Op1I->getOpcode() == Instruction::SDiv)
Reid Spencere0fc4df2006-10-20 07:07:24 +00002038 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002039 if (CSI->isNullValue())
Chris Lattner0aee4b72004-10-06 15:08:25 +00002040 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002041 return BinaryOperator::createSDiv(Op1I->getOperand(0),
Chris Lattner0aee4b72004-10-06 15:08:25 +00002042 ConstantExpr::getNeg(DivRHS));
2043
Chris Lattner57c8d992003-02-18 19:57:07 +00002044 // X - X*C --> X * (1-C)
Reid Spencer4fdd96c2005-06-18 17:37:34 +00002045 ConstantInt *C2 = 0;
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002046 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00002047 Constant *CP1 =
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002048 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1), C2);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002049 return BinaryOperator::createMul(Op0, CP1);
Chris Lattner57c8d992003-02-18 19:57:07 +00002050 }
Chris Lattnerad3c4952002-05-09 01:29:19 +00002051 }
Chris Lattnera9be4492005-04-07 16:15:25 +00002052 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00002053
Chris Lattner7a002fe2006-12-02 00:13:08 +00002054 if (!Op0->getType()->isFPOrFPVector())
Chris Lattner47060462005-04-07 17:14:51 +00002055 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2056 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner411336f2005-01-19 21:50:18 +00002057 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2058 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2059 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2060 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner47060462005-04-07 17:14:51 +00002061 } else if (Op0I->getOpcode() == Instruction::Sub) {
2062 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
2063 return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
Chris Lattner411336f2005-01-19 21:50:18 +00002064 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002065
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002066 ConstantInt *C1;
2067 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2068 if (X == Op1) { // X*C - X --> X * (C-1)
2069 Constant *CP1 = ConstantExpr::getSub(C1, ConstantInt::get(I.getType(),1));
2070 return BinaryOperator::createMul(Op1, CP1);
2071 }
Chris Lattner57c8d992003-02-18 19:57:07 +00002072
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002073 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
2074 if (X == dyn_castFoldableMul(Op1, C2))
2075 return BinaryOperator::createMul(Op1, ConstantExpr::getSub(C1, C2));
2076 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002077 return 0;
Chris Lattner260ab202002-04-18 17:39:14 +00002078}
2079
Chris Lattnere79e8542004-02-23 06:38:22 +00002080/// isSignBitCheck - Given an exploded setcc instruction, return true if it is
2081/// really just returns true if the most significant (sign) bit is set.
2082static bool isSignBitCheck(unsigned Opcode, Value *LHS, ConstantInt *RHS) {
2083 if (RHS->getType()->isSigned()) {
2084 // True if source is LHS < 0 or LHS <= -1
2085 return Opcode == Instruction::SetLT && RHS->isNullValue() ||
2086 Opcode == Instruction::SetLE && RHS->isAllOnesValue();
2087 } else {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002088 ConstantInt *RHSC = cast<ConstantInt>(RHS);
Chris Lattnere79e8542004-02-23 06:38:22 +00002089 // True if source is LHS > 127 or LHS >= 128, where the constants depend on
2090 // the size of the integer type.
2091 if (Opcode == Instruction::SetGE)
Reid Spencere0fc4df2006-10-20 07:07:24 +00002092 return RHSC->getZExtValue() ==
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002093 1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1);
Chris Lattnere79e8542004-02-23 06:38:22 +00002094 if (Opcode == Instruction::SetGT)
Reid Spencere0fc4df2006-10-20 07:07:24 +00002095 return RHSC->getZExtValue() ==
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002096 (1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1))-1;
Chris Lattnere79e8542004-02-23 06:38:22 +00002097 }
2098 return false;
2099}
2100
Chris Lattner113f4f42002-06-25 16:13:24 +00002101Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00002102 bool Changed = SimplifyCommutative(I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002103 Value *Op0 = I.getOperand(0);
Chris Lattner260ab202002-04-18 17:39:14 +00002104
Chris Lattner81a7a232004-10-16 18:11:37 +00002105 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
2106 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2107
Chris Lattnere6794492002-08-12 21:17:25 +00002108 // Simplify mul instructions with a constant RHS...
Chris Lattner3082c5a2003-02-18 19:28:33 +00002109 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2110 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerede3fe02003-08-13 04:18:28 +00002111
2112 // ((X << C1)*C2) == (X * (C2 << C1))
2113 if (ShiftInst *SI = dyn_cast<ShiftInst>(Op0))
2114 if (SI->getOpcode() == Instruction::Shl)
2115 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002116 return BinaryOperator::createMul(SI->getOperand(0),
2117 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanb1c93172005-04-21 23:48:37 +00002118
Chris Lattnercce81be2003-09-11 22:24:54 +00002119 if (CI->isNullValue())
2120 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2121 if (CI->equalsInt(1)) // X * 1 == X
2122 return ReplaceInstUsesWith(I, Op0);
2123 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Chris Lattner35236d82003-06-25 17:09:20 +00002124 return BinaryOperator::createNeg(Op0, I.getName());
Chris Lattner31ba1292002-04-29 22:24:47 +00002125
Reid Spencere0fc4df2006-10-20 07:07:24 +00002126 int64_t Val = (int64_t)cast<ConstantInt>(CI)->getZExtValue();
Chris Lattner22d00a82005-08-02 19:16:58 +00002127 if (isPowerOf2_64(Val)) { // Replace X*(2^C) with X << C
2128 uint64_t C = Log2_64(Val);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002129 return new ShiftInst(Instruction::Shl, Op0,
Reid Spencere0fc4df2006-10-20 07:07:24 +00002130 ConstantInt::get(Type::UByteTy, C));
Chris Lattner22d00a82005-08-02 19:16:58 +00002131 }
Robert Bocchino7b5b86c2004-07-27 21:02:21 +00002132 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00002133 if (Op1F->isNullValue())
2134 return ReplaceInstUsesWith(I, Op1);
Chris Lattner31ba1292002-04-29 22:24:47 +00002135
Chris Lattner3082c5a2003-02-18 19:28:33 +00002136 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2137 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2138 if (Op1F->getValue() == 1.0)
2139 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
2140 }
Chris Lattner32c01df2006-03-04 06:04:02 +00002141
2142 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2143 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2144 isa<ConstantInt>(Op0I->getOperand(1))) {
2145 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2146 Instruction *Add = BinaryOperator::createMul(Op0I->getOperand(0),
2147 Op1, "tmp");
2148 InsertNewInstBefore(Add, I);
2149 Value *C1C2 = ConstantExpr::getMul(Op1,
2150 cast<Constant>(Op0I->getOperand(1)));
2151 return BinaryOperator::createAdd(Add, C1C2);
2152
2153 }
Chris Lattner183b3362004-04-09 19:05:30 +00002154
2155 // Try to fold constant mul into select arguments.
2156 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00002157 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00002158 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002159
2160 if (isa<PHINode>(Op0))
2161 if (Instruction *NV = FoldOpIntoPhi(I))
2162 return NV;
Chris Lattner260ab202002-04-18 17:39:14 +00002163 }
2164
Chris Lattner934a64cf2003-03-10 23:23:04 +00002165 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
2166 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002167 return BinaryOperator::createMul(Op0v, Op1v);
Chris Lattner934a64cf2003-03-10 23:23:04 +00002168
Chris Lattner2635b522004-02-23 05:39:21 +00002169 // If one of the operands of the multiply is a cast from a boolean value, then
2170 // we know the bool is either zero or one, so this is a 'masking' multiply.
2171 // See if we can simplify things based on how the boolean was originally
2172 // formed.
2173 CastInst *BoolCast = 0;
2174 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(0)))
Reid Spencer612683b2006-12-13 08:33:33 +00002175 if (CI->getOperand(0)->getType() == Type::BoolTy &&
2176 CI->getOpcode() == Instruction::ZExt)
Chris Lattner2635b522004-02-23 05:39:21 +00002177 BoolCast = CI;
2178 if (!BoolCast)
2179 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(1)))
Reid Spencer612683b2006-12-13 08:33:33 +00002180 if (CI->getOperand(0)->getType() == Type::BoolTy &&
2181 CI->getOpcode() == Instruction::ZExt)
Chris Lattner2635b522004-02-23 05:39:21 +00002182 BoolCast = CI;
2183 if (BoolCast) {
2184 if (SetCondInst *SCI = dyn_cast<SetCondInst>(BoolCast->getOperand(0))) {
2185 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2186 const Type *SCOpTy = SCIOp0->getType();
2187
Chris Lattnere79e8542004-02-23 06:38:22 +00002188 // If the setcc is true iff the sign bit of X is set, then convert this
2189 // multiply into a shift/and combination.
2190 if (isa<ConstantInt>(SCIOp1) &&
2191 isSignBitCheck(SCI->getOpcode(), SCIOp0, cast<ConstantInt>(SCIOp1))) {
Chris Lattner2635b522004-02-23 05:39:21 +00002192 // Shift the X value right to turn it into "all signbits".
Reid Spencere0fc4df2006-10-20 07:07:24 +00002193 Constant *Amt = ConstantInt::get(Type::UByteTy,
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002194 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattnere79e8542004-02-23 06:38:22 +00002195 Value *V =
Reid Spencerfdff9382006-11-08 06:47:33 +00002196 InsertNewInstBefore(new ShiftInst(Instruction::AShr, SCIOp0, Amt,
Chris Lattnere79e8542004-02-23 06:38:22 +00002197 BoolCast->getOperand(0)->getName()+
2198 ".mask"), I);
Chris Lattner2635b522004-02-23 05:39:21 +00002199
2200 // If the multiply type is not the same as the source type, sign extend
2201 // or truncate to the multiply type.
Reid Spencer13bc5d72006-12-12 09:18:51 +00002202 if (I.getType() != V->getType()) {
2203 unsigned SrcBits = V->getType()->getPrimitiveSizeInBits();
2204 unsigned DstBits = I.getType()->getPrimitiveSizeInBits();
2205 Instruction::CastOps opcode =
2206 (SrcBits == DstBits ? Instruction::BitCast :
2207 (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2208 V = InsertCastBefore(opcode, V, I.getType(), I);
2209 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002210
Chris Lattner2635b522004-02-23 05:39:21 +00002211 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002212 return BinaryOperator::createAnd(V, OtherOp);
Chris Lattner2635b522004-02-23 05:39:21 +00002213 }
2214 }
2215 }
2216
Chris Lattner113f4f42002-06-25 16:13:24 +00002217 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +00002218}
2219
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002220/// This function implements the transforms on div instructions that work
2221/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2222/// used by the visitors to those instructions.
2223/// @brief Transforms common to all three div instructions
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002224Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002225 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner81a7a232004-10-16 18:11:37 +00002226
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002227 // undef / X -> 0
2228 if (isa<UndefValue>(Op0))
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002229 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002230
2231 // X / undef -> undef
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002232 if (isa<UndefValue>(Op1))
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002233 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002234
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002235 // Handle cases involving: div X, (select Cond, Y, Z)
Chris Lattnerd79dc792006-09-09 20:26:32 +00002236 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2237 // div X, (Cond ? 0 : Y) -> div X, Y. If the div and the select are in the
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002238 // same basic block, then we replace the select with Y, and the condition
2239 // of the select with false (if the cond value is in the same BB). If the
Chris Lattnerd79dc792006-09-09 20:26:32 +00002240 // select has uses other than the div, this allows them to be simplified
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002241 // also. Note that div X, Y is just as good as div X, 0 (undef)
Chris Lattnerd79dc792006-09-09 20:26:32 +00002242 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2243 if (ST->isNullValue()) {
2244 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2245 if (CondI && CondI->getParent() == I.getParent())
Chris Lattner6ab03f62006-09-28 23:35:22 +00002246 UpdateValueUsesWith(CondI, ConstantBool::getFalse());
Chris Lattnerd79dc792006-09-09 20:26:32 +00002247 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2248 I.setOperand(1, SI->getOperand(2));
2249 else
2250 UpdateValueUsesWith(SI, SI->getOperand(2));
2251 return &I;
2252 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002253
Chris Lattnerd79dc792006-09-09 20:26:32 +00002254 // Likewise for: div X, (Cond ? Y : 0) -> div X, Y
2255 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2256 if (ST->isNullValue()) {
2257 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2258 if (CondI && CondI->getParent() == I.getParent())
Chris Lattner6ab03f62006-09-28 23:35:22 +00002259 UpdateValueUsesWith(CondI, ConstantBool::getTrue());
Chris Lattnerd79dc792006-09-09 20:26:32 +00002260 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2261 I.setOperand(1, SI->getOperand(1));
2262 else
2263 UpdateValueUsesWith(SI, SI->getOperand(1));
2264 return &I;
2265 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002266 }
Chris Lattnerd79dc792006-09-09 20:26:32 +00002267
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002268 return 0;
2269}
Misha Brukmanb1c93172005-04-21 23:48:37 +00002270
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002271/// This function implements the transforms common to both integer division
2272/// instructions (udiv and sdiv). It is called by the visitors to those integer
2273/// division instructions.
2274/// @brief Common integer divide transforms
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002275Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002276 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2277
2278 if (Instruction *Common = commonDivTransforms(I))
2279 return Common;
2280
2281 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2282 // div X, 1 == X
2283 if (RHS->equalsInt(1))
2284 return ReplaceInstUsesWith(I, Op0);
2285
2286 // (X / C1) / C2 -> X / (C1*C2)
2287 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2288 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2289 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
2290 return BinaryOperator::create(I.getOpcode(), LHS->getOperand(0),
2291 ConstantExpr::getMul(RHS, LHSRHS));
Chris Lattner42362612005-04-08 04:03:26 +00002292 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002293
2294 if (!RHS->isNullValue()) { // avoid X udiv 0
2295 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2296 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2297 return R;
2298 if (isa<PHINode>(Op0))
2299 if (Instruction *NV = FoldOpIntoPhi(I))
2300 return NV;
2301 }
Chris Lattnerd79dc792006-09-09 20:26:32 +00002302 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002303
Chris Lattner3082c5a2003-02-18 19:28:33 +00002304 // 0 / X == 0, we don't need to preserve faults!
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002305 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattner3082c5a2003-02-18 19:28:33 +00002306 if (LHS->equalsInt(0))
2307 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2308
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002309 return 0;
2310}
2311
2312Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2313 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2314
2315 // Handle the integer div common cases
2316 if (Instruction *Common = commonIDivTransforms(I))
2317 return Common;
2318
2319 // X udiv C^2 -> X >> C
2320 // Check to see if this is an unsigned division with an exact power of 2,
2321 // if so, convert to a right shift.
2322 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
2323 if (uint64_t Val = C->getZExtValue()) // Don't break X / 0
2324 if (isPowerOf2_64(Val)) {
2325 uint64_t ShiftAmt = Log2_64(Val);
Reid Spencerfdff9382006-11-08 06:47:33 +00002326 return new ShiftInst(Instruction::LShr, Op0,
2327 ConstantInt::get(Type::UByteTy, ShiftAmt));
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002328 }
2329 }
2330
2331 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
2332 if (ShiftInst *RHSI = dyn_cast<ShiftInst>(I.getOperand(1))) {
2333 if (RHSI->getOpcode() == Instruction::Shl &&
2334 isa<ConstantInt>(RHSI->getOperand(0))) {
2335 uint64_t C1 = cast<ConstantInt>(RHSI->getOperand(0))->getZExtValue();
2336 if (isPowerOf2_64(C1)) {
2337 Value *N = RHSI->getOperand(1);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002338 const Type *NTy = N->getType();
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002339 if (uint64_t C2 = Log2_64(C1)) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002340 Constant *C2V = ConstantInt::get(NTy, C2);
2341 N = InsertNewInstBefore(BinaryOperator::createAdd(N, C2V, "tmp"), I);
Chris Lattner2e90b732006-02-05 07:54:04 +00002342 }
Reid Spencerfdff9382006-11-08 06:47:33 +00002343 return new ShiftInst(Instruction::LShr, Op0, N);
Chris Lattner2e90b732006-02-05 07:54:04 +00002344 }
2345 }
Chris Lattnerdd0c1742005-11-05 07:40:31 +00002346 }
2347
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002348 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
2349 // where C1&C2 are powers of two.
2350 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2351 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2352 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2)))
2353 if (!STO->isNullValue() && !STO->isNullValue()) {
2354 uint64_t TVA = STO->getZExtValue(), FVA = SFO->getZExtValue();
2355 if (isPowerOf2_64(TVA) && isPowerOf2_64(FVA)) {
2356 // Compute the shift amounts
2357 unsigned TSA = Log2_64(TVA), FSA = Log2_64(FVA);
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002358 // Construct the "on true" case of the select
2359 Constant *TC = ConstantInt::get(Type::UByteTy, TSA);
2360 Instruction *TSI =
Reid Spencerfdff9382006-11-08 06:47:33 +00002361 new ShiftInst(Instruction::LShr, Op0, TC, SI->getName()+".t");
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002362 TSI = InsertNewInstBefore(TSI, I);
2363
2364 // Construct the "on false" case of the select
2365 Constant *FC = ConstantInt::get(Type::UByteTy, FSA);
2366 Instruction *FSI =
Reid Spencerfdff9382006-11-08 06:47:33 +00002367 new ShiftInst(Instruction::LShr, Op0, FC, SI->getName()+".f");
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002368 FSI = InsertNewInstBefore(FSI, I);
2369
2370 // construct the select instruction and return it.
Reid Spencerfdff9382006-11-08 06:47:33 +00002371 return new SelectInst(SI->getOperand(0), TSI, FSI, SI->getName());
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002372 }
2373 }
2374 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002375 return 0;
2376}
2377
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002378Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
2379 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2380
2381 // Handle the integer div common cases
2382 if (Instruction *Common = commonIDivTransforms(I))
2383 return Common;
2384
2385 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2386 // sdiv X, -1 == -X
2387 if (RHS->isAllOnesValue())
2388 return BinaryOperator::createNeg(Op0);
2389
2390 // -X/C -> X/-C
2391 if (Value *LHSNeg = dyn_castNegVal(Op0))
2392 return BinaryOperator::createSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
2393 }
2394
2395 // If the sign bits of both operands are zero (i.e. we can prove they are
2396 // unsigned inputs), turn this into a udiv.
2397 if (I.getType()->isInteger()) {
2398 uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
2399 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2400 return BinaryOperator::createUDiv(Op0, Op1, I.getName());
2401 }
2402 }
2403
2404 return 0;
2405}
2406
2407Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
2408 return commonDivTransforms(I);
2409}
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002410
Chris Lattner85dda9a2006-03-02 06:50:58 +00002411/// GetFactor - If we can prove that the specified value is at least a multiple
2412/// of some factor, return that factor.
2413static Constant *GetFactor(Value *V) {
2414 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
2415 return CI;
2416
2417 // Unless we can be tricky, we know this is a multiple of 1.
2418 Constant *Result = ConstantInt::get(V->getType(), 1);
2419
2420 Instruction *I = dyn_cast<Instruction>(V);
2421 if (!I) return Result;
2422
2423 if (I->getOpcode() == Instruction::Mul) {
2424 // Handle multiplies by a constant, etc.
2425 return ConstantExpr::getMul(GetFactor(I->getOperand(0)),
2426 GetFactor(I->getOperand(1)));
2427 } else if (I->getOpcode() == Instruction::Shl) {
2428 // (X<<C) -> X * (1 << C)
2429 if (Constant *ShRHS = dyn_cast<Constant>(I->getOperand(1))) {
2430 ShRHS = ConstantExpr::getShl(Result, ShRHS);
2431 return ConstantExpr::getMul(GetFactor(I->getOperand(0)), ShRHS);
2432 }
2433 } else if (I->getOpcode() == Instruction::And) {
2434 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
2435 // X & 0xFFF0 is known to be a multiple of 16.
2436 unsigned Zeros = CountTrailingZeros_64(RHS->getZExtValue());
2437 if (Zeros != V->getType()->getPrimitiveSizeInBits())
2438 return ConstantExpr::getShl(Result,
Reid Spencere0fc4df2006-10-20 07:07:24 +00002439 ConstantInt::get(Type::UByteTy, Zeros));
Chris Lattner85dda9a2006-03-02 06:50:58 +00002440 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002441 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
Chris Lattner85dda9a2006-03-02 06:50:58 +00002442 // Only handle int->int casts.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002443 if (!CI->isIntegerCast())
2444 return Result;
2445 Value *Op = CI->getOperand(0);
2446 return ConstantExpr::getCast(CI->getOpcode(), GetFactor(Op), V->getType());
Chris Lattner85dda9a2006-03-02 06:50:58 +00002447 }
2448 return Result;
2449}
2450
Reid Spencer7eb55b32006-11-02 01:53:59 +00002451/// This function implements the transforms on rem instructions that work
2452/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
2453/// is used by the visitors to those instructions.
2454/// @brief Transforms common to all three rem instructions
2455Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002456 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Reid Spencer7eb55b32006-11-02 01:53:59 +00002457
Chris Lattner0de4a8d2006-02-28 05:30:45 +00002458 // 0 % X == 0, we don't need to preserve faults!
2459 if (Constant *LHS = dyn_cast<Constant>(Op0))
2460 if (LHS->isNullValue())
2461 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2462
2463 if (isa<UndefValue>(Op0)) // undef % X -> 0
2464 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2465 if (isa<UndefValue>(Op1))
2466 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Reid Spencer7eb55b32006-11-02 01:53:59 +00002467
2468 // Handle cases involving: rem X, (select Cond, Y, Z)
2469 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2470 // rem X, (Cond ? 0 : Y) -> rem X, Y. If the rem and the select are in
2471 // the same basic block, then we replace the select with Y, and the
2472 // condition of the select with false (if the cond value is in the same
2473 // BB). If the select has uses other than the div, this allows them to be
2474 // simplified also.
2475 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2476 if (ST->isNullValue()) {
2477 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2478 if (CondI && CondI->getParent() == I.getParent())
2479 UpdateValueUsesWith(CondI, ConstantBool::getFalse());
2480 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2481 I.setOperand(1, SI->getOperand(2));
2482 else
2483 UpdateValueUsesWith(SI, SI->getOperand(2));
Chris Lattner7fd5f072004-07-06 07:01:22 +00002484 return &I;
2485 }
Reid Spencer7eb55b32006-11-02 01:53:59 +00002486 // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
2487 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2488 if (ST->isNullValue()) {
2489 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2490 if (CondI && CondI->getParent() == I.getParent())
2491 UpdateValueUsesWith(CondI, ConstantBool::getTrue());
2492 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2493 I.setOperand(1, SI->getOperand(1));
2494 else
2495 UpdateValueUsesWith(SI, SI->getOperand(1));
2496 return &I;
2497 }
Chris Lattnere9ff0ea2005-11-05 07:28:37 +00002498 }
Chris Lattner7fd5f072004-07-06 07:01:22 +00002499
Reid Spencer7eb55b32006-11-02 01:53:59 +00002500 return 0;
2501}
2502
2503/// This function implements the transforms common to both integer remainder
2504/// instructions (urem and srem). It is called by the visitors to those integer
2505/// remainder instructions.
2506/// @brief Common integer remainder transforms
2507Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
2508 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2509
2510 if (Instruction *common = commonRemTransforms(I))
2511 return common;
2512
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002513 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner0de4a8d2006-02-28 05:30:45 +00002514 // X % 0 == undef, we don't need to preserve faults!
2515 if (RHS->equalsInt(0))
2516 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2517
Chris Lattner3082c5a2003-02-18 19:28:33 +00002518 if (RHS->equalsInt(1)) // X % 1 == 0
2519 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2520
Chris Lattnerb70f1412006-02-28 05:49:21 +00002521 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2522 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2523 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2524 return R;
2525 } else if (isa<PHINode>(Op0I)) {
2526 if (Instruction *NV = FoldOpIntoPhi(I))
2527 return NV;
Chris Lattnerb70f1412006-02-28 05:49:21 +00002528 }
Reid Spencer7eb55b32006-11-02 01:53:59 +00002529 // (X * C1) % C2 --> 0 iff C1 % C2 == 0
2530 if (ConstantExpr::getSRem(GetFactor(Op0I), RHS)->isNullValue())
Chris Lattner85dda9a2006-03-02 06:50:58 +00002531 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerb70f1412006-02-28 05:49:21 +00002532 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00002533 }
2534
Reid Spencer7eb55b32006-11-02 01:53:59 +00002535 return 0;
2536}
2537
2538Instruction *InstCombiner::visitURem(BinaryOperator &I) {
2539 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2540
2541 if (Instruction *common = commonIRemTransforms(I))
2542 return common;
2543
2544 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2545 // X urem C^2 -> X and C
2546 // Check to see if this is an unsigned remainder with an exact power of 2,
2547 // if so, convert to a bitwise and.
2548 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
2549 if (isPowerOf2_64(C->getZExtValue()))
2550 return BinaryOperator::createAnd(Op0, SubOne(C));
2551 }
2552
Chris Lattner2e90b732006-02-05 07:54:04 +00002553 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00002554 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
2555 if (RHSI->getOpcode() == Instruction::Shl &&
2556 isa<ConstantInt>(RHSI->getOperand(0))) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002557 unsigned C1 = cast<ConstantInt>(RHSI->getOperand(0))->getZExtValue();
Chris Lattner2e90b732006-02-05 07:54:04 +00002558 if (isPowerOf2_64(C1)) {
2559 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
2560 Value *Add = InsertNewInstBefore(BinaryOperator::createAdd(RHSI, N1,
2561 "tmp"), I);
2562 return BinaryOperator::createAnd(Op0, Add);
2563 }
2564 }
Reid Spencer7eb55b32006-11-02 01:53:59 +00002565 }
Chris Lattnerd79dc792006-09-09 20:26:32 +00002566
Reid Spencer7eb55b32006-11-02 01:53:59 +00002567 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
2568 // where C1&C2 are powers of two.
2569 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2570 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2571 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
2572 // STO == 0 and SFO == 0 handled above.
2573 if (isPowerOf2_64(STO->getZExtValue()) &&
2574 isPowerOf2_64(SFO->getZExtValue())) {
2575 Value *TrueAnd = InsertNewInstBefore(
2576 BinaryOperator::createAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
2577 Value *FalseAnd = InsertNewInstBefore(
2578 BinaryOperator::createAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
2579 return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
2580 }
2581 }
Chris Lattner2e90b732006-02-05 07:54:04 +00002582 }
2583
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002584 return 0;
2585}
2586
Reid Spencer7eb55b32006-11-02 01:53:59 +00002587Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
2588 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2589
2590 if (Instruction *common = commonIRemTransforms(I))
2591 return common;
2592
2593 if (Value *RHSNeg = dyn_castNegVal(Op1))
2594 if (!isa<ConstantInt>(RHSNeg) ||
2595 cast<ConstantInt>(RHSNeg)->getSExtValue() > 0) {
2596 // X % -Y -> X % Y
2597 AddUsesToWorkList(I);
2598 I.setOperand(1, RHSNeg);
2599 return &I;
2600 }
2601
2602 // If the top bits of both operands are zero (i.e. we can prove they are
2603 // unsigned inputs), turn this into a urem.
2604 uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
2605 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2606 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
2607 return BinaryOperator::createURem(Op0, Op1, I.getName());
2608 }
2609
2610 return 0;
2611}
2612
2613Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00002614 return commonRemTransforms(I);
2615}
2616
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002617// isMaxValueMinusOne - return true if this is Max-1
Chris Lattnere6794492002-08-12 21:17:25 +00002618static bool isMaxValueMinusOne(const ConstantInt *C) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002619 if (C->getType()->isUnsigned())
2620 return C->getZExtValue() == C->getType()->getIntegralTypeMask()-1;
Misha Brukmanb1c93172005-04-21 23:48:37 +00002621
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002622 // Calculate 0111111111..11111
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002623 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002624 int64_t Val = INT64_MAX; // All ones
2625 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
Reid Spencere0fc4df2006-10-20 07:07:24 +00002626 return C->getSExtValue() == Val-1;
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002627}
2628
2629// isMinValuePlusOne - return true if this is Min+1
Chris Lattnere6794492002-08-12 21:17:25 +00002630static bool isMinValuePlusOne(const ConstantInt *C) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002631 if (C->getType()->isUnsigned())
2632 return C->getZExtValue() == 1;
Misha Brukmanb1c93172005-04-21 23:48:37 +00002633
2634 // Calculate 1111111111000000000000
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002635 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002636 int64_t Val = -1; // All ones
2637 Val <<= TypeBits-1; // Shift over to the right spot
Reid Spencere0fc4df2006-10-20 07:07:24 +00002638 return C->getSExtValue() == Val+1;
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002639}
2640
Chris Lattner35167c32004-06-09 07:59:58 +00002641// isOneBitSet - Return true if there is exactly one bit set in the specified
2642// constant.
2643static bool isOneBitSet(const ConstantInt *CI) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002644 uint64_t V = CI->getZExtValue();
Chris Lattner35167c32004-06-09 07:59:58 +00002645 return V && (V & (V-1)) == 0;
2646}
2647
Chris Lattner8fc5af42004-09-23 21:46:38 +00002648#if 0 // Currently unused
2649// isLowOnes - Return true if the constant is of the form 0+1+.
2650static bool isLowOnes(const ConstantInt *CI) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002651 uint64_t V = CI->getZExtValue();
Chris Lattner8fc5af42004-09-23 21:46:38 +00002652
2653 // There won't be bits set in parts that the type doesn't contain.
Reid Spencere0fc4df2006-10-20 07:07:24 +00002654 V &= ConstantInt::getAllOnesValue(CI->getType())->getZExtValue();
Chris Lattner8fc5af42004-09-23 21:46:38 +00002655
2656 uint64_t U = V+1; // If it is low ones, this should be a power of two.
2657 return U && V && (U & V) == 0;
2658}
2659#endif
2660
2661// isHighOnes - Return true if the constant is of the form 1+0+.
2662// This is the same as lowones(~X).
2663static bool isHighOnes(const ConstantInt *CI) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002664 uint64_t V = ~CI->getZExtValue();
Chris Lattner2c14cf72005-08-07 07:03:10 +00002665 if (~V == 0) return false; // 0's does not match "1+"
Chris Lattner8fc5af42004-09-23 21:46:38 +00002666
2667 // There won't be bits set in parts that the type doesn't contain.
Reid Spencere0fc4df2006-10-20 07:07:24 +00002668 V &= ConstantInt::getAllOnesValue(CI->getType())->getZExtValue();
Chris Lattner8fc5af42004-09-23 21:46:38 +00002669
2670 uint64_t U = V+1; // If it is low ones, this should be a power of two.
2671 return U && V && (U & V) == 0;
2672}
2673
2674
Chris Lattner3ac7c262003-08-13 20:16:26 +00002675/// getSetCondCode - Encode a setcc opcode into a three bit mask. These bits
2676/// are carefully arranged to allow folding of expressions such as:
2677///
2678/// (A < B) | (A > B) --> (A != B)
2679///
2680/// Bit value '4' represents that the comparison is true if A > B, bit value '2'
2681/// represents that the comparison is true if A == B, and bit value '1' is true
2682/// if A < B.
2683///
2684static unsigned getSetCondCode(const SetCondInst *SCI) {
2685 switch (SCI->getOpcode()) {
2686 // False -> 0
2687 case Instruction::SetGT: return 1;
2688 case Instruction::SetEQ: return 2;
2689 case Instruction::SetGE: return 3;
2690 case Instruction::SetLT: return 4;
2691 case Instruction::SetNE: return 5;
2692 case Instruction::SetLE: return 6;
2693 // True -> 7
2694 default:
2695 assert(0 && "Invalid SetCC opcode!");
2696 return 0;
2697 }
2698}
2699
2700/// getSetCCValue - This is the complement of getSetCondCode, which turns an
2701/// opcode and two operands into either a constant true or false, or a brand new
2702/// SetCC instruction.
2703static Value *getSetCCValue(unsigned Opcode, Value *LHS, Value *RHS) {
2704 switch (Opcode) {
Chris Lattner6ab03f62006-09-28 23:35:22 +00002705 case 0: return ConstantBool::getFalse();
Chris Lattner3ac7c262003-08-13 20:16:26 +00002706 case 1: return new SetCondInst(Instruction::SetGT, LHS, RHS);
2707 case 2: return new SetCondInst(Instruction::SetEQ, LHS, RHS);
2708 case 3: return new SetCondInst(Instruction::SetGE, LHS, RHS);
2709 case 4: return new SetCondInst(Instruction::SetLT, LHS, RHS);
2710 case 5: return new SetCondInst(Instruction::SetNE, LHS, RHS);
2711 case 6: return new SetCondInst(Instruction::SetLE, LHS, RHS);
Chris Lattner6ab03f62006-09-28 23:35:22 +00002712 case 7: return ConstantBool::getTrue();
Chris Lattner3ac7c262003-08-13 20:16:26 +00002713 default: assert(0 && "Illegal SetCCCode!"); return 0;
2714 }
2715}
2716
2717// FoldSetCCLogical - Implements (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
Chris Lattnere3a63d12006-11-15 04:53:24 +00002718namespace {
Chris Lattner3ac7c262003-08-13 20:16:26 +00002719struct FoldSetCCLogical {
2720 InstCombiner &IC;
2721 Value *LHS, *RHS;
2722 FoldSetCCLogical(InstCombiner &ic, SetCondInst *SCI)
2723 : IC(ic), LHS(SCI->getOperand(0)), RHS(SCI->getOperand(1)) {}
2724 bool shouldApply(Value *V) const {
2725 if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
2726 return (SCI->getOperand(0) == LHS && SCI->getOperand(1) == RHS ||
2727 SCI->getOperand(0) == RHS && SCI->getOperand(1) == LHS);
2728 return false;
2729 }
2730 Instruction *apply(BinaryOperator &Log) const {
2731 SetCondInst *SCI = cast<SetCondInst>(Log.getOperand(0));
2732 if (SCI->getOperand(0) != LHS) {
2733 assert(SCI->getOperand(1) == LHS);
2734 SCI->swapOperands(); // Swap the LHS and RHS of the SetCC
2735 }
2736
2737 unsigned LHSCode = getSetCondCode(SCI);
2738 unsigned RHSCode = getSetCondCode(cast<SetCondInst>(Log.getOperand(1)));
2739 unsigned Code;
2740 switch (Log.getOpcode()) {
2741 case Instruction::And: Code = LHSCode & RHSCode; break;
2742 case Instruction::Or: Code = LHSCode | RHSCode; break;
2743 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner2caaaba2003-09-22 20:33:34 +00002744 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattner3ac7c262003-08-13 20:16:26 +00002745 }
2746
2747 Value *RV = getSetCCValue(Code, LHS, RHS);
2748 if (Instruction *I = dyn_cast<Instruction>(RV))
2749 return I;
2750 // Otherwise, it's a constant boolean value...
2751 return IC.ReplaceInstUsesWith(Log, RV);
2752 }
2753};
Chris Lattnere3a63d12006-11-15 04:53:24 +00002754} // end anonymous namespace
Chris Lattner3ac7c262003-08-13 20:16:26 +00002755
Chris Lattnerba1cb382003-09-19 17:17:26 +00002756// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
2757// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
2758// guaranteed to be either a shift instruction or a binary operator.
2759Instruction *InstCombiner::OptAndOp(Instruction *Op,
2760 ConstantIntegral *OpRHS,
2761 ConstantIntegral *AndRHS,
2762 BinaryOperator &TheAnd) {
2763 Value *X = Op->getOperand(0);
Chris Lattnerfcf21a72004-01-12 19:47:05 +00002764 Constant *Together = 0;
2765 if (!isa<ShiftInst>(Op))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002766 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002767
Chris Lattnerba1cb382003-09-19 17:17:26 +00002768 switch (Op->getOpcode()) {
2769 case Instruction::Xor:
Chris Lattner86102b82005-01-01 16:22:27 +00002770 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00002771 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
2772 std::string OpName = Op->getName(); Op->setName("");
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002773 Instruction *And = BinaryOperator::createAnd(X, AndRHS, OpName);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002774 InsertNewInstBefore(And, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002775 return BinaryOperator::createXor(And, Together);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002776 }
2777 break;
2778 case Instruction::Or:
Chris Lattner86102b82005-01-01 16:22:27 +00002779 if (Together == AndRHS) // (X | C) & C --> C
2780 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002781
Chris Lattner86102b82005-01-01 16:22:27 +00002782 if (Op->hasOneUse() && Together != OpRHS) {
2783 // (X | C1) & C2 --> (X | (C1&C2)) & C2
2784 std::string Op0Name = Op->getName(); Op->setName("");
2785 Instruction *Or = BinaryOperator::createOr(X, Together, Op0Name);
2786 InsertNewInstBefore(Or, TheAnd);
2787 return BinaryOperator::createAnd(Or, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002788 }
2789 break;
2790 case Instruction::Add:
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002791 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00002792 // Adding a one to a single bit bit-field should be turned into an XOR
2793 // of the bit. First thing to check is to see if this AND is with a
2794 // single bit constant.
Reid Spencere0fc4df2006-10-20 07:07:24 +00002795 uint64_t AndRHSV = cast<ConstantInt>(AndRHS)->getZExtValue();
Chris Lattnerba1cb382003-09-19 17:17:26 +00002796
2797 // Clear bits that are not part of the constant.
Chris Lattner77defba2006-02-07 07:00:41 +00002798 AndRHSV &= AndRHS->getType()->getIntegralTypeMask();
Chris Lattnerba1cb382003-09-19 17:17:26 +00002799
2800 // If there is only one bit set...
Chris Lattner35167c32004-06-09 07:59:58 +00002801 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00002802 // Ok, at this point, we know that we are masking the result of the
2803 // ADD down to exactly one bit. If the constant we are adding has
2804 // no bits set below this bit, then we can eliminate the ADD.
Reid Spencere0fc4df2006-10-20 07:07:24 +00002805 uint64_t AddRHS = cast<ConstantInt>(OpRHS)->getZExtValue();
Misha Brukmanb1c93172005-04-21 23:48:37 +00002806
Chris Lattnerba1cb382003-09-19 17:17:26 +00002807 // Check to see if any bits below the one bit set in AndRHSV are set.
2808 if ((AddRHS & (AndRHSV-1)) == 0) {
2809 // If not, the only thing that can effect the output of the AND is
2810 // the bit specified by AndRHSV. If that bit is set, the effect of
2811 // the XOR is to toggle the bit. If it is clear, then the ADD has
2812 // no effect.
2813 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
2814 TheAnd.setOperand(0, X);
2815 return &TheAnd;
2816 } else {
2817 std::string Name = Op->getName(); Op->setName("");
2818 // Pull the XOR out of the AND.
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002819 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS, Name);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002820 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002821 return BinaryOperator::createXor(NewAnd, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002822 }
2823 }
2824 }
2825 }
2826 break;
Chris Lattner2da29172003-09-19 19:05:02 +00002827
2828 case Instruction::Shl: {
2829 // We know that the AND will not produce any of the bits shifted in, so if
2830 // the anded constant includes them, clear them now!
2831 //
2832 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner7e794272004-09-24 15:21:34 +00002833 Constant *ShlMask = ConstantExpr::getShl(AllOne, OpRHS);
2834 Constant *CI = ConstantExpr::getAnd(AndRHS, ShlMask);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002835
Chris Lattner7e794272004-09-24 15:21:34 +00002836 if (CI == ShlMask) { // Masking out bits that the shift already masks
2837 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
2838 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner2da29172003-09-19 19:05:02 +00002839 TheAnd.setOperand(1, CI);
2840 return &TheAnd;
2841 }
2842 break;
Misha Brukmanb1c93172005-04-21 23:48:37 +00002843 }
Reid Spencerfdff9382006-11-08 06:47:33 +00002844 case Instruction::LShr:
2845 {
Chris Lattner2da29172003-09-19 19:05:02 +00002846 // We know that the AND will not produce any of the bits shifted in, so if
2847 // the anded constant includes them, clear them now! This only applies to
2848 // unsigned shifts, because a signed shr may bring in set bits!
2849 //
Reid Spencerfdff9382006-11-08 06:47:33 +00002850 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
2851 Constant *ShrMask = ConstantExpr::getLShr(AllOne, OpRHS);
2852 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
Chris Lattner7e794272004-09-24 15:21:34 +00002853
Reid Spencerfdff9382006-11-08 06:47:33 +00002854 if (CI == ShrMask) { // Masking out bits that the shift already masks.
2855 return ReplaceInstUsesWith(TheAnd, Op);
2856 } else if (CI != AndRHS) {
2857 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
2858 return &TheAnd;
2859 }
2860 break;
2861 }
2862 case Instruction::AShr:
2863 // Signed shr.
2864 // See if this is shifting in some sign extension, then masking it out
2865 // with an and.
2866 if (Op->hasOneUse()) {
2867 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
2868 Constant *ShrMask = ConstantExpr::getLShr(AllOne, OpRHS);
Reid Spencer2a499b02006-12-13 17:19:09 +00002869 Constant *C = ConstantExpr::getAnd(AndRHS, ShrMask);
2870 if (C == AndRHS) { // Masking out bits shifted in.
Reid Spencer13bc5d72006-12-12 09:18:51 +00002871 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
Reid Spencerfdff9382006-11-08 06:47:33 +00002872 // Make the argument unsigned.
2873 Value *ShVal = Op->getOperand(0);
Reid Spencer2a499b02006-12-13 17:19:09 +00002874 ShVal = InsertNewInstBefore(new ShiftInst(Instruction::LShr, ShVal,
2875 OpRHS, Op->getName()), TheAnd);
2876 return BinaryOperator::createAnd(ShVal, AndRHS, TheAnd.getName());
Chris Lattner7e794272004-09-24 15:21:34 +00002877 }
Chris Lattner2da29172003-09-19 19:05:02 +00002878 }
2879 break;
Chris Lattnerba1cb382003-09-19 17:17:26 +00002880 }
2881 return 0;
2882}
2883
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002884
Chris Lattner6862fbd2004-09-29 17:40:11 +00002885/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
2886/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
2887/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. IB is the location to
2888/// insert new instructions.
2889Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
2890 bool Inside, Instruction &IB) {
2891 assert(cast<ConstantBool>(ConstantExpr::getSetLE(Lo, Hi))->getValue() &&
2892 "Lo is not <= Hi in range emission code!");
2893 if (Inside) {
2894 if (Lo == Hi) // Trivially false.
2895 return new SetCondInst(Instruction::SetNE, V, V);
Reid Spencer4ae56f32006-12-06 20:39:57 +00002896 if (cast<ConstantIntegral>(Lo)->isMinValue(Lo->getType()->isSigned()))
Chris Lattner6862fbd2004-09-29 17:40:11 +00002897 return new SetCondInst(Instruction::SetLT, V, Hi);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002898
Chris Lattner6862fbd2004-09-29 17:40:11 +00002899 Constant *AddCST = ConstantExpr::getNeg(Lo);
2900 Instruction *Add = BinaryOperator::createAdd(V, AddCST,V->getName()+".off");
2901 InsertNewInstBefore(Add, IB);
2902 // Convert to unsigned for the comparison.
2903 const Type *UnsType = Add->getType()->getUnsignedVersion();
Reid Spencer13bc5d72006-12-12 09:18:51 +00002904 Value *OffsetVal = InsertCastBefore(Instruction::BitCast, Add, UnsType, IB);
Chris Lattner6862fbd2004-09-29 17:40:11 +00002905 AddCST = ConstantExpr::getAdd(AddCST, Hi);
Reid Spencer13bc5d72006-12-12 09:18:51 +00002906 AddCST = ConstantExpr::getBitCast(AddCST, UnsType);
Chris Lattner6862fbd2004-09-29 17:40:11 +00002907 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
2908 }
2909
2910 if (Lo == Hi) // Trivially true.
2911 return new SetCondInst(Instruction::SetEQ, V, V);
2912
2913 Hi = SubOne(cast<ConstantInt>(Hi));
Reid Spencere0fc4df2006-10-20 07:07:24 +00002914
2915 // V < 0 || V >= Hi ->'V > Hi-1'
Reid Spencer4ae56f32006-12-06 20:39:57 +00002916 if (cast<ConstantIntegral>(Lo)->isMinValue(Lo->getType()->isSigned()))
Chris Lattner6862fbd2004-09-29 17:40:11 +00002917 return new SetCondInst(Instruction::SetGT, V, Hi);
2918
2919 // Emit X-Lo > Hi-Lo-1
2920 Constant *AddCST = ConstantExpr::getNeg(Lo);
2921 Instruction *Add = BinaryOperator::createAdd(V, AddCST, V->getName()+".off");
2922 InsertNewInstBefore(Add, IB);
2923 // Convert to unsigned for the comparison.
2924 const Type *UnsType = Add->getType()->getUnsignedVersion();
Reid Spencer13bc5d72006-12-12 09:18:51 +00002925 Value *OffsetVal = InsertCastBefore(Instruction::BitCast, Add, UnsType, IB);
Chris Lattner6862fbd2004-09-29 17:40:11 +00002926 AddCST = ConstantExpr::getAdd(AddCST, Hi);
Reid Spencer13bc5d72006-12-12 09:18:51 +00002927 AddCST = ConstantExpr::getBitCast(AddCST, UnsType);
Chris Lattner6862fbd2004-09-29 17:40:11 +00002928 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
2929}
2930
Chris Lattnerb4b25302005-09-18 07:22:02 +00002931// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
2932// any number of 0s on either side. The 1s are allowed to wrap from LSB to
2933// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
2934// not, since all 1s are not contiguous.
2935static bool isRunOfOnes(ConstantIntegral *Val, unsigned &MB, unsigned &ME) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002936 uint64_t V = Val->getZExtValue();
Chris Lattnerb4b25302005-09-18 07:22:02 +00002937 if (!isShiftedMask_64(V)) return false;
2938
2939 // look for the first zero bit after the run of ones
2940 MB = 64-CountLeadingZeros_64((V - 1) ^ V);
2941 // look for the first non-zero bit
2942 ME = 64-CountLeadingZeros_64(V);
2943 return true;
2944}
2945
2946
2947
2948/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
2949/// where isSub determines whether the operator is a sub. If we can fold one of
2950/// the following xforms:
Chris Lattneraf517572005-09-18 04:24:45 +00002951///
2952/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
2953/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
2954/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
2955///
2956/// return (A +/- B).
2957///
2958Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
2959 ConstantIntegral *Mask, bool isSub,
2960 Instruction &I) {
2961 Instruction *LHSI = dyn_cast<Instruction>(LHS);
2962 if (!LHSI || LHSI->getNumOperands() != 2 ||
2963 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
2964
2965 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
2966
2967 switch (LHSI->getOpcode()) {
2968 default: return 0;
2969 case Instruction::And:
Chris Lattnerb4b25302005-09-18 07:22:02 +00002970 if (ConstantExpr::getAnd(N, Mask) == Mask) {
2971 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Reid Spencere0fc4df2006-10-20 07:07:24 +00002972 if ((Mask->getZExtValue() & Mask->getZExtValue()+1) == 0)
Chris Lattnerb4b25302005-09-18 07:22:02 +00002973 break;
2974
2975 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
2976 // part, we don't need any explicit masks to take them out of A. If that
2977 // is all N is, ignore it.
2978 unsigned MB, ME;
2979 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Chris Lattnerc3ebf402006-02-07 07:27:52 +00002980 uint64_t Mask = RHS->getType()->getIntegralTypeMask();
2981 Mask >>= 64-MB+1;
2982 if (MaskedValueIsZero(RHS, Mask))
Chris Lattnerb4b25302005-09-18 07:22:02 +00002983 break;
2984 }
2985 }
Chris Lattneraf517572005-09-18 04:24:45 +00002986 return 0;
2987 case Instruction::Or:
2988 case Instruction::Xor:
Chris Lattnerb4b25302005-09-18 07:22:02 +00002989 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Reid Spencere0fc4df2006-10-20 07:07:24 +00002990 if ((Mask->getZExtValue() & Mask->getZExtValue()+1) == 0 &&
Chris Lattnerb4b25302005-09-18 07:22:02 +00002991 ConstantExpr::getAnd(N, Mask)->isNullValue())
Chris Lattneraf517572005-09-18 04:24:45 +00002992 break;
2993 return 0;
2994 }
2995
2996 Instruction *New;
2997 if (isSub)
2998 New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
2999 else
3000 New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
3001 return InsertNewInstBefore(New, I);
3002}
3003
Chris Lattner113f4f42002-06-25 16:13:24 +00003004Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003005 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00003006 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003007
Chris Lattner81a7a232004-10-16 18:11:37 +00003008 if (isa<UndefValue>(Op1)) // X & undef -> 0
3009 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3010
Chris Lattner86102b82005-01-01 16:22:27 +00003011 // and X, X = X
3012 if (Op0 == Op1)
Chris Lattnere6794492002-08-12 21:17:25 +00003013 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003014
Chris Lattner5b2edb12006-02-12 08:02:11 +00003015 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner5997cf92006-02-08 03:25:32 +00003016 // purpose is to compute bits we don't care about.
Chris Lattner0157e7f2006-02-11 09:31:47 +00003017 uint64_t KnownZero, KnownOne;
Chris Lattnerd70d9f52006-03-25 21:58:26 +00003018 if (!isa<PackedType>(I.getType()) &&
3019 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
Chris Lattner0157e7f2006-02-11 09:31:47 +00003020 KnownZero, KnownOne))
Chris Lattner5997cf92006-02-08 03:25:32 +00003021 return &I;
3022
Chris Lattner86102b82005-01-01 16:22:27 +00003023 if (ConstantIntegral *AndRHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00003024 uint64_t AndRHSMask = AndRHS->getZExtValue();
3025 uint64_t TypeMask = Op0->getType()->getIntegralTypeMask();
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00003026 uint64_t NotAndRHS = AndRHSMask^TypeMask;
Chris Lattner86102b82005-01-01 16:22:27 +00003027
Chris Lattnerba1cb382003-09-19 17:17:26 +00003028 // Optimize a variety of ((val OP C1) & C2) combinations...
3029 if (isa<BinaryOperator>(Op0) || isa<ShiftInst>(Op0)) {
3030 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner86102b82005-01-01 16:22:27 +00003031 Value *Op0LHS = Op0I->getOperand(0);
3032 Value *Op0RHS = Op0I->getOperand(1);
3033 switch (Op0I->getOpcode()) {
3034 case Instruction::Xor:
3035 case Instruction::Or:
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00003036 // If the mask is only needed on one incoming arm, push it up.
3037 if (Op0I->hasOneUse()) {
3038 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3039 // Not masking anything out for the LHS, move to RHS.
3040 Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
3041 Op0RHS->getName()+".masked");
3042 InsertNewInstBefore(NewRHS, I);
3043 return BinaryOperator::create(
3044 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003045 }
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003046 if (!isa<Constant>(Op0RHS) &&
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00003047 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3048 // Not masking anything out for the RHS, move to LHS.
3049 Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
3050 Op0LHS->getName()+".masked");
3051 InsertNewInstBefore(NewLHS, I);
3052 return BinaryOperator::create(
3053 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3054 }
3055 }
3056
Chris Lattner86102b82005-01-01 16:22:27 +00003057 break;
Chris Lattneraf517572005-09-18 04:24:45 +00003058 case Instruction::Add:
Chris Lattnerb4b25302005-09-18 07:22:02 +00003059 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3060 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3061 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3062 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
3063 return BinaryOperator::createAnd(V, AndRHS);
3064 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
3065 return BinaryOperator::createAnd(V, AndRHS); // Add commutes
Chris Lattneraf517572005-09-18 04:24:45 +00003066 break;
3067
3068 case Instruction::Sub:
Chris Lattnerb4b25302005-09-18 07:22:02 +00003069 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3070 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3071 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3072 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
3073 return BinaryOperator::createAnd(V, AndRHS);
Chris Lattneraf517572005-09-18 04:24:45 +00003074 break;
Chris Lattner86102b82005-01-01 16:22:27 +00003075 }
3076
Chris Lattner16464b32003-07-23 19:25:52 +00003077 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner86102b82005-01-01 16:22:27 +00003078 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerba1cb382003-09-19 17:17:26 +00003079 return Res;
Chris Lattner86102b82005-01-01 16:22:27 +00003080 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
Chris Lattner2c14cf72005-08-07 07:03:10 +00003081 // If this is an integer truncation or change from signed-to-unsigned, and
3082 // if the source is an and/or with immediate, transform it. This
3083 // frequently occurs for bitfield accesses.
3084 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003085 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
Chris Lattner2c14cf72005-08-07 07:03:10 +00003086 CastOp->getNumOperands() == 2)
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00003087 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1)))
Chris Lattner2c14cf72005-08-07 07:03:10 +00003088 if (CastOp->getOpcode() == Instruction::And) {
3089 // Change: and (cast (and X, C1) to T), C2
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003090 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
3091 // This will fold the two constants together, which may allow
3092 // other simplifications.
Reid Spencerbb65ebf2006-12-12 23:36:14 +00003093 Instruction *NewCast = CastInst::createTruncOrBitCast(
3094 CastOp->getOperand(0), I.getType(),
3095 CastOp->getName()+".shrunk");
Chris Lattner2c14cf72005-08-07 07:03:10 +00003096 NewCast = InsertNewInstBefore(NewCast, I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003097 // trunc_or_bitcast(C1)&C2
Reid Spencerbb65ebf2006-12-12 23:36:14 +00003098 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003099 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
Chris Lattner2dc148e2006-12-12 19:11:20 +00003104 Constant *C3 = ConstantExpr::getTruncOrBitCast(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();
Reid Spencer13bc5d72006-12-12 09:18:51 +00003229 Value *OffsetVal = InsertCastBefore(Instruction::BitCast, Add,
3230 UnsType, I);
Chris Lattner623826c2004-09-28 21:48:02 +00003231 AddCST = ConstantExpr::getSub(RHSCst, LHSCst);
Reid Spencer13bc5d72006-12-12 09:18:51 +00003232 AddCST = ConstantExpr::getBitCast(AddCST, UnsType);
Chris Lattner623826c2004-09-28 21:48:02 +00003233 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
3234 }
3235 break; // (X != 13 & X != 15) -> no change
3236 }
3237 break;
3238 case Instruction::SetLT:
3239 switch (RHSCC) {
3240 default: assert(0 && "Unknown integer condition code!");
3241 case Instruction::SetEQ: // (X < 13 & X == 15) -> false
3242 case Instruction::SetGT: // (X < 13 & X > 15) -> false
Chris Lattner6ab03f62006-09-28 23:35:22 +00003243 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattner623826c2004-09-28 21:48:02 +00003244 case Instruction::SetNE: // (X < 13 & X != 15) -> X < 13
3245 case Instruction::SetLT: // (X < 13 & X < 15) -> X < 13
3246 return ReplaceInstUsesWith(I, LHS);
3247 }
3248 case Instruction::SetGT:
3249 switch (RHSCC) {
3250 default: assert(0 && "Unknown integer condition code!");
3251 case Instruction::SetEQ: // (X > 13 & X == 15) -> X > 13
3252 return ReplaceInstUsesWith(I, LHS);
3253 case Instruction::SetGT: // (X > 13 & X > 15) -> X > 15
3254 return ReplaceInstUsesWith(I, RHS);
3255 case Instruction::SetNE:
3256 if (RHSCst == AddOne(LHSCst)) // (X > 13 & X != 14) -> X > 14
3257 return new SetCondInst(Instruction::SetGT, LHSVal, RHSCst);
3258 break; // (X > 13 & X != 15) -> no change
Chris Lattner6862fbd2004-09-29 17:40:11 +00003259 case Instruction::SetLT: // (X > 13 & X < 15) -> (X-14) <u 1
3260 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true, I);
Chris Lattner623826c2004-09-28 21:48:02 +00003261 }
3262 }
3263 }
3264 }
3265
Chris Lattner3af10532006-05-05 06:39:07 +00003266 // fold (and (cast A), (cast B)) -> (cast (and A, B))
Reid Spencer799b5bf2006-12-13 08:27:15 +00003267 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
3268 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3269 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
3270 const Type *SrcTy = Op0C->getOperand(0)->getType();
3271 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegral() &&
3272 // Only do this if the casts both really cause code to be generated.
3273 ValueRequiresCast(Op0C->getOperand(0), I.getType(), TD) &&
3274 ValueRequiresCast(Op1C->getOperand(0), I.getType(), TD)) {
3275 Instruction *NewOp = BinaryOperator::createAnd(Op0C->getOperand(0),
3276 Op1C->getOperand(0),
3277 I.getName());
3278 InsertNewInstBefore(NewOp, I);
3279 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
3280 }
Chris Lattner3af10532006-05-05 06:39:07 +00003281 }
Chris Lattnerf05d69a2006-11-14 07:46:50 +00003282
3283 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
3284 if (ShiftInst *SI1 = dyn_cast<ShiftInst>(Op1)) {
3285 if (ShiftInst *SI0 = dyn_cast<ShiftInst>(Op0))
3286 if (SI0->getOpcode() == SI1->getOpcode() &&
3287 SI0->getOperand(1) == SI1->getOperand(1) &&
3288 (SI0->hasOneUse() || SI1->hasOneUse())) {
3289 Instruction *NewOp =
3290 InsertNewInstBefore(BinaryOperator::createAnd(SI0->getOperand(0),
3291 SI1->getOperand(0),
3292 SI0->getName()), I);
3293 return new ShiftInst(SI1->getOpcode(), NewOp, SI1->getOperand(1));
3294 }
Chris Lattner3af10532006-05-05 06:39:07 +00003295 }
3296
Chris Lattner113f4f42002-06-25 16:13:24 +00003297 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003298}
3299
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003300/// CollectBSwapParts - Look to see if the specified value defines a single byte
3301/// in the result. If it does, and if the specified byte hasn't been filled in
3302/// yet, fill it in and return false.
3303static bool CollectBSwapParts(Value *V, std::vector<Value*> &ByteValues) {
3304 Instruction *I = dyn_cast<Instruction>(V);
3305 if (I == 0) return true;
3306
3307 // If this is an or instruction, it is an inner node of the bswap.
3308 if (I->getOpcode() == Instruction::Or)
3309 return CollectBSwapParts(I->getOperand(0), ByteValues) ||
3310 CollectBSwapParts(I->getOperand(1), ByteValues);
3311
3312 // If this is a shift by a constant int, and it is "24", then its operand
3313 // defines a byte. We only handle unsigned types here.
3314 if (isa<ShiftInst>(I) && isa<ConstantInt>(I->getOperand(1))) {
3315 // Not shifting the entire input by N-1 bytes?
Reid Spencere0fc4df2006-10-20 07:07:24 +00003316 if (cast<ConstantInt>(I->getOperand(1))->getZExtValue() !=
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003317 8*(ByteValues.size()-1))
3318 return true;
3319
3320 unsigned DestNo;
3321 if (I->getOpcode() == Instruction::Shl) {
3322 // X << 24 defines the top byte with the lowest of the input bytes.
3323 DestNo = ByteValues.size()-1;
3324 } else {
3325 // X >>u 24 defines the low byte with the highest of the input bytes.
3326 DestNo = 0;
3327 }
3328
3329 // If the destination byte value is already defined, the values are or'd
3330 // together, which isn't a bswap (unless it's an or of the same bits).
3331 if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
3332 return true;
3333 ByteValues[DestNo] = I->getOperand(0);
3334 return false;
3335 }
3336
3337 // Otherwise, we can only handle and(shift X, imm), imm). Bail out of if we
3338 // don't have this.
3339 Value *Shift = 0, *ShiftLHS = 0;
3340 ConstantInt *AndAmt = 0, *ShiftAmt = 0;
3341 if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
3342 !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
3343 return true;
3344 Instruction *SI = cast<Instruction>(Shift);
3345
3346 // Make sure that the shift amount is by a multiple of 8 and isn't too big.
Reid Spencere0fc4df2006-10-20 07:07:24 +00003347 if (ShiftAmt->getZExtValue() & 7 ||
3348 ShiftAmt->getZExtValue() > 8*ByteValues.size())
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003349 return true;
3350
3351 // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
3352 unsigned DestByte;
3353 for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
Reid Spencere0fc4df2006-10-20 07:07:24 +00003354 if (AndAmt->getZExtValue() == uint64_t(0xFF) << 8*DestByte)
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003355 break;
3356 // Unknown mask for bswap.
3357 if (DestByte == ByteValues.size()) return true;
3358
Reid Spencere0fc4df2006-10-20 07:07:24 +00003359 unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003360 unsigned SrcByte;
3361 if (SI->getOpcode() == Instruction::Shl)
3362 SrcByte = DestByte - ShiftBytes;
3363 else
3364 SrcByte = DestByte + ShiftBytes;
3365
3366 // If the SrcByte isn't a bswapped value from the DestByte, reject it.
3367 if (SrcByte != ByteValues.size()-DestByte-1)
3368 return true;
3369
3370 // If the destination byte value is already defined, the values are or'd
3371 // together, which isn't a bswap (unless it's an or of the same bits).
3372 if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
3373 return true;
3374 ByteValues[DestByte] = SI->getOperand(0);
3375 return false;
3376}
3377
3378/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
3379/// If so, insert the new bswap intrinsic and return it.
3380Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
3381 // We can only handle bswap of unsigned integers, and cannot bswap one byte.
3382 if (!I.getType()->isUnsigned() || I.getType() == Type::UByteTy)
3383 return 0;
3384
3385 /// ByteValues - For each byte of the result, we keep track of which value
3386 /// defines each byte.
3387 std::vector<Value*> ByteValues;
3388 ByteValues.resize(I.getType()->getPrimitiveSize());
3389
3390 // Try to find all the pieces corresponding to the bswap.
3391 if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
3392 CollectBSwapParts(I.getOperand(1), ByteValues))
3393 return 0;
3394
3395 // Check to see if all of the bytes come from the same value.
3396 Value *V = ByteValues[0];
3397 if (V == 0) return 0; // Didn't find a byte? Must be zero.
3398
3399 // Check to make sure that all of the bytes come from the same value.
3400 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
3401 if (ByteValues[i] != V)
3402 return 0;
3403
3404 // If they do then *success* we can turn this into a bswap. Figure out what
3405 // bswap to make it into.
3406 Module *M = I.getParent()->getParent()->getParent();
Chris Lattner091b6ea2006-07-11 18:31:26 +00003407 const char *FnName = 0;
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003408 if (I.getType() == Type::UShortTy)
3409 FnName = "llvm.bswap.i16";
3410 else if (I.getType() == Type::UIntTy)
3411 FnName = "llvm.bswap.i32";
3412 else if (I.getType() == Type::ULongTy)
3413 FnName = "llvm.bswap.i64";
3414 else
3415 assert(0 && "Unknown integer type!");
3416 Function *F = M->getOrInsertFunction(FnName, I.getType(), I.getType(), NULL);
3417
3418 return new CallInst(F, V);
3419}
3420
3421
Chris Lattner113f4f42002-06-25 16:13:24 +00003422Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003423 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00003424 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003425
Chris Lattner81a7a232004-10-16 18:11:37 +00003426 if (isa<UndefValue>(Op1))
3427 return ReplaceInstUsesWith(I, // X | undef -> -1
3428 ConstantIntegral::getAllOnesValue(I.getType()));
3429
Chris Lattner5b2edb12006-02-12 08:02:11 +00003430 // or X, X = X
3431 if (Op0 == Op1)
Chris Lattnere6794492002-08-12 21:17:25 +00003432 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003433
Chris Lattner5b2edb12006-02-12 08:02:11 +00003434 // See if we can simplify any instructions used by the instruction whose sole
3435 // purpose is to compute bits we don't care about.
3436 uint64_t KnownZero, KnownOne;
Chris Lattnerd70d9f52006-03-25 21:58:26 +00003437 if (!isa<PackedType>(I.getType()) &&
3438 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
Chris Lattner5b2edb12006-02-12 08:02:11 +00003439 KnownZero, KnownOne))
3440 return &I;
3441
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003442 // or X, -1 == -1
Chris Lattner8f0d1562003-07-23 18:29:44 +00003443 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner330628a2006-01-06 17:59:59 +00003444 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00003445 // (X & C1) | C2 --> (X | C2) & (C1|C2)
3446 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Chris Lattnerb62f5082005-05-09 04:58:36 +00003447 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0->getName());
3448 Op0->setName("");
Chris Lattnerd4252a72004-07-30 07:50:03 +00003449 InsertNewInstBefore(Or, I);
3450 return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, C1));
3451 }
Chris Lattner8f0d1562003-07-23 18:29:44 +00003452
Chris Lattnerd4252a72004-07-30 07:50:03 +00003453 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
3454 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
3455 std::string Op0Name = Op0->getName(); Op0->setName("");
3456 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
3457 InsertNewInstBefore(Or, I);
3458 return BinaryOperator::createXor(Or,
3459 ConstantExpr::getAnd(C1, ConstantExpr::getNot(RHS)));
Chris Lattner8f0d1562003-07-23 18:29:44 +00003460 }
Chris Lattner183b3362004-04-09 19:05:30 +00003461
3462 // Try to fold constant and into select arguments.
3463 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00003464 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00003465 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00003466 if (isa<PHINode>(Op0))
3467 if (Instruction *NV = FoldOpIntoPhi(I))
3468 return NV;
Chris Lattner8f0d1562003-07-23 18:29:44 +00003469 }
3470
Chris Lattner330628a2006-01-06 17:59:59 +00003471 Value *A = 0, *B = 0;
3472 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattner4294cec2005-05-07 23:49:08 +00003473
3474 if (match(Op0, m_And(m_Value(A), m_Value(B))))
3475 if (A == Op1 || B == Op1) // (A & ?) | A --> A
3476 return ReplaceInstUsesWith(I, Op1);
3477 if (match(Op1, m_And(m_Value(A), m_Value(B))))
3478 if (A == Op0 || B == Op0) // A | (A & ?) --> A
3479 return ReplaceInstUsesWith(I, Op0);
3480
Chris Lattnerb7845d62006-07-10 20:25:24 +00003481 // (A | B) | C and A | (B | C) -> bswap if possible.
3482 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003483 if (match(Op0, m_Or(m_Value(), m_Value())) ||
Chris Lattnerb7845d62006-07-10 20:25:24 +00003484 match(Op1, m_Or(m_Value(), m_Value())) ||
3485 (match(Op0, m_Shift(m_Value(), m_Value())) &&
3486 match(Op1, m_Shift(m_Value(), m_Value())))) {
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003487 if (Instruction *BSwap = MatchBSwap(I))
3488 return BSwap;
3489 }
3490
Chris Lattnerb62f5082005-05-09 04:58:36 +00003491 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
3492 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003493 MaskedValueIsZero(Op1, C1->getZExtValue())) {
Chris Lattnerb62f5082005-05-09 04:58:36 +00003494 Instruction *NOr = BinaryOperator::createOr(A, Op1, Op0->getName());
3495 Op0->setName("");
3496 return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
3497 }
3498
3499 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
3500 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003501 MaskedValueIsZero(Op0, C1->getZExtValue())) {
Chris Lattnerb62f5082005-05-09 04:58:36 +00003502 Instruction *NOr = BinaryOperator::createOr(A, Op0, Op1->getName());
3503 Op0->setName("");
3504 return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
3505 }
3506
Chris Lattner15212982005-09-18 03:42:07 +00003507 // (A & C1)|(B & C2)
Chris Lattnerd4252a72004-07-30 07:50:03 +00003508 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattner15212982005-09-18 03:42:07 +00003509 match(Op1, m_And(m_Value(B), m_ConstantInt(C2)))) {
3510
3511 if (A == B) // (A & C1)|(A & C2) == A & (C1|C2)
3512 return BinaryOperator::createAnd(A, ConstantExpr::getOr(C1, C2));
3513
3514
Chris Lattner01f56c62005-09-18 06:02:59 +00003515 // If we have: ((V + N) & C1) | (V & C2)
3516 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
3517 // replace with V+N.
3518 if (C1 == ConstantExpr::getNot(C2)) {
Chris Lattner330628a2006-01-06 17:59:59 +00003519 Value *V1 = 0, *V2 = 0;
Reid Spencere0fc4df2006-10-20 07:07:24 +00003520 if ((C2->getZExtValue() & (C2->getZExtValue()+1)) == 0 && // C2 == 0+1+
Chris Lattner01f56c62005-09-18 06:02:59 +00003521 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
3522 // Add commutes, try both ways.
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003523 if (V1 == B && MaskedValueIsZero(V2, C2->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003524 return ReplaceInstUsesWith(I, A);
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003525 if (V2 == B && MaskedValueIsZero(V1, C2->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003526 return ReplaceInstUsesWith(I, A);
3527 }
3528 // Or commutes, try both ways.
Reid Spencere0fc4df2006-10-20 07:07:24 +00003529 if ((C1->getZExtValue() & (C1->getZExtValue()+1)) == 0 &&
Chris Lattner01f56c62005-09-18 06:02:59 +00003530 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
3531 // Add commutes, try both ways.
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003532 if (V1 == A && MaskedValueIsZero(V2, C1->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003533 return ReplaceInstUsesWith(I, B);
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003534 if (V2 == A && MaskedValueIsZero(V1, C1->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003535 return ReplaceInstUsesWith(I, B);
Chris Lattner15212982005-09-18 03:42:07 +00003536 }
3537 }
3538 }
Chris Lattnerf05d69a2006-11-14 07:46:50 +00003539
3540 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
3541 if (ShiftInst *SI1 = dyn_cast<ShiftInst>(Op1)) {
3542 if (ShiftInst *SI0 = dyn_cast<ShiftInst>(Op0))
3543 if (SI0->getOpcode() == SI1->getOpcode() &&
3544 SI0->getOperand(1) == SI1->getOperand(1) &&
3545 (SI0->hasOneUse() || SI1->hasOneUse())) {
3546 Instruction *NewOp =
3547 InsertNewInstBefore(BinaryOperator::createOr(SI0->getOperand(0),
3548 SI1->getOperand(0),
3549 SI0->getName()), I);
3550 return new ShiftInst(SI1->getOpcode(), NewOp, SI1->getOperand(1));
3551 }
3552 }
Chris Lattner812aab72003-08-12 19:11:07 +00003553
Chris Lattnerd4252a72004-07-30 07:50:03 +00003554 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
3555 if (A == Op1) // ~A | A == -1
Misha Brukmanb1c93172005-04-21 23:48:37 +00003556 return ReplaceInstUsesWith(I,
Chris Lattnerd4252a72004-07-30 07:50:03 +00003557 ConstantIntegral::getAllOnesValue(I.getType()));
3558 } else {
3559 A = 0;
3560 }
Chris Lattner4294cec2005-05-07 23:49:08 +00003561 // Note, A is still live here!
Chris Lattnerd4252a72004-07-30 07:50:03 +00003562 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
3563 if (Op0 == B)
Misha Brukmanb1c93172005-04-21 23:48:37 +00003564 return ReplaceInstUsesWith(I,
Chris Lattnerd4252a72004-07-30 07:50:03 +00003565 ConstantIntegral::getAllOnesValue(I.getType()));
Chris Lattner3e327a42003-03-10 23:13:59 +00003566
Misha Brukman9c003d82004-07-30 12:50:08 +00003567 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattnerd4252a72004-07-30 07:50:03 +00003568 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3569 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
3570 I.getName()+".demorgan"), I);
3571 return BinaryOperator::createNot(And);
3572 }
Chris Lattner3e327a42003-03-10 23:13:59 +00003573 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00003574
Chris Lattner3ac7c262003-08-13 20:16:26 +00003575 // (setcc1 A, B) | (setcc2 A, B) --> (setcc3 A, B)
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003576 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1))) {
Chris Lattner3ac7c262003-08-13 20:16:26 +00003577 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
3578 return R;
3579
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003580 Value *LHSVal, *RHSVal;
3581 ConstantInt *LHSCst, *RHSCst;
3582 Instruction::BinaryOps LHSCC, RHSCC;
3583 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3584 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3585 if (LHSVal == RHSVal && // Found (X setcc C1) | (X setcc C2)
3586 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
Misha Brukmanb1c93172005-04-21 23:48:37 +00003587 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003588 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
3589 // Ensure that the larger constant is on the RHS.
3590 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
3591 SetCondInst *LHS = cast<SetCondInst>(Op0);
3592 if (cast<ConstantBool>(Cmp)->getValue()) {
3593 std::swap(LHS, RHS);
3594 std::swap(LHSCst, RHSCst);
3595 std::swap(LHSCC, RHSCC);
3596 }
3597
3598 // At this point, we know we have have two setcc instructions
3599 // comparing a value against two constants and or'ing the result
3600 // together. Because of the above check, we know that we only have
3601 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
3602 // FoldSetCCLogical check above), that the two constants are not
3603 // equal.
3604 assert(LHSCst != RHSCst && "Compares not folded above?");
3605
3606 switch (LHSCC) {
3607 default: assert(0 && "Unknown integer condition code!");
3608 case Instruction::SetEQ:
3609 switch (RHSCC) {
3610 default: assert(0 && "Unknown integer condition code!");
3611 case Instruction::SetEQ:
3612 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
3613 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3614 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3615 LHSVal->getName()+".off");
3616 InsertNewInstBefore(Add, I);
3617 const Type *UnsType = Add->getType()->getUnsignedVersion();
Reid Spencer13bc5d72006-12-12 09:18:51 +00003618 Value *OffsetVal = InsertCastBefore(Instruction::BitCast, Add,
3619 UnsType, I);
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003620 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
Reid Spencer13bc5d72006-12-12 09:18:51 +00003621 AddCST = ConstantExpr::getBitCast(AddCST, UnsType);
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003622 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
3623 }
3624 break; // (X == 13 | X == 15) -> no change
3625
Chris Lattner5c219462005-04-19 06:04:18 +00003626 case Instruction::SetGT: // (X == 13 | X > 14) -> no change
3627 break;
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003628 case Instruction::SetNE: // (X == 13 | X != 15) -> X != 15
3629 case Instruction::SetLT: // (X == 13 | X < 15) -> X < 15
3630 return ReplaceInstUsesWith(I, RHS);
3631 }
3632 break;
3633 case Instruction::SetNE:
3634 switch (RHSCC) {
3635 default: assert(0 && "Unknown integer condition code!");
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003636 case Instruction::SetEQ: // (X != 13 | X == 15) -> X != 13
3637 case Instruction::SetGT: // (X != 13 | X > 15) -> X != 13
3638 return ReplaceInstUsesWith(I, LHS);
3639 case Instruction::SetNE: // (X != 13 | X != 15) -> true
Chris Lattner2ceb6ee2005-06-17 03:59:17 +00003640 case Instruction::SetLT: // (X != 13 | X < 15) -> true
Chris Lattner6ab03f62006-09-28 23:35:22 +00003641 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003642 }
3643 break;
3644 case Instruction::SetLT:
3645 switch (RHSCC) {
3646 default: assert(0 && "Unknown integer condition code!");
3647 case Instruction::SetEQ: // (X < 13 | X == 14) -> no change
3648 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00003649 case Instruction::SetGT: // (X < 13 | X > 15) -> (X-13) > 2
3650 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false, I);
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003651 case Instruction::SetNE: // (X < 13 | X != 15) -> X != 15
3652 case Instruction::SetLT: // (X < 13 | X < 15) -> X < 15
3653 return ReplaceInstUsesWith(I, RHS);
3654 }
3655 break;
3656 case Instruction::SetGT:
3657 switch (RHSCC) {
3658 default: assert(0 && "Unknown integer condition code!");
3659 case Instruction::SetEQ: // (X > 13 | X == 15) -> X > 13
3660 case Instruction::SetGT: // (X > 13 | X > 15) -> X > 13
3661 return ReplaceInstUsesWith(I, LHS);
3662 case Instruction::SetNE: // (X > 13 | X != 15) -> true
3663 case Instruction::SetLT: // (X > 13 | X < 15) -> true
Chris Lattner6ab03f62006-09-28 23:35:22 +00003664 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003665 }
3666 }
3667 }
3668 }
Chris Lattner3af10532006-05-05 06:39:07 +00003669
3670 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Reid Spencer799b5bf2006-12-13 08:27:15 +00003671 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
Chris Lattner3af10532006-05-05 06:39:07 +00003672 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer799b5bf2006-12-13 08:27:15 +00003673 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
3674 const Type *SrcTy = Op0C->getOperand(0)->getType();
3675 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegral() &&
3676 // Only do this if the casts both really cause code to be generated.
3677 ValueRequiresCast(Op0C->getOperand(0), I.getType(), TD) &&
3678 ValueRequiresCast(Op1C->getOperand(0), I.getType(), TD)) {
3679 Instruction *NewOp = BinaryOperator::createOr(Op0C->getOperand(0),
3680 Op1C->getOperand(0),
3681 I.getName());
3682 InsertNewInstBefore(NewOp, I);
3683 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
3684 }
Chris Lattner3af10532006-05-05 06:39:07 +00003685 }
Chris Lattner3af10532006-05-05 06:39:07 +00003686
Chris Lattner15212982005-09-18 03:42:07 +00003687
Chris Lattner113f4f42002-06-25 16:13:24 +00003688 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003689}
3690
Chris Lattnerc2076352004-02-16 01:20:27 +00003691// XorSelf - Implements: X ^ X --> 0
3692struct XorSelf {
3693 Value *RHS;
3694 XorSelf(Value *rhs) : RHS(rhs) {}
3695 bool shouldApply(Value *LHS) const { return LHS == RHS; }
3696 Instruction *apply(BinaryOperator &Xor) const {
3697 return &Xor;
3698 }
3699};
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003700
3701
Chris Lattner113f4f42002-06-25 16:13:24 +00003702Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003703 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00003704 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003705
Chris Lattner81a7a232004-10-16 18:11:37 +00003706 if (isa<UndefValue>(Op1))
3707 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
3708
Chris Lattnerc2076352004-02-16 01:20:27 +00003709 // xor X, X = 0, even if X is nested in a sequence of Xor's.
3710 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
3711 assert(Result == &I && "AssociativeOpt didn't work?");
Chris Lattnere6794492002-08-12 21:17:25 +00003712 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc2076352004-02-16 01:20:27 +00003713 }
Chris Lattner5b2edb12006-02-12 08:02:11 +00003714
3715 // See if we can simplify any instructions used by the instruction whose sole
3716 // purpose is to compute bits we don't care about.
3717 uint64_t KnownZero, KnownOne;
Chris Lattnerd70d9f52006-03-25 21:58:26 +00003718 if (!isa<PackedType>(I.getType()) &&
3719 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
Chris Lattner5b2edb12006-02-12 08:02:11 +00003720 KnownZero, KnownOne))
3721 return &I;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003722
Chris Lattner97638592003-07-23 21:37:07 +00003723 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner97638592003-07-23 21:37:07 +00003724 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerb8d6e402002-08-20 18:24:26 +00003725 // xor (setcc A, B), true = not (setcc A, B) = setncc A, B
Chris Lattner97638592003-07-23 21:37:07 +00003726 if (SetCondInst *SCI = dyn_cast<SetCondInst>(Op0I))
Chris Lattner6ab03f62006-09-28 23:35:22 +00003727 if (RHS == ConstantBool::getTrue() && SCI->hasOneUse())
Chris Lattnerb8d6e402002-08-20 18:24:26 +00003728 return new SetCondInst(SCI->getInverseCondition(),
3729 SCI->getOperand(0), SCI->getOperand(1));
Chris Lattnere5806662003-11-04 23:50:51 +00003730
Chris Lattner8f2f5982003-11-05 01:06:05 +00003731 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003732 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
3733 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003734 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
3735 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003736 ConstantInt::get(I.getType(), 1));
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003737 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003738 }
Chris Lattner023a4832004-06-18 06:07:51 +00003739
3740 // ~(~X & Y) --> (X | ~Y)
3741 if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
3742 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
3743 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
3744 Instruction *NotY =
Misha Brukmanb1c93172005-04-21 23:48:37 +00003745 BinaryOperator::createNot(Op0I->getOperand(1),
Chris Lattner023a4832004-06-18 06:07:51 +00003746 Op0I->getOperand(1)->getName()+".not");
3747 InsertNewInstBefore(NotY, I);
3748 return BinaryOperator::createOr(Op0NotVal, NotY);
3749 }
3750 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003751
Chris Lattner97638592003-07-23 21:37:07 +00003752 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner5b2edb12006-02-12 08:02:11 +00003753 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner0f68fa62003-11-04 23:37:10 +00003754 // ~(X-c) --> (-c-1)-X
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003755 if (RHS->isAllOnesValue()) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003756 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
3757 return BinaryOperator::createSub(
3758 ConstantExpr::getSub(NegOp0CI,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003759 ConstantInt::get(I.getType(), 1)),
Chris Lattner0f68fa62003-11-04 23:37:10 +00003760 Op0I->getOperand(0));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003761 }
Chris Lattnerf78df7c2006-02-26 19:57:54 +00003762 } else if (Op0I->getOpcode() == Instruction::Or) {
3763 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
3764 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getZExtValue())) {
3765 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
3766 // Anything in both C1 and C2 is known to be zero, remove it from
3767 // NewRHS.
3768 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
3769 NewRHS = ConstantExpr::getAnd(NewRHS,
3770 ConstantExpr::getNot(CommonBits));
3771 WorkList.push_back(Op0I);
3772 I.setOperand(0, Op0I->getOperand(0));
3773 I.setOperand(1, NewRHS);
3774 return &I;
3775 }
Chris Lattner97638592003-07-23 21:37:07 +00003776 }
Chris Lattnerb8d6e402002-08-20 18:24:26 +00003777 }
Chris Lattner183b3362004-04-09 19:05:30 +00003778
3779 // Try to fold constant and into select arguments.
3780 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00003781 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00003782 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00003783 if (isa<PHINode>(Op0))
3784 if (Instruction *NV = FoldOpIntoPhi(I))
3785 return NV;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003786 }
3787
Chris Lattnerbb74e222003-03-10 23:06:50 +00003788 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00003789 if (X == Op1)
3790 return ReplaceInstUsesWith(I,
3791 ConstantIntegral::getAllOnesValue(I.getType()));
3792
Chris Lattnerbb74e222003-03-10 23:06:50 +00003793 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00003794 if (X == Op0)
3795 return ReplaceInstUsesWith(I,
3796 ConstantIntegral::getAllOnesValue(I.getType()));
3797
Chris Lattnerdcd07922006-04-01 08:03:55 +00003798 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1))
Chris Lattnerb36d9082004-02-16 03:54:20 +00003799 if (Op1I->getOpcode() == Instruction::Or) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003800 if (Op1I->getOperand(0) == Op0) { // B^(B|A) == (A|B)^B
Chris Lattnerdcd07922006-04-01 08:03:55 +00003801 Op1I->swapOperands();
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003802 I.swapOperands();
3803 std::swap(Op0, Op1);
3804 } else if (Op1I->getOperand(1) == Op0) { // B^(A|B) == (A|B)^B
Chris Lattnerdcd07922006-04-01 08:03:55 +00003805 I.swapOperands(); // Simplified below.
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003806 std::swap(Op0, Op1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003807 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00003808 } else if (Op1I->getOpcode() == Instruction::Xor) {
3809 if (Op0 == Op1I->getOperand(0)) // A^(A^B) == B
3810 return ReplaceInstUsesWith(I, Op1I->getOperand(1));
3811 else if (Op0 == Op1I->getOperand(1)) // A^(B^A) == B
3812 return ReplaceInstUsesWith(I, Op1I->getOperand(0));
Chris Lattnerdcd07922006-04-01 08:03:55 +00003813 } else if (Op1I->getOpcode() == Instruction::And && Op1I->hasOneUse()) {
3814 if (Op1I->getOperand(0) == Op0) // A^(A&B) -> A^(B&A)
3815 Op1I->swapOperands();
3816 if (Op0 == Op1I->getOperand(1)) { // A^(B&A) -> (B&A)^A
3817 I.swapOperands(); // Simplified below.
3818 std::swap(Op0, Op1);
3819 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00003820 }
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003821
Chris Lattnerdcd07922006-04-01 08:03:55 +00003822 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00003823 if (Op0I->getOpcode() == Instruction::Or && Op0I->hasOneUse()) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003824 if (Op0I->getOperand(0) == Op1) // (B|A)^B == (A|B)^B
Chris Lattnerdcd07922006-04-01 08:03:55 +00003825 Op0I->swapOperands();
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003826 if (Op0I->getOperand(1) == Op1) { // (A|B)^B == A & ~B
Chris Lattnerdcd07922006-04-01 08:03:55 +00003827 Instruction *NotB = BinaryOperator::createNot(Op1, "tmp");
3828 InsertNewInstBefore(NotB, I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003829 return BinaryOperator::createAnd(Op0I->getOperand(0), NotB);
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003830 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00003831 } else if (Op0I->getOpcode() == Instruction::Xor) {
3832 if (Op1 == Op0I->getOperand(0)) // (A^B)^A == B
3833 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
3834 else if (Op1 == Op0I->getOperand(1)) // (B^A)^A == B
3835 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattnerdcd07922006-04-01 08:03:55 +00003836 } else if (Op0I->getOpcode() == Instruction::And && Op0I->hasOneUse()) {
3837 if (Op0I->getOperand(0) == Op1) // (A&B)^A -> (B&A)^A
3838 Op0I->swapOperands();
Chris Lattner6cf49142006-04-01 22:05:01 +00003839 if (Op0I->getOperand(1) == Op1 && // (B&A)^A == ~B & A
3840 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattnerdcd07922006-04-01 08:03:55 +00003841 Instruction *N = BinaryOperator::createNot(Op0I->getOperand(0), "tmp");
3842 InsertNewInstBefore(N, I);
3843 return BinaryOperator::createAnd(N, Op1);
3844 }
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003845 }
3846
Chris Lattner3ac7c262003-08-13 20:16:26 +00003847 // (setcc1 A, B) ^ (setcc2 A, B) --> (setcc3 A, B)
3848 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
3849 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
3850 return R;
3851
Chris Lattner3af10532006-05-05 06:39:07 +00003852 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Reid Spencer799b5bf2006-12-13 08:27:15 +00003853 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
Chris Lattner3af10532006-05-05 06:39:07 +00003854 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer799b5bf2006-12-13 08:27:15 +00003855 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
3856 const Type *SrcTy = Op0C->getOperand(0)->getType();
3857 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegral() &&
3858 // Only do this if the casts both really cause code to be generated.
3859 ValueRequiresCast(Op0C->getOperand(0), I.getType(), TD) &&
3860 ValueRequiresCast(Op1C->getOperand(0), I.getType(), TD)) {
3861 Instruction *NewOp = BinaryOperator::createXor(Op0C->getOperand(0),
3862 Op1C->getOperand(0),
3863 I.getName());
3864 InsertNewInstBefore(NewOp, I);
3865 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
3866 }
Chris Lattner3af10532006-05-05 06:39:07 +00003867 }
Chris Lattnerf05d69a2006-11-14 07:46:50 +00003868
3869 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
3870 if (ShiftInst *SI1 = dyn_cast<ShiftInst>(Op1)) {
3871 if (ShiftInst *SI0 = dyn_cast<ShiftInst>(Op0))
3872 if (SI0->getOpcode() == SI1->getOpcode() &&
3873 SI0->getOperand(1) == SI1->getOperand(1) &&
3874 (SI0->hasOneUse() || SI1->hasOneUse())) {
3875 Instruction *NewOp =
3876 InsertNewInstBefore(BinaryOperator::createXor(SI0->getOperand(0),
3877 SI1->getOperand(0),
3878 SI0->getName()), I);
3879 return new ShiftInst(SI1->getOpcode(), NewOp, SI1->getOperand(1));
3880 }
3881 }
Chris Lattner3af10532006-05-05 06:39:07 +00003882
Chris Lattner113f4f42002-06-25 16:13:24 +00003883 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003884}
3885
Chris Lattner6862fbd2004-09-29 17:40:11 +00003886static bool isPositive(ConstantInt *C) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00003887 return C->getSExtValue() >= 0;
Chris Lattner6862fbd2004-09-29 17:40:11 +00003888}
3889
3890/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
3891/// overflowed for this type.
3892static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
3893 ConstantInt *In2) {
3894 Result = cast<ConstantInt>(ConstantExpr::getAdd(In1, In2));
3895
3896 if (In1->getType()->isUnsigned())
Reid Spencere0fc4df2006-10-20 07:07:24 +00003897 return cast<ConstantInt>(Result)->getZExtValue() <
3898 cast<ConstantInt>(In1)->getZExtValue();
Chris Lattner6862fbd2004-09-29 17:40:11 +00003899 if (isPositive(In1) != isPositive(In2))
3900 return false;
3901 if (isPositive(In1))
Reid Spencere0fc4df2006-10-20 07:07:24 +00003902 return cast<ConstantInt>(Result)->getSExtValue() <
3903 cast<ConstantInt>(In1)->getSExtValue();
3904 return cast<ConstantInt>(Result)->getSExtValue() >
3905 cast<ConstantInt>(In1)->getSExtValue();
Chris Lattner6862fbd2004-09-29 17:40:11 +00003906}
3907
Chris Lattner0798af32005-01-13 20:14:25 +00003908/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
3909/// code necessary to compute the offset from the base pointer (without adding
3910/// in the base pointer). Return the result as a signed integer of intptr size.
3911static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
3912 TargetData &TD = IC.getTargetData();
3913 gep_type_iterator GTI = gep_type_begin(GEP);
3914 const Type *UIntPtrTy = TD.getIntPtrType();
3915 const Type *SIntPtrTy = UIntPtrTy->getSignedVersion();
3916 Value *Result = Constant::getNullValue(SIntPtrTy);
3917
3918 // Build a mask for high order bits.
Chris Lattner77defba2006-02-07 07:00:41 +00003919 uint64_t PtrSizeMask = ~0ULL >> (64-TD.getPointerSize()*8);
Chris Lattner0798af32005-01-13 20:14:25 +00003920
Chris Lattner0798af32005-01-13 20:14:25 +00003921 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
3922 Value *Op = GEP->getOperand(i);
Chris Lattnerd35d2102005-01-13 23:26:48 +00003923 uint64_t Size = TD.getTypeSize(GTI.getIndexedType()) & PtrSizeMask;
Reid Spencer2a499b02006-12-13 17:19:09 +00003924 Constant *Scale = ConstantInt::get(SIntPtrTy, Size);
Chris Lattner0798af32005-01-13 20:14:25 +00003925 if (Constant *OpC = dyn_cast<Constant>(Op)) {
3926 if (!OpC->isNullValue()) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00003927 OpC = ConstantExpr::getIntegerCast(OpC, SIntPtrTy, true /*SExt*/);
Chris Lattner0798af32005-01-13 20:14:25 +00003928 Scale = ConstantExpr::getMul(OpC, Scale);
3929 if (Constant *RC = dyn_cast<Constant>(Result))
3930 Result = ConstantExpr::getAdd(RC, Scale);
3931 else {
3932 // Emit an add instruction.
3933 Result = IC.InsertNewInstBefore(
3934 BinaryOperator::createAdd(Result, Scale,
3935 GEP->getName()+".offs"), I);
3936 }
3937 }
3938 } else {
Chris Lattner7aa41cf2005-01-14 17:17:59 +00003939 // Convert to correct type.
Reid Spencerbb65ebf2006-12-12 23:36:14 +00003940 Op = IC.InsertNewInstBefore(CastInst::createSExtOrBitCast(Op, SIntPtrTy,
Chris Lattner7aa41cf2005-01-14 17:17:59 +00003941 Op->getName()+".c"), I);
3942 if (Size != 1)
Chris Lattner4cb9fa32005-01-13 20:40:58 +00003943 // We'll let instcombine(mul) convert this to a shl if possible.
3944 Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
3945 GEP->getName()+".idx"), I);
Chris Lattner0798af32005-01-13 20:14:25 +00003946
3947 // Emit an add instruction.
Chris Lattner4cb9fa32005-01-13 20:40:58 +00003948 Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
Chris Lattner0798af32005-01-13 20:14:25 +00003949 GEP->getName()+".offs"), I);
3950 }
3951 }
3952 return Result;
3953}
3954
3955/// FoldGEPSetCC - Fold comparisons between a GEP instruction and something
3956/// else. At this point we know that the GEP is on the LHS of the comparison.
3957Instruction *InstCombiner::FoldGEPSetCC(User *GEPLHS, Value *RHS,
3958 Instruction::BinaryOps Cond,
3959 Instruction &I) {
3960 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattner81e84172005-01-13 22:25:21 +00003961
3962 if (CastInst *CI = dyn_cast<CastInst>(RHS))
3963 if (isa<PointerType>(CI->getOperand(0)->getType()))
3964 RHS = CI->getOperand(0);
3965
Chris Lattner0798af32005-01-13 20:14:25 +00003966 Value *PtrBase = GEPLHS->getOperand(0);
3967 if (PtrBase == RHS) {
3968 // As an optimization, we don't actually have to compute the actual value of
3969 // OFFSET if this is a seteq or setne comparison, just return whether each
3970 // index is zero or not.
Chris Lattner81e84172005-01-13 22:25:21 +00003971 if (Cond == Instruction::SetEQ || Cond == Instruction::SetNE) {
3972 Instruction *InVal = 0;
Chris Lattnercd517ff2005-01-28 19:32:01 +00003973 gep_type_iterator GTI = gep_type_begin(GEPLHS);
3974 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i, ++GTI) {
Chris Lattner81e84172005-01-13 22:25:21 +00003975 bool EmitIt = true;
3976 if (Constant *C = dyn_cast<Constant>(GEPLHS->getOperand(i))) {
3977 if (isa<UndefValue>(C)) // undef index -> undef.
3978 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
3979 if (C->isNullValue())
3980 EmitIt = false;
Chris Lattnercd517ff2005-01-28 19:32:01 +00003981 else if (TD->getTypeSize(GTI.getIndexedType()) == 0) {
3982 EmitIt = false; // This is indexing into a zero sized array?
Misha Brukmanb1c93172005-04-21 23:48:37 +00003983 } else if (isa<ConstantInt>(C))
Chris Lattner81e84172005-01-13 22:25:21 +00003984 return ReplaceInstUsesWith(I, // No comparison is needed here.
3985 ConstantBool::get(Cond == Instruction::SetNE));
3986 }
3987
3988 if (EmitIt) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00003989 Instruction *Comp =
Chris Lattner81e84172005-01-13 22:25:21 +00003990 new SetCondInst(Cond, GEPLHS->getOperand(i),
3991 Constant::getNullValue(GEPLHS->getOperand(i)->getType()));
3992 if (InVal == 0)
3993 InVal = Comp;
3994 else {
3995 InVal = InsertNewInstBefore(InVal, I);
3996 InsertNewInstBefore(Comp, I);
3997 if (Cond == Instruction::SetNE) // True if any are unequal
3998 InVal = BinaryOperator::createOr(InVal, Comp);
3999 else // True if all are equal
4000 InVal = BinaryOperator::createAnd(InVal, Comp);
4001 }
4002 }
4003 }
4004
4005 if (InVal)
4006 return InVal;
4007 else
4008 ReplaceInstUsesWith(I, // No comparison is needed here, all indexes = 0
4009 ConstantBool::get(Cond == Instruction::SetEQ));
4010 }
Chris Lattner0798af32005-01-13 20:14:25 +00004011
4012 // Only lower this if the setcc is the only user of the GEP or if we expect
4013 // the result to fold to a constant!
4014 if (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) {
4015 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
4016 Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
4017 return new SetCondInst(Cond, Offset,
4018 Constant::getNullValue(Offset->getType()));
4019 }
4020 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
Chris Lattnera21bf8d2005-04-25 20:17:30 +00004021 // If the base pointers are different, but the indices are the same, just
4022 // compare the base pointer.
4023 if (PtrBase != GEPRHS->getOperand(0)) {
4024 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00004025 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattnerbd43b9d2005-04-26 14:40:41 +00004026 GEPRHS->getOperand(0)->getType();
Chris Lattnera21bf8d2005-04-25 20:17:30 +00004027 if (IndicesTheSame)
4028 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4029 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4030 IndicesTheSame = false;
4031 break;
4032 }
4033
4034 // If all indices are the same, just compare the base pointers.
4035 if (IndicesTheSame)
4036 return new SetCondInst(Cond, GEPLHS->getOperand(0),
4037 GEPRHS->getOperand(0));
4038
4039 // Otherwise, the base pointers are different and the indices are
4040 // different, bail out.
Chris Lattner0798af32005-01-13 20:14:25 +00004041 return 0;
Chris Lattnera21bf8d2005-04-25 20:17:30 +00004042 }
Chris Lattner0798af32005-01-13 20:14:25 +00004043
Chris Lattner81e84172005-01-13 22:25:21 +00004044 // If one of the GEPs has all zero indices, recurse.
4045 bool AllZeros = true;
4046 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4047 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
4048 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
4049 AllZeros = false;
4050 break;
4051 }
4052 if (AllZeros)
4053 return FoldGEPSetCC(GEPRHS, GEPLHS->getOperand(0),
4054 SetCondInst::getSwappedCondition(Cond), I);
Chris Lattner4fa89822005-01-14 00:20:05 +00004055
4056 // If the other GEP has all zero indices, recurse.
Chris Lattner81e84172005-01-13 22:25:21 +00004057 AllZeros = true;
4058 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4059 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
4060 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
4061 AllZeros = false;
4062 break;
4063 }
4064 if (AllZeros)
4065 return FoldGEPSetCC(GEPLHS, GEPRHS->getOperand(0), Cond, I);
4066
Chris Lattner4fa89822005-01-14 00:20:05 +00004067 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
4068 // If the GEPs only differ by one index, compare it.
4069 unsigned NumDifferences = 0; // Keep track of # differences.
4070 unsigned DiffOperand = 0; // The operand that differs.
4071 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4072 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004073 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
4074 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattnerfc4429e2005-01-21 23:06:49 +00004075 // Irreconcilable differences.
Chris Lattner4fa89822005-01-14 00:20:05 +00004076 NumDifferences = 2;
4077 break;
4078 } else {
4079 if (NumDifferences++) break;
4080 DiffOperand = i;
4081 }
4082 }
4083
4084 if (NumDifferences == 0) // SAME GEP?
4085 return ReplaceInstUsesWith(I, // No comparison is needed here.
4086 ConstantBool::get(Cond == Instruction::SetEQ));
4087 else if (NumDifferences == 1) {
Chris Lattnerfc4429e2005-01-21 23:06:49 +00004088 Value *LHSV = GEPLHS->getOperand(DiffOperand);
4089 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Chris Lattner247aef82005-07-18 23:07:33 +00004090
4091 // Convert the operands to signed values to make sure to perform a
4092 // signed comparison.
4093 const Type *NewTy = LHSV->getType()->getSignedVersion();
4094 if (LHSV->getType() != NewTy)
Reid Spencer13bc5d72006-12-12 09:18:51 +00004095 LHSV = InsertCastBefore(Instruction::BitCast, LHSV, NewTy, I);
Chris Lattner247aef82005-07-18 23:07:33 +00004096 if (RHSV->getType() != NewTy)
Reid Spencer13bc5d72006-12-12 09:18:51 +00004097 RHSV = InsertCastBefore(Instruction::BitCast, RHSV, NewTy, I);
Chris Lattner247aef82005-07-18 23:07:33 +00004098 return new SetCondInst(Cond, LHSV, RHSV);
Chris Lattner4fa89822005-01-14 00:20:05 +00004099 }
4100 }
4101
Chris Lattner0798af32005-01-13 20:14:25 +00004102 // Only lower this if the setcc is the only user of the GEP or if we expect
4103 // the result to fold to a constant!
4104 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
4105 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
4106 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
4107 Value *L = EmitGEPOffset(GEPLHS, I, *this);
4108 Value *R = EmitGEPOffset(GEPRHS, I, *this);
4109 return new SetCondInst(Cond, L, R);
4110 }
4111 }
4112 return 0;
4113}
4114
4115
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004116Instruction *InstCombiner::visitSetCondInst(SetCondInst &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00004117 bool Changed = SimplifyCommutative(I);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004118 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4119 const Type *Ty = Op0->getType();
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004120
4121 // setcc X, X
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004122 if (Op0 == Op1)
4123 return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
Chris Lattner1fc23f32002-05-09 20:11:54 +00004124
Chris Lattner81a7a232004-10-16 18:11:37 +00004125 if (isa<UndefValue>(Op1)) // X setcc undef -> undef
4126 return ReplaceInstUsesWith(I, UndefValue::get(Type::BoolTy));
4127
Chris Lattner15ff1e12004-11-14 07:33:16 +00004128 // setcc <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
4129 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanb1c93172005-04-21 23:48:37 +00004130 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
4131 isa<ConstantPointerNull>(Op0)) &&
4132 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner15ff1e12004-11-14 07:33:16 +00004133 isa<ConstantPointerNull>(Op1)))
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004134 return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
4135
4136 // setcc's with boolean values can always be turned into bitwise operations
4137 if (Ty == Type::BoolTy) {
Chris Lattner4456da62004-08-11 00:50:51 +00004138 switch (I.getOpcode()) {
4139 default: assert(0 && "Invalid setcc instruction!");
4140 case Instruction::SetEQ: { // seteq bool %A, %B -> ~(A^B)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004141 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004142 InsertNewInstBefore(Xor, I);
Chris Lattner16930792003-11-03 04:25:02 +00004143 return BinaryOperator::createNot(Xor);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004144 }
Chris Lattner4456da62004-08-11 00:50:51 +00004145 case Instruction::SetNE:
4146 return BinaryOperator::createXor(Op0, Op1);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004147
Chris Lattner4456da62004-08-11 00:50:51 +00004148 case Instruction::SetGT:
4149 std::swap(Op0, Op1); // Change setgt -> setlt
4150 // FALL THROUGH
4151 case Instruction::SetLT: { // setlt bool A, B -> ~X & Y
4152 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4153 InsertNewInstBefore(Not, I);
4154 return BinaryOperator::createAnd(Not, Op1);
4155 }
4156 case Instruction::SetGE:
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004157 std::swap(Op0, Op1); // Change setge -> setle
Chris Lattner4456da62004-08-11 00:50:51 +00004158 // FALL THROUGH
4159 case Instruction::SetLE: { // setle bool %A, %B -> ~A | B
4160 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4161 InsertNewInstBefore(Not, I);
4162 return BinaryOperator::createOr(Not, Op1);
4163 }
4164 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004165 }
4166
Chris Lattner2dd01742004-06-09 04:24:29 +00004167 // See if we are doing a comparison between a constant and an instruction that
4168 // can be folded into the comparison.
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004169 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner6862fbd2004-09-29 17:40:11 +00004170 // Check to see if we are comparing against the minimum or maximum value...
Reid Spencer4ae56f32006-12-06 20:39:57 +00004171 if (CI->isMinValue(CI->getType()->isSigned())) {
Chris Lattner6862fbd2004-09-29 17:40:11 +00004172 if (I.getOpcode() == Instruction::SetLT) // A < MIN -> FALSE
Chris Lattner6ab03f62006-09-28 23:35:22 +00004173 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattner6862fbd2004-09-29 17:40:11 +00004174 if (I.getOpcode() == Instruction::SetGE) // A >= MIN -> TRUE
Chris Lattner6ab03f62006-09-28 23:35:22 +00004175 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
Chris Lattner6862fbd2004-09-29 17:40:11 +00004176 if (I.getOpcode() == Instruction::SetLE) // A <= MIN -> A == MIN
4177 return BinaryOperator::createSetEQ(Op0, Op1);
4178 if (I.getOpcode() == Instruction::SetGT) // A > MIN -> A != MIN
4179 return BinaryOperator::createSetNE(Op0, Op1);
4180
Reid Spencer4ae56f32006-12-06 20:39:57 +00004181 } else if (CI->isMaxValue(CI->getType()->isSigned())) {
Chris Lattner6862fbd2004-09-29 17:40:11 +00004182 if (I.getOpcode() == Instruction::SetGT) // A > MAX -> FALSE
Chris Lattner6ab03f62006-09-28 23:35:22 +00004183 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattner6862fbd2004-09-29 17:40:11 +00004184 if (I.getOpcode() == Instruction::SetLE) // A <= MAX -> TRUE
Chris Lattner6ab03f62006-09-28 23:35:22 +00004185 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
Chris Lattner6862fbd2004-09-29 17:40:11 +00004186 if (I.getOpcode() == Instruction::SetGE) // A >= MAX -> A == MAX
4187 return BinaryOperator::createSetEQ(Op0, Op1);
4188 if (I.getOpcode() == Instruction::SetLT) // A < MAX -> A != MAX
4189 return BinaryOperator::createSetNE(Op0, Op1);
4190
4191 // Comparing against a value really close to min or max?
4192 } else if (isMinValuePlusOne(CI)) {
4193 if (I.getOpcode() == Instruction::SetLT) // A < MIN+1 -> A == MIN
4194 return BinaryOperator::createSetEQ(Op0, SubOne(CI));
4195 if (I.getOpcode() == Instruction::SetGE) // A >= MIN-1 -> A != MIN
4196 return BinaryOperator::createSetNE(Op0, SubOne(CI));
4197
4198 } else if (isMaxValueMinusOne(CI)) {
4199 if (I.getOpcode() == Instruction::SetGT) // A > MAX-1 -> A == MAX
4200 return BinaryOperator::createSetEQ(Op0, AddOne(CI));
4201 if (I.getOpcode() == Instruction::SetLE) // A <= MAX-1 -> A != MAX
4202 return BinaryOperator::createSetNE(Op0, AddOne(CI));
4203 }
4204
4205 // If we still have a setle or setge instruction, turn it into the
4206 // appropriate setlt or setgt instruction. Since the border cases have
4207 // already been handled above, this requires little checking.
4208 //
4209 if (I.getOpcode() == Instruction::SetLE)
4210 return BinaryOperator::createSetLT(Op0, AddOne(CI));
4211 if (I.getOpcode() == Instruction::SetGE)
4212 return BinaryOperator::createSetGT(Op0, SubOne(CI));
4213
Chris Lattneree0f2802006-02-12 02:07:56 +00004214
4215 // See if we can fold the comparison based on bits known to be zero or one
4216 // in the input.
4217 uint64_t KnownZero, KnownOne;
4218 if (SimplifyDemandedBits(Op0, Ty->getIntegralTypeMask(),
4219 KnownZero, KnownOne, 0))
4220 return &I;
4221
4222 // Given the known and unknown bits, compute a range that the LHS could be
4223 // in.
4224 if (KnownOne | KnownZero) {
4225 if (Ty->isUnsigned()) { // Unsigned comparison.
4226 uint64_t Min, Max;
4227 uint64_t RHSVal = CI->getZExtValue();
4228 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne,
4229 Min, Max);
4230 switch (I.getOpcode()) { // LE/GE have been folded already.
4231 default: assert(0 && "Unknown setcc opcode!");
4232 case Instruction::SetEQ:
4233 if (Max < RHSVal || Min > RHSVal)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004234 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattneree0f2802006-02-12 02:07:56 +00004235 break;
4236 case Instruction::SetNE:
4237 if (Max < RHSVal || Min > RHSVal)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004238 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
Chris Lattneree0f2802006-02-12 02:07:56 +00004239 break;
4240 case Instruction::SetLT:
Chris Lattner6ab03f62006-09-28 23:35:22 +00004241 if (Max < RHSVal)
4242 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4243 if (Min > RHSVal)
4244 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattneree0f2802006-02-12 02:07:56 +00004245 break;
4246 case Instruction::SetGT:
Chris Lattner6ab03f62006-09-28 23:35:22 +00004247 if (Min > RHSVal)
4248 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4249 if (Max < RHSVal)
4250 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattneree0f2802006-02-12 02:07:56 +00004251 break;
4252 }
4253 } else { // Signed comparison.
4254 int64_t Min, Max;
4255 int64_t RHSVal = CI->getSExtValue();
4256 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne,
4257 Min, Max);
4258 switch (I.getOpcode()) { // LE/GE have been folded already.
4259 default: assert(0 && "Unknown setcc opcode!");
4260 case Instruction::SetEQ:
4261 if (Max < RHSVal || Min > RHSVal)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004262 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattneree0f2802006-02-12 02:07:56 +00004263 break;
4264 case Instruction::SetNE:
4265 if (Max < RHSVal || Min > RHSVal)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004266 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
Chris Lattneree0f2802006-02-12 02:07:56 +00004267 break;
4268 case Instruction::SetLT:
Chris Lattner6ab03f62006-09-28 23:35:22 +00004269 if (Max < RHSVal)
4270 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4271 if (Min > RHSVal)
4272 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattneree0f2802006-02-12 02:07:56 +00004273 break;
4274 case Instruction::SetGT:
Chris Lattner6ab03f62006-09-28 23:35:22 +00004275 if (Min > RHSVal)
4276 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4277 if (Max < RHSVal)
4278 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattneree0f2802006-02-12 02:07:56 +00004279 break;
4280 }
4281 }
4282 }
4283
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004284 // Since the RHS is a constantInt (CI), if the left hand side is an
4285 // instruction, see if that instruction also has constants so that the
4286 // instruction can be folded into the setcc
Chris Lattnere1e10e12004-05-25 06:32:08 +00004287 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004288 switch (LHSI->getOpcode()) {
4289 case Instruction::And:
4290 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
4291 LHSI->getOperand(0)->hasOneUse()) {
Chris Lattner4922a0e2006-09-18 05:27:43 +00004292 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
4293
4294 // If an operand is an AND of a truncating cast, we can widen the
4295 // and/compare to be the input width without changing the value
4296 // produced, eliminating a cast.
4297 if (CastInst *Cast = dyn_cast<CastInst>(LHSI->getOperand(0))) {
4298 // We can do this transformation if either the AND constant does not
4299 // have its sign bit set or if it is an equality comparison.
4300 // Extending a relational comparison when we're checking the sign
4301 // bit would not work.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00004302 if (Cast->hasOneUse() && isa<TruncInst>(Cast) &&
Chris Lattner4922a0e2006-09-18 05:27:43 +00004303 (I.isEquality() ||
4304 (AndCST->getZExtValue() == (uint64_t)AndCST->getSExtValue()) &&
4305 (CI->getZExtValue() == (uint64_t)CI->getSExtValue()))) {
4306 ConstantInt *NewCST;
4307 ConstantInt *NewCI;
4308 if (Cast->getOperand(0)->getType()->isSigned()) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00004309 NewCST = ConstantInt::get(Cast->getOperand(0)->getType(),
Chris Lattner4922a0e2006-09-18 05:27:43 +00004310 AndCST->getZExtValue());
Reid Spencere0fc4df2006-10-20 07:07:24 +00004311 NewCI = ConstantInt::get(Cast->getOperand(0)->getType(),
Chris Lattner4922a0e2006-09-18 05:27:43 +00004312 CI->getZExtValue());
4313 } else {
Reid Spencere0fc4df2006-10-20 07:07:24 +00004314 NewCST = ConstantInt::get(Cast->getOperand(0)->getType(),
Chris Lattner4922a0e2006-09-18 05:27:43 +00004315 AndCST->getZExtValue());
Reid Spencere0fc4df2006-10-20 07:07:24 +00004316 NewCI = ConstantInt::get(Cast->getOperand(0)->getType(),
Chris Lattner4922a0e2006-09-18 05:27:43 +00004317 CI->getZExtValue());
4318 }
4319 Instruction *NewAnd =
4320 BinaryOperator::createAnd(Cast->getOperand(0), NewCST,
4321 LHSI->getName());
4322 InsertNewInstBefore(NewAnd, I);
4323 return new SetCondInst(I.getOpcode(), NewAnd, NewCI);
4324 }
4325 }
4326
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004327 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
4328 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
4329 // happens a LOT in code produced by the C front-end, for bitfield
4330 // access.
4331 ShiftInst *Shift = dyn_cast<ShiftInst>(LHSI->getOperand(0));
Chris Lattneree0f2802006-02-12 02:07:56 +00004332
4333 // Check to see if there is a noop-cast between the shift and the and.
4334 if (!Shift) {
4335 if (CastInst *CI = dyn_cast<CastInst>(LHSI->getOperand(0)))
Reid Spencer2a499b02006-12-13 17:19:09 +00004336 if (CI->getOpcode() == Instruction::BitCast &&
4337 CI->getType()->isIntegral())
Chris Lattneree0f2802006-02-12 02:07:56 +00004338 Shift = dyn_cast<ShiftInst>(CI->getOperand(0));
4339 }
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004340
Reid Spencere0fc4df2006-10-20 07:07:24 +00004341 ConstantInt *ShAmt;
4342 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
Chris Lattneree0f2802006-02-12 02:07:56 +00004343 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
4344 const Type *AndTy = AndCST->getType(); // Type of the and.
Misha Brukmanb1c93172005-04-21 23:48:37 +00004345
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004346 // We can fold this as long as we can't shift unknown bits
4347 // into the mask. This can only happen with signed shift
4348 // rights, as they sign-extend.
4349 if (ShAmt) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004350 bool CanFold = Shift->isLogicalShift();
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004351 if (!CanFold) {
4352 // To test for the bad case of the signed shr, see if any
4353 // of the bits shifted in could be tested after the mask.
Reid Spencere0fc4df2006-10-20 07:07:24 +00004354 int ShAmtVal = Ty->getPrimitiveSizeInBits()-ShAmt->getZExtValue();
Chris Lattnerc53cb9d2005-06-17 01:29:28 +00004355 if (ShAmtVal < 0) ShAmtVal = 0; // Out of range shift.
4356
Reid Spencere0fc4df2006-10-20 07:07:24 +00004357 Constant *OShAmt = ConstantInt::get(Type::UByteTy, ShAmtVal);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004358 Constant *ShVal =
Chris Lattneree0f2802006-02-12 02:07:56 +00004359 ConstantExpr::getShl(ConstantInt::getAllOnesValue(AndTy),
4360 OShAmt);
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004361 if (ConstantExpr::getAnd(ShVal, AndCST)->isNullValue())
4362 CanFold = true;
4363 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004364
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004365 if (CanFold) {
Chris Lattner6afc02f2004-09-28 17:54:07 +00004366 Constant *NewCst;
4367 if (Shift->getOpcode() == Instruction::Shl)
Reid Spencerfdff9382006-11-08 06:47:33 +00004368 NewCst = ConstantExpr::getLShr(CI, ShAmt);
Chris Lattner6afc02f2004-09-28 17:54:07 +00004369 else
4370 NewCst = ConstantExpr::getShl(CI, ShAmt);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004371
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004372 // Check to see if we are shifting out any of the bits being
4373 // compared.
4374 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != CI){
4375 // If we shifted bits out, the fold is not going to work out.
4376 // As a special case, check to see if this means that the
4377 // result is always true or false now.
4378 if (I.getOpcode() == Instruction::SetEQ)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004379 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004380 if (I.getOpcode() == Instruction::SetNE)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004381 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004382 } else {
4383 I.setOperand(1, NewCst);
Chris Lattner6afc02f2004-09-28 17:54:07 +00004384 Constant *NewAndCST;
4385 if (Shift->getOpcode() == Instruction::Shl)
Reid Spencerfdff9382006-11-08 06:47:33 +00004386 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
Chris Lattner6afc02f2004-09-28 17:54:07 +00004387 else
4388 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
4389 LHSI->setOperand(1, NewAndCST);
Chris Lattneree0f2802006-02-12 02:07:56 +00004390 if (AndTy == Ty)
4391 LHSI->setOperand(0, Shift->getOperand(0));
4392 else {
Reid Spencer13bc5d72006-12-12 09:18:51 +00004393 Value *NewCast = InsertCastBefore(Instruction::BitCast,
4394 Shift->getOperand(0), AndTy,
Chris Lattneree0f2802006-02-12 02:07:56 +00004395 *Shift);
4396 LHSI->setOperand(0, NewCast);
4397 }
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004398 WorkList.push_back(Shift); // Shift is dead.
4399 AddUsesToWorkList(I);
4400 return &I;
Chris Lattner1638de42004-07-21 19:50:44 +00004401 }
4402 }
Chris Lattner35167c32004-06-09 07:59:58 +00004403 }
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004404
4405 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
4406 // preferable because it allows the C<<Y expression to be hoisted out
4407 // of a loop if Y is invariant and X is not.
4408 if (Shift && Shift->hasOneUse() && CI->isNullValue() &&
Chris Lattnerde077922006-09-18 18:27:05 +00004409 I.isEquality() && !Shift->isArithmeticShift() &&
4410 isa<Instruction>(Shift->getOperand(0))) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004411 // Compute C << Y.
4412 Value *NS;
Reid Spencerfdff9382006-11-08 06:47:33 +00004413 if (Shift->getOpcode() == Instruction::LShr) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004414 NS = new ShiftInst(Instruction::Shl, AndCST, Shift->getOperand(1),
4415 "tmp");
4416 } else {
Reid Spencer2a499b02006-12-13 17:19:09 +00004417 // Insert a logical shift.
4418 NS = new ShiftInst(Instruction::LShr, AndCST,
Chris Lattner4922a0e2006-09-18 05:27:43 +00004419 Shift->getOperand(1), "tmp");
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004420 }
4421 InsertNewInstBefore(cast<Instruction>(NS), I);
4422
4423 // If C's sign doesn't agree with the and, insert a cast now.
4424 if (NS->getType() != LHSI->getType())
Reid Spencer13bc5d72006-12-12 09:18:51 +00004425 NS = InsertCastBefore(Instruction::BitCast, NS, LHSI->getType(),
4426 I);
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004427
4428 Value *ShiftOp = Shift->getOperand(0);
4429 if (ShiftOp->getType() != LHSI->getType())
Reid Spencer13bc5d72006-12-12 09:18:51 +00004430 ShiftOp = InsertCastBefore(Instruction::BitCast, ShiftOp,
4431 LHSI->getType(), I);
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004432
4433 // Compute X & (C << Y).
4434 Instruction *NewAnd =
4435 BinaryOperator::createAnd(ShiftOp, NS, LHSI->getName());
4436 InsertNewInstBefore(NewAnd, I);
4437
4438 I.setOperand(0, NewAnd);
4439 return &I;
4440 }
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004441 }
4442 break;
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004443
Chris Lattner272d5ca2004-09-28 18:22:15 +00004444 case Instruction::Shl: // (setcc (shl X, ShAmt), CI)
Reid Spencere0fc4df2006-10-20 07:07:24 +00004445 if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004446 if (I.isEquality()) {
Chris Lattner19b57f52005-06-15 20:53:31 +00004447 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
4448
4449 // Check that the shift amount is in range. If not, don't perform
4450 // undefined shifts. When the shift is visited it will be
4451 // simplified.
Reid Spencere0fc4df2006-10-20 07:07:24 +00004452 if (ShAmt->getZExtValue() >= TypeBits)
Chris Lattner19b57f52005-06-15 20:53:31 +00004453 break;
4454
Chris Lattner272d5ca2004-09-28 18:22:15 +00004455 // If we are comparing against bits always shifted out, the
4456 // comparison cannot succeed.
Misha Brukmanb1c93172005-04-21 23:48:37 +00004457 Constant *Comp =
Reid Spencerfdff9382006-11-08 06:47:33 +00004458 ConstantExpr::getShl(ConstantExpr::getLShr(CI, ShAmt), ShAmt);
Chris Lattner272d5ca2004-09-28 18:22:15 +00004459 if (Comp != CI) {// Comparing against a bit that we know is zero.
4460 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
4461 Constant *Cst = ConstantBool::get(IsSetNE);
4462 return ReplaceInstUsesWith(I, Cst);
4463 }
4464
4465 if (LHSI->hasOneUse()) {
4466 // Otherwise strength reduce the shift into an and.
Reid Spencere0fc4df2006-10-20 07:07:24 +00004467 unsigned ShAmtVal = (unsigned)ShAmt->getZExtValue();
Chris Lattner272d5ca2004-09-28 18:22:15 +00004468 uint64_t Val = (1ULL << (TypeBits-ShAmtVal))-1;
4469
4470 Constant *Mask;
4471 if (CI->getType()->isUnsigned()) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00004472 Mask = ConstantInt::get(CI->getType(), Val);
Chris Lattner272d5ca2004-09-28 18:22:15 +00004473 } else if (ShAmtVal != 0) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00004474 Mask = ConstantInt::get(CI->getType(), Val);
Chris Lattner272d5ca2004-09-28 18:22:15 +00004475 } else {
4476 Mask = ConstantInt::getAllOnesValue(CI->getType());
4477 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004478
Chris Lattner272d5ca2004-09-28 18:22:15 +00004479 Instruction *AndI =
4480 BinaryOperator::createAnd(LHSI->getOperand(0),
4481 Mask, LHSI->getName()+".mask");
4482 Value *And = InsertNewInstBefore(AndI, I);
4483 return new SetCondInst(I.getOpcode(), And,
Reid Spencerfdff9382006-11-08 06:47:33 +00004484 ConstantExpr::getLShr(CI, ShAmt));
Chris Lattner272d5ca2004-09-28 18:22:15 +00004485 }
4486 }
Chris Lattner272d5ca2004-09-28 18:22:15 +00004487 }
4488 break;
4489
Reid Spencerfdff9382006-11-08 06:47:33 +00004490 case Instruction::LShr: // (setcc (shr X, ShAmt), CI)
4491 case Instruction::AShr:
Reid Spencere0fc4df2006-10-20 07:07:24 +00004492 if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004493 if (I.isEquality()) {
Chris Lattner19b57f52005-06-15 20:53:31 +00004494 // Check that the shift amount is in range. If not, don't perform
4495 // undefined shifts. When the shift is visited it will be
4496 // simplified.
Chris Lattner104002b2005-06-16 01:52:07 +00004497 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
Reid Spencere0fc4df2006-10-20 07:07:24 +00004498 if (ShAmt->getZExtValue() >= TypeBits)
Chris Lattner19b57f52005-06-15 20:53:31 +00004499 break;
4500
Chris Lattner1023b872004-09-27 16:18:50 +00004501 // If we are comparing against bits always shifted out, the
4502 // comparison cannot succeed.
Reid Spencerfdff9382006-11-08 06:47:33 +00004503 Constant *Comp;
4504 if (CI->getType()->isUnsigned())
4505 Comp = ConstantExpr::getLShr(ConstantExpr::getShl(CI, ShAmt),
4506 ShAmt);
4507 else
4508 Comp = ConstantExpr::getAShr(ConstantExpr::getShl(CI, ShAmt),
4509 ShAmt);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004510
Chris Lattner1023b872004-09-27 16:18:50 +00004511 if (Comp != CI) {// Comparing against a bit that we know is zero.
4512 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
4513 Constant *Cst = ConstantBool::get(IsSetNE);
4514 return ReplaceInstUsesWith(I, Cst);
4515 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004516
Chris Lattner1023b872004-09-27 16:18:50 +00004517 if (LHSI->hasOneUse() || CI->isNullValue()) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00004518 unsigned ShAmtVal = (unsigned)ShAmt->getZExtValue();
Chris Lattner272d5ca2004-09-28 18:22:15 +00004519
Chris Lattner1023b872004-09-27 16:18:50 +00004520 // Otherwise strength reduce the shift into an and.
4521 uint64_t Val = ~0ULL; // All ones.
4522 Val <<= ShAmtVal; // Shift over to the right spot.
4523
4524 Constant *Mask;
4525 if (CI->getType()->isUnsigned()) {
Chris Lattner2f1457f2005-04-24 17:46:05 +00004526 Val &= ~0ULL >> (64-TypeBits);
Reid Spencere0fc4df2006-10-20 07:07:24 +00004527 Mask = ConstantInt::get(CI->getType(), Val);
Chris Lattner1023b872004-09-27 16:18:50 +00004528 } else {
Reid Spencere0fc4df2006-10-20 07:07:24 +00004529 Mask = ConstantInt::get(CI->getType(), Val);
Chris Lattner1023b872004-09-27 16:18:50 +00004530 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004531
Chris Lattner1023b872004-09-27 16:18:50 +00004532 Instruction *AndI =
4533 BinaryOperator::createAnd(LHSI->getOperand(0),
4534 Mask, LHSI->getName()+".mask");
4535 Value *And = InsertNewInstBefore(AndI, I);
4536 return new SetCondInst(I.getOpcode(), And,
4537 ConstantExpr::getShl(CI, ShAmt));
4538 }
Chris Lattner1023b872004-09-27 16:18:50 +00004539 }
4540 }
4541 break;
Chris Lattner7e794272004-09-24 15:21:34 +00004542
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004543 case Instruction::SDiv:
4544 case Instruction::UDiv:
4545 // Fold: setcc ([us]div X, C1), C2 -> range test
4546 // Fold this div into the comparison, producing a range check.
4547 // Determine, based on the divide type, what the range is being
4548 // checked. If there is an overflow on the low or high side, remember
4549 // it, otherwise compute the range [low, hi) bounding the new value.
4550 // See: InsertRangeTest above for the kinds of replacements possible.
Chris Lattner6862fbd2004-09-29 17:40:11 +00004551 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004552 // FIXME: If the operand types don't match the type of the divide
4553 // then don't attempt this transform. The code below doesn't have the
4554 // logic to deal with a signed divide and an unsigned compare (and
4555 // vice versa). This is because (x /s C1) <s C2 produces different
4556 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
4557 // (x /u C1) <u C2. Simply casting the operands and result won't
4558 // work. :( The if statement below tests that condition and bails
4559 // if it finds it.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00004560 const Type *DivRHSTy = DivRHS->getType();
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004561 unsigned DivOpCode = LHSI->getOpcode();
4562 if (I.isEquality() &&
4563 ((DivOpCode == Instruction::SDiv && DivRHSTy->isUnsigned()) ||
4564 (DivOpCode == Instruction::UDiv && DivRHSTy->isSigned())))
4565 break;
4566
4567 // Initialize the variables that will indicate the nature of the
4568 // range check.
4569 bool LoOverflow = false, HiOverflow = false;
Chris Lattner6862fbd2004-09-29 17:40:11 +00004570 ConstantInt *LoBound = 0, *HiBound = 0;
4571
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004572 // Compute Prod = CI * DivRHS. We are essentially solving an equation
4573 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
4574 // C2 (CI). By solving for X we can turn this into a range check
4575 // instead of computing a divide.
4576 ConstantInt *Prod =
4577 cast<ConstantInt>(ConstantExpr::getMul(CI, DivRHS));
Chris Lattner6862fbd2004-09-29 17:40:11 +00004578
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004579 // Determine if the product overflows by seeing if the product is
4580 // not equal to the divide. Make sure we do the same kind of divide
4581 // as in the LHS instruction that we're folding.
4582 bool ProdOV = !DivRHS->isNullValue() &&
4583 (DivOpCode == Instruction::SDiv ?
4584 ConstantExpr::getSDiv(Prod, DivRHS) :
4585 ConstantExpr::getUDiv(Prod, DivRHS)) != CI;
4586
4587 // Get the SetCC opcode
Chris Lattnera92af962004-10-11 19:40:04 +00004588 Instruction::BinaryOps Opcode = I.getOpcode();
4589
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004590 if (DivRHS->isNullValue()) {
4591 // Don't hack on divide by zeros!
4592 } else if (DivOpCode == Instruction::UDiv) { // udiv
Chris Lattner6862fbd2004-09-29 17:40:11 +00004593 LoBound = Prod;
4594 LoOverflow = ProdOV;
4595 HiOverflow = ProdOV || AddWithOverflow(HiBound, LoBound, DivRHS);
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004596 } else if (isPositive(DivRHS)) { // Divisor is > 0.
Chris Lattner6862fbd2004-09-29 17:40:11 +00004597 if (CI->isNullValue()) { // (X / pos) op 0
4598 // Can't overflow.
4599 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
4600 HiBound = DivRHS;
4601 } else if (isPositive(CI)) { // (X / pos) op pos
4602 LoBound = Prod;
4603 LoOverflow = ProdOV;
4604 HiOverflow = ProdOV || AddWithOverflow(HiBound, Prod, DivRHS);
4605 } else { // (X / pos) op neg
4606 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
4607 LoOverflow = AddWithOverflow(LoBound, Prod,
4608 cast<ConstantInt>(DivRHSH));
4609 HiBound = Prod;
4610 HiOverflow = ProdOV;
4611 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004612 } else { // Divisor is < 0.
Chris Lattner6862fbd2004-09-29 17:40:11 +00004613 if (CI->isNullValue()) { // (X / neg) op 0
4614 LoBound = AddOne(DivRHS);
4615 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner73bcba52005-06-17 02:05:55 +00004616 if (HiBound == DivRHS)
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004617 LoBound = 0; // - INTMIN = INTMIN
Chris Lattner6862fbd2004-09-29 17:40:11 +00004618 } else if (isPositive(CI)) { // (X / neg) op pos
4619 HiOverflow = LoOverflow = ProdOV;
4620 if (!LoOverflow)
4621 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS));
4622 HiBound = AddOne(Prod);
4623 } else { // (X / neg) op neg
4624 LoBound = Prod;
4625 LoOverflow = HiOverflow = ProdOV;
4626 HiBound = cast<ConstantInt>(ConstantExpr::getSub(Prod, DivRHS));
4627 }
Chris Lattner0b41e862004-10-08 19:15:44 +00004628
Chris Lattnera92af962004-10-11 19:40:04 +00004629 // Dividing by a negate swaps the condition.
4630 Opcode = SetCondInst::getSwappedCondition(Opcode);
Chris Lattner6862fbd2004-09-29 17:40:11 +00004631 }
4632
4633 if (LoBound) {
4634 Value *X = LHSI->getOperand(0);
Chris Lattnera92af962004-10-11 19:40:04 +00004635 switch (Opcode) {
Chris Lattner6862fbd2004-09-29 17:40:11 +00004636 default: assert(0 && "Unhandled setcc opcode!");
4637 case Instruction::SetEQ:
4638 if (LoOverflow && HiOverflow)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004639 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattner6862fbd2004-09-29 17:40:11 +00004640 else if (HiOverflow)
4641 return new SetCondInst(Instruction::SetGE, X, LoBound);
4642 else if (LoOverflow)
4643 return new SetCondInst(Instruction::SetLT, X, HiBound);
4644 else
4645 return InsertRangeTest(X, LoBound, HiBound, true, I);
4646 case Instruction::SetNE:
4647 if (LoOverflow && HiOverflow)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004648 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
Chris Lattner6862fbd2004-09-29 17:40:11 +00004649 else if (HiOverflow)
4650 return new SetCondInst(Instruction::SetLT, X, LoBound);
4651 else if (LoOverflow)
4652 return new SetCondInst(Instruction::SetGE, X, HiBound);
4653 else
4654 return InsertRangeTest(X, LoBound, HiBound, false, I);
4655 case Instruction::SetLT:
4656 if (LoOverflow)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004657 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattner6862fbd2004-09-29 17:40:11 +00004658 return new SetCondInst(Instruction::SetLT, X, LoBound);
4659 case Instruction::SetGT:
4660 if (HiOverflow)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004661 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattner6862fbd2004-09-29 17:40:11 +00004662 return new SetCondInst(Instruction::SetGE, X, HiBound);
4663 }
4664 }
4665 }
4666 break;
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004667 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004668
Chris Lattnera7942b72006-11-29 05:02:16 +00004669 // Simplify seteq and setne instructions with integer constant RHS.
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004670 if (I.isEquality()) {
Chris Lattnerd492a0b2003-07-23 17:02:11 +00004671 bool isSetNE = I.getOpcode() == Instruction::SetNE;
4672
Reid Spencere0fc4df2006-10-20 07:07:24 +00004673 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
4674 // the second operand is a constant, simplify a bit.
Chris Lattnerc992add2003-08-13 05:33:12 +00004675 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
4676 switch (BO->getOpcode()) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00004677 case Instruction::SRem:
4678 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
4679 if (CI->isNullValue() && isa<ConstantInt>(BO->getOperand(1)) &&
4680 BO->hasOneUse()) {
4681 int64_t V = cast<ConstantInt>(BO->getOperand(1))->getSExtValue();
4682 if (V > 1 && isPowerOf2_64(V)) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00004683 Value *NewRem = InsertNewInstBefore(BinaryOperator::createURem(
4684 BO->getOperand(0), BO->getOperand(1), BO->getName()), I);
Chris Lattner23b47b62004-07-06 07:38:18 +00004685 return BinaryOperator::create(I.getOpcode(), NewRem,
Reid Spencer7eb55b32006-11-02 01:53:59 +00004686 Constant::getNullValue(BO->getType()));
Chris Lattner23b47b62004-07-06 07:38:18 +00004687 }
Chris Lattner22d00a82005-08-02 19:16:58 +00004688 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004689 break;
Chris Lattnerc992add2003-08-13 05:33:12 +00004690 case Instruction::Add:
Chris Lattner6e079362004-06-27 22:51:36 +00004691 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
4692 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerb121ae12004-09-21 21:35:23 +00004693 if (BO->hasOneUse())
4694 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
4695 ConstantExpr::getSub(CI, BOp1C));
Chris Lattner6e079362004-06-27 22:51:36 +00004696 } else if (CI->isNullValue()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00004697 // Replace ((add A, B) != 0) with (A != -B) if A or B is
4698 // efficiently invertible, or if the add has just this one use.
4699 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004700
Chris Lattnerc992add2003-08-13 05:33:12 +00004701 if (Value *NegVal = dyn_castNegVal(BOp1))
4702 return new SetCondInst(I.getOpcode(), BOp0, NegVal);
4703 else if (Value *NegVal = dyn_castNegVal(BOp0))
4704 return new SetCondInst(I.getOpcode(), NegVal, BOp1);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00004705 else if (BO->hasOneUse()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00004706 Instruction *Neg = BinaryOperator::createNeg(BOp1, BO->getName());
4707 BO->setName("");
4708 InsertNewInstBefore(Neg, I);
4709 return new SetCondInst(I.getOpcode(), BOp0, Neg);
4710 }
4711 }
4712 break;
4713 case Instruction::Xor:
4714 // For the xor case, we can xor two constants together, eliminating
4715 // the explicit xor.
4716 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
4717 return BinaryOperator::create(I.getOpcode(), BO->getOperand(0),
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004718 ConstantExpr::getXor(CI, BOC));
Chris Lattnerc992add2003-08-13 05:33:12 +00004719
4720 // FALLTHROUGH
4721 case Instruction::Sub:
4722 // Replace (([sub|xor] A, B) != 0) with (A != B)
4723 if (CI->isNullValue())
4724 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
4725 BO->getOperand(1));
4726 break;
4727
4728 case Instruction::Or:
4729 // If bits are being or'd in that are not present in the constant we
4730 // are comparing against, then the comparison could never succeed!
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00004731 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Chris Lattnerc8e7e292004-06-10 02:12:35 +00004732 Constant *NotCI = ConstantExpr::getNot(CI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004733 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Chris Lattnerd492a0b2003-07-23 17:02:11 +00004734 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00004735 }
Chris Lattnerc992add2003-08-13 05:33:12 +00004736 break;
4737
4738 case Instruction::And:
4739 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerd492a0b2003-07-23 17:02:11 +00004740 // If bits are being compared against that are and'd out, then the
4741 // comparison can never succeed!
Chris Lattnerc8e7e292004-06-10 02:12:35 +00004742 if (!ConstantExpr::getAnd(CI,
4743 ConstantExpr::getNot(BOC))->isNullValue())
Chris Lattnerd492a0b2003-07-23 17:02:11 +00004744 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattnerc992add2003-08-13 05:33:12 +00004745
Chris Lattner35167c32004-06-09 07:59:58 +00004746 // If we have ((X & C) == C), turn it into ((X & C) != 0).
Chris Lattneree59d4b2004-06-10 02:33:20 +00004747 if (CI == BOC && isOneBitSet(CI))
Chris Lattner35167c32004-06-09 07:59:58 +00004748 return new SetCondInst(isSetNE ? Instruction::SetEQ :
4749 Instruction::SetNE, Op0,
4750 Constant::getNullValue(CI->getType()));
Chris Lattner35167c32004-06-09 07:59:58 +00004751
Chris Lattnerc992add2003-08-13 05:33:12 +00004752 // Replace (and X, (1 << size(X)-1) != 0) with x < 0, converting X
4753 // to be a signed value as appropriate.
4754 if (isSignBit(BOC)) {
4755 Value *X = BO->getOperand(0);
4756 // If 'X' is not signed, insert a cast now...
4757 if (!BOC->getType()->isSigned()) {
Chris Lattner97bfcea2004-06-17 18:16:02 +00004758 const Type *DestTy = BOC->getType()->getSignedVersion();
Reid Spencer13bc5d72006-12-12 09:18:51 +00004759 X = InsertCastBefore(Instruction::BitCast, X, DestTy, I);
Chris Lattnerc992add2003-08-13 05:33:12 +00004760 }
4761 return new SetCondInst(isSetNE ? Instruction::SetLT :
4762 Instruction::SetGE, X,
4763 Constant::getNullValue(X->getType()));
4764 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004765
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004766 // ((X & ~7) == 0) --> X < 8
Chris Lattner8fc5af42004-09-23 21:46:38 +00004767 if (CI->isNullValue() && isHighOnes(BOC)) {
4768 Value *X = BO->getOperand(0);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004769 Constant *NegX = ConstantExpr::getNeg(BOC);
Chris Lattner8fc5af42004-09-23 21:46:38 +00004770
4771 // If 'X' is signed, insert a cast now.
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004772 if (NegX->getType()->isSigned()) {
4773 const Type *DestTy = NegX->getType()->getUnsignedVersion();
Reid Spencer13bc5d72006-12-12 09:18:51 +00004774 X = InsertCastBefore(Instruction::BitCast, X, DestTy, I);
4775 NegX = ConstantExpr::getBitCast(NegX, DestTy);
Chris Lattner8fc5af42004-09-23 21:46:38 +00004776 }
4777
4778 return new SetCondInst(isSetNE ? Instruction::SetGE :
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004779 Instruction::SetLT, X, NegX);
Chris Lattner8fc5af42004-09-23 21:46:38 +00004780 }
4781
Chris Lattnerd492a0b2003-07-23 17:02:11 +00004782 }
Chris Lattnerc992add2003-08-13 05:33:12 +00004783 default: break;
4784 }
Chris Lattnera7942b72006-11-29 05:02:16 +00004785 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Op0)) {
4786 // Handle set{eq|ne} <intrinsic>, intcst.
4787 switch (II->getIntrinsicID()) {
4788 default: break;
4789 case Intrinsic::bswap_i16: // seteq (bswap(x)), c -> seteq(x,bswap(c))
4790 WorkList.push_back(II); // Dead?
4791 I.setOperand(0, II->getOperand(1));
4792 I.setOperand(1, ConstantInt::get(Type::UShortTy,
4793 ByteSwap_16(CI->getZExtValue())));
4794 return &I;
4795 case Intrinsic::bswap_i32: // seteq (bswap(x)), c -> seteq(x,bswap(c))
4796 WorkList.push_back(II); // Dead?
4797 I.setOperand(0, II->getOperand(1));
4798 I.setOperand(1, ConstantInt::get(Type::UIntTy,
4799 ByteSwap_32(CI->getZExtValue())));
4800 return &I;
4801 case Intrinsic::bswap_i64: // seteq (bswap(x)), c -> seteq(x,bswap(c))
4802 WorkList.push_back(II); // Dead?
4803 I.setOperand(0, II->getOperand(1));
4804 I.setOperand(1, ConstantInt::get(Type::ULongTy,
4805 ByteSwap_64(CI->getZExtValue())));
4806 return &I;
4807 }
Chris Lattnerc992add2003-08-13 05:33:12 +00004808 }
Chris Lattner2b55ea32004-02-23 07:16:20 +00004809 } else { // Not a SetEQ/SetNE
Misha Brukmanb1c93172005-04-21 23:48:37 +00004810 // If the LHS is a cast from an integral value of the same size,
Chris Lattner2b55ea32004-02-23 07:16:20 +00004811 if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
4812 Value *CastOp = Cast->getOperand(0);
4813 const Type *SrcTy = CastOp->getType();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004814 unsigned SrcTySize = SrcTy->getPrimitiveSizeInBits();
Chris Lattner2b55ea32004-02-23 07:16:20 +00004815 if (SrcTy != Cast->getType() && SrcTy->isInteger() &&
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004816 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00004817 assert((SrcTy->isSigned() ^ Cast->getType()->isSigned()) &&
Chris Lattner2b55ea32004-02-23 07:16:20 +00004818 "Source and destination signednesses should differ!");
4819 if (Cast->getType()->isSigned()) {
4820 // If this is a signed comparison, check for comparisons in the
4821 // vicinity of zero.
4822 if (I.getOpcode() == Instruction::SetLT && CI->isNullValue())
4823 // X < 0 => x > 127
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004824 return BinaryOperator::createSetGT(CastOp,
Reid Spencere0fc4df2006-10-20 07:07:24 +00004825 ConstantInt::get(SrcTy, (1ULL << (SrcTySize-1))-1));
Chris Lattner2b55ea32004-02-23 07:16:20 +00004826 else if (I.getOpcode() == Instruction::SetGT &&
Reid Spencere0fc4df2006-10-20 07:07:24 +00004827 cast<ConstantInt>(CI)->getSExtValue() == -1)
Chris Lattner2b55ea32004-02-23 07:16:20 +00004828 // X > -1 => x < 128
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004829 return BinaryOperator::createSetLT(CastOp,
Reid Spencere0fc4df2006-10-20 07:07:24 +00004830 ConstantInt::get(SrcTy, 1ULL << (SrcTySize-1)));
Chris Lattner2b55ea32004-02-23 07:16:20 +00004831 } else {
Reid Spencere0fc4df2006-10-20 07:07:24 +00004832 ConstantInt *CUI = cast<ConstantInt>(CI);
Chris Lattner2b55ea32004-02-23 07:16:20 +00004833 if (I.getOpcode() == Instruction::SetLT &&
Reid Spencere0fc4df2006-10-20 07:07:24 +00004834 CUI->getZExtValue() == 1ULL << (SrcTySize-1))
Chris Lattner2b55ea32004-02-23 07:16:20 +00004835 // X < 128 => X > -1
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004836 return BinaryOperator::createSetGT(CastOp,
Reid Spencere0fc4df2006-10-20 07:07:24 +00004837 ConstantInt::get(SrcTy, -1));
Chris Lattner2b55ea32004-02-23 07:16:20 +00004838 else if (I.getOpcode() == Instruction::SetGT &&
Reid Spencere0fc4df2006-10-20 07:07:24 +00004839 CUI->getZExtValue() == (1ULL << (SrcTySize-1))-1)
Chris Lattner2b55ea32004-02-23 07:16:20 +00004840 // X > 127 => X < 0
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004841 return BinaryOperator::createSetLT(CastOp,
4842 Constant::getNullValue(SrcTy));
Chris Lattner2b55ea32004-02-23 07:16:20 +00004843 }
4844 }
4845 }
Chris Lattnere967b342003-06-04 05:10:11 +00004846 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004847 }
4848
Chris Lattner77c32c32005-04-23 15:31:55 +00004849 // Handle setcc with constant RHS's that can be integer, FP or pointer.
4850 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
4851 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4852 switch (LHSI->getOpcode()) {
Chris Lattnera816eee2005-05-01 04:42:15 +00004853 case Instruction::GetElementPtr:
4854 if (RHSC->isNullValue()) {
4855 // Transform setcc GEP P, int 0, int 0, int 0, null -> setcc P, null
4856 bool isAllZeros = true;
4857 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
4858 if (!isa<Constant>(LHSI->getOperand(i)) ||
4859 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
4860 isAllZeros = false;
4861 break;
4862 }
4863 if (isAllZeros)
4864 return new SetCondInst(I.getOpcode(), LHSI->getOperand(0),
4865 Constant::getNullValue(LHSI->getOperand(0)->getType()));
4866 }
4867 break;
4868
Chris Lattner77c32c32005-04-23 15:31:55 +00004869 case Instruction::PHI:
4870 if (Instruction *NV = FoldOpIntoPhi(I))
4871 return NV;
4872 break;
4873 case Instruction::Select:
4874 // If either operand of the select is a constant, we can fold the
4875 // comparison into the select arms, which will cause one to be
4876 // constant folded and the select turned into a bitwise or.
4877 Value *Op1 = 0, *Op2 = 0;
4878 if (LHSI->hasOneUse()) {
4879 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
4880 // Fold the known value into the constant operand.
4881 Op1 = ConstantExpr::get(I.getOpcode(), C, RHSC);
4882 // Insert a new SetCC of the other select operand.
4883 Op2 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
4884 LHSI->getOperand(2), RHSC,
4885 I.getName()), I);
4886 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
4887 // Fold the known value into the constant operand.
4888 Op2 = ConstantExpr::get(I.getOpcode(), C, RHSC);
4889 // Insert a new SetCC of the other select operand.
4890 Op1 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
4891 LHSI->getOperand(1), RHSC,
4892 I.getName()), I);
4893 }
4894 }
Jeff Cohen82639852005-04-23 21:38:35 +00004895
Chris Lattner77c32c32005-04-23 15:31:55 +00004896 if (Op1)
4897 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
4898 break;
4899 }
4900 }
4901
Chris Lattner0798af32005-01-13 20:14:25 +00004902 // If we can optimize a 'setcc GEP, P' or 'setcc P, GEP', do so now.
4903 if (User *GEP = dyn_castGetElementPtr(Op0))
4904 if (Instruction *NI = FoldGEPSetCC(GEP, Op1, I.getOpcode(), I))
4905 return NI;
4906 if (User *GEP = dyn_castGetElementPtr(Op1))
4907 if (Instruction *NI = FoldGEPSetCC(GEP, Op0,
4908 SetCondInst::getSwappedCondition(I.getOpcode()), I))
4909 return NI;
4910
Chris Lattner16930792003-11-03 04:25:02 +00004911 // Test to see if the operands of the setcc are casted versions of other
4912 // values. If the cast can be stripped off both arguments, we do so now.
Chris Lattner6444c372003-11-03 05:17:03 +00004913 if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
4914 Value *CastOp0 = CI->getOperand(0);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00004915 if (CI->isLosslessCast() && I.isEquality() &&
4916 (isa<Constant>(Op1) || isa<CastInst>(Op1))) {
Chris Lattner16930792003-11-03 04:25:02 +00004917 // We keep moving the cast from the left operand over to the right
4918 // operand, where it can often be eliminated completely.
Chris Lattner6444c372003-11-03 05:17:03 +00004919 Op0 = CastOp0;
Misha Brukmanb1c93172005-04-21 23:48:37 +00004920
Chris Lattner16930792003-11-03 04:25:02 +00004921 // If operand #1 is a cast instruction, see if we can eliminate it as
4922 // well.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00004923 if (CastInst *CI2 = dyn_cast<CastInst>(Op1)) {
4924 Value *CI2Op0 = CI2->getOperand(0);
4925 if (CI2Op0->getType()->canLosslesslyBitCastTo(Op0->getType()))
4926 Op1 = CI2Op0;
4927 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004928
Chris Lattner16930792003-11-03 04:25:02 +00004929 // If Op1 is a constant, we can fold the cast into the constant.
4930 if (Op1->getType() != Op0->getType())
4931 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Reid Spencerbb65ebf2006-12-12 23:36:14 +00004932 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
Chris Lattner16930792003-11-03 04:25:02 +00004933 } else {
4934 // Otherwise, cast the RHS right before the setcc
Reid Spencer13bc5d72006-12-12 09:18:51 +00004935 Op1 = InsertCastBefore(Instruction::BitCast, Op1, Op0->getType(), I);
Chris Lattner16930792003-11-03 04:25:02 +00004936 }
4937 return BinaryOperator::create(I.getOpcode(), Op0, Op1);
4938 }
4939
Chris Lattner6444c372003-11-03 05:17:03 +00004940 // Handle the special case of: setcc (cast bool to X), <cst>
4941 // This comes up when you have code like
4942 // int X = A < B;
4943 // if (X) ...
4944 // For generality, we handle any zero-extension of any operand comparison
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004945 // with a constant or another cast from the same type.
4946 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
4947 if (Instruction *R = visitSetCondInstWithCastAndCast(I))
4948 return R;
Chris Lattner6444c372003-11-03 05:17:03 +00004949 }
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00004950
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004951 if (I.isEquality()) {
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00004952 Value *A, *B;
4953 if (match(Op0, m_Xor(m_Value(A), m_Value(B))) &&
4954 (A == Op1 || B == Op1)) {
4955 // (A^B) == A -> B == 0
4956 Value *OtherVal = A == Op1 ? B : A;
4957 return BinaryOperator::create(I.getOpcode(), OtherVal,
4958 Constant::getNullValue(A->getType()));
4959 } else if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
4960 (A == Op0 || B == Op0)) {
4961 // A == (A^B) -> B == 0
4962 Value *OtherVal = A == Op0 ? B : A;
4963 return BinaryOperator::create(I.getOpcode(), OtherVal,
4964 Constant::getNullValue(A->getType()));
4965 } else if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
4966 // (A-B) == A -> B == 0
4967 return BinaryOperator::create(I.getOpcode(), B,
4968 Constant::getNullValue(B->getType()));
4969 } else if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
4970 // A == (A-B) -> B == 0
4971 return BinaryOperator::create(I.getOpcode(), B,
4972 Constant::getNullValue(B->getType()));
4973 }
Chris Lattnerd12a4bf2006-11-14 06:06:06 +00004974
4975 Value *C, *D;
4976 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
4977 if (Op0->hasOneUse() && Op1->hasOneUse() &&
4978 match(Op0, m_And(m_Value(A), m_Value(B))) &&
4979 match(Op1, m_And(m_Value(C), m_Value(D)))) {
4980 Value *X = 0, *Y = 0, *Z = 0;
4981
4982 if (A == C) {
4983 X = B; Y = D; Z = A;
4984 } else if (A == D) {
4985 X = B; Y = C; Z = A;
4986 } else if (B == C) {
4987 X = A; Y = D; Z = B;
4988 } else if (B == D) {
4989 X = A; Y = C; Z = B;
4990 }
4991
4992 if (X) { // Build (X^Y) & Z
4993 Op1 = InsertNewInstBefore(BinaryOperator::createXor(X, Y, "tmp"), I);
4994 Op1 = InsertNewInstBefore(BinaryOperator::createAnd(Op1, Z, "tmp"), I);
4995 I.setOperand(0, Op1);
4996 I.setOperand(1, Constant::getNullValue(Op1->getType()));
4997 return &I;
4998 }
4999 }
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00005000 }
Chris Lattner113f4f42002-06-25 16:13:24 +00005001 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005002}
5003
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005004// visitSetCondInstWithCastAndCast - Handle setcond (cast x to y), (cast/cst).
5005// We only handle extending casts so far.
5006//
5007Instruction *InstCombiner::visitSetCondInstWithCastAndCast(SetCondInst &SCI) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005008 const CastInst *LHSCI = cast<CastInst>(SCI.getOperand(0));
5009 Value *LHSCIOp = LHSCI->getOperand(0);
5010 const Type *SrcTy = LHSCIOp->getType();
5011 const Type *DestTy = SCI.getOperand(0)->getType();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005012 Value *RHSCIOp;
5013
5014 if (!DestTy->isIntegral() || !SrcTy->isIntegral())
Chris Lattner03f06f12005-01-17 03:20:02 +00005015 return 0;
5016
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005017 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
5018 unsigned DestBits = DestTy->getPrimitiveSizeInBits();
5019 if (SrcBits >= DestBits) return 0; // Only handle extending cast.
5020
5021 // Is this a sign or zero extension?
5022 bool isSignSrc = SrcTy->isSigned();
5023 bool isSignDest = DestTy->isSigned();
5024
5025 if (CastInst *CI = dyn_cast<CastInst>(SCI.getOperand(1))) {
5026 // Not an extension from the same type?
5027 RHSCIOp = CI->getOperand(0);
5028 if (RHSCIOp->getType() != LHSCIOp->getType()) return 0;
5029 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(SCI.getOperand(1))) {
5030 // Compute the constant that would happen if we truncated to SrcTy then
5031 // reextended to DestTy.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005032 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
5033 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005034
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005035 if (Res2 == CI) {
Devang Patelb42aef42006-10-19 18:54:08 +00005036 // Make sure that src sign and dest sign match. For example,
5037 //
5038 // %A = cast short %X to uint
5039 // %B = setgt uint %A, 1330
5040 //
Devang Patel88afd002006-10-19 19:21:36 +00005041 // It is incorrect to transform this into
Devang Patelb42aef42006-10-19 18:54:08 +00005042 //
5043 // %B = setgt short %X, 1330
5044 //
5045 // because %A may have negative value.
Devang Patel5d6df952006-10-19 20:59:13 +00005046 // However, it is OK if SrcTy is bool (See cast-set.ll testcase)
5047 // OR operation is EQ/NE.
5048 if (isSignSrc == isSignDest || SrcTy == Type::BoolTy || SCI.isEquality())
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005049 RHSCIOp = Res1;
Devang Patelb42aef42006-10-19 18:54:08 +00005050 else
5051 return 0;
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005052 } else {
5053 // If the value cannot be represented in the shorter type, we cannot emit
5054 // a simple comparison.
5055 if (SCI.getOpcode() == Instruction::SetEQ)
Chris Lattner6ab03f62006-09-28 23:35:22 +00005056 return ReplaceInstUsesWith(SCI, ConstantBool::getFalse());
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005057 if (SCI.getOpcode() == Instruction::SetNE)
Chris Lattner6ab03f62006-09-28 23:35:22 +00005058 return ReplaceInstUsesWith(SCI, ConstantBool::getTrue());
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005059
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005060 // Evaluate the comparison for LT.
5061 Value *Result;
5062 if (DestTy->isSigned()) {
5063 // We're performing a signed comparison.
5064 if (isSignSrc) {
5065 // Signed extend and signed comparison.
Reid Spencere0fc4df2006-10-20 07:07:24 +00005066 if (cast<ConstantInt>(CI)->getSExtValue() < 0)// X < (small) --> false
Chris Lattner6ab03f62006-09-28 23:35:22 +00005067 Result = ConstantBool::getFalse();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005068 else
Reid Spencere0fc4df2006-10-20 07:07:24 +00005069 Result = ConstantBool::getTrue(); // X < (large) --> true
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005070 } else {
5071 // Unsigned extend and signed comparison.
Reid Spencere0fc4df2006-10-20 07:07:24 +00005072 if (cast<ConstantInt>(CI)->getSExtValue() < 0)
Chris Lattner6ab03f62006-09-28 23:35:22 +00005073 Result = ConstantBool::getFalse();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005074 else
Chris Lattner6ab03f62006-09-28 23:35:22 +00005075 Result = ConstantBool::getTrue();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005076 }
5077 } else {
5078 // We're performing an unsigned comparison.
5079 if (!isSignSrc) {
5080 // Unsigned extend & compare -> always true.
Chris Lattner6ab03f62006-09-28 23:35:22 +00005081 Result = ConstantBool::getTrue();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005082 } else {
5083 // We're performing an unsigned comp with a sign extended value.
5084 // This is true if the input is >= 0. [aka >s -1]
5085 Constant *NegOne = ConstantIntegral::getAllOnesValue(SrcTy);
5086 Result = InsertNewInstBefore(BinaryOperator::createSetGT(LHSCIOp,
5087 NegOne, SCI.getName()), SCI);
5088 }
Reid Spencer279fa252004-11-28 21:31:15 +00005089 }
Chris Lattner03f06f12005-01-17 03:20:02 +00005090
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00005091 // Finally, return the value computed.
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005092 if (SCI.getOpcode() == Instruction::SetLT) {
5093 return ReplaceInstUsesWith(SCI, Result);
5094 } else {
5095 assert(SCI.getOpcode()==Instruction::SetGT &&"SetCC should be folded!");
5096 if (Constant *CI = dyn_cast<Constant>(Result))
5097 return ReplaceInstUsesWith(SCI, ConstantExpr::getNot(CI));
5098 else
5099 return BinaryOperator::createNot(Result);
5100 }
Chris Lattner03f06f12005-01-17 03:20:02 +00005101 }
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005102 } else {
5103 return 0;
Reid Spencer279fa252004-11-28 21:31:15 +00005104 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005105
Chris Lattner252a8452005-06-16 03:00:08 +00005106 // Okay, just insert a compare of the reduced operands now!
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005107 return BinaryOperator::create(SCI.getOpcode(), LHSCIOp, RHSCIOp);
5108}
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005109
Chris Lattnere8d6c602003-03-10 19:16:08 +00005110Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +00005111 assert(I.getOperand(1)->getType() == Type::UByteTy);
5112 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00005113 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005114
5115 // shl X, 0 == X and shr X, 0 == X
5116 // shl 0, X == 0 and shr 0, X == 0
5117 if (Op1 == Constant::getNullValue(Type::UByteTy) ||
Chris Lattnere6794492002-08-12 21:17:25 +00005118 Op0 == Constant::getNullValue(Op0->getType()))
5119 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf5b4ef72006-02-12 08:07:37 +00005120
Chris Lattner81a7a232004-10-16 18:11:37 +00005121 if (isa<UndefValue>(Op0)) { // undef >>s X -> undef
5122 if (!isLeftShift && I.getType()->isSigned())
Chris Lattner67f05452004-10-16 23:28:04 +00005123 return ReplaceInstUsesWith(I, Op0);
Chris Lattner81a7a232004-10-16 18:11:37 +00005124 else // undef << X -> 0 AND undef >>u X -> 0
5125 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5126 }
5127 if (isa<UndefValue>(Op1)) {
Chris Lattner18aa4d82005-07-20 18:49:28 +00005128 if (isLeftShift || I.getType()->isUnsigned())// X << undef, X >>u undef -> 0
Chris Lattner81a7a232004-10-16 18:11:37 +00005129 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5130 else
5131 return ReplaceInstUsesWith(I, Op0); // X >>s undef -> X
5132 }
5133
Chris Lattnerd4dee402006-11-10 23:38:52 +00005134 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
5135 if (I.getOpcode() == Instruction::AShr)
Reid Spencere0fc4df2006-10-20 07:07:24 +00005136 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Chris Lattnerd4dee402006-11-10 23:38:52 +00005137 if (CSI->isAllOnesValue())
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00005138 return ReplaceInstUsesWith(I, CSI);
5139
Chris Lattner183b3362004-04-09 19:05:30 +00005140 // Try to fold constant and into select arguments.
5141 if (isa<Constant>(Op0))
5142 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner86102b82005-01-01 16:22:27 +00005143 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00005144 return R;
5145
Chris Lattnerb18dbbf2005-05-08 17:34:56 +00005146 // See if we can turn a signed shr into an unsigned shr.
Chris Lattnerb3f24c92006-09-18 04:22:48 +00005147 if (I.isArithmeticShift()) {
Chris Lattnerc3ebf402006-02-07 07:27:52 +00005148 if (MaskedValueIsZero(Op0,
5149 1ULL << (I.getType()->getPrimitiveSizeInBits()-1))) {
Reid Spencerfdff9382006-11-08 06:47:33 +00005150 return new ShiftInst(Instruction::LShr, Op0, Op1, I.getName());
Chris Lattnerb18dbbf2005-05-08 17:34:56 +00005151 }
5152 }
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00005153
Reid Spencere0fc4df2006-10-20 07:07:24 +00005154 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
5155 if (CUI->getType()->isUnsigned())
5156 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
5157 return Res;
Chris Lattner14553932006-01-06 07:12:35 +00005158 return 0;
5159}
5160
Reid Spencere0fc4df2006-10-20 07:07:24 +00005161Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Chris Lattner14553932006-01-06 07:12:35 +00005162 ShiftInst &I) {
5163 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Reid Spencerfdff9382006-11-08 06:47:33 +00005164 bool isSignedShift = isLeftShift ? Op0->getType()->isSigned() :
5165 I.getOpcode() == Instruction::AShr;
Chris Lattnerb3309392006-01-06 07:22:22 +00005166 bool isUnsignedShift = !isSignedShift;
Chris Lattner14553932006-01-06 07:12:35 +00005167
Chris Lattnerf5b4ef72006-02-12 08:07:37 +00005168 // See if we can simplify any instructions used by the instruction whose sole
5169 // purpose is to compute bits we don't care about.
5170 uint64_t KnownZero, KnownOne;
5171 if (SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
5172 KnownZero, KnownOne))
5173 return &I;
5174
Chris Lattner14553932006-01-06 07:12:35 +00005175 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
5176 // of a signed value.
5177 //
5178 unsigned TypeBits = Op0->getType()->getPrimitiveSizeInBits();
Reid Spencere0fc4df2006-10-20 07:07:24 +00005179 if (Op1->getZExtValue() >= TypeBits) {
Chris Lattnerb3309392006-01-06 07:22:22 +00005180 if (isUnsignedShift || isLeftShift)
Chris Lattner14553932006-01-06 07:12:35 +00005181 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
5182 else {
Reid Spencere0fc4df2006-10-20 07:07:24 +00005183 I.setOperand(1, ConstantInt::get(Type::UByteTy, TypeBits-1));
Chris Lattner14553932006-01-06 07:12:35 +00005184 return &I;
Chris Lattnerf5ce2542004-02-23 20:30:06 +00005185 }
Chris Lattner14553932006-01-06 07:12:35 +00005186 }
5187
5188 // ((X*C1) << C2) == (X * (C1 << C2))
5189 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
5190 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
5191 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
5192 return BinaryOperator::createMul(BO->getOperand(0),
5193 ConstantExpr::getShl(BOOp, Op1));
5194
5195 // Try to fold constant and into select arguments.
5196 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5197 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5198 return R;
5199 if (isa<PHINode>(Op0))
5200 if (Instruction *NV = FoldOpIntoPhi(I))
5201 return NV;
5202
5203 if (Op0->hasOneUse()) {
Chris Lattner14553932006-01-06 07:12:35 +00005204 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
5205 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
5206 Value *V1, *V2;
5207 ConstantInt *CC;
5208 switch (Op0BO->getOpcode()) {
Chris Lattner27cb9db2005-09-18 05:12:10 +00005209 default: break;
5210 case Instruction::Add:
5211 case Instruction::And:
5212 case Instruction::Or:
5213 case Instruction::Xor:
5214 // These operators commute.
5215 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner797dee72005-09-18 06:30:59 +00005216 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
5217 match(Op0BO->getOperand(1),
Chris Lattner14553932006-01-06 07:12:35 +00005218 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Chris Lattner797dee72005-09-18 06:30:59 +00005219 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00005220 Op0BO->getOperand(0), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00005221 Op0BO->getName());
5222 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005223 Instruction *X =
5224 BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
5225 Op0BO->getOperand(1)->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00005226 InsertNewInstBefore(X, I); // (X + (Y << C))
5227 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
Chris Lattner14553932006-01-06 07:12:35 +00005228 C2 = ConstantExpr::getShl(C2, Op1);
Chris Lattner797dee72005-09-18 06:30:59 +00005229 return BinaryOperator::createAnd(X, C2);
5230 }
Chris Lattner14553932006-01-06 07:12:35 +00005231
Chris Lattner797dee72005-09-18 06:30:59 +00005232 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
5233 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
5234 match(Op0BO->getOperand(1),
5235 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner14553932006-01-06 07:12:35 +00005236 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005237 cast<BinaryOperator>(Op0BO->getOperand(1))->getOperand(0)->hasOneUse()) {
Chris Lattner797dee72005-09-18 06:30:59 +00005238 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00005239 Op0BO->getOperand(0), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00005240 Op0BO->getName());
5241 InsertNewInstBefore(YS, I); // (Y << C)
5242 Instruction *XM =
Chris Lattner14553932006-01-06 07:12:35 +00005243 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner797dee72005-09-18 06:30:59 +00005244 V1->getName()+".mask");
5245 InsertNewInstBefore(XM, I); // X & (CC << C)
5246
5247 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
5248 }
Chris Lattner14553932006-01-06 07:12:35 +00005249
Chris Lattner797dee72005-09-18 06:30:59 +00005250 // FALL THROUGH.
Chris Lattner27cb9db2005-09-18 05:12:10 +00005251 case Instruction::Sub:
5252 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner797dee72005-09-18 06:30:59 +00005253 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
5254 match(Op0BO->getOperand(0),
Chris Lattner14553932006-01-06 07:12:35 +00005255 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Chris Lattner797dee72005-09-18 06:30:59 +00005256 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00005257 Op0BO->getOperand(1), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00005258 Op0BO->getName());
5259 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005260 Instruction *X =
Chris Lattner1df0e982006-05-31 21:14:00 +00005261 BinaryOperator::create(Op0BO->getOpcode(), V1, YS,
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005262 Op0BO->getOperand(0)->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00005263 InsertNewInstBefore(X, I); // (X + (Y << C))
5264 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
Chris Lattner14553932006-01-06 07:12:35 +00005265 C2 = ConstantExpr::getShl(C2, Op1);
Chris Lattner797dee72005-09-18 06:30:59 +00005266 return BinaryOperator::createAnd(X, C2);
5267 }
Chris Lattner14553932006-01-06 07:12:35 +00005268
Chris Lattner1df0e982006-05-31 21:14:00 +00005269 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner797dee72005-09-18 06:30:59 +00005270 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
5271 match(Op0BO->getOperand(0),
5272 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner14553932006-01-06 07:12:35 +00005273 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005274 cast<BinaryOperator>(Op0BO->getOperand(0))
5275 ->getOperand(0)->hasOneUse()) {
Chris Lattner797dee72005-09-18 06:30:59 +00005276 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00005277 Op0BO->getOperand(1), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00005278 Op0BO->getName());
5279 InsertNewInstBefore(YS, I); // (Y << C)
5280 Instruction *XM =
Chris Lattner14553932006-01-06 07:12:35 +00005281 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner797dee72005-09-18 06:30:59 +00005282 V1->getName()+".mask");
5283 InsertNewInstBefore(XM, I); // X & (CC << C)
5284
Chris Lattner1df0e982006-05-31 21:14:00 +00005285 return BinaryOperator::create(Op0BO->getOpcode(), XM, YS);
Chris Lattner797dee72005-09-18 06:30:59 +00005286 }
Chris Lattner14553932006-01-06 07:12:35 +00005287
Chris Lattner27cb9db2005-09-18 05:12:10 +00005288 break;
Chris Lattner14553932006-01-06 07:12:35 +00005289 }
5290
5291
5292 // If the operand is an bitwise operator with a constant RHS, and the
5293 // shift is the only use, we can pull it out of the shift.
5294 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
5295 bool isValid = true; // Valid only for And, Or, Xor
5296 bool highBitSet = false; // Transform if high bit of constant set?
5297
5298 switch (Op0BO->getOpcode()) {
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00005299 default: isValid = false; break; // Do not perform transform!
Chris Lattner44bd3922004-10-08 03:46:20 +00005300 case Instruction::Add:
5301 isValid = isLeftShift;
5302 break;
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00005303 case Instruction::Or:
5304 case Instruction::Xor:
5305 highBitSet = false;
5306 break;
5307 case Instruction::And:
5308 highBitSet = true;
5309 break;
Chris Lattner14553932006-01-06 07:12:35 +00005310 }
5311
5312 // If this is a signed shift right, and the high bit is modified
5313 // by the logical operation, do not perform the transformation.
5314 // The highBitSet boolean indicates the value of the high bit of
5315 // the constant which would cause it to be modified for this
5316 // operation.
5317 //
Chris Lattnerb3309392006-01-06 07:22:22 +00005318 if (isValid && !isLeftShift && isSignedShift) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00005319 uint64_t Val = Op0C->getZExtValue();
Chris Lattner14553932006-01-06 07:12:35 +00005320 isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
5321 }
5322
5323 if (isValid) {
5324 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
5325
5326 Instruction *NewShift =
5327 new ShiftInst(I.getOpcode(), Op0BO->getOperand(0), Op1,
5328 Op0BO->getName());
5329 Op0BO->setName("");
5330 InsertNewInstBefore(NewShift, I);
5331
5332 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
5333 NewRHS);
5334 }
5335 }
5336 }
5337 }
5338
Chris Lattnereb372a02006-01-06 07:52:12 +00005339 // Find out if this is a shift of a shift by a constant.
5340 ShiftInst *ShiftOp = 0;
Chris Lattner14553932006-01-06 07:12:35 +00005341 if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0))
Chris Lattnereb372a02006-01-06 07:52:12 +00005342 ShiftOp = Op0SI;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005343 else if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
5344 // If this is a noop-integer cast of a shift instruction, use the shift.
5345 if (isa<ShiftInst>(CI->getOperand(0))) {
Chris Lattnereb372a02006-01-06 07:52:12 +00005346 ShiftOp = cast<ShiftInst>(CI->getOperand(0));
5347 }
5348 }
5349
Reid Spencere0fc4df2006-10-20 07:07:24 +00005350 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Chris Lattnereb372a02006-01-06 07:52:12 +00005351 // Find the operands and properties of the input shift. Note that the
5352 // signedness of the input shift may differ from the current shift if there
5353 // is a noop cast between the two.
5354 bool isShiftOfLeftShift = ShiftOp->getOpcode() == Instruction::Shl;
Reid Spencerfdff9382006-11-08 06:47:33 +00005355 bool isShiftOfSignedShift = isShiftOfLeftShift ?
5356 ShiftOp->getType()->isSigned() :
5357 ShiftOp->getOpcode() == Instruction::AShr;
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005358 bool isShiftOfUnsignedShift = !isShiftOfSignedShift;
Chris Lattnereb372a02006-01-06 07:52:12 +00005359
Reid Spencere0fc4df2006-10-20 07:07:24 +00005360 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Chris Lattnereb372a02006-01-06 07:52:12 +00005361
Reid Spencere0fc4df2006-10-20 07:07:24 +00005362 unsigned ShiftAmt1 = (unsigned)ShiftAmt1C->getZExtValue();
5363 unsigned ShiftAmt2 = (unsigned)Op1->getZExtValue();
Chris Lattnereb372a02006-01-06 07:52:12 +00005364
5365 // Check for (A << c1) << c2 and (A >> c1) >> c2.
5366 if (isLeftShift == isShiftOfLeftShift) {
5367 // Do not fold these shifts if the first one is signed and the second one
5368 // is unsigned and this is a right shift. Further, don't do any folding
5369 // on them.
5370 if (isShiftOfSignedShift && isUnsignedShift && !isLeftShift)
5371 return 0;
Chris Lattner14553932006-01-06 07:12:35 +00005372
Chris Lattnereb372a02006-01-06 07:52:12 +00005373 unsigned Amt = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
5374 if (Amt > Op0->getType()->getPrimitiveSizeInBits())
5375 Amt = Op0->getType()->getPrimitiveSizeInBits();
Chris Lattner14553932006-01-06 07:12:35 +00005376
Chris Lattnereb372a02006-01-06 07:52:12 +00005377 Value *Op = ShiftOp->getOperand(0);
5378 if (isShiftOfSignedShift != isSignedShift)
Reid Spencerbb65ebf2006-12-12 23:36:14 +00005379 Op = InsertNewInstBefore(new BitCastInst(Op, I.getType(), "tmp"), I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005380 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 Spencer13bc5d72006-12-12 09:18:51 +00005401 Op = InsertCastBefore(Instruction::BitCast, 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
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005423 Instruction *Shift =
Reid Spencer2a499b02006-12-13 17:19:09 +00005424 new ShiftInst(ShiftOp->getOpcode(), Mask,
Reid Spencere0fc4df2006-10-20 07:07:24 +00005425 ConstantInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005426 InsertNewInstBefore(Shift, I);
5427
5428 C = ConstantIntegral::getAllOnesValue(Shift->getType());
5429 C = ConstantExpr::getShl(C, Op1);
Reid Spencer2a499b02006-12-13 17:19:09 +00005430 return BinaryOperator::createAnd(Shift, C, Op->getName()+".mask");
Chris Lattnereb372a02006-01-06 07:52:12 +00005431 }
5432 } else {
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005433 // We can handle signed (X << C1) >>s C2 if it's a sign extend. In
Chris Lattnereb372a02006-01-06 07:52:12 +00005434 // this case, C1 == C2 and C1 is 8, 16, or 32.
5435 if (ShiftAmt1 == ShiftAmt2) {
5436 const Type *SExtType = 0;
Chris Lattner655d08f2006-04-28 22:21:41 +00005437 switch (Op0->getType()->getPrimitiveSizeInBits() - ShiftAmt1) {
Chris Lattnereb372a02006-01-06 07:52:12 +00005438 case 8 : SExtType = Type::SByteTy; break;
5439 case 16: SExtType = Type::ShortTy; break;
5440 case 32: SExtType = Type::IntTy; break;
5441 }
5442
5443 if (SExtType) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005444 Instruction *NewTrunc =
5445 new TruncInst(ShiftOp->getOperand(0), SExtType, "sext");
Chris Lattnereb372a02006-01-06 07:52:12 +00005446 InsertNewInstBefore(NewTrunc, I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005447 return new SExtInst(NewTrunc, I.getType());
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00005448 }
Chris Lattner27cb9db2005-09-18 05:12:10 +00005449 }
Chris Lattner86102b82005-01-01 16:22:27 +00005450 }
Chris Lattnereb372a02006-01-06 07:52:12 +00005451 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005452 return 0;
5453}
5454
Chris Lattner48a44f72002-05-02 17:06:02 +00005455
Chris Lattner8f663e82005-10-29 04:36:15 +00005456/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
5457/// expression. If so, decompose it, returning some value X, such that Val is
5458/// X*Scale+Offset.
5459///
5460static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
5461 unsigned &Offset) {
5462 assert(Val->getType() == Type::UIntTy && "Unexpected allocation size type!");
Reid Spencere0fc4df2006-10-20 07:07:24 +00005463 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
5464 if (CI->getType()->isUnsigned()) {
5465 Offset = CI->getZExtValue();
5466 Scale = 1;
5467 return ConstantInt::get(Type::UIntTy, 0);
5468 }
Chris Lattner8f663e82005-10-29 04:36:15 +00005469 } else if (Instruction *I = dyn_cast<Instruction>(Val)) {
5470 if (I->getNumOperands() == 2) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00005471 if (ConstantInt *CUI = dyn_cast<ConstantInt>(I->getOperand(1))) {
5472 if (CUI->getType()->isUnsigned()) {
5473 if (I->getOpcode() == Instruction::Shl) {
5474 // This is a value scaled by '1 << the shift amt'.
5475 Scale = 1U << CUI->getZExtValue();
5476 Offset = 0;
5477 return I->getOperand(0);
5478 } else if (I->getOpcode() == Instruction::Mul) {
5479 // This value is scaled by 'CUI'.
5480 Scale = CUI->getZExtValue();
5481 Offset = 0;
5482 return I->getOperand(0);
5483 } else if (I->getOpcode() == Instruction::Add) {
5484 // We have X+C. Check to see if we really have (X*C2)+C1,
5485 // where C1 is divisible by C2.
5486 unsigned SubScale;
5487 Value *SubVal =
5488 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
5489 Offset += CUI->getZExtValue();
5490 if (SubScale > 1 && (Offset % SubScale == 0)) {
5491 Scale = SubScale;
5492 return SubVal;
5493 }
Chris Lattner8f663e82005-10-29 04:36:15 +00005494 }
5495 }
5496 }
5497 }
5498 }
5499
5500 // Otherwise, we can't look past this.
5501 Scale = 1;
5502 Offset = 0;
5503 return Val;
5504}
5505
5506
Chris Lattner216be912005-10-24 06:03:58 +00005507/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
5508/// try to eliminate the cast by moving the type information into the alloc.
5509Instruction *InstCombiner::PromoteCastOfAllocation(CastInst &CI,
5510 AllocationInst &AI) {
5511 const PointerType *PTy = dyn_cast<PointerType>(CI.getType());
Chris Lattnerbb171802005-10-27 05:53:56 +00005512 if (!PTy) return 0; // Not casting the allocation to a pointer type.
Chris Lattner216be912005-10-24 06:03:58 +00005513
Chris Lattnerac87beb2005-10-24 06:22:12 +00005514 // Remove any uses of AI that are dead.
5515 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
5516 std::vector<Instruction*> DeadUsers;
5517 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
5518 Instruction *User = cast<Instruction>(*UI++);
5519 if (isInstructionTriviallyDead(User)) {
5520 while (UI != E && *UI == User)
5521 ++UI; // If this instruction uses AI more than once, don't break UI.
5522
5523 // Add operands to the worklist.
5524 AddUsesToWorkList(*User);
5525 ++NumDeadInst;
Bill Wendling5dbf43c2006-11-26 09:46:52 +00005526 DOUT << "IC: DCE: " << *User;
Chris Lattnerac87beb2005-10-24 06:22:12 +00005527
5528 User->eraseFromParent();
5529 removeFromWorkList(User);
5530 }
5531 }
5532
Chris Lattner216be912005-10-24 06:03:58 +00005533 // Get the type really allocated and the type casted to.
5534 const Type *AllocElTy = AI.getAllocatedType();
5535 const Type *CastElTy = PTy->getElementType();
5536 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner355ecc02005-10-24 06:26:18 +00005537
Chris Lattner7d190672006-10-01 19:40:58 +00005538 unsigned AllocElTyAlign = TD->getTypeAlignment(AllocElTy);
5539 unsigned CastElTyAlign = TD->getTypeAlignment(CastElTy);
Chris Lattner355ecc02005-10-24 06:26:18 +00005540 if (CastElTyAlign < AllocElTyAlign) return 0;
5541
Chris Lattner46705b22005-10-24 06:35:18 +00005542 // If the allocation has multiple uses, only promote it if we are strictly
5543 // increasing the alignment of the resultant allocation. If we keep it the
5544 // same, we open the door to infinite loops of various kinds.
5545 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
5546
Chris Lattner216be912005-10-24 06:03:58 +00005547 uint64_t AllocElTySize = TD->getTypeSize(AllocElTy);
5548 uint64_t CastElTySize = TD->getTypeSize(CastElTy);
Chris Lattnerbb171802005-10-27 05:53:56 +00005549 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner355ecc02005-10-24 06:26:18 +00005550
Chris Lattner8270c332005-10-29 03:19:53 +00005551 // See if we can satisfy the modulus by pulling a scale out of the array
5552 // size argument.
Chris Lattner8f663e82005-10-29 04:36:15 +00005553 unsigned ArraySizeScale, ArrayOffset;
5554 Value *NumElements = // See if the array size is a decomposable linear expr.
5555 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
5556
Chris Lattner8270c332005-10-29 03:19:53 +00005557 // If we can now satisfy the modulus, by using a non-1 scale, we really can
5558 // do the xform.
Chris Lattner8f663e82005-10-29 04:36:15 +00005559 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
5560 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattnerb3ecf962005-10-27 06:12:00 +00005561
Chris Lattner8270c332005-10-29 03:19:53 +00005562 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
5563 Value *Amt = 0;
5564 if (Scale == 1) {
5565 Amt = NumElements;
5566 } else {
Reid Spencere0fc4df2006-10-20 07:07:24 +00005567 // If the allocation size is constant, form a constant mul expression
5568 Amt = ConstantInt::get(Type::UIntTy, Scale);
5569 if (isa<ConstantInt>(NumElements) && NumElements->getType()->isUnsigned())
5570 Amt = ConstantExpr::getMul(
5571 cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
5572 // otherwise multiply the amount and the number of elements
Chris Lattner8270c332005-10-29 03:19:53 +00005573 else if (Scale != 1) {
5574 Instruction *Tmp = BinaryOperator::createMul(Amt, NumElements, "tmp");
5575 Amt = InsertNewInstBefore(Tmp, AI);
Chris Lattnerb3ecf962005-10-27 06:12:00 +00005576 }
Chris Lattnerbb171802005-10-27 05:53:56 +00005577 }
5578
Chris Lattner8f663e82005-10-29 04:36:15 +00005579 if (unsigned Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00005580 Value *Off = ConstantInt::get(Type::UIntTy, Offset);
Chris Lattner8f663e82005-10-29 04:36:15 +00005581 Instruction *Tmp = BinaryOperator::createAdd(Amt, Off, "tmp");
5582 Amt = InsertNewInstBefore(Tmp, AI);
5583 }
5584
Chris Lattner216be912005-10-24 06:03:58 +00005585 std::string Name = AI.getName(); AI.setName("");
5586 AllocationInst *New;
5587 if (isa<MallocInst>(AI))
Nate Begeman848622f2005-11-05 09:21:28 +00005588 New = new MallocInst(CastElTy, Amt, AI.getAlignment(), Name);
Chris Lattner216be912005-10-24 06:03:58 +00005589 else
Nate Begeman848622f2005-11-05 09:21:28 +00005590 New = new AllocaInst(CastElTy, Amt, AI.getAlignment(), Name);
Chris Lattner216be912005-10-24 06:03:58 +00005591 InsertNewInstBefore(New, AI);
Chris Lattner46705b22005-10-24 06:35:18 +00005592
5593 // If the allocation has multiple uses, insert a cast and change all things
5594 // that used it to use the new cast. This will also hack on CI, but it will
5595 // die soon.
5596 if (!AI.hasOneUse()) {
5597 AddUsesToWorkList(AI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005598 // New is the allocation instruction, pointer typed. AI is the original
5599 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
5600 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
Chris Lattner46705b22005-10-24 06:35:18 +00005601 InsertNewInstBefore(NewCast, AI);
5602 AI.replaceAllUsesWith(NewCast);
5603 }
Chris Lattner216be912005-10-24 06:03:58 +00005604 return ReplaceInstUsesWith(CI, New);
5605}
5606
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005607/// CanEvaluateInDifferentType - Return true if we can take the specified value
5608/// and return it without inserting any new casts. This is used by code that
5609/// tries to decide whether promoting or shrinking integer operations to wider
5610/// or smaller types will allow us to eliminate a truncate or extend.
5611static bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
5612 int &NumCastsRemoved) {
5613 if (isa<Constant>(V)) return true;
5614
5615 Instruction *I = dyn_cast<Instruction>(V);
5616 if (!I || !I->hasOneUse()) return false;
5617
5618 switch (I->getOpcode()) {
5619 case Instruction::And:
5620 case Instruction::Or:
5621 case Instruction::Xor:
5622 // These operators can all arbitrarily be extended or truncated.
5623 return CanEvaluateInDifferentType(I->getOperand(0), Ty, NumCastsRemoved) &&
5624 CanEvaluateInDifferentType(I->getOperand(1), Ty, NumCastsRemoved);
Chris Lattner960acb02006-11-29 07:18:39 +00005625 case Instruction::AShr:
5626 case Instruction::LShr:
5627 case Instruction::Shl:
5628 // If this is just a bitcast changing the sign of the operation, we can
5629 // convert if the operand can be converted.
5630 if (V->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
5631 return CanEvaluateInDifferentType(I->getOperand(0), Ty, NumCastsRemoved);
5632 break;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005633 case Instruction::Trunc:
5634 case Instruction::ZExt:
5635 case Instruction::SExt:
5636 case Instruction::BitCast:
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005637 // If this is a cast from the destination type, we can trivially eliminate
5638 // it, and this will remove a cast overall.
5639 if (I->getOperand(0)->getType() == Ty) {
Chris Lattner3fda3862006-06-28 17:34:50 +00005640 // If the first operand is itself a cast, and is eliminable, do not count
5641 // this as an eliminable cast. We would prefer to eliminate those two
5642 // casts first.
Reid Spencerde46e482006-11-02 20:25:50 +00005643 if (isa<CastInst>(I->getOperand(0)))
Chris Lattner3fda3862006-06-28 17:34:50 +00005644 return true;
5645
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005646 ++NumCastsRemoved;
5647 return true;
5648 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005649 break;
5650 default:
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005651 // TODO: Can handle more cases here.
5652 break;
5653 }
5654
5655 return false;
5656}
5657
5658/// EvaluateInDifferentType - Given an expression that
5659/// CanEvaluateInDifferentType returns true for, actually insert the code to
5660/// evaluate the expression.
5661Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty) {
5662 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencerbb65ebf2006-12-12 23:36:14 +00005663 return ConstantExpr::getIntegerCast(C, Ty, C->getType()->isSigned());
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005664
5665 // Otherwise, it must be an instruction.
5666 Instruction *I = cast<Instruction>(V);
Chris Lattnerd0622b62006-05-20 23:14:03 +00005667 Instruction *Res = 0;
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005668 switch (I->getOpcode()) {
5669 case Instruction::And:
5670 case Instruction::Or:
5671 case Instruction::Xor: {
5672 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty);
5673 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty);
5674 Res = BinaryOperator::create((Instruction::BinaryOps)I->getOpcode(),
5675 LHS, RHS, I->getName());
5676 break;
5677 }
Chris Lattner960acb02006-11-29 07:18:39 +00005678 case Instruction::AShr:
5679 case Instruction::LShr:
5680 case Instruction::Shl: {
5681 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty);
5682 Res = new ShiftInst((Instruction::OtherOps)I->getOpcode(), LHS,
5683 I->getOperand(1), I->getName());
5684 break;
5685 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005686 case Instruction::Trunc:
5687 case Instruction::ZExt:
5688 case Instruction::SExt:
5689 case Instruction::BitCast:
5690 // If the source type of the cast is the type we're trying for then we can
5691 // just return the source. There's no need to insert it because its not new.
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005692 if (I->getOperand(0)->getType() == Ty)
5693 return I->getOperand(0);
5694
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005695 // Some other kind of cast, which shouldn't happen, so just ..
5696 // FALL THROUGH
5697 default:
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005698 // TODO: Can handle more cases here.
5699 assert(0 && "Unreachable!");
5700 break;
5701 }
5702
5703 return InsertNewInstBefore(Res, *I);
5704}
5705
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005706/// @brief Implement the transforms common to all CastInst visitors.
5707Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
Chris Lattner55d4bda2003-06-23 21:59:52 +00005708 Value *Src = CI.getOperand(0);
5709
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005710 // Casting undef to anything results in undef so might as just replace it and
5711 // get rid of the cast.
Chris Lattner81a7a232004-10-16 18:11:37 +00005712 if (isa<UndefValue>(Src)) // cast undef -> undef
5713 return ReplaceInstUsesWith(CI, UndefValue::get(CI.getType()));
5714
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005715 // Many cases of "cast of a cast" are eliminable. If its eliminable we just
5716 // eliminate it now.
Chris Lattner86102b82005-01-01 16:22:27 +00005717 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005718 if (Instruction::CastOps opc =
5719 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
5720 // The first cast (CSrc) is eliminable so we need to fix up or replace
5721 // the second cast (CI). CSrc will then have a good chance of being dead.
5722 return CastInst::create(opc, CSrc->getOperand(0), CI.getType());
Chris Lattner650b6da2002-08-02 20:00:25 +00005723 }
5724 }
Chris Lattner03841652004-05-25 04:29:21 +00005725
Chris Lattnerd0d51602003-06-21 23:12:02 +00005726 // If casting the result of a getelementptr instruction with no offset, turn
5727 // this into a cast of the original pointer!
5728 //
Chris Lattner55d4bda2003-06-23 21:59:52 +00005729 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattnerd0d51602003-06-21 23:12:02 +00005730 bool AllZeroOperands = true;
5731 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
5732 if (!isa<Constant>(GEP->getOperand(i)) ||
5733 !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
5734 AllZeroOperands = false;
5735 break;
5736 }
5737 if (AllZeroOperands) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005738 // Changing the cast operand is usually not a good idea but it is safe
5739 // here because the pointer operand is being replaced with another
5740 // pointer operand so the opcode doesn't need to change.
Chris Lattnerd0d51602003-06-21 23:12:02 +00005741 CI.setOperand(0, GEP->getOperand(0));
5742 return &CI;
5743 }
5744 }
Chris Lattnerec45a4c2006-11-21 17:05:13 +00005745
Chris Lattnerf4ad1652003-11-02 05:57:39 +00005746 // If we are casting a malloc or alloca to a pointer to a type of the same
5747 // size, rewrite the allocation instruction to allocate the "right" type.
Chris Lattnerf4ad1652003-11-02 05:57:39 +00005748 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
Chris Lattner216be912005-10-24 06:03:58 +00005749 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
5750 return V;
Chris Lattnerf4ad1652003-11-02 05:57:39 +00005751
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005752 // If we are casting a select then fold the cast into the select
Chris Lattner86102b82005-01-01 16:22:27 +00005753 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
5754 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
5755 return NV;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005756
5757 // If we are casting a PHI then fold the cast into the PHI
Chris Lattner6a4adcd2004-09-29 05:07:12 +00005758 if (isa<PHINode>(Src))
5759 if (Instruction *NV = FoldOpIntoPhi(CI))
5760 return NV;
Chris Lattnerb19a5c62006-04-12 18:09:35 +00005761
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005762 return 0;
5763}
5764
5765/// Only the TRUNC, ZEXT, SEXT, and BITCONVERT can have both operands as
5766/// integers. This function implements the common transforms for all those
5767/// cases.
5768/// @brief Implement the transforms common to CastInst with integer operands
5769Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
5770 if (Instruction *Result = commonCastTransforms(CI))
5771 return Result;
5772
5773 Value *Src = CI.getOperand(0);
5774 const Type *SrcTy = Src->getType();
5775 const Type *DestTy = CI.getType();
5776 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
5777 unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
5778
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005779 // See if we can simplify any instructions used by the LHS whose sole
5780 // purpose is to compute bits we don't care about.
5781 uint64_t KnownZero = 0, KnownOne = 0;
5782 if (SimplifyDemandedBits(&CI, DestTy->getIntegralTypeMask(),
5783 KnownZero, KnownOne))
5784 return &CI;
5785
5786 // If the source isn't an instruction or has more than one use then we
5787 // can't do anything more.
5788 if (!isa<Instruction>(Src) || !Src->hasOneUse())
5789 return 0;
5790
5791 // Attempt to propagate the cast into the instruction.
5792 Instruction *SrcI = cast<Instruction>(Src);
5793 int NumCastsRemoved = 0;
5794 if (CanEvaluateInDifferentType(SrcI, DestTy, NumCastsRemoved)) {
5795 // If this cast is a truncate, evaluting in a different type always
5796 // eliminates the cast, so it is always a win. If this is a noop-cast
5797 // this just removes a noop cast which isn't pointful, but simplifies
5798 // the code. If this is a zero-extension, we need to do an AND to
5799 // maintain the clear top-part of the computation, so we require that
5800 // the input have eliminated at least one cast. If this is a sign
5801 // extension, we insert two new casts (to do the extension) so we
5802 // require that two casts have been eliminated.
5803 bool DoXForm = CI.isNoopCast(TD->getIntPtrType());
5804 if (!DoXForm) {
5805 switch (CI.getOpcode()) {
5806 case Instruction::Trunc:
5807 DoXForm = true;
5808 break;
5809 case Instruction::ZExt:
5810 DoXForm = NumCastsRemoved >= 1;
5811 break;
5812 case Instruction::SExt:
5813 DoXForm = NumCastsRemoved >= 2;
5814 break;
5815 case Instruction::BitCast:
5816 DoXForm = false;
5817 break;
5818 default:
5819 // All the others use floating point so we shouldn't actually
5820 // get here because of the check above.
5821 assert(!"Unknown cast type .. unreachable");
5822 break;
5823 }
5824 }
5825
5826 if (DoXForm) {
5827 Value *Res = EvaluateInDifferentType(SrcI, DestTy);
5828 assert(Res->getType() == DestTy);
5829 switch (CI.getOpcode()) {
5830 default: assert(0 && "Unknown cast type!");
5831 case Instruction::Trunc:
5832 case Instruction::BitCast:
5833 // Just replace this cast with the result.
5834 return ReplaceInstUsesWith(CI, Res);
5835 case Instruction::ZExt: {
5836 // We need to emit an AND to clear the high bits.
5837 assert(SrcBitSize < DestBitSize && "Not a zext?");
5838 Constant *C =
5839 ConstantInt::get(Type::ULongTy, (1ULL << SrcBitSize)-1);
5840 if (DestBitSize < 64)
5841 C = ConstantExpr::getTrunc(C, DestTy);
5842 else {
5843 assert(DestBitSize == 64);
5844 C = ConstantExpr::getBitCast(C, DestTy);
5845 }
5846 return BinaryOperator::createAnd(Res, C);
5847 }
5848 case Instruction::SExt:
5849 // We need to emit a cast to truncate, then a cast to sext.
5850 return CastInst::create(Instruction::SExt,
Reid Spencer13bc5d72006-12-12 09:18:51 +00005851 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
5852 CI), DestTy);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005853 }
5854 }
5855 }
5856
5857 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
5858 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
5859
5860 switch (SrcI->getOpcode()) {
5861 case Instruction::Add:
5862 case Instruction::Mul:
5863 case Instruction::And:
5864 case Instruction::Or:
5865 case Instruction::Xor:
5866 // If we are discarding information, or just changing the sign,
5867 // rewrite.
5868 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
5869 // Don't insert two casts if they cannot be eliminated. We allow
5870 // two casts to be inserted if the sizes are the same. This could
5871 // only be converting signedness, which is a noop.
5872 if (DestBitSize == SrcBitSize ||
5873 !ValueRequiresCast(Op1, DestTy,TD) ||
5874 !ValueRequiresCast(Op0, DestTy, TD)) {
Reid Spencer2a499b02006-12-13 17:19:09 +00005875 Instruction::CastOps opcode = CI.getOpcode();
Reid Spencer13bc5d72006-12-12 09:18:51 +00005876 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
5877 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
5878 return BinaryOperator::create(
5879 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005880 }
5881 }
5882
5883 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
5884 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
5885 SrcI->getOpcode() == Instruction::Xor &&
5886 Op1 == ConstantBool::getTrue() &&
5887 (!Op0->hasOneUse() || !isa<SetCondInst>(Op0))) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00005888 Value *New = InsertOperandCastBefore(Instruction::ZExt, Op0, DestTy, &CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005889 return BinaryOperator::createXor(New, ConstantInt::get(CI.getType(), 1));
5890 }
5891 break;
5892 case Instruction::SDiv:
5893 case Instruction::UDiv:
5894 case Instruction::SRem:
5895 case Instruction::URem:
5896 // If we are just changing the sign, rewrite.
5897 if (DestBitSize == SrcBitSize) {
5898 // Don't insert two casts if they cannot be eliminated. We allow
5899 // two casts to be inserted if the sizes are the same. This could
5900 // only be converting signedness, which is a noop.
5901 if (!ValueRequiresCast(Op1, DestTy,TD) ||
5902 !ValueRequiresCast(Op0, DestTy, TD)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00005903 Value *Op0c = InsertOperandCastBefore(Instruction::BitCast,
5904 Op0, DestTy, SrcI);
5905 Value *Op1c = InsertOperandCastBefore(Instruction::BitCast,
5906 Op1, DestTy, SrcI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005907 return BinaryOperator::create(
5908 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
5909 }
5910 }
5911 break;
5912
5913 case Instruction::Shl:
5914 // Allow changing the sign of the source operand. Do not allow
5915 // changing the size of the shift, UNLESS the shift amount is a
5916 // constant. We must not change variable sized shifts to a smaller
5917 // size, because it is undefined to shift more bits out than exist
5918 // in the value.
5919 if (DestBitSize == SrcBitSize ||
5920 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00005921 Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
5922 Instruction::BitCast : Instruction::Trunc);
5923 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005924 return new ShiftInst(Instruction::Shl, Op0c, Op1);
5925 }
5926 break;
5927 case Instruction::AShr:
5928 // If this is a signed shr, and if all bits shifted in are about to be
5929 // truncated off, turn it into an unsigned shr to allow greater
5930 // simplifications.
5931 if (DestBitSize < SrcBitSize &&
5932 isa<ConstantInt>(Op1)) {
5933 unsigned ShiftAmt = cast<ConstantInt>(Op1)->getZExtValue();
5934 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
5935 // Insert the new logical shift right.
5936 return new ShiftInst(Instruction::LShr, Op0, Op1);
5937 }
5938 }
5939 break;
5940
5941 case Instruction::SetEQ:
5942 case Instruction::SetNE:
5943 // If we are just checking for a seteq of a single bit and casting it
5944 // to an integer. If so, shift the bit to the appropriate place then
5945 // cast to integer to avoid the comparison.
5946 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
5947 uint64_t Op1CV = Op1C->getZExtValue();
5948 // cast (X == 0) to int --> X^1 iff X has only the low bit set.
5949 // cast (X == 0) to int --> (X>>1)^1 iff X has only the 2nd bit set.
5950 // cast (X == 1) to int --> X iff X has only the low bit set.
5951 // cast (X == 2) to int --> X>>1 iff X has only the 2nd bit set.
5952 // cast (X != 0) to int --> X iff X has only the low bit set.
5953 // cast (X != 0) to int --> X>>1 iff X has only the 2nd bit set.
5954 // cast (X != 1) to int --> X^1 iff X has only the low bit set.
5955 // cast (X != 2) to int --> (X>>1)^1 iff X has only the 2nd bit set.
5956 if (Op1CV == 0 || isPowerOf2_64(Op1CV)) {
5957 // If Op1C some other power of two, convert:
5958 uint64_t KnownZero, KnownOne;
5959 uint64_t TypeMask = Op1->getType()->getIntegralTypeMask();
5960 ComputeMaskedBits(Op0, TypeMask, KnownZero, KnownOne);
5961
5962 if (isPowerOf2_64(KnownZero^TypeMask)) { // Exactly 1 possible 1?
5963 bool isSetNE = SrcI->getOpcode() == Instruction::SetNE;
5964 if (Op1CV && (Op1CV != (KnownZero^TypeMask))) {
5965 // (X&4) == 2 --> false
5966 // (X&4) != 2 --> true
5967 Constant *Res = ConstantBool::get(isSetNE);
Reid Spencerbb65ebf2006-12-12 23:36:14 +00005968 Res = ConstantExpr::getZExt(Res, CI.getType());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005969 return ReplaceInstUsesWith(CI, Res);
5970 }
5971
5972 unsigned ShiftAmt = Log2_64(KnownZero^TypeMask);
5973 Value *In = Op0;
5974 if (ShiftAmt) {
5975 // Perform a logical shr by shiftamt.
5976 // Insert the shift to put the result in the low bit.
5977 In = InsertNewInstBefore(
5978 new ShiftInst(Instruction::LShr, In,
5979 ConstantInt::get(Type::UByteTy, ShiftAmt),
5980 In->getName()+".lobit"), CI);
5981 }
5982
5983 if ((Op1CV != 0) == isSetNE) { // Toggle the low bit.
5984 Constant *One = ConstantInt::get(In->getType(), 1);
5985 In = BinaryOperator::createXor(In, One, "tmp");
5986 InsertNewInstBefore(cast<Instruction>(In), CI);
5987 }
5988
5989 if (CI.getType() == In->getType())
5990 return ReplaceInstUsesWith(CI, In);
5991 else
Reid Spencerbb65ebf2006-12-12 23:36:14 +00005992 return CastInst::createIntegerCast(In, CI.getType(), false/*ZExt*/);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005993 }
5994 }
5995 }
5996 break;
5997 }
5998 return 0;
5999}
6000
6001Instruction *InstCombiner::visitTrunc(CastInst &CI) {
Chris Lattnerd747f012006-11-29 07:04:07 +00006002 if (Instruction *Result = commonIntCastTransforms(CI))
6003 return Result;
6004
6005 Value *Src = CI.getOperand(0);
6006 const Type *Ty = CI.getType();
6007 unsigned DestBitWidth = Ty->getPrimitiveSizeInBits();
6008
6009 if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
6010 switch (SrcI->getOpcode()) {
6011 default: break;
6012 case Instruction::LShr:
6013 // We can shrink lshr to something smaller if we know the bits shifted in
6014 // are already zeros.
6015 if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
6016 unsigned ShAmt = ShAmtV->getZExtValue();
6017
6018 // Get a mask for the bits shifting in.
6019 uint64_t Mask = (~0ULL >> (64-ShAmt)) << DestBitWidth;
Reid Spencer13bc5d72006-12-12 09:18:51 +00006020 Value* SrcIOp0 = SrcI->getOperand(0);
6021 if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
Chris Lattnerd747f012006-11-29 07:04:07 +00006022 if (ShAmt >= DestBitWidth) // All zeros.
6023 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
6024
6025 // Okay, we can shrink this. Truncate the input, then return a new
6026 // shift.
Reid Spencer2a499b02006-12-13 17:19:09 +00006027 Value *V = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
Chris Lattnerd747f012006-11-29 07:04:07 +00006028 return new ShiftInst(Instruction::LShr, V, SrcI->getOperand(1));
6029 }
Chris Lattnerc209b582006-12-05 01:26:29 +00006030 } else { // This is a variable shr.
6031
6032 // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'. This is
6033 // more LLVM instructions, but allows '1 << Y' to be hoisted if
6034 // loop-invariant and CSE'd.
6035 if (CI.getType() == Type::BoolTy && SrcI->hasOneUse()) {
6036 Value *One = ConstantInt::get(SrcI->getType(), 1);
6037
6038 Value *V = InsertNewInstBefore(new ShiftInst(Instruction::Shl, One,
6039 SrcI->getOperand(1),
6040 "tmp"), CI);
6041 V = InsertNewInstBefore(BinaryOperator::createAnd(V,
6042 SrcI->getOperand(0),
6043 "tmp"), CI);
6044 Value *Zero = Constant::getNullValue(V->getType());
6045 return BinaryOperator::createSetNE(V, Zero);
6046 }
Chris Lattnerd747f012006-11-29 07:04:07 +00006047 }
6048 break;
6049 }
6050 }
6051
6052 return 0;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006053}
6054
6055Instruction *InstCombiner::visitZExt(CastInst &CI) {
6056 // If one of the common conversion will work ..
6057 if (Instruction *Result = commonIntCastTransforms(CI))
6058 return Result;
6059
6060 Value *Src = CI.getOperand(0);
6061
6062 // If this is a cast of a cast
6063 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006064 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
6065 // types and if the sizes are just right we can convert this into a logical
6066 // 'and' which will be much cheaper than the pair of casts.
6067 if (isa<TruncInst>(CSrc)) {
6068 // Get the sizes of the types involved
6069 Value *A = CSrc->getOperand(0);
6070 unsigned SrcSize = A->getType()->getPrimitiveSizeInBits();
6071 unsigned MidSize = CSrc->getType()->getPrimitiveSizeInBits();
6072 unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
6073 // If we're actually extending zero bits and the trunc is a no-op
6074 if (MidSize < DstSize && SrcSize == DstSize) {
6075 // Replace both of the casts with an And of the type mask.
6076 uint64_t AndValue = CSrc->getType()->getIntegralTypeMask();
6077 Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
6078 Instruction *And =
6079 BinaryOperator::createAnd(CSrc->getOperand(0), AndConst);
6080 // Unfortunately, if the type changed, we need to cast it back.
6081 if (And->getType() != CI.getType()) {
6082 And->setName(CSrc->getName()+".mask");
6083 InsertNewInstBefore(And, CI);
Reid Spencerbb65ebf2006-12-12 23:36:14 +00006084 And = CastInst::createIntegerCast(And, CI.getType(), false/*ZExt*/);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006085 }
6086 return And;
6087 }
6088 }
6089 }
6090
6091 return 0;
6092}
6093
6094Instruction *InstCombiner::visitSExt(CastInst &CI) {
6095 return commonIntCastTransforms(CI);
6096}
6097
6098Instruction *InstCombiner::visitFPTrunc(CastInst &CI) {
6099 return commonCastTransforms(CI);
6100}
6101
6102Instruction *InstCombiner::visitFPExt(CastInst &CI) {
6103 return commonCastTransforms(CI);
6104}
6105
6106Instruction *InstCombiner::visitFPToUI(CastInst &CI) {
Reid Spencerad05ee92006-11-30 23:13:36 +00006107 return commonCastTransforms(CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006108}
6109
6110Instruction *InstCombiner::visitFPToSI(CastInst &CI) {
Reid Spencerad05ee92006-11-30 23:13:36 +00006111 return commonCastTransforms(CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006112}
6113
6114Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
6115 return commonCastTransforms(CI);
6116}
6117
6118Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
6119 return commonCastTransforms(CI);
6120}
6121
6122Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
Reid Spencerad05ee92006-11-30 23:13:36 +00006123 return commonCastTransforms(CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006124}
6125
6126Instruction *InstCombiner::visitIntToPtr(CastInst &CI) {
6127 return commonCastTransforms(CI);
6128}
6129
6130Instruction *InstCombiner::visitBitCast(CastInst &CI) {
6131
6132 // If the operands are integer typed then apply the integer transforms,
6133 // otherwise just apply the common ones.
6134 Value *Src = CI.getOperand(0);
6135 const Type *SrcTy = Src->getType();
6136 const Type *DestTy = CI.getType();
6137
6138 if (SrcTy->isInteger() && DestTy->isInteger()) {
6139 if (Instruction *Result = commonIntCastTransforms(CI))
6140 return Result;
6141 } else {
6142 if (Instruction *Result = commonCastTransforms(CI))
6143 return Result;
6144 }
6145
6146
6147 // Get rid of casts from one type to the same type. These are useless and can
6148 // be replaced by the operand.
6149 if (DestTy == Src->getType())
6150 return ReplaceInstUsesWith(CI, Src);
6151
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006152 // If the source and destination are pointers, and this cast is equivalent to
6153 // a getelementptr X, 0, 0, 0... turn it into the appropriate getelementptr.
6154 // This can enhance SROA and other transforms that want type-safe pointers.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006155 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
6156 if (const PointerType *SrcPTy = dyn_cast<PointerType>(SrcTy)) {
6157 const Type *DstElTy = DstPTy->getElementType();
6158 const Type *SrcElTy = SrcPTy->getElementType();
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006159
6160 Constant *ZeroUInt = Constant::getNullValue(Type::UIntTy);
6161 unsigned NumZeros = 0;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006162 while (SrcElTy != DstElTy &&
6163 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
6164 SrcElTy->getNumContainedTypes() /* not "{}" */) {
6165 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006166 ++NumZeros;
6167 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00006168
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006169 // If we found a path from the src to dest, create the getelementptr now.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006170 if (SrcElTy == DstElTy) {
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006171 std::vector<Value*> Idxs(NumZeros+1, ZeroUInt);
6172 return new GetElementPtrInst(Src, Idxs);
6173 }
6174 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006175 }
Chris Lattnerdfae8be2003-07-24 17:35:25 +00006176
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006177 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
6178 if (SVI->hasOneUse()) {
6179 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
6180 // a bitconvert to a vector with the same # elts.
6181 if (isa<PackedType>(DestTy) &&
6182 cast<PackedType>(DestTy)->getNumElements() ==
6183 SVI->getType()->getNumElements()) {
6184 CastInst *Tmp;
6185 // If either of the operands is a cast from CI.getType(), then
6186 // evaluating the shuffle in the casted destination's type will allow
6187 // us to eliminate at least one cast.
6188 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
6189 Tmp->getOperand(0)->getType() == DestTy) ||
6190 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
6191 Tmp->getOperand(0)->getType() == DestTy)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00006192 Value *LHS = InsertOperandCastBefore(Instruction::BitCast,
6193 SVI->getOperand(0), DestTy, &CI);
6194 Value *RHS = InsertOperandCastBefore(Instruction::BitCast,
6195 SVI->getOperand(1), DestTy, &CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006196 // Return a new shuffle vector. Use the same element ID's, as we
6197 // know the vector types match #elts.
6198 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner99155be2006-05-25 23:24:33 +00006199 }
6200 }
6201 }
6202 }
Chris Lattner260ab202002-04-18 17:39:14 +00006203 return 0;
Chris Lattnerca081252001-12-14 16:52:21 +00006204}
6205
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006206/// GetSelectFoldableOperands - We want to turn code that looks like this:
6207/// %C = or %A, %B
6208/// %D = select %cond, %C, %A
6209/// into:
6210/// %C = select %cond, %B, 0
6211/// %D = or %A, %C
6212///
6213/// Assuming that the specified instruction is an operand to the select, return
6214/// a bitmask indicating which operands of this instruction are foldable if they
6215/// equal the other incoming value of the select.
6216///
6217static unsigned GetSelectFoldableOperands(Instruction *I) {
6218 switch (I->getOpcode()) {
6219 case Instruction::Add:
6220 case Instruction::Mul:
6221 case Instruction::And:
6222 case Instruction::Or:
6223 case Instruction::Xor:
6224 return 3; // Can fold through either operand.
6225 case Instruction::Sub: // Can only fold on the amount subtracted.
6226 case Instruction::Shl: // Can only fold on the shift amount.
Reid Spencerfdff9382006-11-08 06:47:33 +00006227 case Instruction::LShr:
6228 case Instruction::AShr:
Misha Brukmanb1c93172005-04-21 23:48:37 +00006229 return 1;
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006230 default:
6231 return 0; // Cannot fold
6232 }
6233}
6234
6235/// GetSelectFoldableConstant - For the same transformation as the previous
6236/// function, return the identity constant that goes into the select.
6237static Constant *GetSelectFoldableConstant(Instruction *I) {
6238 switch (I->getOpcode()) {
6239 default: assert(0 && "This cannot happen!"); abort();
6240 case Instruction::Add:
6241 case Instruction::Sub:
6242 case Instruction::Or:
6243 case Instruction::Xor:
6244 return Constant::getNullValue(I->getType());
6245 case Instruction::Shl:
Reid Spencerfdff9382006-11-08 06:47:33 +00006246 case Instruction::LShr:
6247 case Instruction::AShr:
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006248 return Constant::getNullValue(Type::UByteTy);
6249 case Instruction::And:
6250 return ConstantInt::getAllOnesValue(I->getType());
6251 case Instruction::Mul:
6252 return ConstantInt::get(I->getType(), 1);
6253 }
6254}
6255
Chris Lattner411336f2005-01-19 21:50:18 +00006256/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
6257/// have the same opcode and only one use each. Try to simplify this.
6258Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
6259 Instruction *FI) {
6260 if (TI->getNumOperands() == 1) {
6261 // If this is a non-volatile load or a cast from the same type,
6262 // merge.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006263 if (TI->isCast()) {
Chris Lattner411336f2005-01-19 21:50:18 +00006264 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
6265 return 0;
6266 } else {
6267 return 0; // unknown unary op.
6268 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00006269
Chris Lattner411336f2005-01-19 21:50:18 +00006270 // Fold this by inserting a select from the input values.
6271 SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
6272 FI->getOperand(0), SI.getName()+".v");
6273 InsertNewInstBefore(NewSI, SI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006274 return CastInst::create(Instruction::CastOps(TI->getOpcode()), NewSI,
6275 TI->getType());
Chris Lattner411336f2005-01-19 21:50:18 +00006276 }
6277
6278 // Only handle binary operators here.
6279 if (!isa<ShiftInst>(TI) && !isa<BinaryOperator>(TI))
6280 return 0;
6281
6282 // Figure out if the operations have any operands in common.
6283 Value *MatchOp, *OtherOpT, *OtherOpF;
6284 bool MatchIsOpZero;
6285 if (TI->getOperand(0) == FI->getOperand(0)) {
6286 MatchOp = TI->getOperand(0);
6287 OtherOpT = TI->getOperand(1);
6288 OtherOpF = FI->getOperand(1);
6289 MatchIsOpZero = true;
6290 } else if (TI->getOperand(1) == FI->getOperand(1)) {
6291 MatchOp = TI->getOperand(1);
6292 OtherOpT = TI->getOperand(0);
6293 OtherOpF = FI->getOperand(0);
6294 MatchIsOpZero = false;
6295 } else if (!TI->isCommutative()) {
6296 return 0;
6297 } else if (TI->getOperand(0) == FI->getOperand(1)) {
6298 MatchOp = TI->getOperand(0);
6299 OtherOpT = TI->getOperand(1);
6300 OtherOpF = FI->getOperand(0);
6301 MatchIsOpZero = true;
6302 } else if (TI->getOperand(1) == FI->getOperand(0)) {
6303 MatchOp = TI->getOperand(1);
6304 OtherOpT = TI->getOperand(0);
6305 OtherOpF = FI->getOperand(1);
6306 MatchIsOpZero = true;
6307 } else {
6308 return 0;
6309 }
6310
6311 // If we reach here, they do have operations in common.
6312 SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
6313 OtherOpF, SI.getName()+".v");
6314 InsertNewInstBefore(NewSI, SI);
6315
6316 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
6317 if (MatchIsOpZero)
6318 return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
6319 else
6320 return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
6321 } else {
6322 if (MatchIsOpZero)
6323 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), MatchOp, NewSI);
6324 else
6325 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), NewSI, MatchOp);
6326 }
6327}
6328
Chris Lattnerb909e8b2004-03-12 05:52:32 +00006329Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattner533bc492004-03-30 19:37:13 +00006330 Value *CondVal = SI.getCondition();
6331 Value *TrueVal = SI.getTrueValue();
6332 Value *FalseVal = SI.getFalseValue();
6333
6334 // select true, X, Y -> X
6335 // select false, X, Y -> Y
6336 if (ConstantBool *C = dyn_cast<ConstantBool>(CondVal))
Chris Lattner6ab03f62006-09-28 23:35:22 +00006337 return ReplaceInstUsesWith(SI, C->getValue() ? TrueVal : FalseVal);
Chris Lattner533bc492004-03-30 19:37:13 +00006338
6339 // select C, X, X -> X
6340 if (TrueVal == FalseVal)
6341 return ReplaceInstUsesWith(SI, TrueVal);
6342
Chris Lattner81a7a232004-10-16 18:11:37 +00006343 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
6344 return ReplaceInstUsesWith(SI, FalseVal);
6345 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
6346 return ReplaceInstUsesWith(SI, TrueVal);
6347 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
6348 if (isa<Constant>(TrueVal))
6349 return ReplaceInstUsesWith(SI, TrueVal);
6350 else
6351 return ReplaceInstUsesWith(SI, FalseVal);
6352 }
6353
Chris Lattner1c631e82004-04-08 04:43:23 +00006354 if (SI.getType() == Type::BoolTy)
6355 if (ConstantBool *C = dyn_cast<ConstantBool>(TrueVal)) {
Chris Lattner6ab03f62006-09-28 23:35:22 +00006356 if (C->getValue()) {
Chris Lattner1c631e82004-04-08 04:43:23 +00006357 // Change: A = select B, true, C --> A = or B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00006358 return BinaryOperator::createOr(CondVal, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00006359 } else {
6360 // Change: A = select B, false, C --> A = and !B, C
6361 Value *NotCond =
6362 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
6363 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00006364 return BinaryOperator::createAnd(NotCond, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00006365 }
6366 } else if (ConstantBool *C = dyn_cast<ConstantBool>(FalseVal)) {
Chris Lattner6ab03f62006-09-28 23:35:22 +00006367 if (C->getValue() == false) {
Chris Lattner1c631e82004-04-08 04:43:23 +00006368 // Change: A = select B, C, false --> A = and B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00006369 return BinaryOperator::createAnd(CondVal, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00006370 } else {
6371 // Change: A = select B, C, true --> A = or !B, C
6372 Value *NotCond =
6373 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
6374 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00006375 return BinaryOperator::createOr(NotCond, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00006376 }
6377 }
6378
Chris Lattner183b3362004-04-09 19:05:30 +00006379 // Selecting between two integer constants?
6380 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
6381 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
6382 // select C, 1, 0 -> cast C to int
Reid Spencere0fc4df2006-10-20 07:07:24 +00006383 if (FalseValC->isNullValue() && TrueValC->getZExtValue() == 1) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006384 return CastInst::create(Instruction::ZExt, CondVal, SI.getType());
Reid Spencere0fc4df2006-10-20 07:07:24 +00006385 } else if (TrueValC->isNullValue() && FalseValC->getZExtValue() == 1) {
Chris Lattner183b3362004-04-09 19:05:30 +00006386 // select C, 0, 1 -> cast !C to int
6387 Value *NotCond =
6388 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
Chris Lattnercf7baf32004-04-09 18:19:44 +00006389 "not."+CondVal->getName()), SI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006390 return CastInst::create(Instruction::ZExt, NotCond, SI.getType());
Chris Lattnercf7baf32004-04-09 18:19:44 +00006391 }
Chris Lattner35167c32004-06-09 07:59:58 +00006392
Chris Lattner380c7e92006-09-20 04:44:59 +00006393 if (SetCondInst *IC = dyn_cast<SetCondInst>(SI.getCondition())) {
6394
6395 // (x <s 0) ? -1 : 0 -> sra x, 31
6396 // (x >u 2147483647) ? -1 : 0 -> sra x, 31
6397 if (TrueValC->isAllOnesValue() && FalseValC->isNullValue())
6398 if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
6399 bool CanXForm = false;
6400 if (CmpCst->getType()->isSigned())
6401 CanXForm = CmpCst->isNullValue() &&
6402 IC->getOpcode() == Instruction::SetLT;
6403 else {
6404 unsigned Bits = CmpCst->getType()->getPrimitiveSizeInBits();
Reid Spencere0fc4df2006-10-20 07:07:24 +00006405 CanXForm = (CmpCst->getZExtValue() == ~0ULL >> (64-Bits+1)) &&
Chris Lattner380c7e92006-09-20 04:44:59 +00006406 IC->getOpcode() == Instruction::SetGT;
6407 }
6408
6409 if (CanXForm) {
6410 // The comparison constant and the result are not neccessarily the
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006411 // same width. Make an all-ones value by inserting a AShr.
Chris Lattner380c7e92006-09-20 04:44:59 +00006412 Value *X = IC->getOperand(0);
Chris Lattner380c7e92006-09-20 04:44:59 +00006413 unsigned Bits = X->getType()->getPrimitiveSizeInBits();
Reid Spencere0fc4df2006-10-20 07:07:24 +00006414 Constant *ShAmt = ConstantInt::get(Type::UByteTy, Bits-1);
Reid Spencerfdff9382006-11-08 06:47:33 +00006415 Instruction *SRA = new ShiftInst(Instruction::AShr, X,
Chris Lattner380c7e92006-09-20 04:44:59 +00006416 ShAmt, "ones");
6417 InsertNewInstBefore(SRA, SI);
6418
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006419 // Finally, convert to the type of the select RHS. We figure out
6420 // if this requires a SExt, Trunc or BitCast based on the sizes.
6421 Instruction::CastOps opc = Instruction::BitCast;
6422 unsigned SRASize = SRA->getType()->getPrimitiveSizeInBits();
6423 unsigned SISize = SI.getType()->getPrimitiveSizeInBits();
6424 if (SRASize < SISize)
6425 opc = Instruction::SExt;
6426 else if (SRASize > SISize)
6427 opc = Instruction::Trunc;
6428 return CastInst::create(opc, SRA, SI.getType());
Chris Lattner380c7e92006-09-20 04:44:59 +00006429 }
6430 }
6431
6432
6433 // If one of the constants is zero (we know they can't both be) and we
6434 // have a setcc instruction with zero, and we have an 'and' with the
6435 // non-constant value, eliminate this whole mess. This corresponds to
6436 // cases like this: ((X & 27) ? 27 : 0)
6437 if (TrueValC->isNullValue() || FalseValC->isNullValue())
Chris Lattnerb3f24c92006-09-18 04:22:48 +00006438 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner35167c32004-06-09 07:59:58 +00006439 cast<Constant>(IC->getOperand(1))->isNullValue())
6440 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
6441 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00006442 isa<ConstantInt>(ICA->getOperand(1)) &&
6443 (ICA->getOperand(1) == TrueValC ||
6444 ICA->getOperand(1) == FalseValC) &&
Chris Lattner35167c32004-06-09 07:59:58 +00006445 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
6446 // Okay, now we know that everything is set up, we just don't
6447 // know whether we have a setne or seteq and whether the true or
6448 // false val is the zero.
6449 bool ShouldNotVal = !TrueValC->isNullValue();
6450 ShouldNotVal ^= IC->getOpcode() == Instruction::SetNE;
6451 Value *V = ICA;
6452 if (ShouldNotVal)
6453 V = InsertNewInstBefore(BinaryOperator::create(
6454 Instruction::Xor, V, ICA->getOperand(1)), SI);
6455 return ReplaceInstUsesWith(SI, V);
6456 }
Chris Lattner380c7e92006-09-20 04:44:59 +00006457 }
Chris Lattner533bc492004-03-30 19:37:13 +00006458 }
Chris Lattner623fba12004-04-10 22:21:27 +00006459
6460 // See if we are selecting two values based on a comparison of the two values.
6461 if (SetCondInst *SCI = dyn_cast<SetCondInst>(CondVal)) {
6462 if (SCI->getOperand(0) == TrueVal && SCI->getOperand(1) == FalseVal) {
6463 // Transform (X == Y) ? X : Y -> Y
6464 if (SCI->getOpcode() == Instruction::SetEQ)
6465 return ReplaceInstUsesWith(SI, FalseVal);
6466 // Transform (X != Y) ? X : Y -> X
6467 if (SCI->getOpcode() == Instruction::SetNE)
6468 return ReplaceInstUsesWith(SI, TrueVal);
6469 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6470
6471 } else if (SCI->getOperand(0) == FalseVal && SCI->getOperand(1) == TrueVal){
6472 // Transform (X == Y) ? Y : X -> X
6473 if (SCI->getOpcode() == Instruction::SetEQ)
Chris Lattner24cf0202004-04-11 01:39:19 +00006474 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattner623fba12004-04-10 22:21:27 +00006475 // Transform (X != Y) ? Y : X -> Y
6476 if (SCI->getOpcode() == Instruction::SetNE)
Chris Lattner24cf0202004-04-11 01:39:19 +00006477 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattner623fba12004-04-10 22:21:27 +00006478 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6479 }
6480 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00006481
Chris Lattnera04c9042005-01-13 22:52:24 +00006482 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
6483 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
6484 if (TI->hasOneUse() && FI->hasOneUse()) {
Chris Lattnera04c9042005-01-13 22:52:24 +00006485 Instruction *AddOp = 0, *SubOp = 0;
6486
Chris Lattner411336f2005-01-19 21:50:18 +00006487 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
6488 if (TI->getOpcode() == FI->getOpcode())
6489 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
6490 return IV;
6491
6492 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
6493 // even legal for FP.
Chris Lattnera04c9042005-01-13 22:52:24 +00006494 if (TI->getOpcode() == Instruction::Sub &&
6495 FI->getOpcode() == Instruction::Add) {
6496 AddOp = FI; SubOp = TI;
6497 } else if (FI->getOpcode() == Instruction::Sub &&
6498 TI->getOpcode() == Instruction::Add) {
6499 AddOp = TI; SubOp = FI;
6500 }
6501
6502 if (AddOp) {
6503 Value *OtherAddOp = 0;
6504 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
6505 OtherAddOp = AddOp->getOperand(1);
6506 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
6507 OtherAddOp = AddOp->getOperand(0);
6508 }
6509
6510 if (OtherAddOp) {
Chris Lattnerb580d262006-02-24 18:05:58 +00006511 // So at this point we know we have (Y -> OtherAddOp):
6512 // select C, (add X, Y), (sub X, Z)
6513 Value *NegVal; // Compute -Z
6514 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
6515 NegVal = ConstantExpr::getNeg(C);
6516 } else {
6517 NegVal = InsertNewInstBefore(
6518 BinaryOperator::createNeg(SubOp->getOperand(1), "tmp"), SI);
Chris Lattnera04c9042005-01-13 22:52:24 +00006519 }
Chris Lattnerb580d262006-02-24 18:05:58 +00006520
6521 Value *NewTrueOp = OtherAddOp;
6522 Value *NewFalseOp = NegVal;
6523 if (AddOp != TI)
6524 std::swap(NewTrueOp, NewFalseOp);
6525 Instruction *NewSel =
6526 new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
6527
6528 NewSel = InsertNewInstBefore(NewSel, SI);
6529 return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
Chris Lattnera04c9042005-01-13 22:52:24 +00006530 }
6531 }
6532 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00006533
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006534 // See if we can fold the select into one of our operands.
6535 if (SI.getType()->isInteger()) {
6536 // See the comment above GetSelectFoldableOperands for a description of the
6537 // transformation we are doing here.
6538 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
6539 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
6540 !isa<Constant>(FalseVal))
6541 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
6542 unsigned OpToFold = 0;
6543 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
6544 OpToFold = 1;
6545 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
6546 OpToFold = 2;
6547 }
6548
6549 if (OpToFold) {
6550 Constant *C = GetSelectFoldableConstant(TVI);
6551 std::string Name = TVI->getName(); TVI->setName("");
6552 Instruction *NewSel =
6553 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C,
6554 Name);
6555 InsertNewInstBefore(NewSel, SI);
6556 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
6557 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
6558 else if (ShiftInst *SI = dyn_cast<ShiftInst>(TVI))
6559 return new ShiftInst(SI->getOpcode(), FalseVal, NewSel);
6560 else {
6561 assert(0 && "Unknown instruction!!");
6562 }
6563 }
6564 }
Chris Lattner6862fbd2004-09-29 17:40:11 +00006565
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006566 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
6567 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
6568 !isa<Constant>(TrueVal))
6569 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
6570 unsigned OpToFold = 0;
6571 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
6572 OpToFold = 1;
6573 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
6574 OpToFold = 2;
6575 }
6576
6577 if (OpToFold) {
6578 Constant *C = GetSelectFoldableConstant(FVI);
6579 std::string Name = FVI->getName(); FVI->setName("");
6580 Instruction *NewSel =
6581 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold),
6582 Name);
6583 InsertNewInstBefore(NewSel, SI);
6584 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
6585 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
6586 else if (ShiftInst *SI = dyn_cast<ShiftInst>(FVI))
6587 return new ShiftInst(SI->getOpcode(), TrueVal, NewSel);
6588 else {
6589 assert(0 && "Unknown instruction!!");
6590 }
6591 }
6592 }
6593 }
Chris Lattnerd6f636a2005-04-24 07:30:14 +00006594
6595 if (BinaryOperator::isNot(CondVal)) {
6596 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
6597 SI.setOperand(1, FalseVal);
6598 SI.setOperand(2, TrueVal);
6599 return &SI;
6600 }
6601
Chris Lattnerb909e8b2004-03-12 05:52:32 +00006602 return 0;
6603}
6604
Chris Lattner82f2ef22006-03-06 20:18:44 +00006605/// GetKnownAlignment - If the specified pointer has an alignment that we can
6606/// determine, return it, otherwise return 0.
6607static unsigned GetKnownAlignment(Value *V, TargetData *TD) {
6608 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
6609 unsigned Align = GV->getAlignment();
6610 if (Align == 0 && TD)
6611 Align = TD->getTypeAlignment(GV->getType()->getElementType());
6612 return Align;
6613 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
6614 unsigned Align = AI->getAlignment();
6615 if (Align == 0 && TD) {
6616 if (isa<AllocaInst>(AI))
6617 Align = TD->getTypeAlignment(AI->getType()->getElementType());
6618 else if (isa<MallocInst>(AI)) {
6619 // Malloc returns maximally aligned memory.
6620 Align = TD->getTypeAlignment(AI->getType()->getElementType());
6621 Align = std::max(Align, (unsigned)TD->getTypeAlignment(Type::DoubleTy));
6622 Align = std::max(Align, (unsigned)TD->getTypeAlignment(Type::LongTy));
6623 }
6624 }
6625 return Align;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006626 } else if (isa<BitCastInst>(V) ||
Chris Lattner53ef5a02006-03-07 01:28:57 +00006627 (isa<ConstantExpr>(V) &&
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006628 cast<ConstantExpr>(V)->getOpcode() == Instruction::BitCast)) {
Chris Lattner53ef5a02006-03-07 01:28:57 +00006629 User *CI = cast<User>(V);
Chris Lattner82f2ef22006-03-06 20:18:44 +00006630 if (isa<PointerType>(CI->getOperand(0)->getType()))
6631 return GetKnownAlignment(CI->getOperand(0), TD);
6632 return 0;
Chris Lattner53ef5a02006-03-07 01:28:57 +00006633 } else if (isa<GetElementPtrInst>(V) ||
6634 (isa<ConstantExpr>(V) &&
6635 cast<ConstantExpr>(V)->getOpcode()==Instruction::GetElementPtr)) {
6636 User *GEPI = cast<User>(V);
Chris Lattner82f2ef22006-03-06 20:18:44 +00006637 unsigned BaseAlignment = GetKnownAlignment(GEPI->getOperand(0), TD);
6638 if (BaseAlignment == 0) return 0;
6639
6640 // If all indexes are zero, it is just the alignment of the base pointer.
6641 bool AllZeroOperands = true;
6642 for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
6643 if (!isa<Constant>(GEPI->getOperand(i)) ||
6644 !cast<Constant>(GEPI->getOperand(i))->isNullValue()) {
6645 AllZeroOperands = false;
6646 break;
6647 }
6648 if (AllZeroOperands)
6649 return BaseAlignment;
6650
6651 // Otherwise, if the base alignment is >= the alignment we expect for the
6652 // base pointer type, then we know that the resultant pointer is aligned at
6653 // least as much as its type requires.
6654 if (!TD) return 0;
6655
6656 const Type *BasePtrTy = GEPI->getOperand(0)->getType();
6657 if (TD->getTypeAlignment(cast<PointerType>(BasePtrTy)->getElementType())
Chris Lattner53ef5a02006-03-07 01:28:57 +00006658 <= BaseAlignment) {
6659 const Type *GEPTy = GEPI->getType();
6660 return TD->getTypeAlignment(cast<PointerType>(GEPTy)->getElementType());
6661 }
Chris Lattner82f2ef22006-03-06 20:18:44 +00006662 return 0;
6663 }
6664 return 0;
6665}
6666
Chris Lattnerb909e8b2004-03-12 05:52:32 +00006667
Chris Lattnerc66b2232006-01-13 20:11:04 +00006668/// visitCallInst - CallInst simplification. This mostly only handles folding
6669/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
6670/// the heavy lifting.
6671///
Chris Lattner970c33a2003-06-19 17:00:31 +00006672Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattnerc66b2232006-01-13 20:11:04 +00006673 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
6674 if (!II) return visitCallSite(&CI);
6675
Chris Lattner51ea1272004-02-28 05:22:00 +00006676 // Intrinsics cannot occur in an invoke, so handle them here instead of in
6677 // visitCallSite.
Chris Lattnerc66b2232006-01-13 20:11:04 +00006678 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner00648e12004-10-12 04:52:52 +00006679 bool Changed = false;
6680
6681 // memmove/cpy/set of zero bytes is a noop.
6682 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
6683 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
6684
Chris Lattner00648e12004-10-12 04:52:52 +00006685 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencere0fc4df2006-10-20 07:07:24 +00006686 if (CI->getZExtValue() == 1) {
Chris Lattner00648e12004-10-12 04:52:52 +00006687 // Replace the instruction with just byte operations. We would
6688 // transform other cases to loads/stores, but we don't know if
6689 // alignment is sufficient.
6690 }
Chris Lattner51ea1272004-02-28 05:22:00 +00006691 }
6692
Chris Lattner00648e12004-10-12 04:52:52 +00006693 // If we have a memmove and the source operation is a constant global,
6694 // then the source and dest pointers can't alias, so we can change this
6695 // into a call to memcpy.
Chris Lattner82f2ef22006-03-06 20:18:44 +00006696 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(II)) {
Chris Lattner00648e12004-10-12 04:52:52 +00006697 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
6698 if (GVSrc->isConstant()) {
6699 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner681ef2f2006-03-03 01:34:17 +00006700 const char *Name;
Andrew Lenharth0ebb0b02006-11-03 22:45:50 +00006701 if (CI.getCalledFunction()->getFunctionType()->getParamType(2) ==
Chris Lattner681ef2f2006-03-03 01:34:17 +00006702 Type::UIntTy)
6703 Name = "llvm.memcpy.i32";
6704 else
6705 Name = "llvm.memcpy.i64";
6706 Function *MemCpy = M->getOrInsertFunction(Name,
Chris Lattner00648e12004-10-12 04:52:52 +00006707 CI.getCalledFunction()->getFunctionType());
6708 CI.setOperand(0, MemCpy);
6709 Changed = true;
6710 }
Chris Lattner82f2ef22006-03-06 20:18:44 +00006711 }
Chris Lattner00648e12004-10-12 04:52:52 +00006712
Chris Lattner82f2ef22006-03-06 20:18:44 +00006713 // If we can determine a pointer alignment that is bigger than currently
6714 // set, update the alignment.
6715 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
6716 unsigned Alignment1 = GetKnownAlignment(MI->getOperand(1), TD);
6717 unsigned Alignment2 = GetKnownAlignment(MI->getOperand(2), TD);
6718 unsigned Align = std::min(Alignment1, Alignment2);
Reid Spencere0fc4df2006-10-20 07:07:24 +00006719 if (MI->getAlignment()->getZExtValue() < Align) {
6720 MI->setAlignment(ConstantInt::get(Type::UIntTy, Align));
Chris Lattner82f2ef22006-03-06 20:18:44 +00006721 Changed = true;
6722 }
6723 } else if (isa<MemSetInst>(MI)) {
6724 unsigned Alignment = GetKnownAlignment(MI->getDest(), TD);
Reid Spencere0fc4df2006-10-20 07:07:24 +00006725 if (MI->getAlignment()->getZExtValue() < Alignment) {
6726 MI->setAlignment(ConstantInt::get(Type::UIntTy, Alignment));
Chris Lattner82f2ef22006-03-06 20:18:44 +00006727 Changed = true;
6728 }
6729 }
6730
Chris Lattnerc66b2232006-01-13 20:11:04 +00006731 if (Changed) return II;
Chris Lattner503221f2006-01-13 21:28:09 +00006732 } else {
6733 switch (II->getIntrinsicID()) {
6734 default: break;
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00006735 case Intrinsic::ppc_altivec_lvx:
6736 case Intrinsic::ppc_altivec_lvxl:
Chris Lattner36dd7c92006-04-17 22:26:56 +00006737 case Intrinsic::x86_sse_loadu_ps:
6738 case Intrinsic::x86_sse2_loadu_pd:
6739 case Intrinsic::x86_sse2_loadu_dq:
6740 // Turn PPC lvx -> load if the pointer is known aligned.
6741 // Turn X86 loadups -> load if the pointer is known aligned.
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00006742 if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00006743 Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(1),
Chris Lattnere79d2492006-04-06 19:19:17 +00006744 PointerType::get(II->getType()), CI);
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00006745 return new LoadInst(Ptr);
6746 }
6747 break;
6748 case Intrinsic::ppc_altivec_stvx:
6749 case Intrinsic::ppc_altivec_stvxl:
6750 // Turn stvx -> store if the pointer is known aligned.
6751 if (GetKnownAlignment(II->getOperand(2), TD) >= 16) {
Chris Lattnere79d2492006-04-06 19:19:17 +00006752 const Type *OpPtrTy = PointerType::get(II->getOperand(1)->getType());
Reid Spencer13bc5d72006-12-12 09:18:51 +00006753 Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(2),
6754 OpPtrTy, CI);
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00006755 return new StoreInst(II->getOperand(1), Ptr);
6756 }
6757 break;
Chris Lattner36dd7c92006-04-17 22:26:56 +00006758 case Intrinsic::x86_sse_storeu_ps:
6759 case Intrinsic::x86_sse2_storeu_pd:
6760 case Intrinsic::x86_sse2_storeu_dq:
6761 case Intrinsic::x86_sse2_storel_dq:
6762 // Turn X86 storeu -> store if the pointer is known aligned.
6763 if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
6764 const Type *OpPtrTy = PointerType::get(II->getOperand(2)->getType());
Reid Spencer13bc5d72006-12-12 09:18:51 +00006765 Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(1),
6766 OpPtrTy, CI);
Chris Lattner36dd7c92006-04-17 22:26:56 +00006767 return new StoreInst(II->getOperand(2), Ptr);
6768 }
6769 break;
Chris Lattner2deeaea2006-10-05 06:55:50 +00006770
6771 case Intrinsic::x86_sse_cvttss2si: {
6772 // These intrinsics only demands the 0th element of its input vector. If
6773 // we can simplify the input based on that, do so now.
6774 uint64_t UndefElts;
6775 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1,
6776 UndefElts)) {
6777 II->setOperand(1, V);
6778 return II;
6779 }
6780 break;
6781 }
6782
Chris Lattnere79d2492006-04-06 19:19:17 +00006783 case Intrinsic::ppc_altivec_vperm:
6784 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
6785 if (ConstantPacked *Mask = dyn_cast<ConstantPacked>(II->getOperand(3))) {
6786 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
6787
6788 // Check that all of the elements are integer constants or undefs.
6789 bool AllEltsOk = true;
6790 for (unsigned i = 0; i != 16; ++i) {
6791 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
6792 !isa<UndefValue>(Mask->getOperand(i))) {
6793 AllEltsOk = false;
6794 break;
6795 }
6796 }
6797
6798 if (AllEltsOk) {
6799 // Cast the input vectors to byte vectors.
Reid Spencer13bc5d72006-12-12 09:18:51 +00006800 Value *Op0 = InsertCastBefore(Instruction::BitCast,
6801 II->getOperand(1), Mask->getType(), CI);
6802 Value *Op1 = InsertCastBefore(Instruction::BitCast,
6803 II->getOperand(2), Mask->getType(), CI);
Chris Lattnere79d2492006-04-06 19:19:17 +00006804 Value *Result = UndefValue::get(Op0->getType());
6805
6806 // Only extract each element once.
6807 Value *ExtractedElts[32];
6808 memset(ExtractedElts, 0, sizeof(ExtractedElts));
6809
6810 for (unsigned i = 0; i != 16; ++i) {
6811 if (isa<UndefValue>(Mask->getOperand(i)))
6812 continue;
Reid Spencere0fc4df2006-10-20 07:07:24 +00006813 unsigned Idx =cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
Chris Lattnere79d2492006-04-06 19:19:17 +00006814 Idx &= 31; // Match the hardware behavior.
6815
6816 if (ExtractedElts[Idx] == 0) {
6817 Instruction *Elt =
Chris Lattner2deeaea2006-10-05 06:55:50 +00006818 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
Chris Lattnere79d2492006-04-06 19:19:17 +00006819 InsertNewInstBefore(Elt, CI);
6820 ExtractedElts[Idx] = Elt;
6821 }
6822
6823 // Insert this value into the result vector.
Chris Lattner2deeaea2006-10-05 06:55:50 +00006824 Result = new InsertElementInst(Result, ExtractedElts[Idx], i,"tmp");
Chris Lattnere79d2492006-04-06 19:19:17 +00006825 InsertNewInstBefore(cast<Instruction>(Result), CI);
6826 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006827 return CastInst::create(Instruction::BitCast, Result, CI.getType());
Chris Lattnere79d2492006-04-06 19:19:17 +00006828 }
6829 }
6830 break;
6831
Chris Lattner503221f2006-01-13 21:28:09 +00006832 case Intrinsic::stackrestore: {
6833 // If the save is right next to the restore, remove the restore. This can
6834 // happen when variable allocas are DCE'd.
6835 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
6836 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
6837 BasicBlock::iterator BI = SS;
6838 if (&*++BI == II)
6839 return EraseInstFromFunction(CI);
6840 }
6841 }
6842
6843 // If the stack restore is in a return/unwind block and if there are no
6844 // allocas or calls between the restore and the return, nuke the restore.
6845 TerminatorInst *TI = II->getParent()->getTerminator();
6846 if (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)) {
6847 BasicBlock::iterator BI = II;
6848 bool CannotRemove = false;
6849 for (++BI; &*BI != TI; ++BI) {
6850 if (isa<AllocaInst>(BI) ||
6851 (isa<CallInst>(BI) && !isa<IntrinsicInst>(BI))) {
6852 CannotRemove = true;
6853 break;
6854 }
6855 }
6856 if (!CannotRemove)
6857 return EraseInstFromFunction(CI);
6858 }
6859 break;
6860 }
6861 }
Chris Lattner00648e12004-10-12 04:52:52 +00006862 }
6863
Chris Lattnerc66b2232006-01-13 20:11:04 +00006864 return visitCallSite(II);
Chris Lattner970c33a2003-06-19 17:00:31 +00006865}
6866
6867// InvokeInst simplification
6868//
6869Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattneraec3d942003-10-07 22:32:43 +00006870 return visitCallSite(&II);
Chris Lattner970c33a2003-06-19 17:00:31 +00006871}
6872
Chris Lattneraec3d942003-10-07 22:32:43 +00006873// visitCallSite - Improvements for call and invoke instructions.
6874//
6875Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner75b4d1d2003-10-07 22:54:13 +00006876 bool Changed = false;
6877
6878 // If the callee is a constexpr cast of a function, attempt to move the cast
6879 // to the arguments of the call/invoke.
Chris Lattneraec3d942003-10-07 22:32:43 +00006880 if (transformConstExprCastCall(CS)) return 0;
6881
Chris Lattner75b4d1d2003-10-07 22:54:13 +00006882 Value *Callee = CS.getCalledValue();
Chris Lattner81a7a232004-10-16 18:11:37 +00006883
Chris Lattner61d9d812005-05-13 07:09:09 +00006884 if (Function *CalleeF = dyn_cast<Function>(Callee))
6885 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
6886 Instruction *OldCall = CS.getInstruction();
6887 // If the call and callee calling conventions don't match, this call must
6888 // be unreachable, as the call is undefined.
Chris Lattner6ab03f62006-09-28 23:35:22 +00006889 new StoreInst(ConstantBool::getTrue(),
Chris Lattner61d9d812005-05-13 07:09:09 +00006890 UndefValue::get(PointerType::get(Type::BoolTy)), OldCall);
6891 if (!OldCall->use_empty())
6892 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
6893 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
6894 return EraseInstFromFunction(*OldCall);
6895 return 0;
6896 }
6897
Chris Lattner8ba9ec92004-10-18 02:59:09 +00006898 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
6899 // This instruction is not reachable, just remove it. We insert a store to
6900 // undef so that we know that this code is not reachable, despite the fact
6901 // that we can't modify the CFG here.
Chris Lattner6ab03f62006-09-28 23:35:22 +00006902 new StoreInst(ConstantBool::getTrue(),
Chris Lattner8ba9ec92004-10-18 02:59:09 +00006903 UndefValue::get(PointerType::get(Type::BoolTy)),
6904 CS.getInstruction());
6905
6906 if (!CS.getInstruction()->use_empty())
6907 CS.getInstruction()->
6908 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
6909
6910 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
6911 // Don't break the CFG, insert a dummy cond branch.
6912 new BranchInst(II->getNormalDest(), II->getUnwindDest(),
Chris Lattner6ab03f62006-09-28 23:35:22 +00006913 ConstantBool::getTrue(), II);
Chris Lattner81a7a232004-10-16 18:11:37 +00006914 }
Chris Lattner8ba9ec92004-10-18 02:59:09 +00006915 return EraseInstFromFunction(*CS.getInstruction());
6916 }
Chris Lattner81a7a232004-10-16 18:11:37 +00006917
Chris Lattner75b4d1d2003-10-07 22:54:13 +00006918 const PointerType *PTy = cast<PointerType>(Callee->getType());
6919 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
6920 if (FTy->isVarArg()) {
6921 // See if we can optimize any arguments passed through the varargs area of
6922 // the call.
6923 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
6924 E = CS.arg_end(); I != E; ++I)
6925 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
6926 // If this cast does not effect the value passed through the varargs
6927 // area, we can eliminate the use of the cast.
6928 Value *Op = CI->getOperand(0);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006929 if (CI->isLosslessCast()) {
Chris Lattner75b4d1d2003-10-07 22:54:13 +00006930 *I = Op;
6931 Changed = true;
6932 }
6933 }
6934 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00006935
Chris Lattner75b4d1d2003-10-07 22:54:13 +00006936 return Changed ? CS.getInstruction() : 0;
Chris Lattneraec3d942003-10-07 22:32:43 +00006937}
6938
Chris Lattner970c33a2003-06-19 17:00:31 +00006939// transformConstExprCastCall - If the callee is a constexpr cast of a function,
6940// attempt to move the cast to the arguments of the call/invoke.
6941//
6942bool InstCombiner::transformConstExprCastCall(CallSite CS) {
6943 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
6944 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006945 if (CE->getOpcode() != Instruction::BitCast ||
6946 !isa<Function>(CE->getOperand(0)))
Chris Lattner970c33a2003-06-19 17:00:31 +00006947 return false;
Reid Spencer87436872004-07-18 00:38:32 +00006948 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner970c33a2003-06-19 17:00:31 +00006949 Instruction *Caller = CS.getInstruction();
6950
6951 // Okay, this is a cast from a function to a different type. Unless doing so
6952 // would cause a type conversion of one of our arguments, change this call to
6953 // be a direct call with arguments casted to the appropriate types.
6954 //
6955 const FunctionType *FT = Callee->getFunctionType();
6956 const Type *OldRetTy = Caller->getType();
6957
Chris Lattner1f7942f2004-01-14 06:06:08 +00006958 // Check to see if we are changing the return type...
6959 if (OldRetTy != FT->getReturnType()) {
6960 if (Callee->isExternal() &&
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006961 !Caller->use_empty() &&
6962 !(OldRetTy->canLosslesslyBitCastTo(FT->getReturnType()) ||
Andrew Lenharth61eae292006-04-20 14:56:47 +00006963 (isa<PointerType>(FT->getReturnType()) &&
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006964 TD->getIntPtrType()->canLosslesslyBitCastTo(OldRetTy)))
6965 )
Chris Lattner1f7942f2004-01-14 06:06:08 +00006966 return false; // Cannot transform this return value...
6967
6968 // If the callsite is an invoke instruction, and the return value is used by
6969 // a PHI node in a successor, we cannot change the return type of the call
6970 // because there is no place to put the cast instruction (without breaking
6971 // the critical edge). Bail out in this case.
6972 if (!Caller->use_empty())
6973 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
6974 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
6975 UI != E; ++UI)
6976 if (PHINode *PN = dyn_cast<PHINode>(*UI))
6977 if (PN->getParent() == II->getNormalDest() ||
Chris Lattnerfae8ab32004-02-08 21:44:31 +00006978 PN->getParent() == II->getUnwindDest())
Chris Lattner1f7942f2004-01-14 06:06:08 +00006979 return false;
6980 }
Chris Lattner970c33a2003-06-19 17:00:31 +00006981
6982 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
6983 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanb1c93172005-04-21 23:48:37 +00006984
Chris Lattner970c33a2003-06-19 17:00:31 +00006985 CallSite::arg_iterator AI = CS.arg_begin();
6986 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
6987 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthebfa24e2006-06-28 01:01:52 +00006988 const Type *ActTy = (*AI)->getType();
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006989 ConstantInt *c = dyn_cast<ConstantInt>(*AI);
Andrew Lenharthebfa24e2006-06-28 01:01:52 +00006990 //Either we can cast directly, or we can upconvert the argument
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006991 bool isConvertible = ActTy->canLosslesslyBitCastTo(ParamTy) ||
Andrew Lenharthebfa24e2006-06-28 01:01:52 +00006992 (ParamTy->isIntegral() && ActTy->isIntegral() &&
6993 ParamTy->isSigned() == ActTy->isSigned() &&
6994 ParamTy->getPrimitiveSize() >= ActTy->getPrimitiveSize()) ||
6995 (c && ParamTy->getPrimitiveSize() >= ActTy->getPrimitiveSize() &&
Reid Spencere0fc4df2006-10-20 07:07:24 +00006996 c->getSExtValue() > 0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00006997 if (Callee->isExternal() && !isConvertible) return false;
Chris Lattner970c33a2003-06-19 17:00:31 +00006998 }
6999
7000 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
7001 Callee->isExternal())
7002 return false; // Do not delete arguments unless we have a function body...
7003
7004 // Okay, we decided that this is a safe thing to do: go ahead and start
7005 // inserting cast instructions as necessary...
7006 std::vector<Value*> Args;
7007 Args.reserve(NumActualArgs);
7008
7009 AI = CS.arg_begin();
7010 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
7011 const Type *ParamTy = FT->getParamType(i);
7012 if ((*AI)->getType() == ParamTy) {
7013 Args.push_back(*AI);
7014 } else {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007015 CastInst *NewCast = CastInst::createInferredCast(*AI, ParamTy, "tmp");
7016 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
Chris Lattner970c33a2003-06-19 17:00:31 +00007017 }
7018 }
7019
7020 // If the function takes more arguments than the call was taking, add them
7021 // now...
7022 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
7023 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
7024
7025 // If we are removing arguments to the function, emit an obnoxious warning...
7026 if (FT->getNumParams() < NumActualArgs)
7027 if (!FT->isVarArg()) {
Bill Wendlingf3baad32006-12-07 01:30:32 +00007028 cerr << "WARNING: While resolving call to function '"
7029 << Callee->getName() << "' arguments were dropped!\n";
Chris Lattner970c33a2003-06-19 17:00:31 +00007030 } else {
7031 // Add all of the arguments in their promoted form to the arg list...
7032 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
7033 const Type *PTy = getPromotedType((*AI)->getType());
7034 if (PTy != (*AI)->getType()) {
7035 // Must promote to pass through va_arg area!
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007036 Instruction *Cast = CastInst::createInferredCast(*AI, PTy, "tmp");
Chris Lattner970c33a2003-06-19 17:00:31 +00007037 InsertNewInstBefore(Cast, *Caller);
7038 Args.push_back(Cast);
7039 } else {
7040 Args.push_back(*AI);
7041 }
7042 }
7043 }
7044
7045 if (FT->getReturnType() == Type::VoidTy)
7046 Caller->setName(""); // Void type should not have a name...
7047
7048 Instruction *NC;
7049 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Chris Lattnerfae8ab32004-02-08 21:44:31 +00007050 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
Chris Lattner970c33a2003-06-19 17:00:31 +00007051 Args, Caller->getName(), Caller);
Chris Lattner05c703e2005-05-14 12:25:32 +00007052 cast<InvokeInst>(II)->setCallingConv(II->getCallingConv());
Chris Lattner970c33a2003-06-19 17:00:31 +00007053 } else {
7054 NC = new CallInst(Callee, Args, Caller->getName(), Caller);
Chris Lattner6aacb0f2005-05-06 06:48:21 +00007055 if (cast<CallInst>(Caller)->isTailCall())
7056 cast<CallInst>(NC)->setTailCall();
Chris Lattner05c703e2005-05-14 12:25:32 +00007057 cast<CallInst>(NC)->setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Chris Lattner970c33a2003-06-19 17:00:31 +00007058 }
7059
7060 // Insert a cast of the return type as necessary...
7061 Value *NV = NC;
7062 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
7063 if (NV->getType() != Type::VoidTy) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007064 NV = NC = CastInst::createInferredCast(NC, Caller->getType(), "tmp");
Chris Lattner686767f2003-10-30 00:46:41 +00007065
7066 // If this is an invoke instruction, we should insert it after the first
7067 // non-phi, instruction in the normal successor block.
7068 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
7069 BasicBlock::iterator I = II->getNormalDest()->begin();
7070 while (isa<PHINode>(I)) ++I;
7071 InsertNewInstBefore(NC, *I);
7072 } else {
7073 // Otherwise, it's a call, just insert cast right after the call instr
7074 InsertNewInstBefore(NC, *Caller);
7075 }
Chris Lattner51ea1272004-02-28 05:22:00 +00007076 AddUsersToWorkList(*Caller);
Chris Lattner970c33a2003-06-19 17:00:31 +00007077 } else {
Chris Lattnere29d6342004-10-17 21:22:38 +00007078 NV = UndefValue::get(Caller->getType());
Chris Lattner970c33a2003-06-19 17:00:31 +00007079 }
7080 }
7081
7082 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
7083 Caller->replaceAllUsesWith(NV);
7084 Caller->getParent()->getInstList().erase(Caller);
7085 removeFromWorkList(Caller);
7086 return true;
7087}
7088
Chris Lattnercadac0c2006-11-01 04:51:18 +00007089/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
7090/// and if a/b/c/d and the add's all have a single use, turn this into two phi's
7091/// and a single binop.
7092Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
7093 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Chris Lattnereebea432006-11-01 07:43:41 +00007094 assert(isa<BinaryOperator>(FirstInst) || isa<ShiftInst>(FirstInst) ||
7095 isa<GetElementPtrInst>(FirstInst));
Chris Lattnercadac0c2006-11-01 04:51:18 +00007096 unsigned Opc = FirstInst->getOpcode();
Chris Lattnercd62f112006-11-08 19:29:23 +00007097 Value *LHSVal = FirstInst->getOperand(0);
7098 Value *RHSVal = FirstInst->getOperand(1);
7099
7100 const Type *LHSType = LHSVal->getType();
7101 const Type *RHSType = RHSVal->getType();
Chris Lattnercadac0c2006-11-01 04:51:18 +00007102
7103 // Scan to see if all operands are the same opcode, all have one use, and all
7104 // kill their operands (i.e. the operands have one use).
Chris Lattnerdc826fc2006-11-01 04:55:47 +00007105 for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
Chris Lattnercadac0c2006-11-01 04:51:18 +00007106 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Chris Lattnerdc826fc2006-11-01 04:55:47 +00007107 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
7108 // Verify type of the LHS matches so we don't fold setcc's of different
Chris Lattnereebea432006-11-01 07:43:41 +00007109 // types or GEP's with different index types.
7110 I->getOperand(0)->getType() != LHSType ||
7111 I->getOperand(1)->getType() != RHSType)
Chris Lattnercadac0c2006-11-01 04:51:18 +00007112 return 0;
Chris Lattnercd62f112006-11-08 19:29:23 +00007113
7114 // Keep track of which operand needs a phi node.
7115 if (I->getOperand(0) != LHSVal) LHSVal = 0;
7116 if (I->getOperand(1) != RHSVal) RHSVal = 0;
Chris Lattnercadac0c2006-11-01 04:51:18 +00007117 }
7118
Chris Lattner4f218d52006-11-08 19:42:28 +00007119 // Otherwise, this is safe to transform, determine if it is profitable.
7120
7121 // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
7122 // Indexes are often folded into load/store instructions, so we don't want to
7123 // hide them behind a phi.
7124 if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
7125 return 0;
7126
Chris Lattnercadac0c2006-11-01 04:51:18 +00007127 Value *InLHS = FirstInst->getOperand(0);
Chris Lattnercadac0c2006-11-01 04:51:18 +00007128 Value *InRHS = FirstInst->getOperand(1);
Chris Lattner4f218d52006-11-08 19:42:28 +00007129 PHINode *NewLHS = 0, *NewRHS = 0;
Chris Lattnercd62f112006-11-08 19:29:23 +00007130 if (LHSVal == 0) {
7131 NewLHS = new PHINode(LHSType, FirstInst->getOperand(0)->getName()+".pn");
7132 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
7133 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
Chris Lattnereebea432006-11-01 07:43:41 +00007134 InsertNewInstBefore(NewLHS, PN);
7135 LHSVal = NewLHS;
7136 }
Chris Lattnercd62f112006-11-08 19:29:23 +00007137
7138 if (RHSVal == 0) {
7139 NewRHS = new PHINode(RHSType, FirstInst->getOperand(1)->getName()+".pn");
7140 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
7141 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
Chris Lattnereebea432006-11-01 07:43:41 +00007142 InsertNewInstBefore(NewRHS, PN);
7143 RHSVal = NewRHS;
7144 }
7145
Chris Lattnercd62f112006-11-08 19:29:23 +00007146 // Add all operands to the new PHIs.
7147 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7148 if (NewLHS) {
7149 Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
7150 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
7151 }
7152 if (NewRHS) {
7153 Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
7154 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
7155 }
7156 }
7157
Chris Lattnercadac0c2006-11-01 04:51:18 +00007158 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattnereebea432006-11-01 07:43:41 +00007159 return BinaryOperator::create(BinOp->getOpcode(), LHSVal, RHSVal);
7160 else if (ShiftInst *SI = dyn_cast<ShiftInst>(FirstInst))
7161 return new ShiftInst(SI->getOpcode(), LHSVal, RHSVal);
7162 else {
7163 assert(isa<GetElementPtrInst>(FirstInst));
7164 return new GetElementPtrInst(LHSVal, RHSVal);
7165 }
Chris Lattnercadac0c2006-11-01 04:51:18 +00007166}
7167
Chris Lattner14f82c72006-11-01 07:13:54 +00007168/// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
7169/// of the block that defines it. This means that it must be obvious the value
7170/// of the load is not changed from the point of the load to the end of the
7171/// block it is in.
7172static bool isSafeToSinkLoad(LoadInst *L) {
7173 BasicBlock::iterator BBI = L, E = L->getParent()->end();
7174
7175 for (++BBI; BBI != E; ++BBI)
7176 if (BBI->mayWriteToMemory())
7177 return false;
7178 return true;
7179}
7180
Chris Lattner970c33a2003-06-19 17:00:31 +00007181
Chris Lattner7515cab2004-11-14 19:13:23 +00007182// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
7183// operator and they all are only used by the PHI, PHI together their
7184// inputs, and do the operation once, to the result of the PHI.
7185Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
7186 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
7187
7188 // Scan the instruction, looking for input operations that can be folded away.
7189 // If all input operands to the phi are the same instruction (e.g. a cast from
7190 // the same type or "+42") we can pull the operation through the PHI, reducing
7191 // code size and simplifying code.
7192 Constant *ConstantOp = 0;
7193 const Type *CastSrcTy = 0;
Chris Lattner14f82c72006-11-01 07:13:54 +00007194 bool isVolatile = false;
Chris Lattner7515cab2004-11-14 19:13:23 +00007195 if (isa<CastInst>(FirstInst)) {
7196 CastSrcTy = FirstInst->getOperand(0)->getType();
7197 } else if (isa<BinaryOperator>(FirstInst) || isa<ShiftInst>(FirstInst)) {
Chris Lattnercadac0c2006-11-01 04:51:18 +00007198 // Can fold binop or shift here if the RHS is a constant, otherwise call
7199 // FoldPHIArgBinOpIntoPHI.
Chris Lattner7515cab2004-11-14 19:13:23 +00007200 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Chris Lattnercadac0c2006-11-01 04:51:18 +00007201 if (ConstantOp == 0)
7202 return FoldPHIArgBinOpIntoPHI(PN);
Chris Lattner14f82c72006-11-01 07:13:54 +00007203 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
7204 isVolatile = LI->isVolatile();
7205 // We can't sink the load if the loaded value could be modified between the
7206 // load and the PHI.
7207 if (LI->getParent() != PN.getIncomingBlock(0) ||
7208 !isSafeToSinkLoad(LI))
7209 return 0;
Chris Lattnereebea432006-11-01 07:43:41 +00007210 } else if (isa<GetElementPtrInst>(FirstInst)) {
Chris Lattner4f218d52006-11-08 19:42:28 +00007211 if (FirstInst->getNumOperands() == 2)
Chris Lattnereebea432006-11-01 07:43:41 +00007212 return FoldPHIArgBinOpIntoPHI(PN);
7213 // Can't handle general GEPs yet.
7214 return 0;
Chris Lattner7515cab2004-11-14 19:13:23 +00007215 } else {
7216 return 0; // Cannot fold this operation.
7217 }
7218
7219 // Check to see if all arguments are the same operation.
7220 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7221 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
7222 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
7223 if (!I->hasOneUse() || I->getOpcode() != FirstInst->getOpcode())
7224 return 0;
7225 if (CastSrcTy) {
7226 if (I->getOperand(0)->getType() != CastSrcTy)
7227 return 0; // Cast operation must match.
Chris Lattner14f82c72006-11-01 07:13:54 +00007228 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
7229 // We can't sink the load if the loaded value could be modified between the
7230 // load and the PHI.
7231 if (LI->isVolatile() != isVolatile ||
7232 LI->getParent() != PN.getIncomingBlock(i) ||
7233 !isSafeToSinkLoad(LI))
7234 return 0;
Chris Lattner7515cab2004-11-14 19:13:23 +00007235 } else if (I->getOperand(1) != ConstantOp) {
7236 return 0;
7237 }
7238 }
7239
7240 // Okay, they are all the same operation. Create a new PHI node of the
7241 // correct type, and PHI together all of the LHS's of the instructions.
7242 PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
7243 PN.getName()+".in");
Chris Lattnerd8e20182005-01-29 00:39:08 +00007244 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattner46dd5a62004-11-14 19:29:34 +00007245
7246 Value *InVal = FirstInst->getOperand(0);
7247 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattner7515cab2004-11-14 19:13:23 +00007248
7249 // Add all operands to the new PHI.
Chris Lattner46dd5a62004-11-14 19:29:34 +00007250 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7251 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
7252 if (NewInVal != InVal)
7253 InVal = 0;
7254 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
7255 }
7256
7257 Value *PhiVal;
7258 if (InVal) {
7259 // The new PHI unions all of the same values together. This is really
7260 // common, so we handle it intelligently here for compile-time speed.
7261 PhiVal = InVal;
7262 delete NewPN;
7263 } else {
7264 InsertNewInstBefore(NewPN, PN);
7265 PhiVal = NewPN;
7266 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00007267
Chris Lattner7515cab2004-11-14 19:13:23 +00007268 // Insert and return the new operation.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007269 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
7270 return CastInst::create(FirstCI->getOpcode(), PhiVal, PN.getType());
Reid Spencerde46e482006-11-02 20:25:50 +00007271 else if (isa<LoadInst>(FirstInst))
Chris Lattner14f82c72006-11-01 07:13:54 +00007272 return new LoadInst(PhiVal, "", isVolatile);
Chris Lattner7515cab2004-11-14 19:13:23 +00007273 else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattner46dd5a62004-11-14 19:29:34 +00007274 return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattner7515cab2004-11-14 19:13:23 +00007275 else
7276 return new ShiftInst(cast<ShiftInst>(FirstInst)->getOpcode(),
Chris Lattner46dd5a62004-11-14 19:29:34 +00007277 PhiVal, ConstantOp);
Chris Lattner7515cab2004-11-14 19:13:23 +00007278}
Chris Lattner48a44f72002-05-02 17:06:02 +00007279
Chris Lattner71536432005-01-17 05:10:15 +00007280/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
7281/// that is dead.
7282static bool DeadPHICycle(PHINode *PN, std::set<PHINode*> &PotentiallyDeadPHIs) {
7283 if (PN->use_empty()) return true;
7284 if (!PN->hasOneUse()) return false;
7285
7286 // Remember this node, and if we find the cycle, return.
7287 if (!PotentiallyDeadPHIs.insert(PN).second)
7288 return true;
7289
7290 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
7291 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanb1c93172005-04-21 23:48:37 +00007292
Chris Lattner71536432005-01-17 05:10:15 +00007293 return false;
7294}
7295
Chris Lattnerbbbdd852002-05-06 18:06:38 +00007296// PHINode simplification
7297//
Chris Lattner113f4f42002-06-25 16:13:24 +00007298Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonbbf89902006-07-10 22:15:25 +00007299 // If LCSSA is around, don't mess with Phi nodes
7300 if (mustPreserveAnalysisID(LCSSAID)) return 0;
Owen Andersona6968f82006-07-10 19:03:49 +00007301
Owen Andersonae8aa642006-07-10 22:03:18 +00007302 if (Value *V = PN.hasConstantValue())
7303 return ReplaceInstUsesWith(PN, V);
7304
Owen Andersonae8aa642006-07-10 22:03:18 +00007305 // If all PHI operands are the same operation, pull them through the PHI,
7306 // reducing code size.
7307 if (isa<Instruction>(PN.getIncomingValue(0)) &&
7308 PN.getIncomingValue(0)->hasOneUse())
7309 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
7310 return Result;
7311
7312 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
7313 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
7314 // PHI)... break the cycle.
7315 if (PN.hasOneUse())
7316 if (PHINode *PU = dyn_cast<PHINode>(PN.use_back())) {
7317 std::set<PHINode*> PotentiallyDeadPHIs;
7318 PotentiallyDeadPHIs.insert(&PN);
7319 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
7320 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
7321 }
7322
Chris Lattner91daeb52003-12-19 05:58:40 +00007323 return 0;
Chris Lattnerbbbdd852002-05-06 18:06:38 +00007324}
7325
Reid Spencer13bc5d72006-12-12 09:18:51 +00007326static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
7327 Instruction *InsertPoint,
7328 InstCombiner *IC) {
Reid Spencer2a499b02006-12-13 17:19:09 +00007329 unsigned PtrSize = DTy->getPrimitiveSize();
Reid Spencer13bc5d72006-12-12 09:18:51 +00007330 unsigned VTySize = V->getType()->getPrimitiveSize();
7331 // We must cast correctly to the pointer type. Ensure that we
7332 // sign extend the integer value if it is smaller as this is
7333 // used for address computation.
7334 Instruction::CastOps opcode =
7335 (VTySize < PtrSize ? Instruction::SExt :
7336 (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
7337 return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
Chris Lattner69193f92004-04-05 01:30:19 +00007338}
7339
Chris Lattner48a44f72002-05-02 17:06:02 +00007340
Chris Lattner113f4f42002-06-25 16:13:24 +00007341Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner5f667a62004-05-07 22:09:22 +00007342 Value *PtrOp = GEP.getOperand(0);
Chris Lattner471bd762003-05-22 19:07:21 +00007343 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
Chris Lattner113f4f42002-06-25 16:13:24 +00007344 // If so, eliminate the noop.
Chris Lattner8d0bacb2004-02-22 05:25:17 +00007345 if (GEP.getNumOperands() == 1)
Chris Lattner5f667a62004-05-07 22:09:22 +00007346 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner8d0bacb2004-02-22 05:25:17 +00007347
Chris Lattner81a7a232004-10-16 18:11:37 +00007348 if (isa<UndefValue>(GEP.getOperand(0)))
7349 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
7350
Chris Lattner8d0bacb2004-02-22 05:25:17 +00007351 bool HasZeroPointerIndex = false;
7352 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
7353 HasZeroPointerIndex = C->isNullValue();
7354
7355 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner5f667a62004-05-07 22:09:22 +00007356 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner48a44f72002-05-02 17:06:02 +00007357
Chris Lattner69193f92004-04-05 01:30:19 +00007358 // Eliminate unneeded casts for indices.
7359 bool MadeChange = false;
Chris Lattner2b2412d2004-04-07 18:38:20 +00007360 gep_type_iterator GTI = gep_type_begin(GEP);
7361 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI)
7362 if (isa<SequentialType>(*GTI)) {
7363 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
7364 Value *Src = CI->getOperand(0);
7365 const Type *SrcTy = Src->getType();
7366 const Type *DestTy = CI->getType();
7367 if (Src->getType()->isInteger()) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00007368 if (SrcTy->getPrimitiveSizeInBits() ==
7369 DestTy->getPrimitiveSizeInBits()) {
Chris Lattner2b2412d2004-04-07 18:38:20 +00007370 // We can always eliminate a cast from ulong or long to the other.
7371 // We can always eliminate a cast from uint to int or the other on
7372 // 32-bit pointer platforms.
Chris Lattnerd1f46d32005-04-24 06:59:08 +00007373 if (DestTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()){
Chris Lattner2b2412d2004-04-07 18:38:20 +00007374 MadeChange = true;
7375 GEP.setOperand(i, Src);
7376 }
7377 } else if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
7378 SrcTy->getPrimitiveSize() == 4) {
7379 // We can always eliminate a cast from int to [u]long. We can
7380 // eliminate a cast from uint to [u]long iff the target is a 32-bit
7381 // pointer target.
Misha Brukmanb1c93172005-04-21 23:48:37 +00007382 if (SrcTy->isSigned() ||
Chris Lattnerd1f46d32005-04-24 06:59:08 +00007383 SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
Chris Lattner2b2412d2004-04-07 18:38:20 +00007384 MadeChange = true;
7385 GEP.setOperand(i, Src);
7386 }
Chris Lattner69193f92004-04-05 01:30:19 +00007387 }
7388 }
7389 }
Chris Lattner2b2412d2004-04-07 18:38:20 +00007390 // If we are using a wider index than needed for this platform, shrink it
7391 // to what we need. If the incoming value needs a cast instruction,
7392 // insert it. This explicit cast can make subsequent optimizations more
7393 // obvious.
7394 Value *Op = GEP.getOperand(i);
7395 if (Op->getType()->getPrimitiveSize() > TD->getPointerSize())
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00007396 if (Constant *C = dyn_cast<Constant>(Op)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00007397 GEP.setOperand(i, ConstantExpr::getTrunc(C,
Chris Lattner44d0b952004-07-20 01:48:15 +00007398 TD->getIntPtrType()->getSignedVersion()));
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00007399 MadeChange = true;
7400 } else {
Reid Spencer13bc5d72006-12-12 09:18:51 +00007401 Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
7402 GEP);
Chris Lattner2b2412d2004-04-07 18:38:20 +00007403 GEP.setOperand(i, Op);
7404 MadeChange = true;
7405 }
Chris Lattner44d0b952004-07-20 01:48:15 +00007406
7407 // If this is a constant idx, make sure to canonicalize it to be a signed
7408 // operand, otherwise CSE and other optimizations are pessimized.
Reid Spencere0fc4df2006-10-20 07:07:24 +00007409 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op))
7410 if (CUI->getType()->isUnsigned()) {
7411 GEP.setOperand(i,
Reid Spencer13bc5d72006-12-12 09:18:51 +00007412 ConstantExpr::getBitCast(CUI, CUI->getType()->getSignedVersion()));
Reid Spencere0fc4df2006-10-20 07:07:24 +00007413 MadeChange = true;
7414 }
Chris Lattner69193f92004-04-05 01:30:19 +00007415 }
7416 if (MadeChange) return &GEP;
7417
Chris Lattnerae7a0d32002-08-02 19:29:35 +00007418 // Combine Indices - If the source pointer to this getelementptr instruction
7419 // is a getelementptr instruction, combine the indices of the two
7420 // getelementptr instructions into a single instruction.
7421 //
Chris Lattner57c67b02004-03-25 22:59:29 +00007422 std::vector<Value*> SrcGEPOperands;
Chris Lattner0798af32005-01-13 20:14:25 +00007423 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattner57c67b02004-03-25 22:59:29 +00007424 SrcGEPOperands.assign(Src->op_begin(), Src->op_end());
Chris Lattner57c67b02004-03-25 22:59:29 +00007425
7426 if (!SrcGEPOperands.empty()) {
Chris Lattner5f667a62004-05-07 22:09:22 +00007427 // Note that if our source is a gep chain itself that we wait for that
7428 // chain to be resolved before we perform this transformation. This
7429 // avoids us creating a TON of code in some cases.
7430 //
7431 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
7432 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
7433 return 0; // Wait until our source is folded to completion.
7434
Chris Lattnerae7a0d32002-08-02 19:29:35 +00007435 std::vector<Value *> Indices;
Chris Lattner5f667a62004-05-07 22:09:22 +00007436
7437 // Find out whether the last index in the source GEP is a sequential idx.
7438 bool EndsWithSequential = false;
7439 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
7440 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattner8ec5f882004-05-08 22:41:42 +00007441 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00007442
Chris Lattnerae7a0d32002-08-02 19:29:35 +00007443 // Can we combine the two pointer arithmetics offsets?
Chris Lattner5f667a62004-05-07 22:09:22 +00007444 if (EndsWithSequential) {
Chris Lattner235af562003-03-05 22:33:14 +00007445 // Replace: gep (gep %P, long B), long A, ...
7446 // With: T = long A+B; gep %P, T, ...
7447 //
Chris Lattner5f667a62004-05-07 22:09:22 +00007448 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner69193f92004-04-05 01:30:19 +00007449 if (SO1 == Constant::getNullValue(SO1->getType())) {
7450 Sum = GO1;
7451 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
7452 Sum = SO1;
7453 } else {
7454 // If they aren't the same type, convert both to an integer of the
7455 // target's pointer size.
7456 if (SO1->getType() != GO1->getType()) {
7457 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00007458 SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
Chris Lattner69193f92004-04-05 01:30:19 +00007459 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00007460 GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
Chris Lattner69193f92004-04-05 01:30:19 +00007461 } else {
7462 unsigned PS = TD->getPointerSize();
Chris Lattner69193f92004-04-05 01:30:19 +00007463 if (SO1->getType()->getPrimitiveSize() == PS) {
7464 // Convert GO1 to SO1's type.
Reid Spencer13bc5d72006-12-12 09:18:51 +00007465 GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
Chris Lattner69193f92004-04-05 01:30:19 +00007466
7467 } else if (GO1->getType()->getPrimitiveSize() == PS) {
7468 // Convert SO1 to GO1's type.
Reid Spencer13bc5d72006-12-12 09:18:51 +00007469 SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
Chris Lattner69193f92004-04-05 01:30:19 +00007470 } else {
7471 const Type *PT = TD->getIntPtrType();
Reid Spencer13bc5d72006-12-12 09:18:51 +00007472 SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
7473 GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
Chris Lattner69193f92004-04-05 01:30:19 +00007474 }
7475 }
7476 }
Chris Lattner5f667a62004-05-07 22:09:22 +00007477 if (isa<Constant>(SO1) && isa<Constant>(GO1))
7478 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
7479 else {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00007480 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
7481 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner5f667a62004-05-07 22:09:22 +00007482 }
Chris Lattner69193f92004-04-05 01:30:19 +00007483 }
Chris Lattner5f667a62004-05-07 22:09:22 +00007484
7485 // Recycle the GEP we already have if possible.
7486 if (SrcGEPOperands.size() == 2) {
7487 GEP.setOperand(0, SrcGEPOperands[0]);
7488 GEP.setOperand(1, Sum);
7489 return &GEP;
7490 } else {
7491 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
7492 SrcGEPOperands.end()-1);
7493 Indices.push_back(Sum);
7494 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
7495 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00007496 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner69193f92004-04-05 01:30:19 +00007497 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00007498 SrcGEPOperands.size() != 1) {
Chris Lattnerae7a0d32002-08-02 19:29:35 +00007499 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattner57c67b02004-03-25 22:59:29 +00007500 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
7501 SrcGEPOperands.end());
Chris Lattnerae7a0d32002-08-02 19:29:35 +00007502 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
7503 }
7504
7505 if (!Indices.empty())
Chris Lattner57c67b02004-03-25 22:59:29 +00007506 return new GetElementPtrInst(SrcGEPOperands[0], Indices, GEP.getName());
Chris Lattnerc59af1d2002-08-17 22:21:59 +00007507
Chris Lattner5f667a62004-05-07 22:09:22 +00007508 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattnerc59af1d2002-08-17 22:21:59 +00007509 // GEP of global variable. If all of the indices for this GEP are
7510 // constants, we can promote this to a constexpr instead of an instruction.
7511
7512 // Scan for nonconstants...
7513 std::vector<Constant*> Indices;
7514 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
7515 for (; I != E && isa<Constant>(*I); ++I)
7516 Indices.push_back(cast<Constant>(*I));
7517
7518 if (I == E) { // If they are all constants...
Chris Lattnerf3edc492004-07-18 18:59:44 +00007519 Constant *CE = ConstantExpr::getGetElementPtr(GV, Indices);
Chris Lattnerc59af1d2002-08-17 22:21:59 +00007520
7521 // Replace all uses of the GEP with the new constexpr...
7522 return ReplaceInstUsesWith(GEP, CE);
7523 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007524 } else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast?
Chris Lattner567b81f2005-09-13 00:40:14 +00007525 if (!isa<PointerType>(X->getType())) {
7526 // Not interesting. Source pointer must be a cast from pointer.
7527 } else if (HasZeroPointerIndex) {
7528 // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
7529 // into : GEP [10 x ubyte]* X, long 0, ...
7530 //
7531 // This occurs when the program declares an array extern like "int X[];"
7532 //
7533 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
7534 const PointerType *XTy = cast<PointerType>(X->getType());
7535 if (const ArrayType *XATy =
7536 dyn_cast<ArrayType>(XTy->getElementType()))
7537 if (const ArrayType *CATy =
7538 dyn_cast<ArrayType>(CPTy->getElementType()))
7539 if (CATy->getElementType() == XATy->getElementType()) {
7540 // At this point, we know that the cast source type is a pointer
7541 // to an array of the same type as the destination pointer
7542 // array. Because the array type is never stepped over (there
7543 // is a leading zero) we can fold the cast into this GEP.
7544 GEP.setOperand(0, X);
7545 return &GEP;
7546 }
7547 } else if (GEP.getNumOperands() == 2) {
7548 // Transform things like:
Chris Lattner2a893292005-09-13 18:36:04 +00007549 // %t = getelementptr ubyte* cast ([2 x int]* %str to uint*), uint %V
7550 // into: %t1 = getelementptr [2 x int*]* %str, int 0, uint %V; cast
Chris Lattner567b81f2005-09-13 00:40:14 +00007551 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
7552 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
7553 if (isa<ArrayType>(SrcElTy) &&
7554 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
7555 TD->getTypeSize(ResElTy)) {
7556 Value *V = InsertNewInstBefore(
7557 new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
7558 GEP.getOperand(1), GEP.getName()), GEP);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007559 // V and GEP are both pointer types --> BitCast
7560 return new BitCastInst(V, GEP.getType());
Chris Lattner8d0bacb2004-02-22 05:25:17 +00007561 }
Chris Lattner2a893292005-09-13 18:36:04 +00007562
7563 // Transform things like:
7564 // getelementptr sbyte* cast ([100 x double]* X to sbyte*), int %tmp
7565 // (where tmp = 8*tmp2) into:
7566 // getelementptr [100 x double]* %arr, int 0, int %tmp.2
7567
7568 if (isa<ArrayType>(SrcElTy) &&
7569 (ResElTy == Type::SByteTy || ResElTy == Type::UByteTy)) {
7570 uint64_t ArrayEltSize =
7571 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType());
7572
7573 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
7574 // allow either a mul, shift, or constant here.
7575 Value *NewIdx = 0;
7576 ConstantInt *Scale = 0;
7577 if (ArrayEltSize == 1) {
7578 NewIdx = GEP.getOperand(1);
7579 Scale = ConstantInt::get(NewIdx->getType(), 1);
7580 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Chris Lattnera393e4d2005-09-14 17:32:56 +00007581 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner2a893292005-09-13 18:36:04 +00007582 Scale = CI;
7583 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
7584 if (Inst->getOpcode() == Instruction::Shl &&
7585 isa<ConstantInt>(Inst->getOperand(1))) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00007586 unsigned ShAmt =
7587 cast<ConstantInt>(Inst->getOperand(1))->getZExtValue();
Chris Lattner2a893292005-09-13 18:36:04 +00007588 if (Inst->getType()->isSigned())
Reid Spencere0fc4df2006-10-20 07:07:24 +00007589 Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmt);
Chris Lattner2a893292005-09-13 18:36:04 +00007590 else
Reid Spencere0fc4df2006-10-20 07:07:24 +00007591 Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmt);
Chris Lattner2a893292005-09-13 18:36:04 +00007592 NewIdx = Inst->getOperand(0);
7593 } else if (Inst->getOpcode() == Instruction::Mul &&
7594 isa<ConstantInt>(Inst->getOperand(1))) {
7595 Scale = cast<ConstantInt>(Inst->getOperand(1));
7596 NewIdx = Inst->getOperand(0);
7597 }
7598 }
7599
7600 // If the index will be to exactly the right offset with the scale taken
7601 // out, perform the transformation.
Reid Spencere0fc4df2006-10-20 07:07:24 +00007602 if (Scale && Scale->getZExtValue() % ArrayEltSize == 0) {
Reid Spencerde46e482006-11-02 20:25:50 +00007603 if (isa<ConstantInt>(Scale))
Reid Spencere0fc4df2006-10-20 07:07:24 +00007604 Scale = ConstantInt::get(Scale->getType(),
7605 Scale->getZExtValue() / ArrayEltSize);
7606 if (Scale->getZExtValue() != 1) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00007607 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
7608 true /*SExt*/);
Chris Lattner2a893292005-09-13 18:36:04 +00007609 Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
7610 NewIdx = InsertNewInstBefore(Sc, GEP);
7611 }
7612
7613 // Insert the new GEP instruction.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007614 Instruction *NewGEP =
Chris Lattner2a893292005-09-13 18:36:04 +00007615 new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
7616 NewIdx, GEP.getName());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007617 NewGEP = InsertNewInstBefore(NewGEP, GEP);
7618 // The NewGEP must be pointer typed, so must the old one -> BitCast
7619 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner2a893292005-09-13 18:36:04 +00007620 }
7621 }
Chris Lattner8d0bacb2004-02-22 05:25:17 +00007622 }
Chris Lattnerca081252001-12-14 16:52:21 +00007623 }
7624
Chris Lattnerca081252001-12-14 16:52:21 +00007625 return 0;
7626}
7627
Chris Lattner1085bdf2002-11-04 16:18:53 +00007628Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
7629 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
7630 if (AI.isArrayAllocation()) // Check C != 1
Reid Spencere0fc4df2006-10-20 07:07:24 +00007631 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
7632 const Type *NewTy =
7633 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Chris Lattnera2620ac2002-11-09 00:49:43 +00007634 AllocationInst *New = 0;
Chris Lattner1085bdf2002-11-04 16:18:53 +00007635
7636 // Create and insert the replacement instruction...
7637 if (isa<MallocInst>(AI))
Nate Begeman848622f2005-11-05 09:21:28 +00007638 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00007639 else {
7640 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Nate Begeman848622f2005-11-05 09:21:28 +00007641 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00007642 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00007643
7644 InsertNewInstBefore(New, AI);
Misha Brukmanb1c93172005-04-21 23:48:37 +00007645
Chris Lattner1085bdf2002-11-04 16:18:53 +00007646 // Scan to the end of the allocation instructions, to skip over a block of
7647 // allocas if possible...
7648 //
7649 BasicBlock::iterator It = New;
7650 while (isa<AllocationInst>(*It)) ++It;
7651
7652 // Now that I is pointing to the first non-allocation-inst in the block,
7653 // insert our getelementptr instruction...
7654 //
Chris Lattner809dfac2005-05-04 19:10:26 +00007655 Value *NullIdx = Constant::getNullValue(Type::IntTy);
7656 Value *V = new GetElementPtrInst(New, NullIdx, NullIdx,
7657 New->getName()+".sub", It);
Chris Lattner1085bdf2002-11-04 16:18:53 +00007658
7659 // Now make everything use the getelementptr instead of the original
7660 // allocation.
Chris Lattnerabb77c92004-03-19 06:08:10 +00007661 return ReplaceInstUsesWith(AI, V);
Chris Lattner81a7a232004-10-16 18:11:37 +00007662 } else if (isa<UndefValue>(AI.getArraySize())) {
7663 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner1085bdf2002-11-04 16:18:53 +00007664 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00007665
7666 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
7667 // Note that we only do this for alloca's, because malloc should allocate and
7668 // return a unique pointer, even for a zero byte allocation.
Misha Brukmanb1c93172005-04-21 23:48:37 +00007669 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
Chris Lattner49df6ce2004-07-02 22:55:47 +00007670 TD->getTypeSize(AI.getAllocatedType()) == 0)
Chris Lattnerabb77c92004-03-19 06:08:10 +00007671 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
7672
Chris Lattner1085bdf2002-11-04 16:18:53 +00007673 return 0;
7674}
7675
Chris Lattner8427bff2003-12-07 01:24:23 +00007676Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
7677 Value *Op = FI.getOperand(0);
7678
7679 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
7680 if (CastInst *CI = dyn_cast<CastInst>(Op))
7681 if (isa<PointerType>(CI->getOperand(0)->getType())) {
7682 FI.setOperand(0, CI->getOperand(0));
7683 return &FI;
7684 }
7685
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007686 // free undef -> unreachable.
7687 if (isa<UndefValue>(Op)) {
7688 // Insert a new store to null because we cannot modify the CFG here.
Chris Lattner6ab03f62006-09-28 23:35:22 +00007689 new StoreInst(ConstantBool::getTrue(),
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007690 UndefValue::get(PointerType::get(Type::BoolTy)), &FI);
7691 return EraseInstFromFunction(FI);
7692 }
7693
Chris Lattnerf3a36602004-02-28 04:57:37 +00007694 // If we have 'free null' delete the instruction. This can happen in stl code
7695 // when lots of inlining happens.
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007696 if (isa<ConstantPointerNull>(Op))
Chris Lattner51ea1272004-02-28 05:22:00 +00007697 return EraseInstFromFunction(FI);
Chris Lattnerf3a36602004-02-28 04:57:37 +00007698
Chris Lattner8427bff2003-12-07 01:24:23 +00007699 return 0;
7700}
7701
7702
Chris Lattner72684fe2005-01-31 05:51:45 +00007703/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Chris Lattner35e24772004-07-13 01:49:43 +00007704static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
7705 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00007706 Value *CastOp = CI->getOperand(0);
Chris Lattner35e24772004-07-13 01:49:43 +00007707
7708 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00007709 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Chris Lattner35e24772004-07-13 01:49:43 +00007710 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00007711
Chris Lattnerebca4762006-04-02 05:37:12 +00007712 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
7713 isa<PackedType>(DestPTy)) {
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00007714 // If the source is an array, the code below will not succeed. Check to
7715 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
7716 // constants.
7717 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
7718 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
7719 if (ASrcTy->getNumElements() != 0) {
7720 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
7721 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
7722 SrcTy = cast<PointerType>(CastOp->getType());
7723 SrcPTy = SrcTy->getElementType();
7724 }
7725
Chris Lattnerebca4762006-04-02 05:37:12 +00007726 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
7727 isa<PackedType>(SrcPTy)) &&
Chris Lattnerecfa9b52005-03-29 06:37:47 +00007728 // Do not allow turning this into a load of an integer, which is then
7729 // casted to a pointer, this pessimizes pointer analysis a lot.
7730 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00007731 IC.getTargetData().getTypeSize(SrcPTy) ==
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00007732 IC.getTargetData().getTypeSize(DestPTy)) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00007733
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00007734 // Okay, we are casting from one integer or pointer type to another of
7735 // the same size. Instead of casting the pointer before the load, cast
7736 // the result of the loaded value.
7737 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
7738 CI->getName(),
7739 LI.isVolatile()),LI);
7740 // Now cast the result of the load.
Reid Spencerbb65ebf2006-12-12 23:36:14 +00007741 return new BitCastInst(NewLoad, LI.getType());
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00007742 }
Chris Lattner35e24772004-07-13 01:49:43 +00007743 }
7744 }
7745 return 0;
7746}
7747
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00007748/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattnere6f13092004-09-19 19:18:10 +00007749/// from this value cannot trap. If it is not obviously safe to load from the
7750/// specified pointer, we do a quick local scan of the basic block containing
7751/// ScanFrom, to determine if the address is already accessed.
7752static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
7753 // If it is an alloca or global variable, it is always safe to load from.
7754 if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
7755
7756 // Otherwise, be a little bit agressive by scanning the local block where we
7757 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00007758 // from/to. If so, the previous load or store would have already trapped,
7759 // so there is no harm doing an extra load (also, CSE will later eliminate
7760 // the load entirely).
Chris Lattnere6f13092004-09-19 19:18:10 +00007761 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
7762
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00007763 while (BBI != E) {
Chris Lattnere6f13092004-09-19 19:18:10 +00007764 --BBI;
7765
7766 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
7767 if (LI->getOperand(0) == V) return true;
7768 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
7769 if (SI->getOperand(1) == V) return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +00007770
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00007771 }
Chris Lattnere6f13092004-09-19 19:18:10 +00007772 return false;
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00007773}
7774
Chris Lattner0f1d8a32003-06-26 05:06:25 +00007775Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
7776 Value *Op = LI.getOperand(0);
Chris Lattner7e8af382004-01-12 04:13:56 +00007777
Chris Lattnera9d84e32005-05-01 04:24:53 +00007778 // load (cast X) --> cast (load X) iff safe
Reid Spencerde46e482006-11-02 20:25:50 +00007779 if (isa<CastInst>(Op))
Chris Lattnera9d84e32005-05-01 04:24:53 +00007780 if (Instruction *Res = InstCombineLoadCast(*this, LI))
7781 return Res;
7782
7783 // None of the following transforms are legal for volatile loads.
7784 if (LI.isVolatile()) return 0;
Chris Lattnerb990f7d2005-09-12 22:00:15 +00007785
Chris Lattnerb990f7d2005-09-12 22:00:15 +00007786 if (&LI.getParent()->front() != &LI) {
7787 BasicBlock::iterator BBI = &LI; --BBI;
Chris Lattnere0bfdf12005-09-12 22:21:03 +00007788 // If the instruction immediately before this is a store to the same
7789 // address, do a simple form of store->load forwarding.
Chris Lattnerb990f7d2005-09-12 22:00:15 +00007790 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
7791 if (SI->getOperand(1) == LI.getOperand(0))
7792 return ReplaceInstUsesWith(LI, SI->getOperand(0));
Chris Lattnere0bfdf12005-09-12 22:21:03 +00007793 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
7794 if (LIB->getOperand(0) == LI.getOperand(0))
7795 return ReplaceInstUsesWith(LI, LIB);
Chris Lattnerb990f7d2005-09-12 22:00:15 +00007796 }
Chris Lattnera9d84e32005-05-01 04:24:53 +00007797
7798 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op))
7799 if (isa<ConstantPointerNull>(GEPI->getOperand(0)) ||
7800 isa<UndefValue>(GEPI->getOperand(0))) {
7801 // Insert a new store to null instruction before the load to indicate
7802 // that this code is not reachable. We do this instead of inserting
7803 // an unreachable instruction directly because we cannot modify the
7804 // CFG.
7805 new StoreInst(UndefValue::get(LI.getType()),
7806 Constant::getNullValue(Op->getType()), &LI);
7807 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
7808 }
7809
Chris Lattner81a7a232004-10-16 18:11:37 +00007810 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattnera9d84e32005-05-01 04:24:53 +00007811 // load null/undef -> undef
7812 if ((C->isNullValue() || isa<UndefValue>(C))) {
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007813 // Insert a new store to null instruction before the load to indicate that
7814 // this code is not reachable. We do this instead of inserting an
7815 // unreachable instruction directly because we cannot modify the CFG.
Chris Lattnera9d84e32005-05-01 04:24:53 +00007816 new StoreInst(UndefValue::get(LI.getType()),
7817 Constant::getNullValue(Op->getType()), &LI);
Chris Lattner81a7a232004-10-16 18:11:37 +00007818 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007819 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00007820
Chris Lattner81a7a232004-10-16 18:11:37 +00007821 // Instcombine load (constant global) into the value loaded.
7822 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
7823 if (GV->isConstant() && !GV->isExternal())
7824 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanb1c93172005-04-21 23:48:37 +00007825
Chris Lattner81a7a232004-10-16 18:11:37 +00007826 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
7827 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
7828 if (CE->getOpcode() == Instruction::GetElementPtr) {
7829 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
7830 if (GV->isConstant() && !GV->isExternal())
Chris Lattner0b011ec2005-09-26 05:28:06 +00007831 if (Constant *V =
7832 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
Chris Lattner81a7a232004-10-16 18:11:37 +00007833 return ReplaceInstUsesWith(LI, V);
Chris Lattnera9d84e32005-05-01 04:24:53 +00007834 if (CE->getOperand(0)->isNullValue()) {
7835 // Insert a new store to null instruction before the load to indicate
7836 // that this code is not reachable. We do this instead of inserting
7837 // an unreachable instruction directly because we cannot modify the
7838 // CFG.
7839 new StoreInst(UndefValue::get(LI.getType()),
7840 Constant::getNullValue(Op->getType()), &LI);
7841 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
7842 }
7843
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007844 } else if (CE->isCast()) {
Chris Lattner81a7a232004-10-16 18:11:37 +00007845 if (Instruction *Res = InstCombineLoadCast(*this, LI))
7846 return Res;
7847 }
7848 }
Chris Lattnere228ee52004-04-08 20:39:49 +00007849
Chris Lattnera9d84e32005-05-01 04:24:53 +00007850 if (Op->hasOneUse()) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00007851 // Change select and PHI nodes to select values instead of addresses: this
7852 // helps alias analysis out a lot, allows many others simplifications, and
7853 // exposes redundancy in the code.
7854 //
7855 // Note that we cannot do the transformation unless we know that the
7856 // introduced loads cannot trap! Something like this is valid as long as
7857 // the condition is always false: load (select bool %C, int* null, int* %G),
7858 // but it would not be valid if we transformed it to load from null
7859 // unconditionally.
7860 //
7861 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
7862 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattnere6f13092004-09-19 19:18:10 +00007863 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
7864 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00007865 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner42618552004-09-20 10:15:10 +00007866 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00007867 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner42618552004-09-20 10:15:10 +00007868 SI->getOperand(2)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00007869 return new SelectInst(SI->getCondition(), V1, V2);
7870 }
7871
Chris Lattnerbdcf41a2004-09-23 15:46:00 +00007872 // load (select (cond, null, P)) -> load P
7873 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
7874 if (C->isNullValue()) {
7875 LI.setOperand(0, SI->getOperand(2));
7876 return &LI;
7877 }
7878
7879 // load (select (cond, P, null)) -> load P
7880 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
7881 if (C->isNullValue()) {
7882 LI.setOperand(0, SI->getOperand(1));
7883 return &LI;
7884 }
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00007885 }
7886 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00007887 return 0;
7888}
7889
Chris Lattner72684fe2005-01-31 05:51:45 +00007890/// InstCombineStoreToCast - Fold 'store V, (cast P)' -> store (cast V), P'
7891/// when possible.
7892static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
7893 User *CI = cast<User>(SI.getOperand(1));
7894 Value *CastOp = CI->getOperand(0);
7895
7896 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
7897 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
7898 const Type *SrcPTy = SrcTy->getElementType();
7899
7900 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
7901 // If the source is an array, the code below will not succeed. Check to
7902 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
7903 // constants.
7904 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
7905 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
7906 if (ASrcTy->getNumElements() != 0) {
7907 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
7908 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
7909 SrcTy = cast<PointerType>(CastOp->getType());
7910 SrcPTy = SrcTy->getElementType();
7911 }
7912
7913 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00007914 IC.getTargetData().getTypeSize(SrcPTy) ==
Chris Lattner72684fe2005-01-31 05:51:45 +00007915 IC.getTargetData().getTypeSize(DestPTy)) {
7916
7917 // Okay, we are casting from one integer or pointer type to another of
7918 // the same size. Instead of casting the pointer before the store, cast
7919 // the value to be stored.
7920 Value *NewCast;
Reid Spencerbb65ebf2006-12-12 23:36:14 +00007921 Instruction::CastOps opcode = Instruction::BitCast;
7922 Value *SIOp0 = SI.getOperand(0);
7923 if (SrcPTy->getTypeID() == Type::PointerTyID) {
7924 if (SIOp0->getType()->isIntegral())
7925 opcode = Instruction::IntToPtr;
7926 } else if (SrcPTy->isIntegral()) {
7927 if (SIOp0->getType()->getTypeID() == Type::PointerTyID)
7928 opcode = Instruction::PtrToInt;
7929 }
7930 if (Constant *C = dyn_cast<Constant>(SIOp0))
7931 NewCast = ConstantExpr::getCast(opcode, C, SrcPTy);
Chris Lattner72684fe2005-01-31 05:51:45 +00007932 else
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007933 NewCast = IC.InsertNewInstBefore(
Reid Spencerbb65ebf2006-12-12 23:36:14 +00007934 CastInst::create(opcode, SIOp0, SrcPTy, SIOp0->getName()+".c"), SI);
Chris Lattner72684fe2005-01-31 05:51:45 +00007935 return new StoreInst(NewCast, CastOp);
7936 }
7937 }
7938 }
7939 return 0;
7940}
7941
Chris Lattner31f486c2005-01-31 05:36:43 +00007942Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
7943 Value *Val = SI.getOperand(0);
7944 Value *Ptr = SI.getOperand(1);
7945
7946 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner5997cf92006-02-08 03:25:32 +00007947 EraseInstFromFunction(SI);
Chris Lattner31f486c2005-01-31 05:36:43 +00007948 ++NumCombined;
7949 return 0;
7950 }
7951
Chris Lattner5997cf92006-02-08 03:25:32 +00007952 // Do really simple DSE, to catch cases where there are several consequtive
7953 // stores to the same location, separated by a few arithmetic operations. This
7954 // situation often occurs with bitfield accesses.
7955 BasicBlock::iterator BBI = &SI;
7956 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
7957 --ScanInsts) {
7958 --BBI;
7959
7960 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
7961 // Prev store isn't volatile, and stores to the same location?
7962 if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
7963 ++NumDeadStore;
7964 ++BBI;
7965 EraseInstFromFunction(*PrevSI);
7966 continue;
7967 }
7968 break;
7969 }
7970
Chris Lattnerdab43b22006-05-26 19:19:20 +00007971 // If this is a load, we have to stop. However, if the loaded value is from
7972 // the pointer we're loading and is producing the pointer we're storing,
7973 // then *this* store is dead (X = load P; store X -> P).
7974 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
7975 if (LI == Val && LI->getOperand(0) == Ptr) {
7976 EraseInstFromFunction(SI);
7977 ++NumCombined;
7978 return 0;
7979 }
7980 // Otherwise, this is a load from some other location. Stores before it
7981 // may not be dead.
7982 break;
7983 }
7984
Chris Lattner5997cf92006-02-08 03:25:32 +00007985 // Don't skip over loads or things that can modify memory.
Chris Lattnerdab43b22006-05-26 19:19:20 +00007986 if (BBI->mayWriteToMemory())
Chris Lattner5997cf92006-02-08 03:25:32 +00007987 break;
7988 }
7989
7990
7991 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner31f486c2005-01-31 05:36:43 +00007992
7993 // store X, null -> turns into 'unreachable' in SimplifyCFG
7994 if (isa<ConstantPointerNull>(Ptr)) {
7995 if (!isa<UndefValue>(Val)) {
7996 SI.setOperand(0, UndefValue::get(Val->getType()));
7997 if (Instruction *U = dyn_cast<Instruction>(Val))
7998 WorkList.push_back(U); // Dropped a use.
7999 ++NumCombined;
8000 }
8001 return 0; // Do not modify these!
8002 }
8003
8004 // store undef, Ptr -> noop
8005 if (isa<UndefValue>(Val)) {
Chris Lattner5997cf92006-02-08 03:25:32 +00008006 EraseInstFromFunction(SI);
Chris Lattner31f486c2005-01-31 05:36:43 +00008007 ++NumCombined;
8008 return 0;
8009 }
8010
Chris Lattner72684fe2005-01-31 05:51:45 +00008011 // If the pointer destination is a cast, see if we can fold the cast into the
8012 // source instead.
Reid Spencerde46e482006-11-02 20:25:50 +00008013 if (isa<CastInst>(Ptr))
Chris Lattner72684fe2005-01-31 05:51:45 +00008014 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
8015 return Res;
8016 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008017 if (CE->isCast())
Chris Lattner72684fe2005-01-31 05:51:45 +00008018 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
8019 return Res;
8020
Chris Lattner219175c2005-09-12 23:23:25 +00008021
8022 // If this store is the last instruction in the basic block, and if the block
8023 // ends with an unconditional branch, try to move it to the successor block.
Chris Lattner5997cf92006-02-08 03:25:32 +00008024 BBI = &SI; ++BBI;
Chris Lattner219175c2005-09-12 23:23:25 +00008025 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
8026 if (BI->isUnconditional()) {
8027 // Check to see if the successor block has exactly two incoming edges. If
8028 // so, see if the other predecessor contains a store to the same location.
8029 // if so, insert a PHI node (if needed) and move the stores down.
8030 BasicBlock *Dest = BI->getSuccessor(0);
8031
8032 pred_iterator PI = pred_begin(Dest);
8033 BasicBlock *Other = 0;
8034 if (*PI != BI->getParent())
8035 Other = *PI;
8036 ++PI;
8037 if (PI != pred_end(Dest)) {
8038 if (*PI != BI->getParent())
8039 if (Other)
8040 Other = 0;
8041 else
8042 Other = *PI;
8043 if (++PI != pred_end(Dest))
8044 Other = 0;
8045 }
8046 if (Other) { // If only one other pred...
8047 BBI = Other->getTerminator();
8048 // Make sure this other block ends in an unconditional branch and that
8049 // there is an instruction before the branch.
8050 if (isa<BranchInst>(BBI) && cast<BranchInst>(BBI)->isUnconditional() &&
8051 BBI != Other->begin()) {
8052 --BBI;
8053 StoreInst *OtherStore = dyn_cast<StoreInst>(BBI);
8054
8055 // If this instruction is a store to the same location.
8056 if (OtherStore && OtherStore->getOperand(1) == SI.getOperand(1)) {
8057 // Okay, we know we can perform this transformation. Insert a PHI
8058 // node now if we need it.
8059 Value *MergedVal = OtherStore->getOperand(0);
8060 if (MergedVal != SI.getOperand(0)) {
8061 PHINode *PN = new PHINode(MergedVal->getType(), "storemerge");
8062 PN->reserveOperandSpace(2);
8063 PN->addIncoming(SI.getOperand(0), SI.getParent());
8064 PN->addIncoming(OtherStore->getOperand(0), Other);
8065 MergedVal = InsertNewInstBefore(PN, Dest->front());
8066 }
8067
8068 // Advance to a place where it is safe to insert the new store and
8069 // insert it.
8070 BBI = Dest->begin();
8071 while (isa<PHINode>(BBI)) ++BBI;
8072 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
8073 OtherStore->isVolatile()), *BBI);
8074
8075 // Nuke the old stores.
Chris Lattner5997cf92006-02-08 03:25:32 +00008076 EraseInstFromFunction(SI);
8077 EraseInstFromFunction(*OtherStore);
Chris Lattner219175c2005-09-12 23:23:25 +00008078 ++NumCombined;
8079 return 0;
8080 }
8081 }
8082 }
8083 }
8084
Chris Lattner31f486c2005-01-31 05:36:43 +00008085 return 0;
8086}
8087
8088
Chris Lattner9eef8a72003-06-04 04:46:00 +00008089Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
8090 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4fdd96c2005-06-18 17:37:34 +00008091 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00008092 BasicBlock *TrueDest;
8093 BasicBlock *FalseDest;
8094 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
8095 !isa<Constant>(X)) {
8096 // Swap Destinations and condition...
8097 BI.setCondition(X);
8098 BI.setSuccessor(0, FalseDest);
8099 BI.setSuccessor(1, TrueDest);
8100 return &BI;
8101 }
8102
8103 // Cannonicalize setne -> seteq
8104 Instruction::BinaryOps Op; Value *Y;
8105 if (match(&BI, m_Br(m_SetCond(Op, m_Value(X), m_Value(Y)),
8106 TrueDest, FalseDest)))
8107 if ((Op == Instruction::SetNE || Op == Instruction::SetLE ||
8108 Op == Instruction::SetGE) && BI.getCondition()->hasOneUse()) {
8109 SetCondInst *I = cast<SetCondInst>(BI.getCondition());
8110 std::string Name = I->getName(); I->setName("");
8111 Instruction::BinaryOps NewOpcode = SetCondInst::getInverseCondition(Op);
8112 Value *NewSCC = BinaryOperator::create(NewOpcode, X, Y, Name, I);
Chris Lattnere967b342003-06-04 05:10:11 +00008113 // Swap Destinations and condition...
Chris Lattnerd4252a72004-07-30 07:50:03 +00008114 BI.setCondition(NewSCC);
Chris Lattnere967b342003-06-04 05:10:11 +00008115 BI.setSuccessor(0, FalseDest);
8116 BI.setSuccessor(1, TrueDest);
Chris Lattnerd4252a72004-07-30 07:50:03 +00008117 removeFromWorkList(I);
8118 I->getParent()->getInstList().erase(I);
8119 WorkList.push_back(cast<Instruction>(NewSCC));
Chris Lattnere967b342003-06-04 05:10:11 +00008120 return &BI;
8121 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00008122
Chris Lattner9eef8a72003-06-04 04:46:00 +00008123 return 0;
8124}
Chris Lattner1085bdf2002-11-04 16:18:53 +00008125
Chris Lattner4c9c20a2004-07-03 00:26:11 +00008126Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
8127 Value *Cond = SI.getCondition();
8128 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
8129 if (I->getOpcode() == Instruction::Add)
8130 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
8131 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
8132 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattner81a7a232004-10-16 18:11:37 +00008133 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner4c9c20a2004-07-03 00:26:11 +00008134 AddRHS));
8135 SI.setOperand(0, I->getOperand(0));
8136 WorkList.push_back(I);
8137 return &SI;
8138 }
8139 }
8140 return 0;
8141}
8142
Chris Lattner6bc98652006-03-05 00:22:33 +00008143/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
8144/// is to leave as a vector operation.
8145static bool CheapToScalarize(Value *V, bool isConstant) {
8146 if (isa<ConstantAggregateZero>(V))
8147 return true;
8148 if (ConstantPacked *C = dyn_cast<ConstantPacked>(V)) {
8149 if (isConstant) return true;
8150 // If all elts are the same, we can extract.
8151 Constant *Op0 = C->getOperand(0);
8152 for (unsigned i = 1; i < C->getNumOperands(); ++i)
8153 if (C->getOperand(i) != Op0)
8154 return false;
8155 return true;
8156 }
8157 Instruction *I = dyn_cast<Instruction>(V);
8158 if (!I) return false;
8159
8160 // Insert element gets simplified to the inserted element or is deleted if
8161 // this is constant idx extract element and its a constant idx insertelt.
8162 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
8163 isa<ConstantInt>(I->getOperand(2)))
8164 return true;
8165 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
8166 return true;
8167 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
8168 if (BO->hasOneUse() &&
8169 (CheapToScalarize(BO->getOperand(0), isConstant) ||
8170 CheapToScalarize(BO->getOperand(1), isConstant)))
8171 return true;
8172
8173 return false;
8174}
8175
Chris Lattner12249be2006-05-25 23:48:38 +00008176/// getShuffleMask - Read and decode a shufflevector mask. It turns undef
8177/// elements into values that are larger than the #elts in the input.
8178static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
8179 unsigned NElts = SVI->getType()->getNumElements();
8180 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
8181 return std::vector<unsigned>(NElts, 0);
8182 if (isa<UndefValue>(SVI->getOperand(2)))
8183 return std::vector<unsigned>(NElts, 2*NElts);
8184
8185 std::vector<unsigned> Result;
8186 const ConstantPacked *CP = cast<ConstantPacked>(SVI->getOperand(2));
8187 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
8188 if (isa<UndefValue>(CP->getOperand(i)))
8189 Result.push_back(NElts*2); // undef -> 8
8190 else
Reid Spencere0fc4df2006-10-20 07:07:24 +00008191 Result.push_back(cast<ConstantInt>(CP->getOperand(i))->getZExtValue());
Chris Lattner12249be2006-05-25 23:48:38 +00008192 return Result;
8193}
8194
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008195/// FindScalarElement - Given a vector and an element number, see if the scalar
8196/// value is already around as a register, for example if it were inserted then
8197/// extracted from the vector.
8198static Value *FindScalarElement(Value *V, unsigned EltNo) {
8199 assert(isa<PackedType>(V->getType()) && "Not looking at a vector?");
8200 const PackedType *PTy = cast<PackedType>(V->getType());
Chris Lattner2d37f922006-04-10 23:06:36 +00008201 unsigned Width = PTy->getNumElements();
8202 if (EltNo >= Width) // Out of range access.
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008203 return UndefValue::get(PTy->getElementType());
8204
8205 if (isa<UndefValue>(V))
8206 return UndefValue::get(PTy->getElementType());
8207 else if (isa<ConstantAggregateZero>(V))
8208 return Constant::getNullValue(PTy->getElementType());
8209 else if (ConstantPacked *CP = dyn_cast<ConstantPacked>(V))
8210 return CP->getOperand(EltNo);
8211 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
8212 // If this is an insert to a variable element, we don't know what it is.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008213 if (!isa<ConstantInt>(III->getOperand(2)))
8214 return 0;
8215 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008216
8217 // If this is an insert to the element we are looking for, return the
8218 // inserted value.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008219 if (EltNo == IIElt)
8220 return III->getOperand(1);
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008221
8222 // Otherwise, the insertelement doesn't modify the value, recurse on its
8223 // vector input.
8224 return FindScalarElement(III->getOperand(0), EltNo);
Chris Lattner2d37f922006-04-10 23:06:36 +00008225 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Chris Lattner12249be2006-05-25 23:48:38 +00008226 unsigned InEl = getShuffleMask(SVI)[EltNo];
8227 if (InEl < Width)
8228 return FindScalarElement(SVI->getOperand(0), InEl);
8229 else if (InEl < Width*2)
8230 return FindScalarElement(SVI->getOperand(1), InEl - Width);
8231 else
8232 return UndefValue::get(PTy->getElementType());
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008233 }
8234
8235 // Otherwise, we don't know.
8236 return 0;
8237}
8238
Robert Bocchinoa8352962006-01-13 22:48:06 +00008239Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008240
Chris Lattner92346c32006-03-31 18:25:14 +00008241 // If packed val is undef, replace extract with scalar undef.
8242 if (isa<UndefValue>(EI.getOperand(0)))
8243 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
8244
8245 // If packed val is constant 0, replace extract with scalar 0.
8246 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
8247 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
8248
Robert Bocchinoa8352962006-01-13 22:48:06 +00008249 if (ConstantPacked *C = dyn_cast<ConstantPacked>(EI.getOperand(0))) {
8250 // If packed val is constant with uniform operands, replace EI
8251 // with that operand
Chris Lattner6bc98652006-03-05 00:22:33 +00008252 Constant *op0 = C->getOperand(0);
Robert Bocchinoa8352962006-01-13 22:48:06 +00008253 for (unsigned i = 1; i < C->getNumOperands(); ++i)
Chris Lattner6bc98652006-03-05 00:22:33 +00008254 if (C->getOperand(i) != op0) {
8255 op0 = 0;
8256 break;
8257 }
8258 if (op0)
8259 return ReplaceInstUsesWith(EI, op0);
Robert Bocchinoa8352962006-01-13 22:48:06 +00008260 }
Chris Lattner6bc98652006-03-05 00:22:33 +00008261
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008262 // If extracting a specified index from the vector, see if we can recursively
8263 // find a previously computed scalar that was inserted into the vector.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008264 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Chris Lattner2deeaea2006-10-05 06:55:50 +00008265 // This instruction only demands the single element from the input vector.
8266 // If the input vector has a single use, simplify it based on this use
8267 // property.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008268 uint64_t IndexVal = IdxC->getZExtValue();
Chris Lattner2deeaea2006-10-05 06:55:50 +00008269 if (EI.getOperand(0)->hasOneUse()) {
8270 uint64_t UndefElts;
8271 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Reid Spencere0fc4df2006-10-20 07:07:24 +00008272 1 << IndexVal,
Chris Lattner2deeaea2006-10-05 06:55:50 +00008273 UndefElts)) {
8274 EI.setOperand(0, V);
8275 return &EI;
8276 }
8277 }
8278
Reid Spencere0fc4df2006-10-20 07:07:24 +00008279 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008280 return ReplaceInstUsesWith(EI, Elt);
Chris Lattner2d37f922006-04-10 23:06:36 +00008281 }
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008282
Chris Lattner83f65782006-05-25 22:53:38 +00008283 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Robert Bocchinoa8352962006-01-13 22:48:06 +00008284 if (I->hasOneUse()) {
8285 // Push extractelement into predecessor operation if legal and
8286 // profitable to do so
8287 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Chris Lattner6bc98652006-03-05 00:22:33 +00008288 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
8289 if (CheapToScalarize(BO, isConstantElt)) {
8290 ExtractElementInst *newEI0 =
8291 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
8292 EI.getName()+".lhs");
8293 ExtractElementInst *newEI1 =
8294 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
8295 EI.getName()+".rhs");
8296 InsertNewInstBefore(newEI0, EI);
8297 InsertNewInstBefore(newEI1, EI);
8298 return BinaryOperator::create(BO->getOpcode(), newEI0, newEI1);
8299 }
Reid Spencerde46e482006-11-02 20:25:50 +00008300 } else if (isa<LoadInst>(I)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00008301 Value *Ptr = InsertCastBefore(Instruction::BitCast, I->getOperand(0),
Robert Bocchinoa8352962006-01-13 22:48:06 +00008302 PointerType::get(EI.getType()), EI);
8303 GetElementPtrInst *GEP =
Reid Spencera736fdf2006-11-29 01:11:01 +00008304 new GetElementPtrInst(Ptr, EI.getOperand(1), I->getName() + ".gep");
Robert Bocchinoa8352962006-01-13 22:48:06 +00008305 InsertNewInstBefore(GEP, EI);
8306 return new LoadInst(GEP);
Chris Lattner83f65782006-05-25 22:53:38 +00008307 }
8308 }
8309 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
8310 // Extracting the inserted element?
8311 if (IE->getOperand(2) == EI.getOperand(1))
8312 return ReplaceInstUsesWith(EI, IE->getOperand(1));
8313 // If the inserted and extracted elements are constants, they must not
8314 // be the same value, extract from the pre-inserted value instead.
8315 if (isa<Constant>(IE->getOperand(2)) &&
8316 isa<Constant>(EI.getOperand(1))) {
8317 AddUsesToWorkList(EI);
8318 EI.setOperand(0, IE->getOperand(0));
8319 return &EI;
8320 }
8321 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
8322 // If this is extracting an element from a shufflevector, figure out where
8323 // it came from and extract from the appropriate input element instead.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008324 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
8325 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
Chris Lattner12249be2006-05-25 23:48:38 +00008326 Value *Src;
8327 if (SrcIdx < SVI->getType()->getNumElements())
8328 Src = SVI->getOperand(0);
8329 else if (SrcIdx < SVI->getType()->getNumElements()*2) {
8330 SrcIdx -= SVI->getType()->getNumElements();
8331 Src = SVI->getOperand(1);
8332 } else {
8333 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattner612fa8e2006-03-30 22:02:40 +00008334 }
Chris Lattner2deeaea2006-10-05 06:55:50 +00008335 return new ExtractElementInst(Src, SrcIdx);
Robert Bocchinoa8352962006-01-13 22:48:06 +00008336 }
8337 }
Chris Lattner83f65782006-05-25 22:53:38 +00008338 }
Robert Bocchinoa8352962006-01-13 22:48:06 +00008339 return 0;
8340}
8341
Chris Lattner90951862006-04-16 00:51:47 +00008342/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
8343/// elements from either LHS or RHS, return the shuffle mask and true.
8344/// Otherwise, return false.
8345static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
8346 std::vector<Constant*> &Mask) {
8347 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
8348 "Invalid CollectSingleShuffleElements");
8349 unsigned NumElts = cast<PackedType>(V->getType())->getNumElements();
8350
8351 if (isa<UndefValue>(V)) {
8352 Mask.assign(NumElts, UndefValue::get(Type::UIntTy));
8353 return true;
8354 } else if (V == LHS) {
8355 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencere0fc4df2006-10-20 07:07:24 +00008356 Mask.push_back(ConstantInt::get(Type::UIntTy, i));
Chris Lattner90951862006-04-16 00:51:47 +00008357 return true;
8358 } else if (V == RHS) {
8359 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencere0fc4df2006-10-20 07:07:24 +00008360 Mask.push_back(ConstantInt::get(Type::UIntTy, i+NumElts));
Chris Lattner90951862006-04-16 00:51:47 +00008361 return true;
8362 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
8363 // If this is an insert of an extract from some other vector, include it.
8364 Value *VecOp = IEI->getOperand(0);
8365 Value *ScalarOp = IEI->getOperand(1);
8366 Value *IdxOp = IEI->getOperand(2);
8367
Chris Lattnerb6cb64b2006-04-27 21:14:21 +00008368 if (!isa<ConstantInt>(IdxOp))
8369 return false;
Reid Spencere0fc4df2006-10-20 07:07:24 +00008370 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerb6cb64b2006-04-27 21:14:21 +00008371
8372 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
8373 // Okay, we can handle this if the vector we are insertinting into is
8374 // transitively ok.
8375 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
8376 // If so, update the mask to reflect the inserted undef.
8377 Mask[InsertedIdx] = UndefValue::get(Type::UIntTy);
8378 return true;
8379 }
8380 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
8381 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner90951862006-04-16 00:51:47 +00008382 EI->getOperand(0)->getType() == V->getType()) {
8383 unsigned ExtractedIdx =
Reid Spencere0fc4df2006-10-20 07:07:24 +00008384 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattner90951862006-04-16 00:51:47 +00008385
8386 // This must be extracting from either LHS or RHS.
8387 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
8388 // Okay, we can handle this if the vector we are insertinting into is
8389 // transitively ok.
8390 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
8391 // If so, update the mask to reflect the inserted value.
8392 if (EI->getOperand(0) == LHS) {
8393 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencere0fc4df2006-10-20 07:07:24 +00008394 ConstantInt::get(Type::UIntTy, ExtractedIdx);
Chris Lattner90951862006-04-16 00:51:47 +00008395 } else {
8396 assert(EI->getOperand(0) == RHS);
8397 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencere0fc4df2006-10-20 07:07:24 +00008398 ConstantInt::get(Type::UIntTy, ExtractedIdx+NumElts);
Chris Lattner90951862006-04-16 00:51:47 +00008399
8400 }
8401 return true;
8402 }
8403 }
8404 }
8405 }
8406 }
8407 // TODO: Handle shufflevector here!
8408
8409 return false;
8410}
8411
8412/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
8413/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
8414/// that computes V and the LHS value of the shuffle.
Chris Lattner39fac442006-04-15 01:39:45 +00008415static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Chris Lattner90951862006-04-16 00:51:47 +00008416 Value *&RHS) {
8417 assert(isa<PackedType>(V->getType()) &&
8418 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattner39fac442006-04-15 01:39:45 +00008419 "Invalid shuffle!");
8420 unsigned NumElts = cast<PackedType>(V->getType())->getNumElements();
8421
8422 if (isa<UndefValue>(V)) {
8423 Mask.assign(NumElts, UndefValue::get(Type::UIntTy));
8424 return V;
8425 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00008426 Mask.assign(NumElts, ConstantInt::get(Type::UIntTy, 0));
Chris Lattner39fac442006-04-15 01:39:45 +00008427 return V;
8428 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
8429 // If this is an insert of an extract from some other vector, include it.
8430 Value *VecOp = IEI->getOperand(0);
8431 Value *ScalarOp = IEI->getOperand(1);
8432 Value *IdxOp = IEI->getOperand(2);
8433
8434 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
8435 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
8436 EI->getOperand(0)->getType() == V->getType()) {
8437 unsigned ExtractedIdx =
Reid Spencere0fc4df2006-10-20 07:07:24 +00008438 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
8439 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattner39fac442006-04-15 01:39:45 +00008440
8441 // Either the extracted from or inserted into vector must be RHSVec,
8442 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner90951862006-04-16 00:51:47 +00008443 if (EI->getOperand(0) == RHS || RHS == 0) {
8444 RHS = EI->getOperand(0);
8445 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
Chris Lattner39fac442006-04-15 01:39:45 +00008446 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencere0fc4df2006-10-20 07:07:24 +00008447 ConstantInt::get(Type::UIntTy, NumElts+ExtractedIdx);
Chris Lattner39fac442006-04-15 01:39:45 +00008448 return V;
8449 }
8450
Chris Lattner90951862006-04-16 00:51:47 +00008451 if (VecOp == RHS) {
8452 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
Chris Lattner39fac442006-04-15 01:39:45 +00008453 // Everything but the extracted element is replaced with the RHS.
8454 for (unsigned i = 0; i != NumElts; ++i) {
8455 if (i != InsertedIdx)
Reid Spencere0fc4df2006-10-20 07:07:24 +00008456 Mask[i] = ConstantInt::get(Type::UIntTy, NumElts+i);
Chris Lattner39fac442006-04-15 01:39:45 +00008457 }
8458 return V;
8459 }
Chris Lattner90951862006-04-16 00:51:47 +00008460
8461 // If this insertelement is a chain that comes from exactly these two
8462 // vectors, return the vector and the effective shuffle.
8463 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
8464 return EI->getOperand(0);
8465
Chris Lattner39fac442006-04-15 01:39:45 +00008466 }
8467 }
8468 }
Chris Lattner90951862006-04-16 00:51:47 +00008469 // TODO: Handle shufflevector here!
Chris Lattner39fac442006-04-15 01:39:45 +00008470
8471 // Otherwise, can't do anything fancy. Return an identity vector.
8472 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencere0fc4df2006-10-20 07:07:24 +00008473 Mask.push_back(ConstantInt::get(Type::UIntTy, i));
Chris Lattner39fac442006-04-15 01:39:45 +00008474 return V;
8475}
8476
8477Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
8478 Value *VecOp = IE.getOperand(0);
8479 Value *ScalarOp = IE.getOperand(1);
8480 Value *IdxOp = IE.getOperand(2);
8481
8482 // If the inserted element was extracted from some other vector, and if the
8483 // indexes are constant, try to turn this into a shufflevector operation.
8484 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
8485 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
8486 EI->getOperand(0)->getType() == IE.getType()) {
8487 unsigned NumVectorElts = IE.getType()->getNumElements();
Reid Spencere0fc4df2006-10-20 07:07:24 +00008488 unsigned ExtractedIdx=cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
8489 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattner39fac442006-04-15 01:39:45 +00008490
8491 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
8492 return ReplaceInstUsesWith(IE, VecOp);
8493
8494 if (InsertedIdx >= NumVectorElts) // Out of range insert.
8495 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
8496
8497 // If we are extracting a value from a vector, then inserting it right
8498 // back into the same place, just use the input vector.
8499 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
8500 return ReplaceInstUsesWith(IE, VecOp);
8501
8502 // We could theoretically do this for ANY input. However, doing so could
8503 // turn chains of insertelement instructions into a chain of shufflevector
8504 // instructions, and right now we do not merge shufflevectors. As such,
8505 // only do this in a situation where it is clear that there is benefit.
8506 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
8507 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
8508 // the values of VecOp, except then one read from EIOp0.
8509 // Build a new shuffle mask.
8510 std::vector<Constant*> Mask;
8511 if (isa<UndefValue>(VecOp))
8512 Mask.assign(NumVectorElts, UndefValue::get(Type::UIntTy));
8513 else {
8514 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
Reid Spencere0fc4df2006-10-20 07:07:24 +00008515 Mask.assign(NumVectorElts, ConstantInt::get(Type::UIntTy,
Chris Lattner39fac442006-04-15 01:39:45 +00008516 NumVectorElts));
8517 }
Reid Spencere0fc4df2006-10-20 07:07:24 +00008518 Mask[InsertedIdx] = ConstantInt::get(Type::UIntTy, ExtractedIdx);
Chris Lattner39fac442006-04-15 01:39:45 +00008519 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
8520 ConstantPacked::get(Mask));
8521 }
8522
8523 // If this insertelement isn't used by some other insertelement, turn it
8524 // (and any insertelements it points to), into one big shuffle.
8525 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
8526 std::vector<Constant*> Mask;
Chris Lattner90951862006-04-16 00:51:47 +00008527 Value *RHS = 0;
8528 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
8529 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
8530 // We now have a shuffle of LHS, RHS, Mask.
8531 return new ShuffleVectorInst(LHS, RHS, ConstantPacked::get(Mask));
Chris Lattner39fac442006-04-15 01:39:45 +00008532 }
8533 }
8534 }
8535
8536 return 0;
8537}
8538
8539
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008540Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
8541 Value *LHS = SVI.getOperand(0);
8542 Value *RHS = SVI.getOperand(1);
Chris Lattner12249be2006-05-25 23:48:38 +00008543 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008544
8545 bool MadeChange = false;
8546
Chris Lattner2deeaea2006-10-05 06:55:50 +00008547 // Undefined shuffle mask -> undefined value.
Chris Lattner12249be2006-05-25 23:48:38 +00008548 if (isa<UndefValue>(SVI.getOperand(2)))
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008549 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
8550
Chris Lattner39fac442006-04-15 01:39:45 +00008551 // TODO: If we have shuffle(x, undef, mask) and any elements of mask refer to
8552 // the undef, change them to undefs.
8553
Chris Lattner12249be2006-05-25 23:48:38 +00008554 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
8555 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
8556 if (LHS == RHS || isa<UndefValue>(LHS)) {
8557 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008558 // shuffle(undef,undef,mask) -> undef.
8559 return ReplaceInstUsesWith(SVI, LHS);
8560 }
8561
Chris Lattner12249be2006-05-25 23:48:38 +00008562 // Remap any references to RHS to use LHS.
8563 std::vector<Constant*> Elts;
8564 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner0e477162006-05-26 00:29:06 +00008565 if (Mask[i] >= 2*e)
Chris Lattner12249be2006-05-25 23:48:38 +00008566 Elts.push_back(UndefValue::get(Type::UIntTy));
Chris Lattner0e477162006-05-26 00:29:06 +00008567 else {
8568 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
8569 (Mask[i] < e && isa<UndefValue>(LHS)))
8570 Mask[i] = 2*e; // Turn into undef.
8571 else
8572 Mask[i] &= (e-1); // Force to LHS.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008573 Elts.push_back(ConstantInt::get(Type::UIntTy, Mask[i]));
Chris Lattner0e477162006-05-26 00:29:06 +00008574 }
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008575 }
Chris Lattner12249be2006-05-25 23:48:38 +00008576 SVI.setOperand(0, SVI.getOperand(1));
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008577 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Chris Lattner12249be2006-05-25 23:48:38 +00008578 SVI.setOperand(2, ConstantPacked::get(Elts));
Chris Lattner0e477162006-05-26 00:29:06 +00008579 LHS = SVI.getOperand(0);
8580 RHS = SVI.getOperand(1);
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008581 MadeChange = true;
8582 }
8583
Chris Lattner0e477162006-05-26 00:29:06 +00008584 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner12249be2006-05-25 23:48:38 +00008585 bool isLHSID = true, isRHSID = true;
Chris Lattner34cebe72006-04-16 00:03:56 +00008586
Chris Lattner12249be2006-05-25 23:48:38 +00008587 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
8588 if (Mask[i] >= e*2) continue; // Ignore undef values.
8589 // Is this an identity shuffle of the LHS value?
8590 isLHSID &= (Mask[i] == i);
8591
8592 // Is this an identity shuffle of the RHS value?
8593 isRHSID &= (Mask[i]-e == i);
Chris Lattner34cebe72006-04-16 00:03:56 +00008594 }
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008595
Chris Lattner12249be2006-05-25 23:48:38 +00008596 // Eliminate identity shuffles.
8597 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
8598 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008599
Chris Lattner0e477162006-05-26 00:29:06 +00008600 // If the LHS is a shufflevector itself, see if we can combine it with this
8601 // one without producing an unusual shuffle. Here we are really conservative:
8602 // we are absolutely afraid of producing a shuffle mask not in the input
8603 // program, because the code gen may not be smart enough to turn a merged
8604 // shuffle into two specific shuffles: it may produce worse code. As such,
8605 // we only merge two shuffles if the result is one of the two input shuffle
8606 // masks. In this case, merging the shuffles just removes one instruction,
8607 // which we know is safe. This is good for things like turning:
8608 // (splat(splat)) -> splat.
8609 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
8610 if (isa<UndefValue>(RHS)) {
8611 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
8612
8613 std::vector<unsigned> NewMask;
8614 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
8615 if (Mask[i] >= 2*e)
8616 NewMask.push_back(2*e);
8617 else
8618 NewMask.push_back(LHSMask[Mask[i]]);
8619
8620 // If the result mask is equal to the src shuffle or this shuffle mask, do
8621 // the replacement.
8622 if (NewMask == LHSMask || NewMask == Mask) {
8623 std::vector<Constant*> Elts;
8624 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
8625 if (NewMask[i] >= e*2) {
8626 Elts.push_back(UndefValue::get(Type::UIntTy));
8627 } else {
Reid Spencere0fc4df2006-10-20 07:07:24 +00008628 Elts.push_back(ConstantInt::get(Type::UIntTy, NewMask[i]));
Chris Lattner0e477162006-05-26 00:29:06 +00008629 }
8630 }
8631 return new ShuffleVectorInst(LHSSVI->getOperand(0),
8632 LHSSVI->getOperand(1),
8633 ConstantPacked::get(Elts));
8634 }
8635 }
8636 }
8637
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008638 return MadeChange ? &SVI : 0;
8639}
8640
8641
Robert Bocchinoa8352962006-01-13 22:48:06 +00008642
Chris Lattner99f48c62002-09-02 04:59:56 +00008643void InstCombiner::removeFromWorkList(Instruction *I) {
8644 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
8645 WorkList.end());
8646}
8647
Chris Lattner39c98bb2004-12-08 23:43:58 +00008648
8649/// TryToSinkInstruction - Try to move the specified instruction from its
8650/// current block into the beginning of DestBlock, which can only happen if it's
8651/// safe to move the instruction past all of the instructions between it and the
8652/// end of its block.
8653static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
8654 assert(I->hasOneUse() && "Invariants didn't hold!");
8655
Chris Lattnerc4f67e62005-10-27 17:13:11 +00008656 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
8657 if (isa<PHINode>(I) || I->mayWriteToMemory()) return false;
Misha Brukmanb1c93172005-04-21 23:48:37 +00008658
Chris Lattner39c98bb2004-12-08 23:43:58 +00008659 // Do not sink alloca instructions out of the entry block.
8660 if (isa<AllocaInst>(I) && I->getParent() == &DestBlock->getParent()->front())
8661 return false;
8662
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00008663 // We can only sink load instructions if there is nothing between the load and
8664 // the end of block that could change the value.
8665 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00008666 for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
8667 Scan != E; ++Scan)
8668 if (Scan->mayWriteToMemory())
8669 return false;
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00008670 }
Chris Lattner39c98bb2004-12-08 23:43:58 +00008671
8672 BasicBlock::iterator InsertPos = DestBlock->begin();
8673 while (isa<PHINode>(InsertPos)) ++InsertPos;
8674
Chris Lattner9f269e42005-08-08 19:11:57 +00008675 I->moveBefore(InsertPos);
Chris Lattner39c98bb2004-12-08 23:43:58 +00008676 ++NumSunkInst;
8677 return true;
8678}
8679
Chris Lattner1443bc52006-05-11 17:11:52 +00008680/// OptimizeConstantExpr - Given a constant expression and target data layout
Reid Spencer13bc5d72006-12-12 09:18:51 +00008681/// information, symbolically evaluate the constant expr to something simpler
Chris Lattner1443bc52006-05-11 17:11:52 +00008682/// if possible.
8683static Constant *OptimizeConstantExpr(ConstantExpr *CE, const TargetData *TD) {
8684 if (!TD) return CE;
8685
8686 Constant *Ptr = CE->getOperand(0);
8687 if (CE->getOpcode() == Instruction::GetElementPtr && Ptr->isNullValue() &&
8688 cast<PointerType>(Ptr->getType())->getElementType()->isSized()) {
8689 // If this is a constant expr gep that is effectively computing an
8690 // "offsetof", fold it into 'cast int Size to T*' instead of 'gep 0, 0, 12'
8691 bool isFoldableGEP = true;
8692 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
8693 if (!isa<ConstantInt>(CE->getOperand(i)))
8694 isFoldableGEP = false;
8695 if (isFoldableGEP) {
8696 std::vector<Value*> Ops(CE->op_begin()+1, CE->op_end());
8697 uint64_t Offset = TD->getIndexedOffset(Ptr->getType(), Ops);
Reid Spencer2a499b02006-12-13 17:19:09 +00008698 Constant *C = ConstantInt::get(TD->getIntPtrType(), Offset);
Reid Spencer13bc5d72006-12-12 09:18:51 +00008699 return ConstantExpr::getIntToPtr(C, CE->getType());
Chris Lattner1443bc52006-05-11 17:11:52 +00008700 }
8701 }
8702
8703 return CE;
8704}
8705
Chris Lattnera36ee4e2006-05-10 19:00:36 +00008706
8707/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
8708/// all reachable code to the worklist.
8709///
8710/// This has a couple of tricks to make the code faster and more powerful. In
8711/// particular, we constant fold and DCE instructions as we go, to avoid adding
8712/// them to the worklist (this significantly speeds up instcombine on code where
8713/// many instructions are dead or constant). Additionally, if we find a branch
8714/// whose condition is a known constant, we only visit the reachable successors.
8715///
8716static void AddReachableCodeToWorklist(BasicBlock *BB,
8717 std::set<BasicBlock*> &Visited,
Chris Lattner1443bc52006-05-11 17:11:52 +00008718 std::vector<Instruction*> &WorkList,
8719 const TargetData *TD) {
Chris Lattnera36ee4e2006-05-10 19:00:36 +00008720 // We have now visited this block! If we've already been here, bail out.
8721 if (!Visited.insert(BB).second) return;
8722
8723 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
8724 Instruction *Inst = BBI++;
8725
8726 // DCE instruction if trivially dead.
8727 if (isInstructionTriviallyDead(Inst)) {
8728 ++NumDeadInst;
Bill Wendling5dbf43c2006-11-26 09:46:52 +00008729 DOUT << "IC: DCE: " << *Inst;
Chris Lattnera36ee4e2006-05-10 19:00:36 +00008730 Inst->eraseFromParent();
8731 continue;
8732 }
8733
8734 // ConstantProp instruction if trivially constant.
8735 if (Constant *C = ConstantFoldInstruction(Inst)) {
Chris Lattner1443bc52006-05-11 17:11:52 +00008736 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
8737 C = OptimizeConstantExpr(CE, TD);
Bill Wendling5dbf43c2006-11-26 09:46:52 +00008738 DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
Chris Lattnera36ee4e2006-05-10 19:00:36 +00008739 Inst->replaceAllUsesWith(C);
8740 ++NumConstProp;
8741 Inst->eraseFromParent();
8742 continue;
8743 }
8744
8745 WorkList.push_back(Inst);
8746 }
8747
8748 // Recursively visit successors. If this is a branch or switch on a constant,
8749 // only visit the reachable successor.
8750 TerminatorInst *TI = BB->getTerminator();
8751 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
8752 if (BI->isConditional() && isa<ConstantBool>(BI->getCondition())) {
8753 bool CondVal = cast<ConstantBool>(BI->getCondition())->getValue();
Chris Lattner1443bc52006-05-11 17:11:52 +00008754 AddReachableCodeToWorklist(BI->getSuccessor(!CondVal), Visited, WorkList,
8755 TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00008756 return;
8757 }
8758 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
8759 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
8760 // See if this is an explicit destination.
8761 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
8762 if (SI->getCaseValue(i) == Cond) {
Chris Lattner1443bc52006-05-11 17:11:52 +00008763 AddReachableCodeToWorklist(SI->getSuccessor(i), Visited, WorkList,TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00008764 return;
8765 }
8766
8767 // Otherwise it is the default destination.
Chris Lattner1443bc52006-05-11 17:11:52 +00008768 AddReachableCodeToWorklist(SI->getSuccessor(0), Visited, WorkList, TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00008769 return;
8770 }
8771 }
8772
8773 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
Chris Lattner1443bc52006-05-11 17:11:52 +00008774 AddReachableCodeToWorklist(TI->getSuccessor(i), Visited, WorkList, TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00008775}
8776
Chris Lattner113f4f42002-06-25 16:13:24 +00008777bool InstCombiner::runOnFunction(Function &F) {
Chris Lattner260ab202002-04-18 17:39:14 +00008778 bool Changed = false;
Chris Lattnerf4ad1652003-11-02 05:57:39 +00008779 TD = &getAnalysis<TargetData>();
Chris Lattnerca081252001-12-14 16:52:21 +00008780
Chris Lattner4ed40f72005-07-07 20:40:38 +00008781 {
Chris Lattnera36ee4e2006-05-10 19:00:36 +00008782 // Do a depth-first traversal of the function, populate the worklist with
8783 // the reachable instructions. Ignore blocks that are not reachable. Keep
8784 // track of which blocks we visit.
Chris Lattner4ed40f72005-07-07 20:40:38 +00008785 std::set<BasicBlock*> Visited;
Chris Lattner1443bc52006-05-11 17:11:52 +00008786 AddReachableCodeToWorklist(F.begin(), Visited, WorkList, TD);
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00008787
Chris Lattner4ed40f72005-07-07 20:40:38 +00008788 // Do a quick scan over the function. If we find any blocks that are
8789 // unreachable, remove any instructions inside of them. This prevents
8790 // the instcombine code from having to deal with some bad special cases.
8791 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
8792 if (!Visited.count(BB)) {
8793 Instruction *Term = BB->getTerminator();
8794 while (Term != BB->begin()) { // Remove instrs bottom-up
8795 BasicBlock::iterator I = Term; --I;
Chris Lattner2d3a7a62004-04-27 15:13:33 +00008796
Bill Wendling5dbf43c2006-11-26 09:46:52 +00008797 DOUT << "IC: DCE: " << *I;
Chris Lattner4ed40f72005-07-07 20:40:38 +00008798 ++NumDeadInst;
8799
8800 if (!I->use_empty())
8801 I->replaceAllUsesWith(UndefValue::get(I->getType()));
8802 I->eraseFromParent();
8803 }
8804 }
8805 }
Chris Lattnerca081252001-12-14 16:52:21 +00008806
8807 while (!WorkList.empty()) {
8808 Instruction *I = WorkList.back(); // Get an instruction from the worklist
8809 WorkList.pop_back();
8810
Chris Lattner1443bc52006-05-11 17:11:52 +00008811 // Check to see if we can DCE the instruction.
Chris Lattner99f48c62002-09-02 04:59:56 +00008812 if (isInstructionTriviallyDead(I)) {
Chris Lattner1443bc52006-05-11 17:11:52 +00008813 // Add operands to the worklist.
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00008814 if (I->getNumOperands() < 4)
Chris Lattner51ea1272004-02-28 05:22:00 +00008815 AddUsesToWorkList(*I);
Chris Lattner99f48c62002-09-02 04:59:56 +00008816 ++NumDeadInst;
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00008817
Bill Wendling5dbf43c2006-11-26 09:46:52 +00008818 DOUT << "IC: DCE: " << *I;
Chris Lattnercd517ff2005-01-28 19:32:01 +00008819
8820 I->eraseFromParent();
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00008821 removeFromWorkList(I);
8822 continue;
8823 }
Chris Lattner99f48c62002-09-02 04:59:56 +00008824
Chris Lattner1443bc52006-05-11 17:11:52 +00008825 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattner99f48c62002-09-02 04:59:56 +00008826 if (Constant *C = ConstantFoldInstruction(I)) {
Chris Lattner1443bc52006-05-11 17:11:52 +00008827 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
8828 C = OptimizeConstantExpr(CE, TD);
Bill Wendling5dbf43c2006-11-26 09:46:52 +00008829 DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
Chris Lattnercd517ff2005-01-28 19:32:01 +00008830
Chris Lattner1443bc52006-05-11 17:11:52 +00008831 // Add operands to the worklist.
Chris Lattner51ea1272004-02-28 05:22:00 +00008832 AddUsesToWorkList(*I);
Chris Lattnerc6509f42002-12-05 22:41:53 +00008833 ReplaceInstUsesWith(*I, C);
8834
Chris Lattner99f48c62002-09-02 04:59:56 +00008835 ++NumConstProp;
Chris Lattnera36ee4e2006-05-10 19:00:36 +00008836 I->eraseFromParent();
Chris Lattner800aaaf2003-10-07 15:17:02 +00008837 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00008838 continue;
Chris Lattner99f48c62002-09-02 04:59:56 +00008839 }
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00008840
Chris Lattner39c98bb2004-12-08 23:43:58 +00008841 // See if we can trivially sink this instruction to a successor basic block.
8842 if (I->hasOneUse()) {
8843 BasicBlock *BB = I->getParent();
8844 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
8845 if (UserParent != BB) {
8846 bool UserIsSuccessor = false;
8847 // See if the user is one of our successors.
8848 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
8849 if (*SI == UserParent) {
8850 UserIsSuccessor = true;
8851 break;
8852 }
8853
8854 // If the user is one of our immediate successors, and if that successor
8855 // only has us as a predecessors (we'd have to split the critical edge
8856 // otherwise), we can keep going.
8857 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
8858 next(pred_begin(UserParent)) == pred_end(UserParent))
8859 // Okay, the CFG is simple enough, try to sink this instruction.
8860 Changed |= TryToSinkInstruction(I, UserParent);
8861 }
8862 }
8863
Chris Lattnerca081252001-12-14 16:52:21 +00008864 // Now that we have an instruction, try combining it to simplify it...
Chris Lattnerae7a0d32002-08-02 19:29:35 +00008865 if (Instruction *Result = visit(*I)) {
Chris Lattner0b18c1d2002-05-10 15:38:35 +00008866 ++NumCombined;
Chris Lattner260ab202002-04-18 17:39:14 +00008867 // Should we replace the old instruction with a new one?
Chris Lattner053c0932002-05-14 15:24:07 +00008868 if (Result != I) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +00008869 DOUT << "IC: Old = " << *I
8870 << " New = " << *Result;
Chris Lattner7d2a5392004-03-13 23:54:27 +00008871
Chris Lattner396dbfe2004-06-09 05:08:07 +00008872 // Everything uses the new instruction now.
8873 I->replaceAllUsesWith(Result);
8874
8875 // Push the new instruction and any users onto the worklist.
8876 WorkList.push_back(Result);
8877 AddUsersToWorkList(*Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00008878
8879 // Move the name to the new instruction first...
8880 std::string OldName = I->getName(); I->setName("");
Chris Lattner950fc782003-10-07 22:58:41 +00008881 Result->setName(OldName);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00008882
8883 // Insert the new instruction into the basic block...
8884 BasicBlock *InstParent = I->getParent();
Chris Lattner7515cab2004-11-14 19:13:23 +00008885 BasicBlock::iterator InsertPos = I;
8886
8887 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
8888 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
8889 ++InsertPos;
8890
8891 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00008892
Chris Lattner63d75af2004-05-01 23:27:23 +00008893 // Make sure that we reprocess all operands now that we reduced their
8894 // use counts.
Chris Lattnerb643a9e2004-05-01 23:19:52 +00008895 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);
8898
Chris Lattner396dbfe2004-06-09 05:08:07 +00008899 // Instructions can end up on the worklist more than once. Make sure
8900 // we do not process an instruction that has been deleted.
8901 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00008902
8903 // Erase the old instruction.
8904 InstParent->getInstList().erase(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00008905 } else {
Bill Wendling5dbf43c2006-11-26 09:46:52 +00008906 DOUT << "IC: MOD = " << *I;
Chris Lattner7d2a5392004-03-13 23:54:27 +00008907
Chris Lattnerae7a0d32002-08-02 19:29:35 +00008908 // If the instruction was modified, it's possible that it is now dead.
8909 // if so, remove it.
Chris Lattner63d75af2004-05-01 23:27:23 +00008910 if (isInstructionTriviallyDead(I)) {
8911 // Make sure we process all operands now that we are reducing their
8912 // use counts.
8913 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
8914 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
8915 WorkList.push_back(OpI);
Misha Brukmanb1c93172005-04-21 23:48:37 +00008916
Chris Lattner63d75af2004-05-01 23:27:23 +00008917 // Instructions may end up in the worklist more than once. Erase all
Robert Bocchinoa8352962006-01-13 22:48:06 +00008918 // occurrences of this instruction.
Chris Lattner99f48c62002-09-02 04:59:56 +00008919 removeFromWorkList(I);
Chris Lattner31f486c2005-01-31 05:36:43 +00008920 I->eraseFromParent();
Chris Lattner396dbfe2004-06-09 05:08:07 +00008921 } else {
8922 WorkList.push_back(Result);
8923 AddUsersToWorkList(*Result);
Chris Lattnerae7a0d32002-08-02 19:29:35 +00008924 }
Chris Lattner053c0932002-05-14 15:24:07 +00008925 }
Chris Lattner260ab202002-04-18 17:39:14 +00008926 Changed = true;
Chris Lattnerca081252001-12-14 16:52:21 +00008927 }
8928 }
8929
Chris Lattner260ab202002-04-18 17:39:14 +00008930 return Changed;
Chris Lattner04805fa2002-02-26 21:46:54 +00008931}
8932
Brian Gaeke38b79e82004-07-27 17:43:21 +00008933FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattner260ab202002-04-18 17:39:14 +00008934 return new InstCombiner();
Chris Lattner04805fa2002-02-26 21:46:54 +00008935}
Brian Gaeke960707c2003-11-11 22:41:34 +00008936