blob: 57b17a9c72257662655a0665d54dffa63eb4ffc9 [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 Spencer6c38f0b2006-11-27 01:05:10 +00001795 Instruction *NewTrunc =
1796 CastInst::createInferredCast(XorLHS, MiddleType, "sext");
Chris Lattner0b3557f2005-09-24 23:43:33 +00001797 InsertNewInstBefore(NewTrunc, I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001798 return new SExtInst(NewTrunc, I.getType());
Chris Lattner0b3557f2005-09-24 23:43:33 +00001799 }
1800 }
Chris Lattnercf4a9962004-04-10 22:01:55 +00001801 }
Chris Lattner9fa53de2002-05-06 16:49:18 +00001802
Chris Lattnerb8b97502003-08-13 19:01:45 +00001803 // X + X --> X << 1
Robert Bocchino7b5b86c2004-07-27 21:02:21 +00001804 if (I.getType()->isInteger()) {
Chris Lattnerb8b97502003-08-13 19:01:45 +00001805 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Chris Lattner47060462005-04-07 17:14:51 +00001806
1807 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
1808 if (RHSI->getOpcode() == Instruction::Sub)
1809 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
1810 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
1811 }
1812 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
1813 if (LHSI->getOpcode() == Instruction::Sub)
1814 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
1815 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
1816 }
Robert Bocchino7b5b86c2004-07-27 21:02:21 +00001817 }
Chris Lattnerede3fe02003-08-13 04:18:28 +00001818
Chris Lattner147e9752002-05-08 22:46:53 +00001819 // -A + B --> B - A
Chris Lattnerbb74e222003-03-10 23:06:50 +00001820 if (Value *V = dyn_castNegVal(LHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001821 return BinaryOperator::createSub(RHS, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +00001822
1823 // A + -B --> A - B
Chris Lattnerbb74e222003-03-10 23:06:50 +00001824 if (!isa<Constant>(RHS))
1825 if (Value *V = dyn_castNegVal(RHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001826 return BinaryOperator::createSub(LHS, V);
Chris Lattner260ab202002-04-18 17:39:14 +00001827
Misha Brukmanb1c93172005-04-21 23:48:37 +00001828
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001829 ConstantInt *C2;
1830 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
1831 if (X == RHS) // X*C + X --> X * (C+1)
1832 return BinaryOperator::createMul(RHS, AddOne(C2));
1833
1834 // X*C1 + X*C2 --> X * (C1+C2)
1835 ConstantInt *C1;
1836 if (X == dyn_castFoldableMul(RHS, C1))
1837 return BinaryOperator::createMul(X, ConstantExpr::getAdd(C1, C2));
Chris Lattner57c8d992003-02-18 19:57:07 +00001838 }
1839
1840 // X + X*C --> X * (C+1)
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001841 if (dyn_castFoldableMul(RHS, C2) == LHS)
1842 return BinaryOperator::createMul(LHS, AddOne(C2));
1843
Chris Lattner57c8d992003-02-18 19:57:07 +00001844
Chris Lattnerb8b97502003-08-13 19:01:45 +00001845 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattnerd4252a72004-07-30 07:50:03 +00001846 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattnerb8b97502003-08-13 19:01:45 +00001847 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2))) return R;
Chris Lattner7fb29e12003-03-11 00:12:48 +00001848
Chris Lattnerb9cde762003-10-02 15:11:26 +00001849 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner330628a2006-01-06 17:59:59 +00001850 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00001851 if (match(LHS, m_Not(m_Value(X)))) { // ~X + C --> (C-1) - X
1852 Constant *C= ConstantExpr::getSub(CRHS, ConstantInt::get(I.getType(), 1));
1853 return BinaryOperator::createSub(C, X);
Chris Lattnerb9cde762003-10-02 15:11:26 +00001854 }
Chris Lattnerd4252a72004-07-30 07:50:03 +00001855
Chris Lattnerbff91d92004-10-08 05:07:56 +00001856 // (X & FF00) + xx00 -> (X+xx00) & FF00
1857 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
1858 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
1859 if (Anded == CRHS) {
1860 // See if all bits from the first bit set in the Add RHS up are included
1861 // in the mask. First, get the rightmost bit.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001862 uint64_t AddRHSV = CRHS->getZExtValue();
Chris Lattnerbff91d92004-10-08 05:07:56 +00001863
1864 // Form a mask of all bits from the lowest bit added through the top.
1865 uint64_t AddRHSHighBits = ~((AddRHSV & -AddRHSV)-1);
Chris Lattner77defba2006-02-07 07:00:41 +00001866 AddRHSHighBits &= C2->getType()->getIntegralTypeMask();
Chris Lattnerbff91d92004-10-08 05:07:56 +00001867
1868 // See if the and mask includes all of these bits.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001869 uint64_t AddRHSHighBitsAnd = AddRHSHighBits & C2->getZExtValue();
Misha Brukmanb1c93172005-04-21 23:48:37 +00001870
Chris Lattnerbff91d92004-10-08 05:07:56 +00001871 if (AddRHSHighBits == AddRHSHighBitsAnd) {
1872 // Okay, the xform is safe. Insert the new add pronto.
1873 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
1874 LHS->getName()), I);
1875 return BinaryOperator::createAnd(NewAdd, C2);
1876 }
1877 }
1878 }
1879
Chris Lattnerd4252a72004-07-30 07:50:03 +00001880 // Try to fold constant add into select arguments.
1881 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner86102b82005-01-01 16:22:27 +00001882 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattnerd4252a72004-07-30 07:50:03 +00001883 return R;
Chris Lattnerb9cde762003-10-02 15:11:26 +00001884 }
1885
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001886 // add (cast *A to intptrtype) B ->
1887 // cast (GEP (cast *A to sbyte*) B) ->
1888 // intptrtype
Andrew Lenharth4f339be2006-09-19 18:24:51 +00001889 {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001890 CastInst *CI = dyn_cast<CastInst>(LHS);
1891 Value *Other = RHS;
Andrew Lenharth4f339be2006-09-19 18:24:51 +00001892 if (!CI) {
1893 CI = dyn_cast<CastInst>(RHS);
1894 Other = LHS;
1895 }
Andrew Lenharth44cb67a2006-09-20 15:37:57 +00001896 if (CI && CI->getType()->isSized() &&
1897 (CI->getType()->getPrimitiveSize() ==
1898 TD->getIntPtrType()->getPrimitiveSize())
1899 && isa<PointerType>(CI->getOperand(0)->getType())) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00001900 Value *I2 = InsertCastBefore(Instruction::BitCast, CI->getOperand(0),
Andrew Lenharth44cb67a2006-09-20 15:37:57 +00001901 PointerType::get(Type::SByteTy), I);
1902 I2 = InsertNewInstBefore(new GetElementPtrInst(I2, Other, "ctg2"), I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001903 return new PtrToIntInst(I2, CI->getType());
Andrew Lenharth4f339be2006-09-19 18:24:51 +00001904 }
1905 }
1906
Chris Lattner113f4f42002-06-25 16:13:24 +00001907 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +00001908}
1909
Chris Lattnerbdb0ce02003-07-22 21:46:59 +00001910// isSignBit - Return true if the value represented by the constant only has the
1911// highest order bit set.
1912static bool isSignBit(ConstantInt *CI) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001913 unsigned NumBits = CI->getType()->getPrimitiveSizeInBits();
Reid Spencere0fc4df2006-10-20 07:07:24 +00001914 return (CI->getZExtValue() & (~0ULL >> (64-NumBits))) == (1ULL << (NumBits-1));
Chris Lattnerbdb0ce02003-07-22 21:46:59 +00001915}
1916
Chris Lattner022167f2004-03-13 00:11:49 +00001917/// RemoveNoopCast - Strip off nonconverting casts from the value.
1918///
1919static Value *RemoveNoopCast(Value *V) {
1920 if (CastInst *CI = dyn_cast<CastInst>(V)) {
1921 const Type *CTy = CI->getType();
1922 const Type *OpTy = CI->getOperand(0)->getType();
1923 if (CTy->isInteger() && OpTy->isInteger()) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001924 if (CTy->getPrimitiveSizeInBits() == OpTy->getPrimitiveSizeInBits())
Chris Lattner022167f2004-03-13 00:11:49 +00001925 return RemoveNoopCast(CI->getOperand(0));
1926 } else if (isa<PointerType>(CTy) && isa<PointerType>(OpTy))
1927 return RemoveNoopCast(CI->getOperand(0));
1928 }
1929 return V;
1930}
1931
Chris Lattner113f4f42002-06-25 16:13:24 +00001932Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +00001933 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001934
Chris Lattnere6794492002-08-12 21:17:25 +00001935 if (Op0 == Op1) // sub X, X -> 0
1936 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner260ab202002-04-18 17:39:14 +00001937
Chris Lattnere6794492002-08-12 21:17:25 +00001938 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattnerbb74e222003-03-10 23:06:50 +00001939 if (Value *V = dyn_castNegVal(Op1))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001940 return BinaryOperator::createAdd(Op0, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +00001941
Chris Lattner81a7a232004-10-16 18:11:37 +00001942 if (isa<UndefValue>(Op0))
1943 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
1944 if (isa<UndefValue>(Op1))
1945 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
1946
Chris Lattner8f2f5982003-11-05 01:06:05 +00001947 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
1948 // Replace (-1 - A) with (~A)...
Chris Lattner3082c5a2003-02-18 19:28:33 +00001949 if (C->isAllOnesValue())
1950 return BinaryOperator::createNot(Op1);
Chris Lattnerad3c4952002-05-09 01:29:19 +00001951
Chris Lattner8f2f5982003-11-05 01:06:05 +00001952 // C - ~X == X + (1+C)
Reid Spencer4fdd96c2005-06-18 17:37:34 +00001953 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00001954 if (match(Op1, m_Not(m_Value(X))))
1955 return BinaryOperator::createAdd(X,
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001956 ConstantExpr::getAdd(C, ConstantInt::get(I.getType(), 1)));
Chris Lattner92295c52004-03-12 23:53:13 +00001957 // -((uint)X >> 31) -> ((int)X >> 31)
1958 // -((int)X >> 31) -> ((uint)X >> 31)
Chris Lattner022167f2004-03-13 00:11:49 +00001959 if (C->isNullValue()) {
1960 Value *NoopCastedRHS = RemoveNoopCast(Op1);
1961 if (ShiftInst *SI = dyn_cast<ShiftInst>(NoopCastedRHS))
Reid Spencerfdff9382006-11-08 06:47:33 +00001962 if (SI->getOpcode() == Instruction::LShr) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00001963 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
Chris Lattner92295c52004-03-12 23:53:13 +00001964 // Check to see if we are shifting out everything but the sign bit.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001965 if (CU->getZExtValue() ==
1966 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerfdff9382006-11-08 06:47:33 +00001967 // Ok, the transformation is safe. Insert AShr.
1968 return new ShiftInst(Instruction::AShr, SI->getOperand(0),
1969 CU, SI->getName());
Chris Lattner92295c52004-03-12 23:53:13 +00001970 }
1971 }
Reid Spencerfdff9382006-11-08 06:47:33 +00001972 }
1973 else if (SI->getOpcode() == Instruction::AShr) {
1974 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
1975 // Check to see if we are shifting out everything but the sign bit.
1976 if (CU->getZExtValue() ==
1977 SI->getType()->getPrimitiveSizeInBits()-1) {
1978 // Ok, the transformation is safe. Insert LShr.
1979 return new ShiftInst(Instruction::LShr, SI->getOperand(0),
1980 CU, SI->getName());
1981 }
1982 }
1983 }
Chris Lattner022167f2004-03-13 00:11:49 +00001984 }
Chris Lattner183b3362004-04-09 19:05:30 +00001985
1986 // Try to fold constant sub into select arguments.
1987 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner86102b82005-01-01 16:22:27 +00001988 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00001989 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001990
1991 if (isa<PHINode>(Op0))
1992 if (Instruction *NV = FoldOpIntoPhi(I))
1993 return NV;
Chris Lattner8f2f5982003-11-05 01:06:05 +00001994 }
1995
Chris Lattnera9be4492005-04-07 16:15:25 +00001996 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
1997 if (Op1I->getOpcode() == Instruction::Add &&
Chris Lattner7a002fe2006-12-02 00:13:08 +00001998 !Op0->getType()->isFPOrFPVector()) {
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00001999 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Chris Lattnera9be4492005-04-07 16:15:25 +00002000 return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00002001 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Chris Lattnera9be4492005-04-07 16:15:25 +00002002 return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00002003 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2004 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2005 // C1-(X+C2) --> (C1-C2)-X
2006 return BinaryOperator::createSub(ConstantExpr::getSub(CI1, CI2),
2007 Op1I->getOperand(0));
2008 }
Chris Lattnera9be4492005-04-07 16:15:25 +00002009 }
2010
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002011 if (Op1I->hasOneUse()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00002012 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2013 // is not used by anyone else...
2014 //
Chris Lattnerc2f0aa52004-02-02 20:09:56 +00002015 if (Op1I->getOpcode() == Instruction::Sub &&
Chris Lattner7a002fe2006-12-02 00:13:08 +00002016 !Op1I->getType()->isFPOrFPVector()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00002017 // Swap the two operands of the subexpr...
2018 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2019 Op1I->setOperand(0, IIOp1);
2020 Op1I->setOperand(1, IIOp0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002021
Chris Lattner3082c5a2003-02-18 19:28:33 +00002022 // Create the new top level add instruction...
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002023 return BinaryOperator::createAdd(Op0, Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002024 }
2025
2026 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2027 //
2028 if (Op1I->getOpcode() == Instruction::And &&
2029 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2030 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2031
Chris Lattner396dbfe2004-06-09 05:08:07 +00002032 Value *NewNot =
2033 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002034 return BinaryOperator::createAnd(Op0, NewNot);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002035 }
Chris Lattner57c8d992003-02-18 19:57:07 +00002036
Reid Spencer3c514952006-10-16 23:08:08 +00002037 // 0 - (X sdiv C) -> (X sdiv -C)
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002038 if (Op1I->getOpcode() == Instruction::SDiv)
Reid Spencere0fc4df2006-10-20 07:07:24 +00002039 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002040 if (CSI->isNullValue())
Chris Lattner0aee4b72004-10-06 15:08:25 +00002041 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002042 return BinaryOperator::createSDiv(Op1I->getOperand(0),
Chris Lattner0aee4b72004-10-06 15:08:25 +00002043 ConstantExpr::getNeg(DivRHS));
2044
Chris Lattner57c8d992003-02-18 19:57:07 +00002045 // X - X*C --> X * (1-C)
Reid Spencer4fdd96c2005-06-18 17:37:34 +00002046 ConstantInt *C2 = 0;
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002047 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00002048 Constant *CP1 =
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002049 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1), C2);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002050 return BinaryOperator::createMul(Op0, CP1);
Chris Lattner57c8d992003-02-18 19:57:07 +00002051 }
Chris Lattnerad3c4952002-05-09 01:29:19 +00002052 }
Chris Lattnera9be4492005-04-07 16:15:25 +00002053 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00002054
Chris Lattner7a002fe2006-12-02 00:13:08 +00002055 if (!Op0->getType()->isFPOrFPVector())
Chris Lattner47060462005-04-07 17:14:51 +00002056 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2057 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner411336f2005-01-19 21:50:18 +00002058 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2059 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2060 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2061 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner47060462005-04-07 17:14:51 +00002062 } else if (Op0I->getOpcode() == Instruction::Sub) {
2063 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
2064 return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
Chris Lattner411336f2005-01-19 21:50:18 +00002065 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002066
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002067 ConstantInt *C1;
2068 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2069 if (X == Op1) { // X*C - X --> X * (C-1)
2070 Constant *CP1 = ConstantExpr::getSub(C1, ConstantInt::get(I.getType(),1));
2071 return BinaryOperator::createMul(Op1, CP1);
2072 }
Chris Lattner57c8d992003-02-18 19:57:07 +00002073
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002074 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
2075 if (X == dyn_castFoldableMul(Op1, C2))
2076 return BinaryOperator::createMul(Op1, ConstantExpr::getSub(C1, C2));
2077 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002078 return 0;
Chris Lattner260ab202002-04-18 17:39:14 +00002079}
2080
Chris Lattnere79e8542004-02-23 06:38:22 +00002081/// isSignBitCheck - Given an exploded setcc instruction, return true if it is
2082/// really just returns true if the most significant (sign) bit is set.
2083static bool isSignBitCheck(unsigned Opcode, Value *LHS, ConstantInt *RHS) {
2084 if (RHS->getType()->isSigned()) {
2085 // True if source is LHS < 0 or LHS <= -1
2086 return Opcode == Instruction::SetLT && RHS->isNullValue() ||
2087 Opcode == Instruction::SetLE && RHS->isAllOnesValue();
2088 } else {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002089 ConstantInt *RHSC = cast<ConstantInt>(RHS);
Chris Lattnere79e8542004-02-23 06:38:22 +00002090 // True if source is LHS > 127 or LHS >= 128, where the constants depend on
2091 // the size of the integer type.
2092 if (Opcode == Instruction::SetGE)
Reid Spencere0fc4df2006-10-20 07:07:24 +00002093 return RHSC->getZExtValue() ==
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002094 1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1);
Chris Lattnere79e8542004-02-23 06:38:22 +00002095 if (Opcode == Instruction::SetGT)
Reid Spencere0fc4df2006-10-20 07:07:24 +00002096 return RHSC->getZExtValue() ==
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002097 (1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1))-1;
Chris Lattnere79e8542004-02-23 06:38:22 +00002098 }
2099 return false;
2100}
2101
Chris Lattner113f4f42002-06-25 16:13:24 +00002102Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00002103 bool Changed = SimplifyCommutative(I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002104 Value *Op0 = I.getOperand(0);
Chris Lattner260ab202002-04-18 17:39:14 +00002105
Chris Lattner81a7a232004-10-16 18:11:37 +00002106 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
2107 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2108
Chris Lattnere6794492002-08-12 21:17:25 +00002109 // Simplify mul instructions with a constant RHS...
Chris Lattner3082c5a2003-02-18 19:28:33 +00002110 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2111 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerede3fe02003-08-13 04:18:28 +00002112
2113 // ((X << C1)*C2) == (X * (C2 << C1))
2114 if (ShiftInst *SI = dyn_cast<ShiftInst>(Op0))
2115 if (SI->getOpcode() == Instruction::Shl)
2116 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002117 return BinaryOperator::createMul(SI->getOperand(0),
2118 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanb1c93172005-04-21 23:48:37 +00002119
Chris Lattnercce81be2003-09-11 22:24:54 +00002120 if (CI->isNullValue())
2121 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2122 if (CI->equalsInt(1)) // X * 1 == X
2123 return ReplaceInstUsesWith(I, Op0);
2124 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Chris Lattner35236d82003-06-25 17:09:20 +00002125 return BinaryOperator::createNeg(Op0, I.getName());
Chris Lattner31ba1292002-04-29 22:24:47 +00002126
Reid Spencere0fc4df2006-10-20 07:07:24 +00002127 int64_t Val = (int64_t)cast<ConstantInt>(CI)->getZExtValue();
Chris Lattner22d00a82005-08-02 19:16:58 +00002128 if (isPowerOf2_64(Val)) { // Replace X*(2^C) with X << C
2129 uint64_t C = Log2_64(Val);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002130 return new ShiftInst(Instruction::Shl, Op0,
Reid Spencere0fc4df2006-10-20 07:07:24 +00002131 ConstantInt::get(Type::UByteTy, C));
Chris Lattner22d00a82005-08-02 19:16:58 +00002132 }
Robert Bocchino7b5b86c2004-07-27 21:02:21 +00002133 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00002134 if (Op1F->isNullValue())
2135 return ReplaceInstUsesWith(I, Op1);
Chris Lattner31ba1292002-04-29 22:24:47 +00002136
Chris Lattner3082c5a2003-02-18 19:28:33 +00002137 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2138 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2139 if (Op1F->getValue() == 1.0)
2140 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
2141 }
Chris Lattner32c01df2006-03-04 06:04:02 +00002142
2143 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2144 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2145 isa<ConstantInt>(Op0I->getOperand(1))) {
2146 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2147 Instruction *Add = BinaryOperator::createMul(Op0I->getOperand(0),
2148 Op1, "tmp");
2149 InsertNewInstBefore(Add, I);
2150 Value *C1C2 = ConstantExpr::getMul(Op1,
2151 cast<Constant>(Op0I->getOperand(1)));
2152 return BinaryOperator::createAdd(Add, C1C2);
2153
2154 }
Chris Lattner183b3362004-04-09 19:05:30 +00002155
2156 // Try to fold constant mul into select arguments.
2157 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00002158 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00002159 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002160
2161 if (isa<PHINode>(Op0))
2162 if (Instruction *NV = FoldOpIntoPhi(I))
2163 return NV;
Chris Lattner260ab202002-04-18 17:39:14 +00002164 }
2165
Chris Lattner934a64cf2003-03-10 23:23:04 +00002166 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
2167 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002168 return BinaryOperator::createMul(Op0v, Op1v);
Chris Lattner934a64cf2003-03-10 23:23:04 +00002169
Chris Lattner2635b522004-02-23 05:39:21 +00002170 // If one of the operands of the multiply is a cast from a boolean value, then
2171 // we know the bool is either zero or one, so this is a 'masking' multiply.
2172 // See if we can simplify things based on how the boolean was originally
2173 // formed.
2174 CastInst *BoolCast = 0;
2175 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(0)))
2176 if (CI->getOperand(0)->getType() == Type::BoolTy)
2177 BoolCast = CI;
2178 if (!BoolCast)
2179 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(1)))
2180 if (CI->getOperand(0)->getType() == Type::BoolTy)
2181 BoolCast = CI;
2182 if (BoolCast) {
2183 if (SetCondInst *SCI = dyn_cast<SetCondInst>(BoolCast->getOperand(0))) {
2184 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2185 const Type *SCOpTy = SCIOp0->getType();
2186
Chris Lattnere79e8542004-02-23 06:38:22 +00002187 // If the setcc is true iff the sign bit of X is set, then convert this
2188 // multiply into a shift/and combination.
2189 if (isa<ConstantInt>(SCIOp1) &&
2190 isSignBitCheck(SCI->getOpcode(), SCIOp0, cast<ConstantInt>(SCIOp1))) {
Chris Lattner2635b522004-02-23 05:39:21 +00002191 // Shift the X value right to turn it into "all signbits".
Reid Spencere0fc4df2006-10-20 07:07:24 +00002192 Constant *Amt = ConstantInt::get(Type::UByteTy,
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002193 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattnere79e8542004-02-23 06:38:22 +00002194 if (SCIOp0->getType()->isUnsigned()) {
Chris Lattner97bfcea2004-06-17 18:16:02 +00002195 const Type *NewTy = SCIOp0->getType()->getSignedVersion();
Reid Spencer13bc5d72006-12-12 09:18:51 +00002196 SCIOp0 = InsertCastBefore(Instruction::BitCast, SCIOp0, NewTy, I);
Chris Lattnere79e8542004-02-23 06:38:22 +00002197 }
2198
2199 Value *V =
Reid Spencerfdff9382006-11-08 06:47:33 +00002200 InsertNewInstBefore(new ShiftInst(Instruction::AShr, SCIOp0, Amt,
Chris Lattnere79e8542004-02-23 06:38:22 +00002201 BoolCast->getOperand(0)->getName()+
2202 ".mask"), I);
Chris Lattner2635b522004-02-23 05:39:21 +00002203
2204 // If the multiply type is not the same as the source type, sign extend
2205 // or truncate to the multiply type.
Reid Spencer13bc5d72006-12-12 09:18:51 +00002206 if (I.getType() != V->getType()) {
2207 unsigned SrcBits = V->getType()->getPrimitiveSizeInBits();
2208 unsigned DstBits = I.getType()->getPrimitiveSizeInBits();
2209 Instruction::CastOps opcode =
2210 (SrcBits == DstBits ? Instruction::BitCast :
2211 (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2212 V = InsertCastBefore(opcode, V, I.getType(), I);
2213 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002214
Chris Lattner2635b522004-02-23 05:39:21 +00002215 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002216 return BinaryOperator::createAnd(V, OtherOp);
Chris Lattner2635b522004-02-23 05:39:21 +00002217 }
2218 }
2219 }
2220
Chris Lattner113f4f42002-06-25 16:13:24 +00002221 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +00002222}
2223
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002224/// This function implements the transforms on div instructions that work
2225/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2226/// used by the visitors to those instructions.
2227/// @brief Transforms common to all three div instructions
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002228Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002229 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner81a7a232004-10-16 18:11:37 +00002230
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002231 // undef / X -> 0
2232 if (isa<UndefValue>(Op0))
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002233 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002234
2235 // X / undef -> undef
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002236 if (isa<UndefValue>(Op1))
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002237 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002238
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002239 // Handle cases involving: div X, (select Cond, Y, Z)
Chris Lattnerd79dc792006-09-09 20:26:32 +00002240 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2241 // div X, (Cond ? 0 : Y) -> div X, Y. If the div and the select are in the
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002242 // same basic block, then we replace the select with Y, and the condition
2243 // of the select with false (if the cond value is in the same BB). If the
Chris Lattnerd79dc792006-09-09 20:26:32 +00002244 // select has uses other than the div, this allows them to be simplified
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002245 // also. Note that div X, Y is just as good as div X, 0 (undef)
Chris Lattnerd79dc792006-09-09 20:26:32 +00002246 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2247 if (ST->isNullValue()) {
2248 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2249 if (CondI && CondI->getParent() == I.getParent())
Chris Lattner6ab03f62006-09-28 23:35:22 +00002250 UpdateValueUsesWith(CondI, ConstantBool::getFalse());
Chris Lattnerd79dc792006-09-09 20:26:32 +00002251 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2252 I.setOperand(1, SI->getOperand(2));
2253 else
2254 UpdateValueUsesWith(SI, SI->getOperand(2));
2255 return &I;
2256 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002257
Chris Lattnerd79dc792006-09-09 20:26:32 +00002258 // Likewise for: div X, (Cond ? Y : 0) -> div X, Y
2259 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2260 if (ST->isNullValue()) {
2261 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2262 if (CondI && CondI->getParent() == I.getParent())
Chris Lattner6ab03f62006-09-28 23:35:22 +00002263 UpdateValueUsesWith(CondI, ConstantBool::getTrue());
Chris Lattnerd79dc792006-09-09 20:26:32 +00002264 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2265 I.setOperand(1, SI->getOperand(1));
2266 else
2267 UpdateValueUsesWith(SI, SI->getOperand(1));
2268 return &I;
2269 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002270 }
Chris Lattnerd79dc792006-09-09 20:26:32 +00002271
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002272 return 0;
2273}
Misha Brukmanb1c93172005-04-21 23:48:37 +00002274
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002275/// This function implements the transforms common to both integer division
2276/// instructions (udiv and sdiv). It is called by the visitors to those integer
2277/// division instructions.
2278/// @brief Common integer divide transforms
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002279Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002280 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2281
2282 if (Instruction *Common = commonDivTransforms(I))
2283 return Common;
2284
2285 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2286 // div X, 1 == X
2287 if (RHS->equalsInt(1))
2288 return ReplaceInstUsesWith(I, Op0);
2289
2290 // (X / C1) / C2 -> X / (C1*C2)
2291 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2292 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2293 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
2294 return BinaryOperator::create(I.getOpcode(), LHS->getOperand(0),
2295 ConstantExpr::getMul(RHS, LHSRHS));
Chris Lattner42362612005-04-08 04:03:26 +00002296 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002297
2298 if (!RHS->isNullValue()) { // avoid X udiv 0
2299 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2300 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2301 return R;
2302 if (isa<PHINode>(Op0))
2303 if (Instruction *NV = FoldOpIntoPhi(I))
2304 return NV;
2305 }
Chris Lattnerd79dc792006-09-09 20:26:32 +00002306 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002307
Chris Lattner3082c5a2003-02-18 19:28:33 +00002308 // 0 / X == 0, we don't need to preserve faults!
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002309 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattner3082c5a2003-02-18 19:28:33 +00002310 if (LHS->equalsInt(0))
2311 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2312
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002313 return 0;
2314}
2315
2316Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2317 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2318
2319 // Handle the integer div common cases
2320 if (Instruction *Common = commonIDivTransforms(I))
2321 return Common;
2322
2323 // X udiv C^2 -> X >> C
2324 // Check to see if this is an unsigned division with an exact power of 2,
2325 // if so, convert to a right shift.
2326 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
2327 if (uint64_t Val = C->getZExtValue()) // Don't break X / 0
2328 if (isPowerOf2_64(Val)) {
2329 uint64_t ShiftAmt = Log2_64(Val);
Reid Spencerfdff9382006-11-08 06:47:33 +00002330 return new ShiftInst(Instruction::LShr, Op0,
2331 ConstantInt::get(Type::UByteTy, ShiftAmt));
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002332 }
2333 }
2334
2335 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
2336 if (ShiftInst *RHSI = dyn_cast<ShiftInst>(I.getOperand(1))) {
2337 if (RHSI->getOpcode() == Instruction::Shl &&
2338 isa<ConstantInt>(RHSI->getOperand(0))) {
2339 uint64_t C1 = cast<ConstantInt>(RHSI->getOperand(0))->getZExtValue();
2340 if (isPowerOf2_64(C1)) {
2341 Value *N = RHSI->getOperand(1);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002342 const Type *NTy = N->getType();
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002343 if (uint64_t C2 = Log2_64(C1)) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002344 Constant *C2V = ConstantInt::get(NTy, C2);
2345 N = InsertNewInstBefore(BinaryOperator::createAdd(N, C2V, "tmp"), I);
Chris Lattner2e90b732006-02-05 07:54:04 +00002346 }
Reid Spencerfdff9382006-11-08 06:47:33 +00002347 return new ShiftInst(Instruction::LShr, Op0, N);
Chris Lattner2e90b732006-02-05 07:54:04 +00002348 }
2349 }
Chris Lattnerdd0c1742005-11-05 07:40:31 +00002350 }
2351
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002352 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
2353 // where C1&C2 are powers of two.
2354 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2355 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2356 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2)))
2357 if (!STO->isNullValue() && !STO->isNullValue()) {
2358 uint64_t TVA = STO->getZExtValue(), FVA = SFO->getZExtValue();
2359 if (isPowerOf2_64(TVA) && isPowerOf2_64(FVA)) {
2360 // Compute the shift amounts
2361 unsigned TSA = Log2_64(TVA), FSA = Log2_64(FVA);
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002362 // Construct the "on true" case of the select
2363 Constant *TC = ConstantInt::get(Type::UByteTy, TSA);
2364 Instruction *TSI =
Reid Spencerfdff9382006-11-08 06:47:33 +00002365 new ShiftInst(Instruction::LShr, Op0, TC, SI->getName()+".t");
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002366 TSI = InsertNewInstBefore(TSI, I);
2367
2368 // Construct the "on false" case of the select
2369 Constant *FC = ConstantInt::get(Type::UByteTy, FSA);
2370 Instruction *FSI =
Reid Spencerfdff9382006-11-08 06:47:33 +00002371 new ShiftInst(Instruction::LShr, Op0, FC, SI->getName()+".f");
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002372 FSI = InsertNewInstBefore(FSI, I);
2373
2374 // construct the select instruction and return it.
Reid Spencerfdff9382006-11-08 06:47:33 +00002375 return new SelectInst(SI->getOperand(0), TSI, FSI, SI->getName());
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002376 }
2377 }
2378 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002379 return 0;
2380}
2381
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002382Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
2383 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2384
2385 // Handle the integer div common cases
2386 if (Instruction *Common = commonIDivTransforms(I))
2387 return Common;
2388
2389 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2390 // sdiv X, -1 == -X
2391 if (RHS->isAllOnesValue())
2392 return BinaryOperator::createNeg(Op0);
2393
2394 // -X/C -> X/-C
2395 if (Value *LHSNeg = dyn_castNegVal(Op0))
2396 return BinaryOperator::createSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
2397 }
2398
2399 // If the sign bits of both operands are zero (i.e. we can prove they are
2400 // unsigned inputs), turn this into a udiv.
2401 if (I.getType()->isInteger()) {
2402 uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
2403 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2404 return BinaryOperator::createUDiv(Op0, Op1, I.getName());
2405 }
2406 }
2407
2408 return 0;
2409}
2410
2411Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
2412 return commonDivTransforms(I);
2413}
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002414
Chris Lattner85dda9a2006-03-02 06:50:58 +00002415/// GetFactor - If we can prove that the specified value is at least a multiple
2416/// of some factor, return that factor.
2417static Constant *GetFactor(Value *V) {
2418 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
2419 return CI;
2420
2421 // Unless we can be tricky, we know this is a multiple of 1.
2422 Constant *Result = ConstantInt::get(V->getType(), 1);
2423
2424 Instruction *I = dyn_cast<Instruction>(V);
2425 if (!I) return Result;
2426
2427 if (I->getOpcode() == Instruction::Mul) {
2428 // Handle multiplies by a constant, etc.
2429 return ConstantExpr::getMul(GetFactor(I->getOperand(0)),
2430 GetFactor(I->getOperand(1)));
2431 } else if (I->getOpcode() == Instruction::Shl) {
2432 // (X<<C) -> X * (1 << C)
2433 if (Constant *ShRHS = dyn_cast<Constant>(I->getOperand(1))) {
2434 ShRHS = ConstantExpr::getShl(Result, ShRHS);
2435 return ConstantExpr::getMul(GetFactor(I->getOperand(0)), ShRHS);
2436 }
2437 } else if (I->getOpcode() == Instruction::And) {
2438 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
2439 // X & 0xFFF0 is known to be a multiple of 16.
2440 unsigned Zeros = CountTrailingZeros_64(RHS->getZExtValue());
2441 if (Zeros != V->getType()->getPrimitiveSizeInBits())
2442 return ConstantExpr::getShl(Result,
Reid Spencere0fc4df2006-10-20 07:07:24 +00002443 ConstantInt::get(Type::UByteTy, Zeros));
Chris Lattner85dda9a2006-03-02 06:50:58 +00002444 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002445 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
Chris Lattner85dda9a2006-03-02 06:50:58 +00002446 // Only handle int->int casts.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002447 if (!CI->isIntegerCast())
2448 return Result;
2449 Value *Op = CI->getOperand(0);
2450 return ConstantExpr::getCast(CI->getOpcode(), GetFactor(Op), V->getType());
Chris Lattner85dda9a2006-03-02 06:50:58 +00002451 }
2452 return Result;
2453}
2454
Reid Spencer7eb55b32006-11-02 01:53:59 +00002455/// This function implements the transforms on rem instructions that work
2456/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
2457/// is used by the visitors to those instructions.
2458/// @brief Transforms common to all three rem instructions
2459Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002460 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Reid Spencer7eb55b32006-11-02 01:53:59 +00002461
Chris Lattner0de4a8d2006-02-28 05:30:45 +00002462 // 0 % X == 0, we don't need to preserve faults!
2463 if (Constant *LHS = dyn_cast<Constant>(Op0))
2464 if (LHS->isNullValue())
2465 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2466
2467 if (isa<UndefValue>(Op0)) // undef % X -> 0
2468 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2469 if (isa<UndefValue>(Op1))
2470 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Reid Spencer7eb55b32006-11-02 01:53:59 +00002471
2472 // Handle cases involving: rem X, (select Cond, Y, Z)
2473 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2474 // rem X, (Cond ? 0 : Y) -> rem X, Y. If the rem and the select are in
2475 // the same basic block, then we replace the select with Y, and the
2476 // condition of the select with false (if the cond value is in the same
2477 // BB). If the select has uses other than the div, this allows them to be
2478 // simplified also.
2479 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2480 if (ST->isNullValue()) {
2481 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2482 if (CondI && CondI->getParent() == I.getParent())
2483 UpdateValueUsesWith(CondI, ConstantBool::getFalse());
2484 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2485 I.setOperand(1, SI->getOperand(2));
2486 else
2487 UpdateValueUsesWith(SI, SI->getOperand(2));
Chris Lattner7fd5f072004-07-06 07:01:22 +00002488 return &I;
2489 }
Reid Spencer7eb55b32006-11-02 01:53:59 +00002490 // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
2491 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2492 if (ST->isNullValue()) {
2493 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2494 if (CondI && CondI->getParent() == I.getParent())
2495 UpdateValueUsesWith(CondI, ConstantBool::getTrue());
2496 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2497 I.setOperand(1, SI->getOperand(1));
2498 else
2499 UpdateValueUsesWith(SI, SI->getOperand(1));
2500 return &I;
2501 }
Chris Lattnere9ff0ea2005-11-05 07:28:37 +00002502 }
Chris Lattner7fd5f072004-07-06 07:01:22 +00002503
Reid Spencer7eb55b32006-11-02 01:53:59 +00002504 return 0;
2505}
2506
2507/// This function implements the transforms common to both integer remainder
2508/// instructions (urem and srem). It is called by the visitors to those integer
2509/// remainder instructions.
2510/// @brief Common integer remainder transforms
2511Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
2512 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2513
2514 if (Instruction *common = commonRemTransforms(I))
2515 return common;
2516
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002517 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner0de4a8d2006-02-28 05:30:45 +00002518 // X % 0 == undef, we don't need to preserve faults!
2519 if (RHS->equalsInt(0))
2520 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2521
Chris Lattner3082c5a2003-02-18 19:28:33 +00002522 if (RHS->equalsInt(1)) // X % 1 == 0
2523 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2524
Chris Lattnerb70f1412006-02-28 05:49:21 +00002525 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2526 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2527 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2528 return R;
2529 } else if (isa<PHINode>(Op0I)) {
2530 if (Instruction *NV = FoldOpIntoPhi(I))
2531 return NV;
Chris Lattnerb70f1412006-02-28 05:49:21 +00002532 }
Reid Spencer7eb55b32006-11-02 01:53:59 +00002533 // (X * C1) % C2 --> 0 iff C1 % C2 == 0
2534 if (ConstantExpr::getSRem(GetFactor(Op0I), RHS)->isNullValue())
Chris Lattner85dda9a2006-03-02 06:50:58 +00002535 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerb70f1412006-02-28 05:49:21 +00002536 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00002537 }
2538
Reid Spencer7eb55b32006-11-02 01:53:59 +00002539 return 0;
2540}
2541
2542Instruction *InstCombiner::visitURem(BinaryOperator &I) {
2543 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2544
2545 if (Instruction *common = commonIRemTransforms(I))
2546 return common;
2547
2548 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2549 // X urem C^2 -> X and C
2550 // Check to see if this is an unsigned remainder with an exact power of 2,
2551 // if so, convert to a bitwise and.
2552 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
2553 if (isPowerOf2_64(C->getZExtValue()))
2554 return BinaryOperator::createAnd(Op0, SubOne(C));
2555 }
2556
Chris Lattner2e90b732006-02-05 07:54:04 +00002557 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00002558 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
2559 if (RHSI->getOpcode() == Instruction::Shl &&
2560 isa<ConstantInt>(RHSI->getOperand(0))) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002561 unsigned C1 = cast<ConstantInt>(RHSI->getOperand(0))->getZExtValue();
Chris Lattner2e90b732006-02-05 07:54:04 +00002562 if (isPowerOf2_64(C1)) {
2563 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
2564 Value *Add = InsertNewInstBefore(BinaryOperator::createAdd(RHSI, N1,
2565 "tmp"), I);
2566 return BinaryOperator::createAnd(Op0, Add);
2567 }
2568 }
Reid Spencer7eb55b32006-11-02 01:53:59 +00002569 }
Chris Lattnerd79dc792006-09-09 20:26:32 +00002570
Reid Spencer7eb55b32006-11-02 01:53:59 +00002571 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
2572 // where C1&C2 are powers of two.
2573 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2574 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2575 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
2576 // STO == 0 and SFO == 0 handled above.
2577 if (isPowerOf2_64(STO->getZExtValue()) &&
2578 isPowerOf2_64(SFO->getZExtValue())) {
2579 Value *TrueAnd = InsertNewInstBefore(
2580 BinaryOperator::createAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
2581 Value *FalseAnd = InsertNewInstBefore(
2582 BinaryOperator::createAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
2583 return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
2584 }
2585 }
Chris Lattner2e90b732006-02-05 07:54:04 +00002586 }
2587
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002588 return 0;
2589}
2590
Reid Spencer7eb55b32006-11-02 01:53:59 +00002591Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
2592 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2593
2594 if (Instruction *common = commonIRemTransforms(I))
2595 return common;
2596
2597 if (Value *RHSNeg = dyn_castNegVal(Op1))
2598 if (!isa<ConstantInt>(RHSNeg) ||
2599 cast<ConstantInt>(RHSNeg)->getSExtValue() > 0) {
2600 // X % -Y -> X % Y
2601 AddUsesToWorkList(I);
2602 I.setOperand(1, RHSNeg);
2603 return &I;
2604 }
2605
2606 // If the top bits of both operands are zero (i.e. we can prove they are
2607 // unsigned inputs), turn this into a urem.
2608 uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
2609 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2610 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
2611 return BinaryOperator::createURem(Op0, Op1, I.getName());
2612 }
2613
2614 return 0;
2615}
2616
2617Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00002618 return commonRemTransforms(I);
2619}
2620
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002621// isMaxValueMinusOne - return true if this is Max-1
Chris Lattnere6794492002-08-12 21:17:25 +00002622static bool isMaxValueMinusOne(const ConstantInt *C) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002623 if (C->getType()->isUnsigned())
2624 return C->getZExtValue() == C->getType()->getIntegralTypeMask()-1;
Misha Brukmanb1c93172005-04-21 23:48:37 +00002625
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002626 // Calculate 0111111111..11111
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002627 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002628 int64_t Val = INT64_MAX; // All ones
2629 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
Reid Spencere0fc4df2006-10-20 07:07:24 +00002630 return C->getSExtValue() == Val-1;
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002631}
2632
2633// isMinValuePlusOne - return true if this is Min+1
Chris Lattnere6794492002-08-12 21:17:25 +00002634static bool isMinValuePlusOne(const ConstantInt *C) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002635 if (C->getType()->isUnsigned())
2636 return C->getZExtValue() == 1;
Misha Brukmanb1c93172005-04-21 23:48:37 +00002637
2638 // Calculate 1111111111000000000000
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002639 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002640 int64_t Val = -1; // All ones
2641 Val <<= TypeBits-1; // Shift over to the right spot
Reid Spencere0fc4df2006-10-20 07:07:24 +00002642 return C->getSExtValue() == Val+1;
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002643}
2644
Chris Lattner35167c32004-06-09 07:59:58 +00002645// isOneBitSet - Return true if there is exactly one bit set in the specified
2646// constant.
2647static bool isOneBitSet(const ConstantInt *CI) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002648 uint64_t V = CI->getZExtValue();
Chris Lattner35167c32004-06-09 07:59:58 +00002649 return V && (V & (V-1)) == 0;
2650}
2651
Chris Lattner8fc5af42004-09-23 21:46:38 +00002652#if 0 // Currently unused
2653// isLowOnes - Return true if the constant is of the form 0+1+.
2654static bool isLowOnes(const ConstantInt *CI) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002655 uint64_t V = CI->getZExtValue();
Chris Lattner8fc5af42004-09-23 21:46:38 +00002656
2657 // There won't be bits set in parts that the type doesn't contain.
Reid Spencere0fc4df2006-10-20 07:07:24 +00002658 V &= ConstantInt::getAllOnesValue(CI->getType())->getZExtValue();
Chris Lattner8fc5af42004-09-23 21:46:38 +00002659
2660 uint64_t U = V+1; // If it is low ones, this should be a power of two.
2661 return U && V && (U & V) == 0;
2662}
2663#endif
2664
2665// isHighOnes - Return true if the constant is of the form 1+0+.
2666// This is the same as lowones(~X).
2667static bool isHighOnes(const ConstantInt *CI) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002668 uint64_t V = ~CI->getZExtValue();
Chris Lattner2c14cf72005-08-07 07:03:10 +00002669 if (~V == 0) return false; // 0's does not match "1+"
Chris Lattner8fc5af42004-09-23 21:46:38 +00002670
2671 // There won't be bits set in parts that the type doesn't contain.
Reid Spencere0fc4df2006-10-20 07:07:24 +00002672 V &= ConstantInt::getAllOnesValue(CI->getType())->getZExtValue();
Chris Lattner8fc5af42004-09-23 21:46:38 +00002673
2674 uint64_t U = V+1; // If it is low ones, this should be a power of two.
2675 return U && V && (U & V) == 0;
2676}
2677
2678
Chris Lattner3ac7c262003-08-13 20:16:26 +00002679/// getSetCondCode - Encode a setcc opcode into a three bit mask. These bits
2680/// are carefully arranged to allow folding of expressions such as:
2681///
2682/// (A < B) | (A > B) --> (A != B)
2683///
2684/// Bit value '4' represents that the comparison is true if A > B, bit value '2'
2685/// represents that the comparison is true if A == B, and bit value '1' is true
2686/// if A < B.
2687///
2688static unsigned getSetCondCode(const SetCondInst *SCI) {
2689 switch (SCI->getOpcode()) {
2690 // False -> 0
2691 case Instruction::SetGT: return 1;
2692 case Instruction::SetEQ: return 2;
2693 case Instruction::SetGE: return 3;
2694 case Instruction::SetLT: return 4;
2695 case Instruction::SetNE: return 5;
2696 case Instruction::SetLE: return 6;
2697 // True -> 7
2698 default:
2699 assert(0 && "Invalid SetCC opcode!");
2700 return 0;
2701 }
2702}
2703
2704/// getSetCCValue - This is the complement of getSetCondCode, which turns an
2705/// opcode and two operands into either a constant true or false, or a brand new
2706/// SetCC instruction.
2707static Value *getSetCCValue(unsigned Opcode, Value *LHS, Value *RHS) {
2708 switch (Opcode) {
Chris Lattner6ab03f62006-09-28 23:35:22 +00002709 case 0: return ConstantBool::getFalse();
Chris Lattner3ac7c262003-08-13 20:16:26 +00002710 case 1: return new SetCondInst(Instruction::SetGT, LHS, RHS);
2711 case 2: return new SetCondInst(Instruction::SetEQ, LHS, RHS);
2712 case 3: return new SetCondInst(Instruction::SetGE, LHS, RHS);
2713 case 4: return new SetCondInst(Instruction::SetLT, LHS, RHS);
2714 case 5: return new SetCondInst(Instruction::SetNE, LHS, RHS);
2715 case 6: return new SetCondInst(Instruction::SetLE, LHS, RHS);
Chris Lattner6ab03f62006-09-28 23:35:22 +00002716 case 7: return ConstantBool::getTrue();
Chris Lattner3ac7c262003-08-13 20:16:26 +00002717 default: assert(0 && "Illegal SetCCCode!"); return 0;
2718 }
2719}
2720
2721// FoldSetCCLogical - Implements (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
Chris Lattnere3a63d12006-11-15 04:53:24 +00002722namespace {
Chris Lattner3ac7c262003-08-13 20:16:26 +00002723struct FoldSetCCLogical {
2724 InstCombiner &IC;
2725 Value *LHS, *RHS;
2726 FoldSetCCLogical(InstCombiner &ic, SetCondInst *SCI)
2727 : IC(ic), LHS(SCI->getOperand(0)), RHS(SCI->getOperand(1)) {}
2728 bool shouldApply(Value *V) const {
2729 if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
2730 return (SCI->getOperand(0) == LHS && SCI->getOperand(1) == RHS ||
2731 SCI->getOperand(0) == RHS && SCI->getOperand(1) == LHS);
2732 return false;
2733 }
2734 Instruction *apply(BinaryOperator &Log) const {
2735 SetCondInst *SCI = cast<SetCondInst>(Log.getOperand(0));
2736 if (SCI->getOperand(0) != LHS) {
2737 assert(SCI->getOperand(1) == LHS);
2738 SCI->swapOperands(); // Swap the LHS and RHS of the SetCC
2739 }
2740
2741 unsigned LHSCode = getSetCondCode(SCI);
2742 unsigned RHSCode = getSetCondCode(cast<SetCondInst>(Log.getOperand(1)));
2743 unsigned Code;
2744 switch (Log.getOpcode()) {
2745 case Instruction::And: Code = LHSCode & RHSCode; break;
2746 case Instruction::Or: Code = LHSCode | RHSCode; break;
2747 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner2caaaba2003-09-22 20:33:34 +00002748 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattner3ac7c262003-08-13 20:16:26 +00002749 }
2750
2751 Value *RV = getSetCCValue(Code, LHS, RHS);
2752 if (Instruction *I = dyn_cast<Instruction>(RV))
2753 return I;
2754 // Otherwise, it's a constant boolean value...
2755 return IC.ReplaceInstUsesWith(Log, RV);
2756 }
2757};
Chris Lattnere3a63d12006-11-15 04:53:24 +00002758} // end anonymous namespace
Chris Lattner3ac7c262003-08-13 20:16:26 +00002759
Chris Lattnerba1cb382003-09-19 17:17:26 +00002760// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
2761// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
2762// guaranteed to be either a shift instruction or a binary operator.
2763Instruction *InstCombiner::OptAndOp(Instruction *Op,
2764 ConstantIntegral *OpRHS,
2765 ConstantIntegral *AndRHS,
2766 BinaryOperator &TheAnd) {
2767 Value *X = Op->getOperand(0);
Chris Lattnerfcf21a72004-01-12 19:47:05 +00002768 Constant *Together = 0;
2769 if (!isa<ShiftInst>(Op))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002770 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002771
Chris Lattnerba1cb382003-09-19 17:17:26 +00002772 switch (Op->getOpcode()) {
2773 case Instruction::Xor:
Chris Lattner86102b82005-01-01 16:22:27 +00002774 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00002775 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
2776 std::string OpName = Op->getName(); Op->setName("");
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002777 Instruction *And = BinaryOperator::createAnd(X, AndRHS, OpName);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002778 InsertNewInstBefore(And, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002779 return BinaryOperator::createXor(And, Together);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002780 }
2781 break;
2782 case Instruction::Or:
Chris Lattner86102b82005-01-01 16:22:27 +00002783 if (Together == AndRHS) // (X | C) & C --> C
2784 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002785
Chris Lattner86102b82005-01-01 16:22:27 +00002786 if (Op->hasOneUse() && Together != OpRHS) {
2787 // (X | C1) & C2 --> (X | (C1&C2)) & C2
2788 std::string Op0Name = Op->getName(); Op->setName("");
2789 Instruction *Or = BinaryOperator::createOr(X, Together, Op0Name);
2790 InsertNewInstBefore(Or, TheAnd);
2791 return BinaryOperator::createAnd(Or, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002792 }
2793 break;
2794 case Instruction::Add:
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002795 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00002796 // Adding a one to a single bit bit-field should be turned into an XOR
2797 // of the bit. First thing to check is to see if this AND is with a
2798 // single bit constant.
Reid Spencere0fc4df2006-10-20 07:07:24 +00002799 uint64_t AndRHSV = cast<ConstantInt>(AndRHS)->getZExtValue();
Chris Lattnerba1cb382003-09-19 17:17:26 +00002800
2801 // Clear bits that are not part of the constant.
Chris Lattner77defba2006-02-07 07:00:41 +00002802 AndRHSV &= AndRHS->getType()->getIntegralTypeMask();
Chris Lattnerba1cb382003-09-19 17:17:26 +00002803
2804 // If there is only one bit set...
Chris Lattner35167c32004-06-09 07:59:58 +00002805 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00002806 // Ok, at this point, we know that we are masking the result of the
2807 // ADD down to exactly one bit. If the constant we are adding has
2808 // no bits set below this bit, then we can eliminate the ADD.
Reid Spencere0fc4df2006-10-20 07:07:24 +00002809 uint64_t AddRHS = cast<ConstantInt>(OpRHS)->getZExtValue();
Misha Brukmanb1c93172005-04-21 23:48:37 +00002810
Chris Lattnerba1cb382003-09-19 17:17:26 +00002811 // Check to see if any bits below the one bit set in AndRHSV are set.
2812 if ((AddRHS & (AndRHSV-1)) == 0) {
2813 // If not, the only thing that can effect the output of the AND is
2814 // the bit specified by AndRHSV. If that bit is set, the effect of
2815 // the XOR is to toggle the bit. If it is clear, then the ADD has
2816 // no effect.
2817 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
2818 TheAnd.setOperand(0, X);
2819 return &TheAnd;
2820 } else {
2821 std::string Name = Op->getName(); Op->setName("");
2822 // Pull the XOR out of the AND.
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002823 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS, Name);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002824 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002825 return BinaryOperator::createXor(NewAnd, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002826 }
2827 }
2828 }
2829 }
2830 break;
Chris Lattner2da29172003-09-19 19:05:02 +00002831
2832 case Instruction::Shl: {
2833 // We know that the AND will not produce any of the bits shifted in, so if
2834 // the anded constant includes them, clear them now!
2835 //
2836 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner7e794272004-09-24 15:21:34 +00002837 Constant *ShlMask = ConstantExpr::getShl(AllOne, OpRHS);
2838 Constant *CI = ConstantExpr::getAnd(AndRHS, ShlMask);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002839
Chris Lattner7e794272004-09-24 15:21:34 +00002840 if (CI == ShlMask) { // Masking out bits that the shift already masks
2841 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
2842 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner2da29172003-09-19 19:05:02 +00002843 TheAnd.setOperand(1, CI);
2844 return &TheAnd;
2845 }
2846 break;
Misha Brukmanb1c93172005-04-21 23:48:37 +00002847 }
Reid Spencerfdff9382006-11-08 06:47:33 +00002848 case Instruction::LShr:
2849 {
Chris Lattner2da29172003-09-19 19:05:02 +00002850 // We know that the AND will not produce any of the bits shifted in, so if
2851 // the anded constant includes them, clear them now! This only applies to
2852 // unsigned shifts, because a signed shr may bring in set bits!
2853 //
Reid Spencerfdff9382006-11-08 06:47:33 +00002854 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
2855 Constant *ShrMask = ConstantExpr::getLShr(AllOne, OpRHS);
2856 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
Chris Lattner7e794272004-09-24 15:21:34 +00002857
Reid Spencerfdff9382006-11-08 06:47:33 +00002858 if (CI == ShrMask) { // Masking out bits that the shift already masks.
2859 return ReplaceInstUsesWith(TheAnd, Op);
2860 } else if (CI != AndRHS) {
2861 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
2862 return &TheAnd;
2863 }
2864 break;
2865 }
2866 case Instruction::AShr:
2867 // Signed shr.
2868 // See if this is shifting in some sign extension, then masking it out
2869 // with an and.
2870 if (Op->hasOneUse()) {
2871 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
2872 Constant *ShrMask = ConstantExpr::getLShr(AllOne, OpRHS);
2873 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
2874 if (CI == AndRHS) { // Masking out bits shifted in.
Reid Spencer13bc5d72006-12-12 09:18:51 +00002875 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
Reid Spencerfdff9382006-11-08 06:47:33 +00002876 // Make the argument unsigned.
2877 Value *ShVal = Op->getOperand(0);
2878 ShVal = InsertNewInstBefore(new ShiftInst(Instruction::LShr, ShVal,
2879 OpRHS, Op->getName()),
2880 TheAnd);
Reid Spencer13bc5d72006-12-12 09:18:51 +00002881 Value *AndRHS2 = ConstantExpr::getBitCast(AndRHS, ShVal->getType());
2882
Reid Spencerfdff9382006-11-08 06:47:33 +00002883 return BinaryOperator::createAnd(ShVal, AndRHS2, TheAnd.getName());
Chris Lattner7e794272004-09-24 15:21:34 +00002884 }
Chris Lattner2da29172003-09-19 19:05:02 +00002885 }
2886 break;
Chris Lattnerba1cb382003-09-19 17:17:26 +00002887 }
2888 return 0;
2889}
2890
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002891
Chris Lattner6862fbd2004-09-29 17:40:11 +00002892/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
2893/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
2894/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. IB is the location to
2895/// insert new instructions.
2896Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
2897 bool Inside, Instruction &IB) {
2898 assert(cast<ConstantBool>(ConstantExpr::getSetLE(Lo, Hi))->getValue() &&
2899 "Lo is not <= Hi in range emission code!");
2900 if (Inside) {
2901 if (Lo == Hi) // Trivially false.
2902 return new SetCondInst(Instruction::SetNE, V, V);
Reid Spencer4ae56f32006-12-06 20:39:57 +00002903 if (cast<ConstantIntegral>(Lo)->isMinValue(Lo->getType()->isSigned()))
Chris Lattner6862fbd2004-09-29 17:40:11 +00002904 return new SetCondInst(Instruction::SetLT, V, Hi);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002905
Chris Lattner6862fbd2004-09-29 17:40:11 +00002906 Constant *AddCST = ConstantExpr::getNeg(Lo);
2907 Instruction *Add = BinaryOperator::createAdd(V, AddCST,V->getName()+".off");
2908 InsertNewInstBefore(Add, IB);
2909 // Convert to unsigned for the comparison.
2910 const Type *UnsType = Add->getType()->getUnsignedVersion();
Reid Spencer13bc5d72006-12-12 09:18:51 +00002911 Value *OffsetVal = InsertCastBefore(Instruction::BitCast, Add, UnsType, IB);
Chris Lattner6862fbd2004-09-29 17:40:11 +00002912 AddCST = ConstantExpr::getAdd(AddCST, Hi);
Reid Spencer13bc5d72006-12-12 09:18:51 +00002913 AddCST = ConstantExpr::getBitCast(AddCST, UnsType);
Chris Lattner6862fbd2004-09-29 17:40:11 +00002914 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
2915 }
2916
2917 if (Lo == Hi) // Trivially true.
2918 return new SetCondInst(Instruction::SetEQ, V, V);
2919
2920 Hi = SubOne(cast<ConstantInt>(Hi));
Reid Spencere0fc4df2006-10-20 07:07:24 +00002921
2922 // V < 0 || V >= Hi ->'V > Hi-1'
Reid Spencer4ae56f32006-12-06 20:39:57 +00002923 if (cast<ConstantIntegral>(Lo)->isMinValue(Lo->getType()->isSigned()))
Chris Lattner6862fbd2004-09-29 17:40:11 +00002924 return new SetCondInst(Instruction::SetGT, V, Hi);
2925
2926 // Emit X-Lo > Hi-Lo-1
2927 Constant *AddCST = ConstantExpr::getNeg(Lo);
2928 Instruction *Add = BinaryOperator::createAdd(V, AddCST, V->getName()+".off");
2929 InsertNewInstBefore(Add, IB);
2930 // Convert to unsigned for the comparison.
2931 const Type *UnsType = Add->getType()->getUnsignedVersion();
Reid Spencer13bc5d72006-12-12 09:18:51 +00002932 Value *OffsetVal = InsertCastBefore(Instruction::BitCast, Add, UnsType, IB);
Chris Lattner6862fbd2004-09-29 17:40:11 +00002933 AddCST = ConstantExpr::getAdd(AddCST, Hi);
Reid Spencer13bc5d72006-12-12 09:18:51 +00002934 AddCST = ConstantExpr::getBitCast(AddCST, UnsType);
Chris Lattner6862fbd2004-09-29 17:40:11 +00002935 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
2936}
2937
Chris Lattnerb4b25302005-09-18 07:22:02 +00002938// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
2939// any number of 0s on either side. The 1s are allowed to wrap from LSB to
2940// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
2941// not, since all 1s are not contiguous.
2942static bool isRunOfOnes(ConstantIntegral *Val, unsigned &MB, unsigned &ME) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002943 uint64_t V = Val->getZExtValue();
Chris Lattnerb4b25302005-09-18 07:22:02 +00002944 if (!isShiftedMask_64(V)) return false;
2945
2946 // look for the first zero bit after the run of ones
2947 MB = 64-CountLeadingZeros_64((V - 1) ^ V);
2948 // look for the first non-zero bit
2949 ME = 64-CountLeadingZeros_64(V);
2950 return true;
2951}
2952
2953
2954
2955/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
2956/// where isSub determines whether the operator is a sub. If we can fold one of
2957/// the following xforms:
Chris Lattneraf517572005-09-18 04:24:45 +00002958///
2959/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
2960/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
2961/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
2962///
2963/// return (A +/- B).
2964///
2965Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
2966 ConstantIntegral *Mask, bool isSub,
2967 Instruction &I) {
2968 Instruction *LHSI = dyn_cast<Instruction>(LHS);
2969 if (!LHSI || LHSI->getNumOperands() != 2 ||
2970 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
2971
2972 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
2973
2974 switch (LHSI->getOpcode()) {
2975 default: return 0;
2976 case Instruction::And:
Chris Lattnerb4b25302005-09-18 07:22:02 +00002977 if (ConstantExpr::getAnd(N, Mask) == Mask) {
2978 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Reid Spencere0fc4df2006-10-20 07:07:24 +00002979 if ((Mask->getZExtValue() & Mask->getZExtValue()+1) == 0)
Chris Lattnerb4b25302005-09-18 07:22:02 +00002980 break;
2981
2982 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
2983 // part, we don't need any explicit masks to take them out of A. If that
2984 // is all N is, ignore it.
2985 unsigned MB, ME;
2986 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Chris Lattnerc3ebf402006-02-07 07:27:52 +00002987 uint64_t Mask = RHS->getType()->getIntegralTypeMask();
2988 Mask >>= 64-MB+1;
2989 if (MaskedValueIsZero(RHS, Mask))
Chris Lattnerb4b25302005-09-18 07:22:02 +00002990 break;
2991 }
2992 }
Chris Lattneraf517572005-09-18 04:24:45 +00002993 return 0;
2994 case Instruction::Or:
2995 case Instruction::Xor:
Chris Lattnerb4b25302005-09-18 07:22:02 +00002996 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Reid Spencere0fc4df2006-10-20 07:07:24 +00002997 if ((Mask->getZExtValue() & Mask->getZExtValue()+1) == 0 &&
Chris Lattnerb4b25302005-09-18 07:22:02 +00002998 ConstantExpr::getAnd(N, Mask)->isNullValue())
Chris Lattneraf517572005-09-18 04:24:45 +00002999 break;
3000 return 0;
3001 }
3002
3003 Instruction *New;
3004 if (isSub)
3005 New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
3006 else
3007 New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
3008 return InsertNewInstBefore(New, I);
3009}
3010
Chris Lattner113f4f42002-06-25 16:13:24 +00003011Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003012 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00003013 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003014
Chris Lattner81a7a232004-10-16 18:11:37 +00003015 if (isa<UndefValue>(Op1)) // X & undef -> 0
3016 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3017
Chris Lattner86102b82005-01-01 16:22:27 +00003018 // and X, X = X
3019 if (Op0 == Op1)
Chris Lattnere6794492002-08-12 21:17:25 +00003020 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003021
Chris Lattner5b2edb12006-02-12 08:02:11 +00003022 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner5997cf92006-02-08 03:25:32 +00003023 // purpose is to compute bits we don't care about.
Chris Lattner0157e7f2006-02-11 09:31:47 +00003024 uint64_t KnownZero, KnownOne;
Chris Lattnerd70d9f52006-03-25 21:58:26 +00003025 if (!isa<PackedType>(I.getType()) &&
3026 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
Chris Lattner0157e7f2006-02-11 09:31:47 +00003027 KnownZero, KnownOne))
Chris Lattner5997cf92006-02-08 03:25:32 +00003028 return &I;
3029
Chris Lattner86102b82005-01-01 16:22:27 +00003030 if (ConstantIntegral *AndRHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00003031 uint64_t AndRHSMask = AndRHS->getZExtValue();
3032 uint64_t TypeMask = Op0->getType()->getIntegralTypeMask();
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00003033 uint64_t NotAndRHS = AndRHSMask^TypeMask;
Chris Lattner86102b82005-01-01 16:22:27 +00003034
Chris Lattnerba1cb382003-09-19 17:17:26 +00003035 // Optimize a variety of ((val OP C1) & C2) combinations...
3036 if (isa<BinaryOperator>(Op0) || isa<ShiftInst>(Op0)) {
3037 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner86102b82005-01-01 16:22:27 +00003038 Value *Op0LHS = Op0I->getOperand(0);
3039 Value *Op0RHS = Op0I->getOperand(1);
3040 switch (Op0I->getOpcode()) {
3041 case Instruction::Xor:
3042 case Instruction::Or:
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00003043 // If the mask is only needed on one incoming arm, push it up.
3044 if (Op0I->hasOneUse()) {
3045 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3046 // Not masking anything out for the LHS, move to RHS.
3047 Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
3048 Op0RHS->getName()+".masked");
3049 InsertNewInstBefore(NewRHS, I);
3050 return BinaryOperator::create(
3051 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003052 }
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003053 if (!isa<Constant>(Op0RHS) &&
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00003054 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3055 // Not masking anything out for the RHS, move to LHS.
3056 Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
3057 Op0LHS->getName()+".masked");
3058 InsertNewInstBefore(NewLHS, I);
3059 return BinaryOperator::create(
3060 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3061 }
3062 }
3063
Chris Lattner86102b82005-01-01 16:22:27 +00003064 break;
Chris Lattneraf517572005-09-18 04:24:45 +00003065 case Instruction::Add:
Chris Lattnerb4b25302005-09-18 07:22:02 +00003066 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3067 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3068 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3069 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
3070 return BinaryOperator::createAnd(V, AndRHS);
3071 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
3072 return BinaryOperator::createAnd(V, AndRHS); // Add commutes
Chris Lattneraf517572005-09-18 04:24:45 +00003073 break;
3074
3075 case Instruction::Sub:
Chris Lattnerb4b25302005-09-18 07:22:02 +00003076 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3077 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3078 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3079 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
3080 return BinaryOperator::createAnd(V, AndRHS);
Chris Lattneraf517572005-09-18 04:24:45 +00003081 break;
Chris Lattner86102b82005-01-01 16:22:27 +00003082 }
3083
Chris Lattner16464b32003-07-23 19:25:52 +00003084 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner86102b82005-01-01 16:22:27 +00003085 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerba1cb382003-09-19 17:17:26 +00003086 return Res;
Chris Lattner86102b82005-01-01 16:22:27 +00003087 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
Chris Lattner2c14cf72005-08-07 07:03:10 +00003088 // If this is an integer truncation or change from signed-to-unsigned, and
3089 // if the source is an and/or with immediate, transform it. This
3090 // frequently occurs for bitfield accesses.
3091 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003092 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
Chris Lattner2c14cf72005-08-07 07:03:10 +00003093 CastOp->getNumOperands() == 2)
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00003094 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1)))
Chris Lattner2c14cf72005-08-07 07:03:10 +00003095 if (CastOp->getOpcode() == Instruction::And) {
3096 // Change: and (cast (and X, C1) to T), C2
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003097 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
3098 // This will fold the two constants together, which may allow
3099 // other simplifications.
Chris Lattner2c14cf72005-08-07 07:03:10 +00003100 Instruction *NewCast =
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003101 CastInst::createInferredCast(CastOp->getOperand(0), I.getType(),
Chris Lattner2c14cf72005-08-07 07:03:10 +00003102 CastOp->getName()+".shrunk");
3103 NewCast = InsertNewInstBefore(NewCast, I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003104 // trunc_or_bitcast(C1)&C2
3105 Instruction::CastOps opc = (
3106 AndCI->getType()->getPrimitiveSizeInBits() ==
3107 I.getType()->getPrimitiveSizeInBits() ?
3108 Instruction::BitCast : Instruction::Trunc);
3109 Constant *C3 = ConstantExpr::getCast(opc, AndCI, I.getType());
3110 C3 = ConstantExpr::getAnd(C3, AndRHS);
Chris Lattner2c14cf72005-08-07 07:03:10 +00003111 return BinaryOperator::createAnd(NewCast, C3);
3112 } else if (CastOp->getOpcode() == Instruction::Or) {
3113 // Change: and (cast (or X, C1) to T), C2
3114 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Reid Spencer13bc5d72006-12-12 09:18:51 +00003115 Constant *C3 = ConstantExpr::getBitCast(AndCI, I.getType());
Chris Lattner2c14cf72005-08-07 07:03:10 +00003116 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
3117 return ReplaceInstUsesWith(I, AndRHS);
3118 }
3119 }
Chris Lattner33217db2003-07-23 19:36:21 +00003120 }
Chris Lattner183b3362004-04-09 19:05:30 +00003121
3122 // Try to fold constant and into select arguments.
3123 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00003124 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00003125 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00003126 if (isa<PHINode>(Op0))
3127 if (Instruction *NV = FoldOpIntoPhi(I))
3128 return NV;
Chris Lattner49b47ae2003-07-23 17:57:01 +00003129 }
3130
Chris Lattnerbb74e222003-03-10 23:06:50 +00003131 Value *Op0NotVal = dyn_castNotVal(Op0);
3132 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00003133
Chris Lattner023a4832004-06-18 06:07:51 +00003134 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
3135 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3136
Misha Brukman9c003d82004-07-30 12:50:08 +00003137 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattnerbb74e222003-03-10 23:06:50 +00003138 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003139 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
3140 I.getName()+".demorgan");
Chris Lattner49b47ae2003-07-23 17:57:01 +00003141 InsertNewInstBefore(Or, I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00003142 return BinaryOperator::createNot(Or);
3143 }
Chris Lattner8b10ab32006-02-13 23:07:23 +00003144
3145 {
3146 Value *A = 0, *B = 0;
Chris Lattner8b10ab32006-02-13 23:07:23 +00003147 if (match(Op0, m_Or(m_Value(A), m_Value(B))))
3148 if (A == Op1 || B == Op1) // (A | ?) & A --> A
3149 return ReplaceInstUsesWith(I, Op1);
3150 if (match(Op1, m_Or(m_Value(A), m_Value(B))))
3151 if (A == Op0 || B == Op0) // A & (A | ?) --> A
3152 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerdcd07922006-04-01 08:03:55 +00003153
3154 if (Op0->hasOneUse() &&
3155 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3156 if (A == Op1) { // (A^B)&A -> A&(A^B)
3157 I.swapOperands(); // Simplify below
3158 std::swap(Op0, Op1);
3159 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
3160 cast<BinaryOperator>(Op0)->swapOperands();
3161 I.swapOperands(); // Simplify below
3162 std::swap(Op0, Op1);
3163 }
3164 }
3165 if (Op1->hasOneUse() &&
3166 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3167 if (B == Op0) { // B&(A^B) -> B&(B^A)
3168 cast<BinaryOperator>(Op1)->swapOperands();
3169 std::swap(A, B);
3170 }
3171 if (A == Op0) { // A&(A^B) -> A & ~B
3172 Instruction *NotB = BinaryOperator::createNot(B, "tmp");
3173 InsertNewInstBefore(NotB, I);
3174 return BinaryOperator::createAnd(A, NotB);
3175 }
3176 }
Chris Lattner8b10ab32006-02-13 23:07:23 +00003177 }
3178
Chris Lattner3082c5a2003-02-18 19:28:33 +00003179
Chris Lattner623826c2004-09-28 21:48:02 +00003180 if (SetCondInst *RHS = dyn_cast<SetCondInst>(Op1)) {
3181 // (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
Chris Lattner3ac7c262003-08-13 20:16:26 +00003182 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
3183 return R;
3184
Chris Lattner623826c2004-09-28 21:48:02 +00003185 Value *LHSVal, *RHSVal;
3186 ConstantInt *LHSCst, *RHSCst;
3187 Instruction::BinaryOps LHSCC, RHSCC;
3188 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3189 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3190 if (LHSVal == RHSVal && // Found (X setcc C1) & (X setcc C2)
3191 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
Misha Brukmanb1c93172005-04-21 23:48:37 +00003192 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
Chris Lattner623826c2004-09-28 21:48:02 +00003193 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
3194 // Ensure that the larger constant is on the RHS.
3195 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
3196 SetCondInst *LHS = cast<SetCondInst>(Op0);
3197 if (cast<ConstantBool>(Cmp)->getValue()) {
3198 std::swap(LHS, RHS);
3199 std::swap(LHSCst, RHSCst);
3200 std::swap(LHSCC, RHSCC);
3201 }
3202
3203 // At this point, we know we have have two setcc instructions
3204 // comparing a value against two constants and and'ing the result
3205 // together. Because of the above check, we know that we only have
3206 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
3207 // FoldSetCCLogical check above), that the two constants are not
3208 // equal.
3209 assert(LHSCst != RHSCst && "Compares not folded above?");
3210
3211 switch (LHSCC) {
3212 default: assert(0 && "Unknown integer condition code!");
3213 case Instruction::SetEQ:
3214 switch (RHSCC) {
3215 default: assert(0 && "Unknown integer condition code!");
3216 case Instruction::SetEQ: // (X == 13 & X == 15) -> false
3217 case Instruction::SetGT: // (X == 13 & X > 15) -> false
Chris Lattner6ab03f62006-09-28 23:35:22 +00003218 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattner623826c2004-09-28 21:48:02 +00003219 case Instruction::SetNE: // (X == 13 & X != 15) -> X == 13
3220 case Instruction::SetLT: // (X == 13 & X < 15) -> X == 13
3221 return ReplaceInstUsesWith(I, LHS);
3222 }
3223 case Instruction::SetNE:
3224 switch (RHSCC) {
3225 default: assert(0 && "Unknown integer condition code!");
3226 case Instruction::SetLT:
3227 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X < 14) -> X < 13
3228 return new SetCondInst(Instruction::SetLT, LHSVal, LHSCst);
3229 break; // (X != 13 & X < 15) -> no change
3230 case Instruction::SetEQ: // (X != 13 & X == 15) -> X == 15
3231 case Instruction::SetGT: // (X != 13 & X > 15) -> X > 15
3232 return ReplaceInstUsesWith(I, RHS);
3233 case Instruction::SetNE:
3234 if (LHSCst == SubOne(RHSCst)) {// (X != 13 & X != 14) -> X-13 >u 1
3235 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3236 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3237 LHSVal->getName()+".off");
3238 InsertNewInstBefore(Add, I);
3239 const Type *UnsType = Add->getType()->getUnsignedVersion();
Reid Spencer13bc5d72006-12-12 09:18:51 +00003240 Value *OffsetVal = InsertCastBefore(Instruction::BitCast, Add,
3241 UnsType, I);
Chris Lattner623826c2004-09-28 21:48:02 +00003242 AddCST = ConstantExpr::getSub(RHSCst, LHSCst);
Reid Spencer13bc5d72006-12-12 09:18:51 +00003243 AddCST = ConstantExpr::getBitCast(AddCST, UnsType);
Chris Lattner623826c2004-09-28 21:48:02 +00003244 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
3245 }
3246 break; // (X != 13 & X != 15) -> no change
3247 }
3248 break;
3249 case Instruction::SetLT:
3250 switch (RHSCC) {
3251 default: assert(0 && "Unknown integer condition code!");
3252 case Instruction::SetEQ: // (X < 13 & X == 15) -> false
3253 case Instruction::SetGT: // (X < 13 & X > 15) -> false
Chris Lattner6ab03f62006-09-28 23:35:22 +00003254 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattner623826c2004-09-28 21:48:02 +00003255 case Instruction::SetNE: // (X < 13 & X != 15) -> X < 13
3256 case Instruction::SetLT: // (X < 13 & X < 15) -> X < 13
3257 return ReplaceInstUsesWith(I, LHS);
3258 }
3259 case Instruction::SetGT:
3260 switch (RHSCC) {
3261 default: assert(0 && "Unknown integer condition code!");
3262 case Instruction::SetEQ: // (X > 13 & X == 15) -> X > 13
3263 return ReplaceInstUsesWith(I, LHS);
3264 case Instruction::SetGT: // (X > 13 & X > 15) -> X > 15
3265 return ReplaceInstUsesWith(I, RHS);
3266 case Instruction::SetNE:
3267 if (RHSCst == AddOne(LHSCst)) // (X > 13 & X != 14) -> X > 14
3268 return new SetCondInst(Instruction::SetGT, LHSVal, RHSCst);
3269 break; // (X > 13 & X != 15) -> no change
Chris Lattner6862fbd2004-09-29 17:40:11 +00003270 case Instruction::SetLT: // (X > 13 & X < 15) -> (X-14) <u 1
3271 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true, I);
Chris Lattner623826c2004-09-28 21:48:02 +00003272 }
3273 }
3274 }
3275 }
3276
Chris Lattner3af10532006-05-05 06:39:07 +00003277 // fold (and (cast A), (cast B)) -> (cast (and A, B))
Chris Lattnerf05d69a2006-11-14 07:46:50 +00003278 if (CastInst *Op1C = dyn_cast<CastInst>(Op1)) {
3279 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
3280 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattnere745c7d2006-05-05 20:51:30 +00003281 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegral() &&
Chris Lattner1d441ad2006-05-06 09:00:16 +00003282 // Only do this if the casts both really cause code to be generated.
3283 ValueRequiresCast(Op0C->getOperand(0), I.getType(), TD) &&
3284 ValueRequiresCast(Op1C->getOperand(0), I.getType(), TD)) {
Chris Lattner3af10532006-05-05 06:39:07 +00003285 Instruction *NewOp = BinaryOperator::createAnd(Op0C->getOperand(0),
3286 Op1C->getOperand(0),
3287 I.getName());
3288 InsertNewInstBefore(NewOp, I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003289 return CastInst::createInferredCast(NewOp, I.getType());
Chris Lattner3af10532006-05-05 06:39:07 +00003290 }
Chris Lattnerf05d69a2006-11-14 07:46:50 +00003291 }
3292 }
3293
3294 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
3295 if (ShiftInst *SI1 = dyn_cast<ShiftInst>(Op1)) {
3296 if (ShiftInst *SI0 = dyn_cast<ShiftInst>(Op0))
3297 if (SI0->getOpcode() == SI1->getOpcode() &&
3298 SI0->getOperand(1) == SI1->getOperand(1) &&
3299 (SI0->hasOneUse() || SI1->hasOneUse())) {
3300 Instruction *NewOp =
3301 InsertNewInstBefore(BinaryOperator::createAnd(SI0->getOperand(0),
3302 SI1->getOperand(0),
3303 SI0->getName()), I);
3304 return new ShiftInst(SI1->getOpcode(), NewOp, SI1->getOperand(1));
3305 }
Chris Lattner3af10532006-05-05 06:39:07 +00003306 }
3307
Chris Lattner113f4f42002-06-25 16:13:24 +00003308 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003309}
3310
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003311/// CollectBSwapParts - Look to see if the specified value defines a single byte
3312/// in the result. If it does, and if the specified byte hasn't been filled in
3313/// yet, fill it in and return false.
3314static bool CollectBSwapParts(Value *V, std::vector<Value*> &ByteValues) {
3315 Instruction *I = dyn_cast<Instruction>(V);
3316 if (I == 0) return true;
3317
3318 // If this is an or instruction, it is an inner node of the bswap.
3319 if (I->getOpcode() == Instruction::Or)
3320 return CollectBSwapParts(I->getOperand(0), ByteValues) ||
3321 CollectBSwapParts(I->getOperand(1), ByteValues);
3322
3323 // If this is a shift by a constant int, and it is "24", then its operand
3324 // defines a byte. We only handle unsigned types here.
3325 if (isa<ShiftInst>(I) && isa<ConstantInt>(I->getOperand(1))) {
3326 // Not shifting the entire input by N-1 bytes?
Reid Spencere0fc4df2006-10-20 07:07:24 +00003327 if (cast<ConstantInt>(I->getOperand(1))->getZExtValue() !=
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003328 8*(ByteValues.size()-1))
3329 return true;
3330
3331 unsigned DestNo;
3332 if (I->getOpcode() == Instruction::Shl) {
3333 // X << 24 defines the top byte with the lowest of the input bytes.
3334 DestNo = ByteValues.size()-1;
3335 } else {
3336 // X >>u 24 defines the low byte with the highest of the input bytes.
3337 DestNo = 0;
3338 }
3339
3340 // If the destination byte value is already defined, the values are or'd
3341 // together, which isn't a bswap (unless it's an or of the same bits).
3342 if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
3343 return true;
3344 ByteValues[DestNo] = I->getOperand(0);
3345 return false;
3346 }
3347
3348 // Otherwise, we can only handle and(shift X, imm), imm). Bail out of if we
3349 // don't have this.
3350 Value *Shift = 0, *ShiftLHS = 0;
3351 ConstantInt *AndAmt = 0, *ShiftAmt = 0;
3352 if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
3353 !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
3354 return true;
3355 Instruction *SI = cast<Instruction>(Shift);
3356
3357 // Make sure that the shift amount is by a multiple of 8 and isn't too big.
Reid Spencere0fc4df2006-10-20 07:07:24 +00003358 if (ShiftAmt->getZExtValue() & 7 ||
3359 ShiftAmt->getZExtValue() > 8*ByteValues.size())
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003360 return true;
3361
3362 // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
3363 unsigned DestByte;
3364 for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
Reid Spencere0fc4df2006-10-20 07:07:24 +00003365 if (AndAmt->getZExtValue() == uint64_t(0xFF) << 8*DestByte)
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003366 break;
3367 // Unknown mask for bswap.
3368 if (DestByte == ByteValues.size()) return true;
3369
Reid Spencere0fc4df2006-10-20 07:07:24 +00003370 unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003371 unsigned SrcByte;
3372 if (SI->getOpcode() == Instruction::Shl)
3373 SrcByte = DestByte - ShiftBytes;
3374 else
3375 SrcByte = DestByte + ShiftBytes;
3376
3377 // If the SrcByte isn't a bswapped value from the DestByte, reject it.
3378 if (SrcByte != ByteValues.size()-DestByte-1)
3379 return true;
3380
3381 // If the destination byte value is already defined, the values are or'd
3382 // together, which isn't a bswap (unless it's an or of the same bits).
3383 if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
3384 return true;
3385 ByteValues[DestByte] = SI->getOperand(0);
3386 return false;
3387}
3388
3389/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
3390/// If so, insert the new bswap intrinsic and return it.
3391Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
3392 // We can only handle bswap of unsigned integers, and cannot bswap one byte.
3393 if (!I.getType()->isUnsigned() || I.getType() == Type::UByteTy)
3394 return 0;
3395
3396 /// ByteValues - For each byte of the result, we keep track of which value
3397 /// defines each byte.
3398 std::vector<Value*> ByteValues;
3399 ByteValues.resize(I.getType()->getPrimitiveSize());
3400
3401 // Try to find all the pieces corresponding to the bswap.
3402 if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
3403 CollectBSwapParts(I.getOperand(1), ByteValues))
3404 return 0;
3405
3406 // Check to see if all of the bytes come from the same value.
3407 Value *V = ByteValues[0];
3408 if (V == 0) return 0; // Didn't find a byte? Must be zero.
3409
3410 // Check to make sure that all of the bytes come from the same value.
3411 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
3412 if (ByteValues[i] != V)
3413 return 0;
3414
3415 // If they do then *success* we can turn this into a bswap. Figure out what
3416 // bswap to make it into.
3417 Module *M = I.getParent()->getParent()->getParent();
Chris Lattner091b6ea2006-07-11 18:31:26 +00003418 const char *FnName = 0;
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003419 if (I.getType() == Type::UShortTy)
3420 FnName = "llvm.bswap.i16";
3421 else if (I.getType() == Type::UIntTy)
3422 FnName = "llvm.bswap.i32";
3423 else if (I.getType() == Type::ULongTy)
3424 FnName = "llvm.bswap.i64";
3425 else
3426 assert(0 && "Unknown integer type!");
3427 Function *F = M->getOrInsertFunction(FnName, I.getType(), I.getType(), NULL);
3428
3429 return new CallInst(F, V);
3430}
3431
3432
Chris Lattner113f4f42002-06-25 16:13:24 +00003433Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003434 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00003435 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003436
Chris Lattner81a7a232004-10-16 18:11:37 +00003437 if (isa<UndefValue>(Op1))
3438 return ReplaceInstUsesWith(I, // X | undef -> -1
3439 ConstantIntegral::getAllOnesValue(I.getType()));
3440
Chris Lattner5b2edb12006-02-12 08:02:11 +00003441 // or X, X = X
3442 if (Op0 == Op1)
Chris Lattnere6794492002-08-12 21:17:25 +00003443 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003444
Chris Lattner5b2edb12006-02-12 08:02:11 +00003445 // See if we can simplify any instructions used by the instruction whose sole
3446 // purpose is to compute bits we don't care about.
3447 uint64_t KnownZero, KnownOne;
Chris Lattnerd70d9f52006-03-25 21:58:26 +00003448 if (!isa<PackedType>(I.getType()) &&
3449 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
Chris Lattner5b2edb12006-02-12 08:02:11 +00003450 KnownZero, KnownOne))
3451 return &I;
3452
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003453 // or X, -1 == -1
Chris Lattner8f0d1562003-07-23 18:29:44 +00003454 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner330628a2006-01-06 17:59:59 +00003455 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00003456 // (X & C1) | C2 --> (X | C2) & (C1|C2)
3457 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Chris Lattnerb62f5082005-05-09 04:58:36 +00003458 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0->getName());
3459 Op0->setName("");
Chris Lattnerd4252a72004-07-30 07:50:03 +00003460 InsertNewInstBefore(Or, I);
3461 return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, C1));
3462 }
Chris Lattner8f0d1562003-07-23 18:29:44 +00003463
Chris Lattnerd4252a72004-07-30 07:50:03 +00003464 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
3465 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
3466 std::string Op0Name = Op0->getName(); Op0->setName("");
3467 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
3468 InsertNewInstBefore(Or, I);
3469 return BinaryOperator::createXor(Or,
3470 ConstantExpr::getAnd(C1, ConstantExpr::getNot(RHS)));
Chris Lattner8f0d1562003-07-23 18:29:44 +00003471 }
Chris Lattner183b3362004-04-09 19:05:30 +00003472
3473 // Try to fold constant and into select arguments.
3474 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00003475 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00003476 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00003477 if (isa<PHINode>(Op0))
3478 if (Instruction *NV = FoldOpIntoPhi(I))
3479 return NV;
Chris Lattner8f0d1562003-07-23 18:29:44 +00003480 }
3481
Chris Lattner330628a2006-01-06 17:59:59 +00003482 Value *A = 0, *B = 0;
3483 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattner4294cec2005-05-07 23:49:08 +00003484
3485 if (match(Op0, m_And(m_Value(A), m_Value(B))))
3486 if (A == Op1 || B == Op1) // (A & ?) | A --> A
3487 return ReplaceInstUsesWith(I, Op1);
3488 if (match(Op1, m_And(m_Value(A), m_Value(B))))
3489 if (A == Op0 || B == Op0) // A | (A & ?) --> A
3490 return ReplaceInstUsesWith(I, Op0);
3491
Chris Lattnerb7845d62006-07-10 20:25:24 +00003492 // (A | B) | C and A | (B | C) -> bswap if possible.
3493 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003494 if (match(Op0, m_Or(m_Value(), m_Value())) ||
Chris Lattnerb7845d62006-07-10 20:25:24 +00003495 match(Op1, m_Or(m_Value(), m_Value())) ||
3496 (match(Op0, m_Shift(m_Value(), m_Value())) &&
3497 match(Op1, m_Shift(m_Value(), m_Value())))) {
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003498 if (Instruction *BSwap = MatchBSwap(I))
3499 return BSwap;
3500 }
3501
Chris Lattnerb62f5082005-05-09 04:58:36 +00003502 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
3503 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003504 MaskedValueIsZero(Op1, C1->getZExtValue())) {
Chris Lattnerb62f5082005-05-09 04:58:36 +00003505 Instruction *NOr = BinaryOperator::createOr(A, Op1, Op0->getName());
3506 Op0->setName("");
3507 return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
3508 }
3509
3510 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
3511 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003512 MaskedValueIsZero(Op0, C1->getZExtValue())) {
Chris Lattnerb62f5082005-05-09 04:58:36 +00003513 Instruction *NOr = BinaryOperator::createOr(A, Op0, Op1->getName());
3514 Op0->setName("");
3515 return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
3516 }
3517
Chris Lattner15212982005-09-18 03:42:07 +00003518 // (A & C1)|(B & C2)
Chris Lattnerd4252a72004-07-30 07:50:03 +00003519 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattner15212982005-09-18 03:42:07 +00003520 match(Op1, m_And(m_Value(B), m_ConstantInt(C2)))) {
3521
3522 if (A == B) // (A & C1)|(A & C2) == A & (C1|C2)
3523 return BinaryOperator::createAnd(A, ConstantExpr::getOr(C1, C2));
3524
3525
Chris Lattner01f56c62005-09-18 06:02:59 +00003526 // If we have: ((V + N) & C1) | (V & C2)
3527 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
3528 // replace with V+N.
3529 if (C1 == ConstantExpr::getNot(C2)) {
Chris Lattner330628a2006-01-06 17:59:59 +00003530 Value *V1 = 0, *V2 = 0;
Reid Spencere0fc4df2006-10-20 07:07:24 +00003531 if ((C2->getZExtValue() & (C2->getZExtValue()+1)) == 0 && // C2 == 0+1+
Chris Lattner01f56c62005-09-18 06:02:59 +00003532 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
3533 // Add commutes, try both ways.
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003534 if (V1 == B && MaskedValueIsZero(V2, C2->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003535 return ReplaceInstUsesWith(I, A);
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003536 if (V2 == B && MaskedValueIsZero(V1, C2->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003537 return ReplaceInstUsesWith(I, A);
3538 }
3539 // Or commutes, try both ways.
Reid Spencere0fc4df2006-10-20 07:07:24 +00003540 if ((C1->getZExtValue() & (C1->getZExtValue()+1)) == 0 &&
Chris Lattner01f56c62005-09-18 06:02:59 +00003541 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
3542 // Add commutes, try both ways.
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003543 if (V1 == A && MaskedValueIsZero(V2, C1->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003544 return ReplaceInstUsesWith(I, B);
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003545 if (V2 == A && MaskedValueIsZero(V1, C1->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003546 return ReplaceInstUsesWith(I, B);
Chris Lattner15212982005-09-18 03:42:07 +00003547 }
3548 }
3549 }
Chris Lattnerf05d69a2006-11-14 07:46:50 +00003550
3551 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
3552 if (ShiftInst *SI1 = dyn_cast<ShiftInst>(Op1)) {
3553 if (ShiftInst *SI0 = dyn_cast<ShiftInst>(Op0))
3554 if (SI0->getOpcode() == SI1->getOpcode() &&
3555 SI0->getOperand(1) == SI1->getOperand(1) &&
3556 (SI0->hasOneUse() || SI1->hasOneUse())) {
3557 Instruction *NewOp =
3558 InsertNewInstBefore(BinaryOperator::createOr(SI0->getOperand(0),
3559 SI1->getOperand(0),
3560 SI0->getName()), I);
3561 return new ShiftInst(SI1->getOpcode(), NewOp, SI1->getOperand(1));
3562 }
3563 }
Chris Lattner812aab72003-08-12 19:11:07 +00003564
Chris Lattnerd4252a72004-07-30 07:50:03 +00003565 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
3566 if (A == Op1) // ~A | A == -1
Misha Brukmanb1c93172005-04-21 23:48:37 +00003567 return ReplaceInstUsesWith(I,
Chris Lattnerd4252a72004-07-30 07:50:03 +00003568 ConstantIntegral::getAllOnesValue(I.getType()));
3569 } else {
3570 A = 0;
3571 }
Chris Lattner4294cec2005-05-07 23:49:08 +00003572 // Note, A is still live here!
Chris Lattnerd4252a72004-07-30 07:50:03 +00003573 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
3574 if (Op0 == B)
Misha Brukmanb1c93172005-04-21 23:48:37 +00003575 return ReplaceInstUsesWith(I,
Chris Lattnerd4252a72004-07-30 07:50:03 +00003576 ConstantIntegral::getAllOnesValue(I.getType()));
Chris Lattner3e327a42003-03-10 23:13:59 +00003577
Misha Brukman9c003d82004-07-30 12:50:08 +00003578 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattnerd4252a72004-07-30 07:50:03 +00003579 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3580 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
3581 I.getName()+".demorgan"), I);
3582 return BinaryOperator::createNot(And);
3583 }
Chris Lattner3e327a42003-03-10 23:13:59 +00003584 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00003585
Chris Lattner3ac7c262003-08-13 20:16:26 +00003586 // (setcc1 A, B) | (setcc2 A, B) --> (setcc3 A, B)
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003587 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1))) {
Chris Lattner3ac7c262003-08-13 20:16:26 +00003588 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
3589 return R;
3590
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003591 Value *LHSVal, *RHSVal;
3592 ConstantInt *LHSCst, *RHSCst;
3593 Instruction::BinaryOps LHSCC, RHSCC;
3594 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3595 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3596 if (LHSVal == RHSVal && // Found (X setcc C1) | (X setcc C2)
3597 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
Misha Brukmanb1c93172005-04-21 23:48:37 +00003598 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003599 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
3600 // Ensure that the larger constant is on the RHS.
3601 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
3602 SetCondInst *LHS = cast<SetCondInst>(Op0);
3603 if (cast<ConstantBool>(Cmp)->getValue()) {
3604 std::swap(LHS, RHS);
3605 std::swap(LHSCst, RHSCst);
3606 std::swap(LHSCC, RHSCC);
3607 }
3608
3609 // At this point, we know we have have two setcc instructions
3610 // comparing a value against two constants and or'ing the result
3611 // together. Because of the above check, we know that we only have
3612 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
3613 // FoldSetCCLogical check above), that the two constants are not
3614 // equal.
3615 assert(LHSCst != RHSCst && "Compares not folded above?");
3616
3617 switch (LHSCC) {
3618 default: assert(0 && "Unknown integer condition code!");
3619 case Instruction::SetEQ:
3620 switch (RHSCC) {
3621 default: assert(0 && "Unknown integer condition code!");
3622 case Instruction::SetEQ:
3623 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
3624 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3625 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3626 LHSVal->getName()+".off");
3627 InsertNewInstBefore(Add, I);
3628 const Type *UnsType = Add->getType()->getUnsignedVersion();
Reid Spencer13bc5d72006-12-12 09:18:51 +00003629 Value *OffsetVal = InsertCastBefore(Instruction::BitCast, Add,
3630 UnsType, I);
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003631 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
Reid Spencer13bc5d72006-12-12 09:18:51 +00003632 AddCST = ConstantExpr::getBitCast(AddCST, UnsType);
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003633 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
3634 }
3635 break; // (X == 13 | X == 15) -> no change
3636
Chris Lattner5c219462005-04-19 06:04:18 +00003637 case Instruction::SetGT: // (X == 13 | X > 14) -> no change
3638 break;
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003639 case Instruction::SetNE: // (X == 13 | X != 15) -> X != 15
3640 case Instruction::SetLT: // (X == 13 | X < 15) -> X < 15
3641 return ReplaceInstUsesWith(I, RHS);
3642 }
3643 break;
3644 case Instruction::SetNE:
3645 switch (RHSCC) {
3646 default: assert(0 && "Unknown integer condition code!");
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003647 case Instruction::SetEQ: // (X != 13 | X == 15) -> X != 13
3648 case Instruction::SetGT: // (X != 13 | X > 15) -> X != 13
3649 return ReplaceInstUsesWith(I, LHS);
3650 case Instruction::SetNE: // (X != 13 | X != 15) -> true
Chris Lattner2ceb6ee2005-06-17 03:59:17 +00003651 case Instruction::SetLT: // (X != 13 | X < 15) -> true
Chris Lattner6ab03f62006-09-28 23:35:22 +00003652 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003653 }
3654 break;
3655 case Instruction::SetLT:
3656 switch (RHSCC) {
3657 default: assert(0 && "Unknown integer condition code!");
3658 case Instruction::SetEQ: // (X < 13 | X == 14) -> no change
3659 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00003660 case Instruction::SetGT: // (X < 13 | X > 15) -> (X-13) > 2
3661 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false, I);
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003662 case Instruction::SetNE: // (X < 13 | X != 15) -> X != 15
3663 case Instruction::SetLT: // (X < 13 | X < 15) -> X < 15
3664 return ReplaceInstUsesWith(I, RHS);
3665 }
3666 break;
3667 case Instruction::SetGT:
3668 switch (RHSCC) {
3669 default: assert(0 && "Unknown integer condition code!");
3670 case Instruction::SetEQ: // (X > 13 | X == 15) -> X > 13
3671 case Instruction::SetGT: // (X > 13 | X > 15) -> X > 13
3672 return ReplaceInstUsesWith(I, LHS);
3673 case Instruction::SetNE: // (X > 13 | X != 15) -> true
3674 case Instruction::SetLT: // (X > 13 | X < 15) -> true
Chris Lattner6ab03f62006-09-28 23:35:22 +00003675 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003676 }
3677 }
3678 }
3679 }
Chris Lattner3af10532006-05-05 06:39:07 +00003680
3681 // fold (or (cast A), (cast B)) -> (cast (or A, B))
3682 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattnere745c7d2006-05-05 20:51:30 +00003683 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner3af10532006-05-05 06:39:07 +00003684 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Chris Lattnere745c7d2006-05-05 20:51:30 +00003685 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegral() &&
Chris Lattner1d441ad2006-05-06 09:00:16 +00003686 // Only do this if the casts both really cause code to be generated.
3687 ValueRequiresCast(Op0C->getOperand(0), I.getType(), TD) &&
3688 ValueRequiresCast(Op1C->getOperand(0), I.getType(), TD)) {
Chris Lattner3af10532006-05-05 06:39:07 +00003689 Instruction *NewOp = BinaryOperator::createOr(Op0C->getOperand(0),
3690 Op1C->getOperand(0),
3691 I.getName());
3692 InsertNewInstBefore(NewOp, I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003693 return CastInst::createInferredCast(NewOp, I.getType());
Chris Lattner3af10532006-05-05 06:39:07 +00003694 }
3695 }
3696
Chris Lattner15212982005-09-18 03:42:07 +00003697
Chris Lattner113f4f42002-06-25 16:13:24 +00003698 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003699}
3700
Chris Lattnerc2076352004-02-16 01:20:27 +00003701// XorSelf - Implements: X ^ X --> 0
3702struct XorSelf {
3703 Value *RHS;
3704 XorSelf(Value *rhs) : RHS(rhs) {}
3705 bool shouldApply(Value *LHS) const { return LHS == RHS; }
3706 Instruction *apply(BinaryOperator &Xor) const {
3707 return &Xor;
3708 }
3709};
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003710
3711
Chris Lattner113f4f42002-06-25 16:13:24 +00003712Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003713 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00003714 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003715
Chris Lattner81a7a232004-10-16 18:11:37 +00003716 if (isa<UndefValue>(Op1))
3717 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
3718
Chris Lattnerc2076352004-02-16 01:20:27 +00003719 // xor X, X = 0, even if X is nested in a sequence of Xor's.
3720 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
3721 assert(Result == &I && "AssociativeOpt didn't work?");
Chris Lattnere6794492002-08-12 21:17:25 +00003722 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc2076352004-02-16 01:20:27 +00003723 }
Chris Lattner5b2edb12006-02-12 08:02:11 +00003724
3725 // See if we can simplify any instructions used by the instruction whose sole
3726 // purpose is to compute bits we don't care about.
3727 uint64_t KnownZero, KnownOne;
Chris Lattnerd70d9f52006-03-25 21:58:26 +00003728 if (!isa<PackedType>(I.getType()) &&
3729 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
Chris Lattner5b2edb12006-02-12 08:02:11 +00003730 KnownZero, KnownOne))
3731 return &I;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003732
Chris Lattner97638592003-07-23 21:37:07 +00003733 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner97638592003-07-23 21:37:07 +00003734 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerb8d6e402002-08-20 18:24:26 +00003735 // xor (setcc A, B), true = not (setcc A, B) = setncc A, B
Chris Lattner97638592003-07-23 21:37:07 +00003736 if (SetCondInst *SCI = dyn_cast<SetCondInst>(Op0I))
Chris Lattner6ab03f62006-09-28 23:35:22 +00003737 if (RHS == ConstantBool::getTrue() && SCI->hasOneUse())
Chris Lattnerb8d6e402002-08-20 18:24:26 +00003738 return new SetCondInst(SCI->getInverseCondition(),
3739 SCI->getOperand(0), SCI->getOperand(1));
Chris Lattnere5806662003-11-04 23:50:51 +00003740
Chris Lattner8f2f5982003-11-05 01:06:05 +00003741 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003742 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
3743 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003744 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
3745 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003746 ConstantInt::get(I.getType(), 1));
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003747 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003748 }
Chris Lattner023a4832004-06-18 06:07:51 +00003749
3750 // ~(~X & Y) --> (X | ~Y)
3751 if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
3752 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
3753 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
3754 Instruction *NotY =
Misha Brukmanb1c93172005-04-21 23:48:37 +00003755 BinaryOperator::createNot(Op0I->getOperand(1),
Chris Lattner023a4832004-06-18 06:07:51 +00003756 Op0I->getOperand(1)->getName()+".not");
3757 InsertNewInstBefore(NotY, I);
3758 return BinaryOperator::createOr(Op0NotVal, NotY);
3759 }
3760 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003761
Chris Lattner97638592003-07-23 21:37:07 +00003762 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner5b2edb12006-02-12 08:02:11 +00003763 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner0f68fa62003-11-04 23:37:10 +00003764 // ~(X-c) --> (-c-1)-X
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003765 if (RHS->isAllOnesValue()) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003766 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
3767 return BinaryOperator::createSub(
3768 ConstantExpr::getSub(NegOp0CI,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003769 ConstantInt::get(I.getType(), 1)),
Chris Lattner0f68fa62003-11-04 23:37:10 +00003770 Op0I->getOperand(0));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003771 }
Chris Lattnerf78df7c2006-02-26 19:57:54 +00003772 } else if (Op0I->getOpcode() == Instruction::Or) {
3773 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
3774 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getZExtValue())) {
3775 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
3776 // Anything in both C1 and C2 is known to be zero, remove it from
3777 // NewRHS.
3778 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
3779 NewRHS = ConstantExpr::getAnd(NewRHS,
3780 ConstantExpr::getNot(CommonBits));
3781 WorkList.push_back(Op0I);
3782 I.setOperand(0, Op0I->getOperand(0));
3783 I.setOperand(1, NewRHS);
3784 return &I;
3785 }
Chris Lattner97638592003-07-23 21:37:07 +00003786 }
Chris Lattnerb8d6e402002-08-20 18:24:26 +00003787 }
Chris Lattner183b3362004-04-09 19:05:30 +00003788
3789 // Try to fold constant and into select arguments.
3790 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00003791 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00003792 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00003793 if (isa<PHINode>(Op0))
3794 if (Instruction *NV = FoldOpIntoPhi(I))
3795 return NV;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003796 }
3797
Chris Lattnerbb74e222003-03-10 23:06:50 +00003798 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00003799 if (X == Op1)
3800 return ReplaceInstUsesWith(I,
3801 ConstantIntegral::getAllOnesValue(I.getType()));
3802
Chris Lattnerbb74e222003-03-10 23:06:50 +00003803 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00003804 if (X == Op0)
3805 return ReplaceInstUsesWith(I,
3806 ConstantIntegral::getAllOnesValue(I.getType()));
3807
Chris Lattnerdcd07922006-04-01 08:03:55 +00003808 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1))
Chris Lattnerb36d9082004-02-16 03:54:20 +00003809 if (Op1I->getOpcode() == Instruction::Or) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003810 if (Op1I->getOperand(0) == Op0) { // B^(B|A) == (A|B)^B
Chris Lattnerdcd07922006-04-01 08:03:55 +00003811 Op1I->swapOperands();
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003812 I.swapOperands();
3813 std::swap(Op0, Op1);
3814 } else if (Op1I->getOperand(1) == Op0) { // B^(A|B) == (A|B)^B
Chris Lattnerdcd07922006-04-01 08:03:55 +00003815 I.swapOperands(); // Simplified below.
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003816 std::swap(Op0, Op1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003817 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00003818 } else if (Op1I->getOpcode() == Instruction::Xor) {
3819 if (Op0 == Op1I->getOperand(0)) // A^(A^B) == B
3820 return ReplaceInstUsesWith(I, Op1I->getOperand(1));
3821 else if (Op0 == Op1I->getOperand(1)) // A^(B^A) == B
3822 return ReplaceInstUsesWith(I, Op1I->getOperand(0));
Chris Lattnerdcd07922006-04-01 08:03:55 +00003823 } else if (Op1I->getOpcode() == Instruction::And && Op1I->hasOneUse()) {
3824 if (Op1I->getOperand(0) == Op0) // A^(A&B) -> A^(B&A)
3825 Op1I->swapOperands();
3826 if (Op0 == Op1I->getOperand(1)) { // A^(B&A) -> (B&A)^A
3827 I.swapOperands(); // Simplified below.
3828 std::swap(Op0, Op1);
3829 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00003830 }
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003831
Chris Lattnerdcd07922006-04-01 08:03:55 +00003832 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00003833 if (Op0I->getOpcode() == Instruction::Or && Op0I->hasOneUse()) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003834 if (Op0I->getOperand(0) == Op1) // (B|A)^B == (A|B)^B
Chris Lattnerdcd07922006-04-01 08:03:55 +00003835 Op0I->swapOperands();
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003836 if (Op0I->getOperand(1) == Op1) { // (A|B)^B == A & ~B
Chris Lattnerdcd07922006-04-01 08:03:55 +00003837 Instruction *NotB = BinaryOperator::createNot(Op1, "tmp");
3838 InsertNewInstBefore(NotB, I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003839 return BinaryOperator::createAnd(Op0I->getOperand(0), NotB);
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003840 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00003841 } else if (Op0I->getOpcode() == Instruction::Xor) {
3842 if (Op1 == Op0I->getOperand(0)) // (A^B)^A == B
3843 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
3844 else if (Op1 == Op0I->getOperand(1)) // (B^A)^A == B
3845 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattnerdcd07922006-04-01 08:03:55 +00003846 } else if (Op0I->getOpcode() == Instruction::And && Op0I->hasOneUse()) {
3847 if (Op0I->getOperand(0) == Op1) // (A&B)^A -> (B&A)^A
3848 Op0I->swapOperands();
Chris Lattner6cf49142006-04-01 22:05:01 +00003849 if (Op0I->getOperand(1) == Op1 && // (B&A)^A == ~B & A
3850 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattnerdcd07922006-04-01 08:03:55 +00003851 Instruction *N = BinaryOperator::createNot(Op0I->getOperand(0), "tmp");
3852 InsertNewInstBefore(N, I);
3853 return BinaryOperator::createAnd(N, Op1);
3854 }
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003855 }
3856
Chris Lattner3ac7c262003-08-13 20:16:26 +00003857 // (setcc1 A, B) ^ (setcc2 A, B) --> (setcc3 A, B)
3858 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
3859 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
3860 return R;
3861
Chris Lattner3af10532006-05-05 06:39:07 +00003862 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
3863 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattnere745c7d2006-05-05 20:51:30 +00003864 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner3af10532006-05-05 06:39:07 +00003865 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Chris Lattnere745c7d2006-05-05 20:51:30 +00003866 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegral() &&
Chris Lattner1d441ad2006-05-06 09:00:16 +00003867 // Only do this if the casts both really cause code to be generated.
3868 ValueRequiresCast(Op0C->getOperand(0), I.getType(), TD) &&
3869 ValueRequiresCast(Op1C->getOperand(0), I.getType(), TD)) {
Chris Lattner3af10532006-05-05 06:39:07 +00003870 Instruction *NewOp = BinaryOperator::createXor(Op0C->getOperand(0),
3871 Op1C->getOperand(0),
3872 I.getName());
3873 InsertNewInstBefore(NewOp, I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003874 return CastInst::createInferredCast(NewOp, I.getType());
Chris Lattner3af10532006-05-05 06:39:07 +00003875 }
3876 }
Chris Lattnerf05d69a2006-11-14 07:46:50 +00003877
3878 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
3879 if (ShiftInst *SI1 = dyn_cast<ShiftInst>(Op1)) {
3880 if (ShiftInst *SI0 = dyn_cast<ShiftInst>(Op0))
3881 if (SI0->getOpcode() == SI1->getOpcode() &&
3882 SI0->getOperand(1) == SI1->getOperand(1) &&
3883 (SI0->hasOneUse() || SI1->hasOneUse())) {
3884 Instruction *NewOp =
3885 InsertNewInstBefore(BinaryOperator::createXor(SI0->getOperand(0),
3886 SI1->getOperand(0),
3887 SI0->getName()), I);
3888 return new ShiftInst(SI1->getOpcode(), NewOp, SI1->getOperand(1));
3889 }
3890 }
Chris Lattner3af10532006-05-05 06:39:07 +00003891
Chris Lattner113f4f42002-06-25 16:13:24 +00003892 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003893}
3894
Chris Lattner6862fbd2004-09-29 17:40:11 +00003895static bool isPositive(ConstantInt *C) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00003896 return C->getSExtValue() >= 0;
Chris Lattner6862fbd2004-09-29 17:40:11 +00003897}
3898
3899/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
3900/// overflowed for this type.
3901static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
3902 ConstantInt *In2) {
3903 Result = cast<ConstantInt>(ConstantExpr::getAdd(In1, In2));
3904
3905 if (In1->getType()->isUnsigned())
Reid Spencere0fc4df2006-10-20 07:07:24 +00003906 return cast<ConstantInt>(Result)->getZExtValue() <
3907 cast<ConstantInt>(In1)->getZExtValue();
Chris Lattner6862fbd2004-09-29 17:40:11 +00003908 if (isPositive(In1) != isPositive(In2))
3909 return false;
3910 if (isPositive(In1))
Reid Spencere0fc4df2006-10-20 07:07:24 +00003911 return cast<ConstantInt>(Result)->getSExtValue() <
3912 cast<ConstantInt>(In1)->getSExtValue();
3913 return cast<ConstantInt>(Result)->getSExtValue() >
3914 cast<ConstantInt>(In1)->getSExtValue();
Chris Lattner6862fbd2004-09-29 17:40:11 +00003915}
3916
Chris Lattner0798af32005-01-13 20:14:25 +00003917/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
3918/// code necessary to compute the offset from the base pointer (without adding
3919/// in the base pointer). Return the result as a signed integer of intptr size.
3920static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
3921 TargetData &TD = IC.getTargetData();
3922 gep_type_iterator GTI = gep_type_begin(GEP);
3923 const Type *UIntPtrTy = TD.getIntPtrType();
3924 const Type *SIntPtrTy = UIntPtrTy->getSignedVersion();
3925 Value *Result = Constant::getNullValue(SIntPtrTy);
3926
3927 // Build a mask for high order bits.
Chris Lattner77defba2006-02-07 07:00:41 +00003928 uint64_t PtrSizeMask = ~0ULL >> (64-TD.getPointerSize()*8);
Chris Lattner0798af32005-01-13 20:14:25 +00003929
Chris Lattner0798af32005-01-13 20:14:25 +00003930 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
3931 Value *Op = GEP->getOperand(i);
Chris Lattnerd35d2102005-01-13 23:26:48 +00003932 uint64_t Size = TD.getTypeSize(GTI.getIndexedType()) & PtrSizeMask;
Reid Spencer13bc5d72006-12-12 09:18:51 +00003933 Constant *Scale = ConstantExpr::getBitCast(ConstantInt::get(UIntPtrTy, Size),
Chris Lattner0798af32005-01-13 20:14:25 +00003934 SIntPtrTy);
3935 if (Constant *OpC = dyn_cast<Constant>(Op)) {
3936 if (!OpC->isNullValue()) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00003937 OpC = ConstantExpr::getIntegerCast(OpC, SIntPtrTy, true /*SExt*/);
Chris Lattner0798af32005-01-13 20:14:25 +00003938 Scale = ConstantExpr::getMul(OpC, Scale);
3939 if (Constant *RC = dyn_cast<Constant>(Result))
3940 Result = ConstantExpr::getAdd(RC, Scale);
3941 else {
3942 // Emit an add instruction.
3943 Result = IC.InsertNewInstBefore(
3944 BinaryOperator::createAdd(Result, Scale,
3945 GEP->getName()+".offs"), I);
3946 }
3947 }
3948 } else {
Chris Lattner7aa41cf2005-01-14 17:17:59 +00003949 // Convert to correct type.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003950 Op = IC.InsertNewInstBefore(CastInst::createInferredCast(Op, SIntPtrTy,
Chris Lattner7aa41cf2005-01-14 17:17:59 +00003951 Op->getName()+".c"), I);
3952 if (Size != 1)
Chris Lattner4cb9fa32005-01-13 20:40:58 +00003953 // We'll let instcombine(mul) convert this to a shl if possible.
3954 Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
3955 GEP->getName()+".idx"), I);
Chris Lattner0798af32005-01-13 20:14:25 +00003956
3957 // Emit an add instruction.
Chris Lattner4cb9fa32005-01-13 20:40:58 +00003958 Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
Chris Lattner0798af32005-01-13 20:14:25 +00003959 GEP->getName()+".offs"), I);
3960 }
3961 }
3962 return Result;
3963}
3964
3965/// FoldGEPSetCC - Fold comparisons between a GEP instruction and something
3966/// else. At this point we know that the GEP is on the LHS of the comparison.
3967Instruction *InstCombiner::FoldGEPSetCC(User *GEPLHS, Value *RHS,
3968 Instruction::BinaryOps Cond,
3969 Instruction &I) {
3970 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattner81e84172005-01-13 22:25:21 +00003971
3972 if (CastInst *CI = dyn_cast<CastInst>(RHS))
3973 if (isa<PointerType>(CI->getOperand(0)->getType()))
3974 RHS = CI->getOperand(0);
3975
Chris Lattner0798af32005-01-13 20:14:25 +00003976 Value *PtrBase = GEPLHS->getOperand(0);
3977 if (PtrBase == RHS) {
3978 // As an optimization, we don't actually have to compute the actual value of
3979 // OFFSET if this is a seteq or setne comparison, just return whether each
3980 // index is zero or not.
Chris Lattner81e84172005-01-13 22:25:21 +00003981 if (Cond == Instruction::SetEQ || Cond == Instruction::SetNE) {
3982 Instruction *InVal = 0;
Chris Lattnercd517ff2005-01-28 19:32:01 +00003983 gep_type_iterator GTI = gep_type_begin(GEPLHS);
3984 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i, ++GTI) {
Chris Lattner81e84172005-01-13 22:25:21 +00003985 bool EmitIt = true;
3986 if (Constant *C = dyn_cast<Constant>(GEPLHS->getOperand(i))) {
3987 if (isa<UndefValue>(C)) // undef index -> undef.
3988 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
3989 if (C->isNullValue())
3990 EmitIt = false;
Chris Lattnercd517ff2005-01-28 19:32:01 +00003991 else if (TD->getTypeSize(GTI.getIndexedType()) == 0) {
3992 EmitIt = false; // This is indexing into a zero sized array?
Misha Brukmanb1c93172005-04-21 23:48:37 +00003993 } else if (isa<ConstantInt>(C))
Chris Lattner81e84172005-01-13 22:25:21 +00003994 return ReplaceInstUsesWith(I, // No comparison is needed here.
3995 ConstantBool::get(Cond == Instruction::SetNE));
3996 }
3997
3998 if (EmitIt) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00003999 Instruction *Comp =
Chris Lattner81e84172005-01-13 22:25:21 +00004000 new SetCondInst(Cond, GEPLHS->getOperand(i),
4001 Constant::getNullValue(GEPLHS->getOperand(i)->getType()));
4002 if (InVal == 0)
4003 InVal = Comp;
4004 else {
4005 InVal = InsertNewInstBefore(InVal, I);
4006 InsertNewInstBefore(Comp, I);
4007 if (Cond == Instruction::SetNE) // True if any are unequal
4008 InVal = BinaryOperator::createOr(InVal, Comp);
4009 else // True if all are equal
4010 InVal = BinaryOperator::createAnd(InVal, Comp);
4011 }
4012 }
4013 }
4014
4015 if (InVal)
4016 return InVal;
4017 else
4018 ReplaceInstUsesWith(I, // No comparison is needed here, all indexes = 0
4019 ConstantBool::get(Cond == Instruction::SetEQ));
4020 }
Chris Lattner0798af32005-01-13 20:14:25 +00004021
4022 // Only lower this if the setcc is the only user of the GEP or if we expect
4023 // the result to fold to a constant!
4024 if (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) {
4025 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
4026 Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
4027 return new SetCondInst(Cond, Offset,
4028 Constant::getNullValue(Offset->getType()));
4029 }
4030 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
Chris Lattnera21bf8d2005-04-25 20:17:30 +00004031 // If the base pointers are different, but the indices are the same, just
4032 // compare the base pointer.
4033 if (PtrBase != GEPRHS->getOperand(0)) {
4034 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00004035 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattnerbd43b9d2005-04-26 14:40:41 +00004036 GEPRHS->getOperand(0)->getType();
Chris Lattnera21bf8d2005-04-25 20:17:30 +00004037 if (IndicesTheSame)
4038 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4039 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4040 IndicesTheSame = false;
4041 break;
4042 }
4043
4044 // If all indices are the same, just compare the base pointers.
4045 if (IndicesTheSame)
4046 return new SetCondInst(Cond, GEPLHS->getOperand(0),
4047 GEPRHS->getOperand(0));
4048
4049 // Otherwise, the base pointers are different and the indices are
4050 // different, bail out.
Chris Lattner0798af32005-01-13 20:14:25 +00004051 return 0;
Chris Lattnera21bf8d2005-04-25 20:17:30 +00004052 }
Chris Lattner0798af32005-01-13 20:14:25 +00004053
Chris Lattner81e84172005-01-13 22:25:21 +00004054 // If one of the GEPs has all zero indices, recurse.
4055 bool AllZeros = true;
4056 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4057 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
4058 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
4059 AllZeros = false;
4060 break;
4061 }
4062 if (AllZeros)
4063 return FoldGEPSetCC(GEPRHS, GEPLHS->getOperand(0),
4064 SetCondInst::getSwappedCondition(Cond), I);
Chris Lattner4fa89822005-01-14 00:20:05 +00004065
4066 // If the other GEP has all zero indices, recurse.
Chris Lattner81e84172005-01-13 22:25:21 +00004067 AllZeros = true;
4068 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4069 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
4070 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
4071 AllZeros = false;
4072 break;
4073 }
4074 if (AllZeros)
4075 return FoldGEPSetCC(GEPLHS, GEPRHS->getOperand(0), Cond, I);
4076
Chris Lattner4fa89822005-01-14 00:20:05 +00004077 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
4078 // If the GEPs only differ by one index, compare it.
4079 unsigned NumDifferences = 0; // Keep track of # differences.
4080 unsigned DiffOperand = 0; // The operand that differs.
4081 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4082 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004083 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
4084 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattnerfc4429e2005-01-21 23:06:49 +00004085 // Irreconcilable differences.
Chris Lattner4fa89822005-01-14 00:20:05 +00004086 NumDifferences = 2;
4087 break;
4088 } else {
4089 if (NumDifferences++) break;
4090 DiffOperand = i;
4091 }
4092 }
4093
4094 if (NumDifferences == 0) // SAME GEP?
4095 return ReplaceInstUsesWith(I, // No comparison is needed here.
4096 ConstantBool::get(Cond == Instruction::SetEQ));
4097 else if (NumDifferences == 1) {
Chris Lattnerfc4429e2005-01-21 23:06:49 +00004098 Value *LHSV = GEPLHS->getOperand(DiffOperand);
4099 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Chris Lattner247aef82005-07-18 23:07:33 +00004100
4101 // Convert the operands to signed values to make sure to perform a
4102 // signed comparison.
4103 const Type *NewTy = LHSV->getType()->getSignedVersion();
4104 if (LHSV->getType() != NewTy)
Reid Spencer13bc5d72006-12-12 09:18:51 +00004105 LHSV = InsertCastBefore(Instruction::BitCast, LHSV, NewTy, I);
Chris Lattner247aef82005-07-18 23:07:33 +00004106 if (RHSV->getType() != NewTy)
Reid Spencer13bc5d72006-12-12 09:18:51 +00004107 RHSV = InsertCastBefore(Instruction::BitCast, RHSV, NewTy, I);
Chris Lattner247aef82005-07-18 23:07:33 +00004108 return new SetCondInst(Cond, LHSV, RHSV);
Chris Lattner4fa89822005-01-14 00:20:05 +00004109 }
4110 }
4111
Chris Lattner0798af32005-01-13 20:14:25 +00004112 // Only lower this if the setcc is the only user of the GEP or if we expect
4113 // the result to fold to a constant!
4114 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
4115 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
4116 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
4117 Value *L = EmitGEPOffset(GEPLHS, I, *this);
4118 Value *R = EmitGEPOffset(GEPRHS, I, *this);
4119 return new SetCondInst(Cond, L, R);
4120 }
4121 }
4122 return 0;
4123}
4124
4125
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004126Instruction *InstCombiner::visitSetCondInst(SetCondInst &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00004127 bool Changed = SimplifyCommutative(I);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004128 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4129 const Type *Ty = Op0->getType();
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004130
4131 // setcc X, X
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004132 if (Op0 == Op1)
4133 return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
Chris Lattner1fc23f32002-05-09 20:11:54 +00004134
Chris Lattner81a7a232004-10-16 18:11:37 +00004135 if (isa<UndefValue>(Op1)) // X setcc undef -> undef
4136 return ReplaceInstUsesWith(I, UndefValue::get(Type::BoolTy));
4137
Chris Lattner15ff1e12004-11-14 07:33:16 +00004138 // setcc <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
4139 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanb1c93172005-04-21 23:48:37 +00004140 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
4141 isa<ConstantPointerNull>(Op0)) &&
4142 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner15ff1e12004-11-14 07:33:16 +00004143 isa<ConstantPointerNull>(Op1)))
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004144 return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
4145
4146 // setcc's with boolean values can always be turned into bitwise operations
4147 if (Ty == Type::BoolTy) {
Chris Lattner4456da62004-08-11 00:50:51 +00004148 switch (I.getOpcode()) {
4149 default: assert(0 && "Invalid setcc instruction!");
4150 case Instruction::SetEQ: { // seteq bool %A, %B -> ~(A^B)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004151 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004152 InsertNewInstBefore(Xor, I);
Chris Lattner16930792003-11-03 04:25:02 +00004153 return BinaryOperator::createNot(Xor);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004154 }
Chris Lattner4456da62004-08-11 00:50:51 +00004155 case Instruction::SetNE:
4156 return BinaryOperator::createXor(Op0, Op1);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004157
Chris Lattner4456da62004-08-11 00:50:51 +00004158 case Instruction::SetGT:
4159 std::swap(Op0, Op1); // Change setgt -> setlt
4160 // FALL THROUGH
4161 case Instruction::SetLT: { // setlt bool A, B -> ~X & Y
4162 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4163 InsertNewInstBefore(Not, I);
4164 return BinaryOperator::createAnd(Not, Op1);
4165 }
4166 case Instruction::SetGE:
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004167 std::swap(Op0, Op1); // Change setge -> setle
Chris Lattner4456da62004-08-11 00:50:51 +00004168 // FALL THROUGH
4169 case Instruction::SetLE: { // setle bool %A, %B -> ~A | B
4170 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4171 InsertNewInstBefore(Not, I);
4172 return BinaryOperator::createOr(Not, Op1);
4173 }
4174 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004175 }
4176
Chris Lattner2dd01742004-06-09 04:24:29 +00004177 // See if we are doing a comparison between a constant and an instruction that
4178 // can be folded into the comparison.
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004179 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner6862fbd2004-09-29 17:40:11 +00004180 // Check to see if we are comparing against the minimum or maximum value...
Reid Spencer4ae56f32006-12-06 20:39:57 +00004181 if (CI->isMinValue(CI->getType()->isSigned())) {
Chris Lattner6862fbd2004-09-29 17:40:11 +00004182 if (I.getOpcode() == Instruction::SetLT) // A < MIN -> 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::SetGE) // A >= MIN -> 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::SetLE) // A <= MIN -> A == MIN
4187 return BinaryOperator::createSetEQ(Op0, Op1);
4188 if (I.getOpcode() == Instruction::SetGT) // A > MIN -> A != MIN
4189 return BinaryOperator::createSetNE(Op0, Op1);
4190
Reid Spencer4ae56f32006-12-06 20:39:57 +00004191 } else if (CI->isMaxValue(CI->getType()->isSigned())) {
Chris Lattner6862fbd2004-09-29 17:40:11 +00004192 if (I.getOpcode() == Instruction::SetGT) // A > MAX -> FALSE
Chris Lattner6ab03f62006-09-28 23:35:22 +00004193 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattner6862fbd2004-09-29 17:40:11 +00004194 if (I.getOpcode() == Instruction::SetLE) // A <= MAX -> TRUE
Chris Lattner6ab03f62006-09-28 23:35:22 +00004195 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
Chris Lattner6862fbd2004-09-29 17:40:11 +00004196 if (I.getOpcode() == Instruction::SetGE) // A >= MAX -> A == MAX
4197 return BinaryOperator::createSetEQ(Op0, Op1);
4198 if (I.getOpcode() == Instruction::SetLT) // A < MAX -> A != MAX
4199 return BinaryOperator::createSetNE(Op0, Op1);
4200
4201 // Comparing against a value really close to min or max?
4202 } else if (isMinValuePlusOne(CI)) {
4203 if (I.getOpcode() == Instruction::SetLT) // A < MIN+1 -> A == MIN
4204 return BinaryOperator::createSetEQ(Op0, SubOne(CI));
4205 if (I.getOpcode() == Instruction::SetGE) // A >= MIN-1 -> A != MIN
4206 return BinaryOperator::createSetNE(Op0, SubOne(CI));
4207
4208 } else if (isMaxValueMinusOne(CI)) {
4209 if (I.getOpcode() == Instruction::SetGT) // A > MAX-1 -> A == MAX
4210 return BinaryOperator::createSetEQ(Op0, AddOne(CI));
4211 if (I.getOpcode() == Instruction::SetLE) // A <= MAX-1 -> A != MAX
4212 return BinaryOperator::createSetNE(Op0, AddOne(CI));
4213 }
4214
4215 // If we still have a setle or setge instruction, turn it into the
4216 // appropriate setlt or setgt instruction. Since the border cases have
4217 // already been handled above, this requires little checking.
4218 //
4219 if (I.getOpcode() == Instruction::SetLE)
4220 return BinaryOperator::createSetLT(Op0, AddOne(CI));
4221 if (I.getOpcode() == Instruction::SetGE)
4222 return BinaryOperator::createSetGT(Op0, SubOne(CI));
4223
Chris Lattneree0f2802006-02-12 02:07:56 +00004224
4225 // See if we can fold the comparison based on bits known to be zero or one
4226 // in the input.
4227 uint64_t KnownZero, KnownOne;
4228 if (SimplifyDemandedBits(Op0, Ty->getIntegralTypeMask(),
4229 KnownZero, KnownOne, 0))
4230 return &I;
4231
4232 // Given the known and unknown bits, compute a range that the LHS could be
4233 // in.
4234 if (KnownOne | KnownZero) {
4235 if (Ty->isUnsigned()) { // Unsigned comparison.
4236 uint64_t Min, Max;
4237 uint64_t RHSVal = CI->getZExtValue();
4238 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne,
4239 Min, Max);
4240 switch (I.getOpcode()) { // LE/GE have been folded already.
4241 default: assert(0 && "Unknown setcc opcode!");
4242 case Instruction::SetEQ:
4243 if (Max < RHSVal || Min > RHSVal)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004244 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattneree0f2802006-02-12 02:07:56 +00004245 break;
4246 case Instruction::SetNE:
4247 if (Max < RHSVal || Min > RHSVal)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004248 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
Chris Lattneree0f2802006-02-12 02:07:56 +00004249 break;
4250 case Instruction::SetLT:
Chris Lattner6ab03f62006-09-28 23:35:22 +00004251 if (Max < RHSVal)
4252 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4253 if (Min > RHSVal)
4254 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattneree0f2802006-02-12 02:07:56 +00004255 break;
4256 case Instruction::SetGT:
Chris Lattner6ab03f62006-09-28 23:35:22 +00004257 if (Min > RHSVal)
4258 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4259 if (Max < RHSVal)
4260 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattneree0f2802006-02-12 02:07:56 +00004261 break;
4262 }
4263 } else { // Signed comparison.
4264 int64_t Min, Max;
4265 int64_t RHSVal = CI->getSExtValue();
4266 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne,
4267 Min, Max);
4268 switch (I.getOpcode()) { // LE/GE have been folded already.
4269 default: assert(0 && "Unknown setcc opcode!");
4270 case Instruction::SetEQ:
4271 if (Max < RHSVal || Min > RHSVal)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004272 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattneree0f2802006-02-12 02:07:56 +00004273 break;
4274 case Instruction::SetNE:
4275 if (Max < RHSVal || Min > RHSVal)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004276 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
Chris Lattneree0f2802006-02-12 02:07:56 +00004277 break;
4278 case Instruction::SetLT:
Chris Lattner6ab03f62006-09-28 23:35:22 +00004279 if (Max < RHSVal)
4280 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4281 if (Min > RHSVal)
4282 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattneree0f2802006-02-12 02:07:56 +00004283 break;
4284 case Instruction::SetGT:
Chris Lattner6ab03f62006-09-28 23:35:22 +00004285 if (Min > RHSVal)
4286 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4287 if (Max < RHSVal)
4288 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattneree0f2802006-02-12 02:07:56 +00004289 break;
4290 }
4291 }
4292 }
4293
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004294 // Since the RHS is a constantInt (CI), if the left hand side is an
4295 // instruction, see if that instruction also has constants so that the
4296 // instruction can be folded into the setcc
Chris Lattnere1e10e12004-05-25 06:32:08 +00004297 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004298 switch (LHSI->getOpcode()) {
4299 case Instruction::And:
4300 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
4301 LHSI->getOperand(0)->hasOneUse()) {
Chris Lattner4922a0e2006-09-18 05:27:43 +00004302 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
4303
4304 // If an operand is an AND of a truncating cast, we can widen the
4305 // and/compare to be the input width without changing the value
4306 // produced, eliminating a cast.
4307 if (CastInst *Cast = dyn_cast<CastInst>(LHSI->getOperand(0))) {
4308 // We can do this transformation if either the AND constant does not
4309 // have its sign bit set or if it is an equality comparison.
4310 // Extending a relational comparison when we're checking the sign
4311 // bit would not work.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00004312 if (Cast->hasOneUse() && isa<TruncInst>(Cast) &&
Chris Lattner4922a0e2006-09-18 05:27:43 +00004313 (I.isEquality() ||
4314 (AndCST->getZExtValue() == (uint64_t)AndCST->getSExtValue()) &&
4315 (CI->getZExtValue() == (uint64_t)CI->getSExtValue()))) {
4316 ConstantInt *NewCST;
4317 ConstantInt *NewCI;
4318 if (Cast->getOperand(0)->getType()->isSigned()) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00004319 NewCST = ConstantInt::get(Cast->getOperand(0)->getType(),
Chris Lattner4922a0e2006-09-18 05:27:43 +00004320 AndCST->getZExtValue());
Reid Spencere0fc4df2006-10-20 07:07:24 +00004321 NewCI = ConstantInt::get(Cast->getOperand(0)->getType(),
Chris Lattner4922a0e2006-09-18 05:27:43 +00004322 CI->getZExtValue());
4323 } else {
Reid Spencere0fc4df2006-10-20 07:07:24 +00004324 NewCST = ConstantInt::get(Cast->getOperand(0)->getType(),
Chris Lattner4922a0e2006-09-18 05:27:43 +00004325 AndCST->getZExtValue());
Reid Spencere0fc4df2006-10-20 07:07:24 +00004326 NewCI = ConstantInt::get(Cast->getOperand(0)->getType(),
Chris Lattner4922a0e2006-09-18 05:27:43 +00004327 CI->getZExtValue());
4328 }
4329 Instruction *NewAnd =
4330 BinaryOperator::createAnd(Cast->getOperand(0), NewCST,
4331 LHSI->getName());
4332 InsertNewInstBefore(NewAnd, I);
4333 return new SetCondInst(I.getOpcode(), NewAnd, NewCI);
4334 }
4335 }
4336
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004337 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
4338 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
4339 // happens a LOT in code produced by the C front-end, for bitfield
4340 // access.
4341 ShiftInst *Shift = dyn_cast<ShiftInst>(LHSI->getOperand(0));
Chris Lattneree0f2802006-02-12 02:07:56 +00004342
4343 // Check to see if there is a noop-cast between the shift and the and.
4344 if (!Shift) {
4345 if (CastInst *CI = dyn_cast<CastInst>(LHSI->getOperand(0)))
4346 if (CI->getOperand(0)->getType()->isIntegral() &&
4347 CI->getOperand(0)->getType()->getPrimitiveSizeInBits() ==
4348 CI->getType()->getPrimitiveSizeInBits())
4349 Shift = dyn_cast<ShiftInst>(CI->getOperand(0));
4350 }
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004351
Reid Spencere0fc4df2006-10-20 07:07:24 +00004352 ConstantInt *ShAmt;
4353 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
Chris Lattneree0f2802006-02-12 02:07:56 +00004354 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
4355 const Type *AndTy = AndCST->getType(); // Type of the and.
Misha Brukmanb1c93172005-04-21 23:48:37 +00004356
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004357 // We can fold this as long as we can't shift unknown bits
4358 // into the mask. This can only happen with signed shift
4359 // rights, as they sign-extend.
4360 if (ShAmt) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004361 bool CanFold = Shift->isLogicalShift();
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004362 if (!CanFold) {
4363 // To test for the bad case of the signed shr, see if any
4364 // of the bits shifted in could be tested after the mask.
Reid Spencere0fc4df2006-10-20 07:07:24 +00004365 int ShAmtVal = Ty->getPrimitiveSizeInBits()-ShAmt->getZExtValue();
Chris Lattnerc53cb9d2005-06-17 01:29:28 +00004366 if (ShAmtVal < 0) ShAmtVal = 0; // Out of range shift.
4367
Reid Spencere0fc4df2006-10-20 07:07:24 +00004368 Constant *OShAmt = ConstantInt::get(Type::UByteTy, ShAmtVal);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004369 Constant *ShVal =
Chris Lattneree0f2802006-02-12 02:07:56 +00004370 ConstantExpr::getShl(ConstantInt::getAllOnesValue(AndTy),
4371 OShAmt);
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004372 if (ConstantExpr::getAnd(ShVal, AndCST)->isNullValue())
4373 CanFold = true;
4374 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004375
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004376 if (CanFold) {
Chris Lattner6afc02f2004-09-28 17:54:07 +00004377 Constant *NewCst;
4378 if (Shift->getOpcode() == Instruction::Shl)
Reid Spencerfdff9382006-11-08 06:47:33 +00004379 NewCst = ConstantExpr::getLShr(CI, ShAmt);
Chris Lattner6afc02f2004-09-28 17:54:07 +00004380 else
4381 NewCst = ConstantExpr::getShl(CI, ShAmt);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004382
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004383 // Check to see if we are shifting out any of the bits being
4384 // compared.
4385 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != CI){
4386 // If we shifted bits out, the fold is not going to work out.
4387 // As a special case, check to see if this means that the
4388 // result is always true or false now.
4389 if (I.getOpcode() == Instruction::SetEQ)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004390 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004391 if (I.getOpcode() == Instruction::SetNE)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004392 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004393 } else {
4394 I.setOperand(1, NewCst);
Chris Lattner6afc02f2004-09-28 17:54:07 +00004395 Constant *NewAndCST;
4396 if (Shift->getOpcode() == Instruction::Shl)
Reid Spencerfdff9382006-11-08 06:47:33 +00004397 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
Chris Lattner6afc02f2004-09-28 17:54:07 +00004398 else
4399 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
4400 LHSI->setOperand(1, NewAndCST);
Chris Lattneree0f2802006-02-12 02:07:56 +00004401 if (AndTy == Ty)
4402 LHSI->setOperand(0, Shift->getOperand(0));
4403 else {
Reid Spencer13bc5d72006-12-12 09:18:51 +00004404 Value *NewCast = InsertCastBefore(Instruction::BitCast,
4405 Shift->getOperand(0), AndTy,
Chris Lattneree0f2802006-02-12 02:07:56 +00004406 *Shift);
4407 LHSI->setOperand(0, NewCast);
4408 }
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004409 WorkList.push_back(Shift); // Shift is dead.
4410 AddUsesToWorkList(I);
4411 return &I;
Chris Lattner1638de42004-07-21 19:50:44 +00004412 }
4413 }
Chris Lattner35167c32004-06-09 07:59:58 +00004414 }
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004415
4416 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
4417 // preferable because it allows the C<<Y expression to be hoisted out
4418 // of a loop if Y is invariant and X is not.
4419 if (Shift && Shift->hasOneUse() && CI->isNullValue() &&
Chris Lattnerde077922006-09-18 18:27:05 +00004420 I.isEquality() && !Shift->isArithmeticShift() &&
4421 isa<Instruction>(Shift->getOperand(0))) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004422 // Compute C << Y.
4423 Value *NS;
Reid Spencerfdff9382006-11-08 06:47:33 +00004424 if (Shift->getOpcode() == Instruction::LShr) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004425 NS = new ShiftInst(Instruction::Shl, AndCST, Shift->getOperand(1),
4426 "tmp");
4427 } else {
4428 // Make sure we insert a logical shift.
Chris Lattner4922a0e2006-09-18 05:27:43 +00004429 Constant *NewAndCST = AndCST;
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004430 if (AndCST->getType()->isSigned())
Reid Spencer13bc5d72006-12-12 09:18:51 +00004431 NewAndCST = ConstantExpr::getBitCast(AndCST,
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004432 AndCST->getType()->getUnsignedVersion());
Reid Spencerfdff9382006-11-08 06:47:33 +00004433 NS = new ShiftInst(Instruction::LShr, NewAndCST,
Chris Lattner4922a0e2006-09-18 05:27:43 +00004434 Shift->getOperand(1), "tmp");
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004435 }
4436 InsertNewInstBefore(cast<Instruction>(NS), I);
4437
4438 // If C's sign doesn't agree with the and, insert a cast now.
4439 if (NS->getType() != LHSI->getType())
Reid Spencer13bc5d72006-12-12 09:18:51 +00004440 NS = InsertCastBefore(Instruction::BitCast, NS, LHSI->getType(),
4441 I);
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004442
4443 Value *ShiftOp = Shift->getOperand(0);
4444 if (ShiftOp->getType() != LHSI->getType())
Reid Spencer13bc5d72006-12-12 09:18:51 +00004445 ShiftOp = InsertCastBefore(Instruction::BitCast, ShiftOp,
4446 LHSI->getType(), I);
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004447
4448 // Compute X & (C << Y).
4449 Instruction *NewAnd =
4450 BinaryOperator::createAnd(ShiftOp, NS, LHSI->getName());
4451 InsertNewInstBefore(NewAnd, I);
4452
4453 I.setOperand(0, NewAnd);
4454 return &I;
4455 }
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004456 }
4457 break;
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004458
Chris Lattner272d5ca2004-09-28 18:22:15 +00004459 case Instruction::Shl: // (setcc (shl X, ShAmt), CI)
Reid Spencere0fc4df2006-10-20 07:07:24 +00004460 if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004461 if (I.isEquality()) {
Chris Lattner19b57f52005-06-15 20:53:31 +00004462 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
4463
4464 // Check that the shift amount is in range. If not, don't perform
4465 // undefined shifts. When the shift is visited it will be
4466 // simplified.
Reid Spencere0fc4df2006-10-20 07:07:24 +00004467 if (ShAmt->getZExtValue() >= TypeBits)
Chris Lattner19b57f52005-06-15 20:53:31 +00004468 break;
4469
Chris Lattner272d5ca2004-09-28 18:22:15 +00004470 // If we are comparing against bits always shifted out, the
4471 // comparison cannot succeed.
Misha Brukmanb1c93172005-04-21 23:48:37 +00004472 Constant *Comp =
Reid Spencerfdff9382006-11-08 06:47:33 +00004473 ConstantExpr::getShl(ConstantExpr::getLShr(CI, ShAmt), ShAmt);
Chris Lattner272d5ca2004-09-28 18:22:15 +00004474 if (Comp != CI) {// Comparing against a bit that we know is zero.
4475 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
4476 Constant *Cst = ConstantBool::get(IsSetNE);
4477 return ReplaceInstUsesWith(I, Cst);
4478 }
4479
4480 if (LHSI->hasOneUse()) {
4481 // Otherwise strength reduce the shift into an and.
Reid Spencere0fc4df2006-10-20 07:07:24 +00004482 unsigned ShAmtVal = (unsigned)ShAmt->getZExtValue();
Chris Lattner272d5ca2004-09-28 18:22:15 +00004483 uint64_t Val = (1ULL << (TypeBits-ShAmtVal))-1;
4484
4485 Constant *Mask;
4486 if (CI->getType()->isUnsigned()) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00004487 Mask = ConstantInt::get(CI->getType(), Val);
Chris Lattner272d5ca2004-09-28 18:22:15 +00004488 } else if (ShAmtVal != 0) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00004489 Mask = ConstantInt::get(CI->getType(), Val);
Chris Lattner272d5ca2004-09-28 18:22:15 +00004490 } else {
4491 Mask = ConstantInt::getAllOnesValue(CI->getType());
4492 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004493
Chris Lattner272d5ca2004-09-28 18:22:15 +00004494 Instruction *AndI =
4495 BinaryOperator::createAnd(LHSI->getOperand(0),
4496 Mask, LHSI->getName()+".mask");
4497 Value *And = InsertNewInstBefore(AndI, I);
4498 return new SetCondInst(I.getOpcode(), And,
Reid Spencerfdff9382006-11-08 06:47:33 +00004499 ConstantExpr::getLShr(CI, ShAmt));
Chris Lattner272d5ca2004-09-28 18:22:15 +00004500 }
4501 }
Chris Lattner272d5ca2004-09-28 18:22:15 +00004502 }
4503 break;
4504
Reid Spencerfdff9382006-11-08 06:47:33 +00004505 case Instruction::LShr: // (setcc (shr X, ShAmt), CI)
4506 case Instruction::AShr:
Reid Spencere0fc4df2006-10-20 07:07:24 +00004507 if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004508 if (I.isEquality()) {
Chris Lattner19b57f52005-06-15 20:53:31 +00004509 // Check that the shift amount is in range. If not, don't perform
4510 // undefined shifts. When the shift is visited it will be
4511 // simplified.
Chris Lattner104002b2005-06-16 01:52:07 +00004512 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
Reid Spencere0fc4df2006-10-20 07:07:24 +00004513 if (ShAmt->getZExtValue() >= TypeBits)
Chris Lattner19b57f52005-06-15 20:53:31 +00004514 break;
4515
Chris Lattner1023b872004-09-27 16:18:50 +00004516 // If we are comparing against bits always shifted out, the
4517 // comparison cannot succeed.
Reid Spencerfdff9382006-11-08 06:47:33 +00004518 Constant *Comp;
4519 if (CI->getType()->isUnsigned())
4520 Comp = ConstantExpr::getLShr(ConstantExpr::getShl(CI, ShAmt),
4521 ShAmt);
4522 else
4523 Comp = ConstantExpr::getAShr(ConstantExpr::getShl(CI, ShAmt),
4524 ShAmt);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004525
Chris Lattner1023b872004-09-27 16:18:50 +00004526 if (Comp != CI) {// Comparing against a bit that we know is zero.
4527 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
4528 Constant *Cst = ConstantBool::get(IsSetNE);
4529 return ReplaceInstUsesWith(I, Cst);
4530 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004531
Chris Lattner1023b872004-09-27 16:18:50 +00004532 if (LHSI->hasOneUse() || CI->isNullValue()) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00004533 unsigned ShAmtVal = (unsigned)ShAmt->getZExtValue();
Chris Lattner272d5ca2004-09-28 18:22:15 +00004534
Chris Lattner1023b872004-09-27 16:18:50 +00004535 // Otherwise strength reduce the shift into an and.
4536 uint64_t Val = ~0ULL; // All ones.
4537 Val <<= ShAmtVal; // Shift over to the right spot.
4538
4539 Constant *Mask;
4540 if (CI->getType()->isUnsigned()) {
Chris Lattner2f1457f2005-04-24 17:46:05 +00004541 Val &= ~0ULL >> (64-TypeBits);
Reid Spencere0fc4df2006-10-20 07:07:24 +00004542 Mask = ConstantInt::get(CI->getType(), Val);
Chris Lattner1023b872004-09-27 16:18:50 +00004543 } else {
Reid Spencere0fc4df2006-10-20 07:07:24 +00004544 Mask = ConstantInt::get(CI->getType(), Val);
Chris Lattner1023b872004-09-27 16:18:50 +00004545 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004546
Chris Lattner1023b872004-09-27 16:18:50 +00004547 Instruction *AndI =
4548 BinaryOperator::createAnd(LHSI->getOperand(0),
4549 Mask, LHSI->getName()+".mask");
4550 Value *And = InsertNewInstBefore(AndI, I);
4551 return new SetCondInst(I.getOpcode(), And,
4552 ConstantExpr::getShl(CI, ShAmt));
4553 }
Chris Lattner1023b872004-09-27 16:18:50 +00004554 }
4555 }
4556 break;
Chris Lattner7e794272004-09-24 15:21:34 +00004557
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004558 case Instruction::SDiv:
4559 case Instruction::UDiv:
4560 // Fold: setcc ([us]div X, C1), C2 -> range test
4561 // Fold this div into the comparison, producing a range check.
4562 // Determine, based on the divide type, what the range is being
4563 // checked. If there is an overflow on the low or high side, remember
4564 // it, otherwise compute the range [low, hi) bounding the new value.
4565 // See: InsertRangeTest above for the kinds of replacements possible.
Chris Lattner6862fbd2004-09-29 17:40:11 +00004566 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004567 // FIXME: If the operand types don't match the type of the divide
4568 // then don't attempt this transform. The code below doesn't have the
4569 // logic to deal with a signed divide and an unsigned compare (and
4570 // vice versa). This is because (x /s C1) <s C2 produces different
4571 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
4572 // (x /u C1) <u C2. Simply casting the operands and result won't
4573 // work. :( The if statement below tests that condition and bails
4574 // if it finds it.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00004575 const Type *DivRHSTy = DivRHS->getType();
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004576 unsigned DivOpCode = LHSI->getOpcode();
4577 if (I.isEquality() &&
4578 ((DivOpCode == Instruction::SDiv && DivRHSTy->isUnsigned()) ||
4579 (DivOpCode == Instruction::UDiv && DivRHSTy->isSigned())))
4580 break;
4581
4582 // Initialize the variables that will indicate the nature of the
4583 // range check.
4584 bool LoOverflow = false, HiOverflow = false;
Chris Lattner6862fbd2004-09-29 17:40:11 +00004585 ConstantInt *LoBound = 0, *HiBound = 0;
4586
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004587 // Compute Prod = CI * DivRHS. We are essentially solving an equation
4588 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
4589 // C2 (CI). By solving for X we can turn this into a range check
4590 // instead of computing a divide.
4591 ConstantInt *Prod =
4592 cast<ConstantInt>(ConstantExpr::getMul(CI, DivRHS));
Chris Lattner6862fbd2004-09-29 17:40:11 +00004593
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004594 // Determine if the product overflows by seeing if the product is
4595 // not equal to the divide. Make sure we do the same kind of divide
4596 // as in the LHS instruction that we're folding.
4597 bool ProdOV = !DivRHS->isNullValue() &&
4598 (DivOpCode == Instruction::SDiv ?
4599 ConstantExpr::getSDiv(Prod, DivRHS) :
4600 ConstantExpr::getUDiv(Prod, DivRHS)) != CI;
4601
4602 // Get the SetCC opcode
Chris Lattnera92af962004-10-11 19:40:04 +00004603 Instruction::BinaryOps Opcode = I.getOpcode();
4604
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004605 if (DivRHS->isNullValue()) {
4606 // Don't hack on divide by zeros!
4607 } else if (DivOpCode == Instruction::UDiv) { // udiv
Chris Lattner6862fbd2004-09-29 17:40:11 +00004608 LoBound = Prod;
4609 LoOverflow = ProdOV;
4610 HiOverflow = ProdOV || AddWithOverflow(HiBound, LoBound, DivRHS);
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004611 } else if (isPositive(DivRHS)) { // Divisor is > 0.
Chris Lattner6862fbd2004-09-29 17:40:11 +00004612 if (CI->isNullValue()) { // (X / pos) op 0
4613 // Can't overflow.
4614 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
4615 HiBound = DivRHS;
4616 } else if (isPositive(CI)) { // (X / pos) op pos
4617 LoBound = Prod;
4618 LoOverflow = ProdOV;
4619 HiOverflow = ProdOV || AddWithOverflow(HiBound, Prod, DivRHS);
4620 } else { // (X / pos) op neg
4621 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
4622 LoOverflow = AddWithOverflow(LoBound, Prod,
4623 cast<ConstantInt>(DivRHSH));
4624 HiBound = Prod;
4625 HiOverflow = ProdOV;
4626 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004627 } else { // Divisor is < 0.
Chris Lattner6862fbd2004-09-29 17:40:11 +00004628 if (CI->isNullValue()) { // (X / neg) op 0
4629 LoBound = AddOne(DivRHS);
4630 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner73bcba52005-06-17 02:05:55 +00004631 if (HiBound == DivRHS)
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004632 LoBound = 0; // - INTMIN = INTMIN
Chris Lattner6862fbd2004-09-29 17:40:11 +00004633 } else if (isPositive(CI)) { // (X / neg) op pos
4634 HiOverflow = LoOverflow = ProdOV;
4635 if (!LoOverflow)
4636 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS));
4637 HiBound = AddOne(Prod);
4638 } else { // (X / neg) op neg
4639 LoBound = Prod;
4640 LoOverflow = HiOverflow = ProdOV;
4641 HiBound = cast<ConstantInt>(ConstantExpr::getSub(Prod, DivRHS));
4642 }
Chris Lattner0b41e862004-10-08 19:15:44 +00004643
Chris Lattnera92af962004-10-11 19:40:04 +00004644 // Dividing by a negate swaps the condition.
4645 Opcode = SetCondInst::getSwappedCondition(Opcode);
Chris Lattner6862fbd2004-09-29 17:40:11 +00004646 }
4647
4648 if (LoBound) {
4649 Value *X = LHSI->getOperand(0);
Chris Lattnera92af962004-10-11 19:40:04 +00004650 switch (Opcode) {
Chris Lattner6862fbd2004-09-29 17:40:11 +00004651 default: assert(0 && "Unhandled setcc opcode!");
4652 case Instruction::SetEQ:
4653 if (LoOverflow && HiOverflow)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004654 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattner6862fbd2004-09-29 17:40:11 +00004655 else if (HiOverflow)
4656 return new SetCondInst(Instruction::SetGE, X, LoBound);
4657 else if (LoOverflow)
4658 return new SetCondInst(Instruction::SetLT, X, HiBound);
4659 else
4660 return InsertRangeTest(X, LoBound, HiBound, true, I);
4661 case Instruction::SetNE:
4662 if (LoOverflow && HiOverflow)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004663 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
Chris Lattner6862fbd2004-09-29 17:40:11 +00004664 else if (HiOverflow)
4665 return new SetCondInst(Instruction::SetLT, X, LoBound);
4666 else if (LoOverflow)
4667 return new SetCondInst(Instruction::SetGE, X, HiBound);
4668 else
4669 return InsertRangeTest(X, LoBound, HiBound, false, I);
4670 case Instruction::SetLT:
4671 if (LoOverflow)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004672 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattner6862fbd2004-09-29 17:40:11 +00004673 return new SetCondInst(Instruction::SetLT, X, LoBound);
4674 case Instruction::SetGT:
4675 if (HiOverflow)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004676 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattner6862fbd2004-09-29 17:40:11 +00004677 return new SetCondInst(Instruction::SetGE, X, HiBound);
4678 }
4679 }
4680 }
4681 break;
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004682 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004683
Chris Lattnera7942b72006-11-29 05:02:16 +00004684 // Simplify seteq and setne instructions with integer constant RHS.
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004685 if (I.isEquality()) {
Chris Lattnerd492a0b2003-07-23 17:02:11 +00004686 bool isSetNE = I.getOpcode() == Instruction::SetNE;
4687
Reid Spencere0fc4df2006-10-20 07:07:24 +00004688 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
4689 // the second operand is a constant, simplify a bit.
Chris Lattnerc992add2003-08-13 05:33:12 +00004690 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
4691 switch (BO->getOpcode()) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00004692 case Instruction::SRem:
4693 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
4694 if (CI->isNullValue() && isa<ConstantInt>(BO->getOperand(1)) &&
4695 BO->hasOneUse()) {
4696 int64_t V = cast<ConstantInt>(BO->getOperand(1))->getSExtValue();
4697 if (V > 1 && isPowerOf2_64(V)) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00004698 Value *NewRem = InsertNewInstBefore(BinaryOperator::createURem(
4699 BO->getOperand(0), BO->getOperand(1), BO->getName()), I);
Chris Lattner23b47b62004-07-06 07:38:18 +00004700 return BinaryOperator::create(I.getOpcode(), NewRem,
Reid Spencer7eb55b32006-11-02 01:53:59 +00004701 Constant::getNullValue(BO->getType()));
Chris Lattner23b47b62004-07-06 07:38:18 +00004702 }
Chris Lattner22d00a82005-08-02 19:16:58 +00004703 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004704 break;
Chris Lattnerc992add2003-08-13 05:33:12 +00004705 case Instruction::Add:
Chris Lattner6e079362004-06-27 22:51:36 +00004706 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
4707 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerb121ae12004-09-21 21:35:23 +00004708 if (BO->hasOneUse())
4709 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
4710 ConstantExpr::getSub(CI, BOp1C));
Chris Lattner6e079362004-06-27 22:51:36 +00004711 } else if (CI->isNullValue()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00004712 // Replace ((add A, B) != 0) with (A != -B) if A or B is
4713 // efficiently invertible, or if the add has just this one use.
4714 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004715
Chris Lattnerc992add2003-08-13 05:33:12 +00004716 if (Value *NegVal = dyn_castNegVal(BOp1))
4717 return new SetCondInst(I.getOpcode(), BOp0, NegVal);
4718 else if (Value *NegVal = dyn_castNegVal(BOp0))
4719 return new SetCondInst(I.getOpcode(), NegVal, BOp1);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00004720 else if (BO->hasOneUse()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00004721 Instruction *Neg = BinaryOperator::createNeg(BOp1, BO->getName());
4722 BO->setName("");
4723 InsertNewInstBefore(Neg, I);
4724 return new SetCondInst(I.getOpcode(), BOp0, Neg);
4725 }
4726 }
4727 break;
4728 case Instruction::Xor:
4729 // For the xor case, we can xor two constants together, eliminating
4730 // the explicit xor.
4731 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
4732 return BinaryOperator::create(I.getOpcode(), BO->getOperand(0),
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004733 ConstantExpr::getXor(CI, BOC));
Chris Lattnerc992add2003-08-13 05:33:12 +00004734
4735 // FALLTHROUGH
4736 case Instruction::Sub:
4737 // Replace (([sub|xor] A, B) != 0) with (A != B)
4738 if (CI->isNullValue())
4739 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
4740 BO->getOperand(1));
4741 break;
4742
4743 case Instruction::Or:
4744 // If bits are being or'd in that are not present in the constant we
4745 // are comparing against, then the comparison could never succeed!
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00004746 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Chris Lattnerc8e7e292004-06-10 02:12:35 +00004747 Constant *NotCI = ConstantExpr::getNot(CI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004748 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Chris Lattnerd492a0b2003-07-23 17:02:11 +00004749 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00004750 }
Chris Lattnerc992add2003-08-13 05:33:12 +00004751 break;
4752
4753 case Instruction::And:
4754 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerd492a0b2003-07-23 17:02:11 +00004755 // If bits are being compared against that are and'd out, then the
4756 // comparison can never succeed!
Chris Lattnerc8e7e292004-06-10 02:12:35 +00004757 if (!ConstantExpr::getAnd(CI,
4758 ConstantExpr::getNot(BOC))->isNullValue())
Chris Lattnerd492a0b2003-07-23 17:02:11 +00004759 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattnerc992add2003-08-13 05:33:12 +00004760
Chris Lattner35167c32004-06-09 07:59:58 +00004761 // If we have ((X & C) == C), turn it into ((X & C) != 0).
Chris Lattneree59d4b2004-06-10 02:33:20 +00004762 if (CI == BOC && isOneBitSet(CI))
Chris Lattner35167c32004-06-09 07:59:58 +00004763 return new SetCondInst(isSetNE ? Instruction::SetEQ :
4764 Instruction::SetNE, Op0,
4765 Constant::getNullValue(CI->getType()));
Chris Lattner35167c32004-06-09 07:59:58 +00004766
Chris Lattnerc992add2003-08-13 05:33:12 +00004767 // Replace (and X, (1 << size(X)-1) != 0) with x < 0, converting X
4768 // to be a signed value as appropriate.
4769 if (isSignBit(BOC)) {
4770 Value *X = BO->getOperand(0);
4771 // If 'X' is not signed, insert a cast now...
4772 if (!BOC->getType()->isSigned()) {
Chris Lattner97bfcea2004-06-17 18:16:02 +00004773 const Type *DestTy = BOC->getType()->getSignedVersion();
Reid Spencer13bc5d72006-12-12 09:18:51 +00004774 X = InsertCastBefore(Instruction::BitCast, X, DestTy, I);
Chris Lattnerc992add2003-08-13 05:33:12 +00004775 }
4776 return new SetCondInst(isSetNE ? Instruction::SetLT :
4777 Instruction::SetGE, X,
4778 Constant::getNullValue(X->getType()));
4779 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004780
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004781 // ((X & ~7) == 0) --> X < 8
Chris Lattner8fc5af42004-09-23 21:46:38 +00004782 if (CI->isNullValue() && isHighOnes(BOC)) {
4783 Value *X = BO->getOperand(0);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004784 Constant *NegX = ConstantExpr::getNeg(BOC);
Chris Lattner8fc5af42004-09-23 21:46:38 +00004785
4786 // If 'X' is signed, insert a cast now.
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004787 if (NegX->getType()->isSigned()) {
4788 const Type *DestTy = NegX->getType()->getUnsignedVersion();
Reid Spencer13bc5d72006-12-12 09:18:51 +00004789 X = InsertCastBefore(Instruction::BitCast, X, DestTy, I);
4790 NegX = ConstantExpr::getBitCast(NegX, DestTy);
Chris Lattner8fc5af42004-09-23 21:46:38 +00004791 }
4792
4793 return new SetCondInst(isSetNE ? Instruction::SetGE :
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004794 Instruction::SetLT, X, NegX);
Chris Lattner8fc5af42004-09-23 21:46:38 +00004795 }
4796
Chris Lattnerd492a0b2003-07-23 17:02:11 +00004797 }
Chris Lattnerc992add2003-08-13 05:33:12 +00004798 default: break;
4799 }
Chris Lattnera7942b72006-11-29 05:02:16 +00004800 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Op0)) {
4801 // Handle set{eq|ne} <intrinsic>, intcst.
4802 switch (II->getIntrinsicID()) {
4803 default: break;
4804 case Intrinsic::bswap_i16: // seteq (bswap(x)), c -> seteq(x,bswap(c))
4805 WorkList.push_back(II); // Dead?
4806 I.setOperand(0, II->getOperand(1));
4807 I.setOperand(1, ConstantInt::get(Type::UShortTy,
4808 ByteSwap_16(CI->getZExtValue())));
4809 return &I;
4810 case Intrinsic::bswap_i32: // seteq (bswap(x)), c -> seteq(x,bswap(c))
4811 WorkList.push_back(II); // Dead?
4812 I.setOperand(0, II->getOperand(1));
4813 I.setOperand(1, ConstantInt::get(Type::UIntTy,
4814 ByteSwap_32(CI->getZExtValue())));
4815 return &I;
4816 case Intrinsic::bswap_i64: // seteq (bswap(x)), c -> seteq(x,bswap(c))
4817 WorkList.push_back(II); // Dead?
4818 I.setOperand(0, II->getOperand(1));
4819 I.setOperand(1, ConstantInt::get(Type::ULongTy,
4820 ByteSwap_64(CI->getZExtValue())));
4821 return &I;
4822 }
Chris Lattnerc992add2003-08-13 05:33:12 +00004823 }
Chris Lattner2b55ea32004-02-23 07:16:20 +00004824 } else { // Not a SetEQ/SetNE
Misha Brukmanb1c93172005-04-21 23:48:37 +00004825 // If the LHS is a cast from an integral value of the same size,
Chris Lattner2b55ea32004-02-23 07:16:20 +00004826 if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
4827 Value *CastOp = Cast->getOperand(0);
4828 const Type *SrcTy = CastOp->getType();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004829 unsigned SrcTySize = SrcTy->getPrimitiveSizeInBits();
Chris Lattner2b55ea32004-02-23 07:16:20 +00004830 if (SrcTy != Cast->getType() && SrcTy->isInteger() &&
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004831 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00004832 assert((SrcTy->isSigned() ^ Cast->getType()->isSigned()) &&
Chris Lattner2b55ea32004-02-23 07:16:20 +00004833 "Source and destination signednesses should differ!");
4834 if (Cast->getType()->isSigned()) {
4835 // If this is a signed comparison, check for comparisons in the
4836 // vicinity of zero.
4837 if (I.getOpcode() == Instruction::SetLT && CI->isNullValue())
4838 // X < 0 => x > 127
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004839 return BinaryOperator::createSetGT(CastOp,
Reid Spencere0fc4df2006-10-20 07:07:24 +00004840 ConstantInt::get(SrcTy, (1ULL << (SrcTySize-1))-1));
Chris Lattner2b55ea32004-02-23 07:16:20 +00004841 else if (I.getOpcode() == Instruction::SetGT &&
Reid Spencere0fc4df2006-10-20 07:07:24 +00004842 cast<ConstantInt>(CI)->getSExtValue() == -1)
Chris Lattner2b55ea32004-02-23 07:16:20 +00004843 // X > -1 => x < 128
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004844 return BinaryOperator::createSetLT(CastOp,
Reid Spencere0fc4df2006-10-20 07:07:24 +00004845 ConstantInt::get(SrcTy, 1ULL << (SrcTySize-1)));
Chris Lattner2b55ea32004-02-23 07:16:20 +00004846 } else {
Reid Spencere0fc4df2006-10-20 07:07:24 +00004847 ConstantInt *CUI = cast<ConstantInt>(CI);
Chris Lattner2b55ea32004-02-23 07:16:20 +00004848 if (I.getOpcode() == Instruction::SetLT &&
Reid Spencere0fc4df2006-10-20 07:07:24 +00004849 CUI->getZExtValue() == 1ULL << (SrcTySize-1))
Chris Lattner2b55ea32004-02-23 07:16:20 +00004850 // X < 128 => X > -1
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004851 return BinaryOperator::createSetGT(CastOp,
Reid Spencere0fc4df2006-10-20 07:07:24 +00004852 ConstantInt::get(SrcTy, -1));
Chris Lattner2b55ea32004-02-23 07:16:20 +00004853 else if (I.getOpcode() == Instruction::SetGT &&
Reid Spencere0fc4df2006-10-20 07:07:24 +00004854 CUI->getZExtValue() == (1ULL << (SrcTySize-1))-1)
Chris Lattner2b55ea32004-02-23 07:16:20 +00004855 // X > 127 => X < 0
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004856 return BinaryOperator::createSetLT(CastOp,
4857 Constant::getNullValue(SrcTy));
Chris Lattner2b55ea32004-02-23 07:16:20 +00004858 }
4859 }
4860 }
Chris Lattnere967b342003-06-04 05:10:11 +00004861 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004862 }
4863
Chris Lattner77c32c32005-04-23 15:31:55 +00004864 // Handle setcc with constant RHS's that can be integer, FP or pointer.
4865 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
4866 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4867 switch (LHSI->getOpcode()) {
Chris Lattnera816eee2005-05-01 04:42:15 +00004868 case Instruction::GetElementPtr:
4869 if (RHSC->isNullValue()) {
4870 // Transform setcc GEP P, int 0, int 0, int 0, null -> setcc P, null
4871 bool isAllZeros = true;
4872 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
4873 if (!isa<Constant>(LHSI->getOperand(i)) ||
4874 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
4875 isAllZeros = false;
4876 break;
4877 }
4878 if (isAllZeros)
4879 return new SetCondInst(I.getOpcode(), LHSI->getOperand(0),
4880 Constant::getNullValue(LHSI->getOperand(0)->getType()));
4881 }
4882 break;
4883
Chris Lattner77c32c32005-04-23 15:31:55 +00004884 case Instruction::PHI:
4885 if (Instruction *NV = FoldOpIntoPhi(I))
4886 return NV;
4887 break;
4888 case Instruction::Select:
4889 // If either operand of the select is a constant, we can fold the
4890 // comparison into the select arms, which will cause one to be
4891 // constant folded and the select turned into a bitwise or.
4892 Value *Op1 = 0, *Op2 = 0;
4893 if (LHSI->hasOneUse()) {
4894 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
4895 // Fold the known value into the constant operand.
4896 Op1 = ConstantExpr::get(I.getOpcode(), C, RHSC);
4897 // Insert a new SetCC of the other select operand.
4898 Op2 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
4899 LHSI->getOperand(2), RHSC,
4900 I.getName()), I);
4901 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
4902 // Fold the known value into the constant operand.
4903 Op2 = ConstantExpr::get(I.getOpcode(), C, RHSC);
4904 // Insert a new SetCC of the other select operand.
4905 Op1 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
4906 LHSI->getOperand(1), RHSC,
4907 I.getName()), I);
4908 }
4909 }
Jeff Cohen82639852005-04-23 21:38:35 +00004910
Chris Lattner77c32c32005-04-23 15:31:55 +00004911 if (Op1)
4912 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
4913 break;
4914 }
4915 }
4916
Chris Lattner0798af32005-01-13 20:14:25 +00004917 // If we can optimize a 'setcc GEP, P' or 'setcc P, GEP', do so now.
4918 if (User *GEP = dyn_castGetElementPtr(Op0))
4919 if (Instruction *NI = FoldGEPSetCC(GEP, Op1, I.getOpcode(), I))
4920 return NI;
4921 if (User *GEP = dyn_castGetElementPtr(Op1))
4922 if (Instruction *NI = FoldGEPSetCC(GEP, Op0,
4923 SetCondInst::getSwappedCondition(I.getOpcode()), I))
4924 return NI;
4925
Chris Lattner16930792003-11-03 04:25:02 +00004926 // Test to see if the operands of the setcc are casted versions of other
4927 // values. If the cast can be stripped off both arguments, we do so now.
Chris Lattner6444c372003-11-03 05:17:03 +00004928 if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
4929 Value *CastOp0 = CI->getOperand(0);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00004930 if (CI->isLosslessCast() && I.isEquality() &&
4931 (isa<Constant>(Op1) || isa<CastInst>(Op1))) {
Chris Lattner16930792003-11-03 04:25:02 +00004932 // We keep moving the cast from the left operand over to the right
4933 // operand, where it can often be eliminated completely.
Chris Lattner6444c372003-11-03 05:17:03 +00004934 Op0 = CastOp0;
Misha Brukmanb1c93172005-04-21 23:48:37 +00004935
Chris Lattner16930792003-11-03 04:25:02 +00004936 // If operand #1 is a cast instruction, see if we can eliminate it as
4937 // well.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00004938 if (CastInst *CI2 = dyn_cast<CastInst>(Op1)) {
4939 Value *CI2Op0 = CI2->getOperand(0);
4940 if (CI2Op0->getType()->canLosslesslyBitCastTo(Op0->getType()))
4941 Op1 = CI2Op0;
4942 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004943
Chris Lattner16930792003-11-03 04:25:02 +00004944 // If Op1 is a constant, we can fold the cast into the constant.
4945 if (Op1->getType() != Op0->getType())
4946 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00004947 Op1 = ConstantExpr::getCast(Instruction::BitCast, Op1C,
4948 Op0->getType());
Chris Lattner16930792003-11-03 04:25:02 +00004949 } else {
4950 // Otherwise, cast the RHS right before the setcc
Reid Spencer13bc5d72006-12-12 09:18:51 +00004951 Op1 = InsertCastBefore(Instruction::BitCast, Op1, Op0->getType(), I);
Chris Lattner16930792003-11-03 04:25:02 +00004952 }
4953 return BinaryOperator::create(I.getOpcode(), Op0, Op1);
4954 }
4955
Chris Lattner6444c372003-11-03 05:17:03 +00004956 // Handle the special case of: setcc (cast bool to X), <cst>
4957 // This comes up when you have code like
4958 // int X = A < B;
4959 // if (X) ...
4960 // For generality, we handle any zero-extension of any operand comparison
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004961 // with a constant or another cast from the same type.
4962 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
4963 if (Instruction *R = visitSetCondInstWithCastAndCast(I))
4964 return R;
Chris Lattner6444c372003-11-03 05:17:03 +00004965 }
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00004966
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004967 if (I.isEquality()) {
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00004968 Value *A, *B;
4969 if (match(Op0, m_Xor(m_Value(A), m_Value(B))) &&
4970 (A == Op1 || B == Op1)) {
4971 // (A^B) == A -> B == 0
4972 Value *OtherVal = A == Op1 ? B : A;
4973 return BinaryOperator::create(I.getOpcode(), OtherVal,
4974 Constant::getNullValue(A->getType()));
4975 } else if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
4976 (A == Op0 || B == Op0)) {
4977 // A == (A^B) -> B == 0
4978 Value *OtherVal = A == Op0 ? B : A;
4979 return BinaryOperator::create(I.getOpcode(), OtherVal,
4980 Constant::getNullValue(A->getType()));
4981 } else if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
4982 // (A-B) == A -> B == 0
4983 return BinaryOperator::create(I.getOpcode(), B,
4984 Constant::getNullValue(B->getType()));
4985 } else if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
4986 // A == (A-B) -> B == 0
4987 return BinaryOperator::create(I.getOpcode(), B,
4988 Constant::getNullValue(B->getType()));
4989 }
Chris Lattnerd12a4bf2006-11-14 06:06:06 +00004990
4991 Value *C, *D;
4992 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
4993 if (Op0->hasOneUse() && Op1->hasOneUse() &&
4994 match(Op0, m_And(m_Value(A), m_Value(B))) &&
4995 match(Op1, m_And(m_Value(C), m_Value(D)))) {
4996 Value *X = 0, *Y = 0, *Z = 0;
4997
4998 if (A == C) {
4999 X = B; Y = D; Z = A;
5000 } else if (A == D) {
5001 X = B; Y = C; Z = A;
5002 } else if (B == C) {
5003 X = A; Y = D; Z = B;
5004 } else if (B == D) {
5005 X = A; Y = C; Z = B;
5006 }
5007
5008 if (X) { // Build (X^Y) & Z
5009 Op1 = InsertNewInstBefore(BinaryOperator::createXor(X, Y, "tmp"), I);
5010 Op1 = InsertNewInstBefore(BinaryOperator::createAnd(Op1, Z, "tmp"), I);
5011 I.setOperand(0, Op1);
5012 I.setOperand(1, Constant::getNullValue(Op1->getType()));
5013 return &I;
5014 }
5015 }
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00005016 }
Chris Lattner113f4f42002-06-25 16:13:24 +00005017 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005018}
5019
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005020// visitSetCondInstWithCastAndCast - Handle setcond (cast x to y), (cast/cst).
5021// We only handle extending casts so far.
5022//
5023Instruction *InstCombiner::visitSetCondInstWithCastAndCast(SetCondInst &SCI) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005024 const CastInst *LHSCI = cast<CastInst>(SCI.getOperand(0));
5025 Value *LHSCIOp = LHSCI->getOperand(0);
5026 const Type *SrcTy = LHSCIOp->getType();
5027 const Type *DestTy = SCI.getOperand(0)->getType();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005028 Value *RHSCIOp;
5029
5030 if (!DestTy->isIntegral() || !SrcTy->isIntegral())
Chris Lattner03f06f12005-01-17 03:20:02 +00005031 return 0;
5032
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005033 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
5034 unsigned DestBits = DestTy->getPrimitiveSizeInBits();
5035 if (SrcBits >= DestBits) return 0; // Only handle extending cast.
5036
5037 // Is this a sign or zero extension?
5038 bool isSignSrc = SrcTy->isSigned();
5039 bool isSignDest = DestTy->isSigned();
5040
5041 if (CastInst *CI = dyn_cast<CastInst>(SCI.getOperand(1))) {
5042 // Not an extension from the same type?
5043 RHSCIOp = CI->getOperand(0);
5044 if (RHSCIOp->getType() != LHSCIOp->getType()) return 0;
5045 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(SCI.getOperand(1))) {
5046 // Compute the constant that would happen if we truncated to SrcTy then
5047 // reextended to DestTy.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005048 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
5049 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005050
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005051 if (Res2 == CI) {
Devang Patelb42aef42006-10-19 18:54:08 +00005052 // Make sure that src sign and dest sign match. For example,
5053 //
5054 // %A = cast short %X to uint
5055 // %B = setgt uint %A, 1330
5056 //
Devang Patel88afd002006-10-19 19:21:36 +00005057 // It is incorrect to transform this into
Devang Patelb42aef42006-10-19 18:54:08 +00005058 //
5059 // %B = setgt short %X, 1330
5060 //
5061 // because %A may have negative value.
Devang Patel5d6df952006-10-19 20:59:13 +00005062 // However, it is OK if SrcTy is bool (See cast-set.ll testcase)
5063 // OR operation is EQ/NE.
5064 if (isSignSrc == isSignDest || SrcTy == Type::BoolTy || SCI.isEquality())
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005065 RHSCIOp = Res1;
Devang Patelb42aef42006-10-19 18:54:08 +00005066 else
5067 return 0;
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005068 } else {
5069 // If the value cannot be represented in the shorter type, we cannot emit
5070 // a simple comparison.
5071 if (SCI.getOpcode() == Instruction::SetEQ)
Chris Lattner6ab03f62006-09-28 23:35:22 +00005072 return ReplaceInstUsesWith(SCI, ConstantBool::getFalse());
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005073 if (SCI.getOpcode() == Instruction::SetNE)
Chris Lattner6ab03f62006-09-28 23:35:22 +00005074 return ReplaceInstUsesWith(SCI, ConstantBool::getTrue());
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005075
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005076 // Evaluate the comparison for LT.
5077 Value *Result;
5078 if (DestTy->isSigned()) {
5079 // We're performing a signed comparison.
5080 if (isSignSrc) {
5081 // Signed extend and signed comparison.
Reid Spencere0fc4df2006-10-20 07:07:24 +00005082 if (cast<ConstantInt>(CI)->getSExtValue() < 0)// X < (small) --> false
Chris Lattner6ab03f62006-09-28 23:35:22 +00005083 Result = ConstantBool::getFalse();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005084 else
Reid Spencere0fc4df2006-10-20 07:07:24 +00005085 Result = ConstantBool::getTrue(); // X < (large) --> true
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005086 } else {
5087 // Unsigned extend and signed comparison.
Reid Spencere0fc4df2006-10-20 07:07:24 +00005088 if (cast<ConstantInt>(CI)->getSExtValue() < 0)
Chris Lattner6ab03f62006-09-28 23:35:22 +00005089 Result = ConstantBool::getFalse();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005090 else
Chris Lattner6ab03f62006-09-28 23:35:22 +00005091 Result = ConstantBool::getTrue();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005092 }
5093 } else {
5094 // We're performing an unsigned comparison.
5095 if (!isSignSrc) {
5096 // Unsigned extend & compare -> always true.
Chris Lattner6ab03f62006-09-28 23:35:22 +00005097 Result = ConstantBool::getTrue();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005098 } else {
5099 // We're performing an unsigned comp with a sign extended value.
5100 // This is true if the input is >= 0. [aka >s -1]
5101 Constant *NegOne = ConstantIntegral::getAllOnesValue(SrcTy);
5102 Result = InsertNewInstBefore(BinaryOperator::createSetGT(LHSCIOp,
5103 NegOne, SCI.getName()), SCI);
5104 }
Reid Spencer279fa252004-11-28 21:31:15 +00005105 }
Chris Lattner03f06f12005-01-17 03:20:02 +00005106
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00005107 // Finally, return the value computed.
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005108 if (SCI.getOpcode() == Instruction::SetLT) {
5109 return ReplaceInstUsesWith(SCI, Result);
5110 } else {
5111 assert(SCI.getOpcode()==Instruction::SetGT &&"SetCC should be folded!");
5112 if (Constant *CI = dyn_cast<Constant>(Result))
5113 return ReplaceInstUsesWith(SCI, ConstantExpr::getNot(CI));
5114 else
5115 return BinaryOperator::createNot(Result);
5116 }
Chris Lattner03f06f12005-01-17 03:20:02 +00005117 }
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005118 } else {
5119 return 0;
Reid Spencer279fa252004-11-28 21:31:15 +00005120 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005121
Chris Lattner252a8452005-06-16 03:00:08 +00005122 // Okay, just insert a compare of the reduced operands now!
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005123 return BinaryOperator::create(SCI.getOpcode(), LHSCIOp, RHSCIOp);
5124}
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005125
Chris Lattnere8d6c602003-03-10 19:16:08 +00005126Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +00005127 assert(I.getOperand(1)->getType() == Type::UByteTy);
5128 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00005129 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005130
5131 // shl X, 0 == X and shr X, 0 == X
5132 // shl 0, X == 0 and shr 0, X == 0
5133 if (Op1 == Constant::getNullValue(Type::UByteTy) ||
Chris Lattnere6794492002-08-12 21:17:25 +00005134 Op0 == Constant::getNullValue(Op0->getType()))
5135 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf5b4ef72006-02-12 08:07:37 +00005136
Chris Lattner81a7a232004-10-16 18:11:37 +00005137 if (isa<UndefValue>(Op0)) { // undef >>s X -> undef
5138 if (!isLeftShift && I.getType()->isSigned())
Chris Lattner67f05452004-10-16 23:28:04 +00005139 return ReplaceInstUsesWith(I, Op0);
Chris Lattner81a7a232004-10-16 18:11:37 +00005140 else // undef << X -> 0 AND undef >>u X -> 0
5141 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5142 }
5143 if (isa<UndefValue>(Op1)) {
Chris Lattner18aa4d82005-07-20 18:49:28 +00005144 if (isLeftShift || I.getType()->isUnsigned())// X << undef, X >>u undef -> 0
Chris Lattner81a7a232004-10-16 18:11:37 +00005145 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5146 else
5147 return ReplaceInstUsesWith(I, Op0); // X >>s undef -> X
5148 }
5149
Chris Lattnerd4dee402006-11-10 23:38:52 +00005150 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
5151 if (I.getOpcode() == Instruction::AShr)
Reid Spencere0fc4df2006-10-20 07:07:24 +00005152 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Chris Lattnerd4dee402006-11-10 23:38:52 +00005153 if (CSI->isAllOnesValue())
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00005154 return ReplaceInstUsesWith(I, CSI);
5155
Chris Lattner183b3362004-04-09 19:05:30 +00005156 // Try to fold constant and into select arguments.
5157 if (isa<Constant>(Op0))
5158 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner86102b82005-01-01 16:22:27 +00005159 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00005160 return R;
5161
Chris Lattnerb18dbbf2005-05-08 17:34:56 +00005162 // See if we can turn a signed shr into an unsigned shr.
Chris Lattnerb3f24c92006-09-18 04:22:48 +00005163 if (I.isArithmeticShift()) {
Chris Lattnerc3ebf402006-02-07 07:27:52 +00005164 if (MaskedValueIsZero(Op0,
5165 1ULL << (I.getType()->getPrimitiveSizeInBits()-1))) {
Reid Spencerfdff9382006-11-08 06:47:33 +00005166 return new ShiftInst(Instruction::LShr, Op0, Op1, I.getName());
Chris Lattnerb18dbbf2005-05-08 17:34:56 +00005167 }
5168 }
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00005169
Reid Spencere0fc4df2006-10-20 07:07:24 +00005170 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
5171 if (CUI->getType()->isUnsigned())
5172 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
5173 return Res;
Chris Lattner14553932006-01-06 07:12:35 +00005174 return 0;
5175}
5176
Reid Spencere0fc4df2006-10-20 07:07:24 +00005177Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Chris Lattner14553932006-01-06 07:12:35 +00005178 ShiftInst &I) {
5179 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Reid Spencerfdff9382006-11-08 06:47:33 +00005180 bool isSignedShift = isLeftShift ? Op0->getType()->isSigned() :
5181 I.getOpcode() == Instruction::AShr;
Chris Lattnerb3309392006-01-06 07:22:22 +00005182 bool isUnsignedShift = !isSignedShift;
Chris Lattner14553932006-01-06 07:12:35 +00005183
Chris Lattnerf5b4ef72006-02-12 08:07:37 +00005184 // See if we can simplify any instructions used by the instruction whose sole
5185 // purpose is to compute bits we don't care about.
5186 uint64_t KnownZero, KnownOne;
5187 if (SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
5188 KnownZero, KnownOne))
5189 return &I;
5190
Chris Lattner14553932006-01-06 07:12:35 +00005191 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
5192 // of a signed value.
5193 //
5194 unsigned TypeBits = Op0->getType()->getPrimitiveSizeInBits();
Reid Spencere0fc4df2006-10-20 07:07:24 +00005195 if (Op1->getZExtValue() >= TypeBits) {
Chris Lattnerb3309392006-01-06 07:22:22 +00005196 if (isUnsignedShift || isLeftShift)
Chris Lattner14553932006-01-06 07:12:35 +00005197 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
5198 else {
Reid Spencere0fc4df2006-10-20 07:07:24 +00005199 I.setOperand(1, ConstantInt::get(Type::UByteTy, TypeBits-1));
Chris Lattner14553932006-01-06 07:12:35 +00005200 return &I;
Chris Lattnerf5ce2542004-02-23 20:30:06 +00005201 }
Chris Lattner14553932006-01-06 07:12:35 +00005202 }
5203
5204 // ((X*C1) << C2) == (X * (C1 << C2))
5205 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
5206 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
5207 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
5208 return BinaryOperator::createMul(BO->getOperand(0),
5209 ConstantExpr::getShl(BOOp, Op1));
5210
5211 // Try to fold constant and into select arguments.
5212 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5213 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5214 return R;
5215 if (isa<PHINode>(Op0))
5216 if (Instruction *NV = FoldOpIntoPhi(I))
5217 return NV;
5218
5219 if (Op0->hasOneUse()) {
Chris Lattner14553932006-01-06 07:12:35 +00005220 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
5221 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
5222 Value *V1, *V2;
5223 ConstantInt *CC;
5224 switch (Op0BO->getOpcode()) {
Chris Lattner27cb9db2005-09-18 05:12:10 +00005225 default: break;
5226 case Instruction::Add:
5227 case Instruction::And:
5228 case Instruction::Or:
5229 case Instruction::Xor:
5230 // These operators commute.
5231 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner797dee72005-09-18 06:30:59 +00005232 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
5233 match(Op0BO->getOperand(1),
Chris Lattner14553932006-01-06 07:12:35 +00005234 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Chris Lattner797dee72005-09-18 06:30:59 +00005235 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00005236 Op0BO->getOperand(0), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00005237 Op0BO->getName());
5238 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005239 Instruction *X =
5240 BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
5241 Op0BO->getOperand(1)->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00005242 InsertNewInstBefore(X, I); // (X + (Y << C))
5243 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
Chris Lattner14553932006-01-06 07:12:35 +00005244 C2 = ConstantExpr::getShl(C2, Op1);
Chris Lattner797dee72005-09-18 06:30:59 +00005245 return BinaryOperator::createAnd(X, C2);
5246 }
Chris Lattner14553932006-01-06 07:12:35 +00005247
Chris Lattner797dee72005-09-18 06:30:59 +00005248 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
5249 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
5250 match(Op0BO->getOperand(1),
5251 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner14553932006-01-06 07:12:35 +00005252 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005253 cast<BinaryOperator>(Op0BO->getOperand(1))->getOperand(0)->hasOneUse()) {
Chris Lattner797dee72005-09-18 06:30:59 +00005254 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00005255 Op0BO->getOperand(0), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00005256 Op0BO->getName());
5257 InsertNewInstBefore(YS, I); // (Y << C)
5258 Instruction *XM =
Chris Lattner14553932006-01-06 07:12:35 +00005259 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner797dee72005-09-18 06:30:59 +00005260 V1->getName()+".mask");
5261 InsertNewInstBefore(XM, I); // X & (CC << C)
5262
5263 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
5264 }
Chris Lattner14553932006-01-06 07:12:35 +00005265
Chris Lattner797dee72005-09-18 06:30:59 +00005266 // FALL THROUGH.
Chris Lattner27cb9db2005-09-18 05:12:10 +00005267 case Instruction::Sub:
5268 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner797dee72005-09-18 06:30:59 +00005269 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
5270 match(Op0BO->getOperand(0),
Chris Lattner14553932006-01-06 07:12:35 +00005271 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Chris Lattner797dee72005-09-18 06:30:59 +00005272 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00005273 Op0BO->getOperand(1), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00005274 Op0BO->getName());
5275 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005276 Instruction *X =
Chris Lattner1df0e982006-05-31 21:14:00 +00005277 BinaryOperator::create(Op0BO->getOpcode(), V1, YS,
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005278 Op0BO->getOperand(0)->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00005279 InsertNewInstBefore(X, I); // (X + (Y << C))
5280 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
Chris Lattner14553932006-01-06 07:12:35 +00005281 C2 = ConstantExpr::getShl(C2, Op1);
Chris Lattner797dee72005-09-18 06:30:59 +00005282 return BinaryOperator::createAnd(X, C2);
5283 }
Chris Lattner14553932006-01-06 07:12:35 +00005284
Chris Lattner1df0e982006-05-31 21:14:00 +00005285 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner797dee72005-09-18 06:30:59 +00005286 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
5287 match(Op0BO->getOperand(0),
5288 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner14553932006-01-06 07:12:35 +00005289 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005290 cast<BinaryOperator>(Op0BO->getOperand(0))
5291 ->getOperand(0)->hasOneUse()) {
Chris Lattner797dee72005-09-18 06:30:59 +00005292 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00005293 Op0BO->getOperand(1), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00005294 Op0BO->getName());
5295 InsertNewInstBefore(YS, I); // (Y << C)
5296 Instruction *XM =
Chris Lattner14553932006-01-06 07:12:35 +00005297 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner797dee72005-09-18 06:30:59 +00005298 V1->getName()+".mask");
5299 InsertNewInstBefore(XM, I); // X & (CC << C)
5300
Chris Lattner1df0e982006-05-31 21:14:00 +00005301 return BinaryOperator::create(Op0BO->getOpcode(), XM, YS);
Chris Lattner797dee72005-09-18 06:30:59 +00005302 }
Chris Lattner14553932006-01-06 07:12:35 +00005303
Chris Lattner27cb9db2005-09-18 05:12:10 +00005304 break;
Chris Lattner14553932006-01-06 07:12:35 +00005305 }
5306
5307
5308 // If the operand is an bitwise operator with a constant RHS, and the
5309 // shift is the only use, we can pull it out of the shift.
5310 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
5311 bool isValid = true; // Valid only for And, Or, Xor
5312 bool highBitSet = false; // Transform if high bit of constant set?
5313
5314 switch (Op0BO->getOpcode()) {
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00005315 default: isValid = false; break; // Do not perform transform!
Chris Lattner44bd3922004-10-08 03:46:20 +00005316 case Instruction::Add:
5317 isValid = isLeftShift;
5318 break;
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00005319 case Instruction::Or:
5320 case Instruction::Xor:
5321 highBitSet = false;
5322 break;
5323 case Instruction::And:
5324 highBitSet = true;
5325 break;
Chris Lattner14553932006-01-06 07:12:35 +00005326 }
5327
5328 // If this is a signed shift right, and the high bit is modified
5329 // by the logical operation, do not perform the transformation.
5330 // The highBitSet boolean indicates the value of the high bit of
5331 // the constant which would cause it to be modified for this
5332 // operation.
5333 //
Chris Lattnerb3309392006-01-06 07:22:22 +00005334 if (isValid && !isLeftShift && isSignedShift) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00005335 uint64_t Val = Op0C->getZExtValue();
Chris Lattner14553932006-01-06 07:12:35 +00005336 isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
5337 }
5338
5339 if (isValid) {
5340 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
5341
5342 Instruction *NewShift =
5343 new ShiftInst(I.getOpcode(), Op0BO->getOperand(0), Op1,
5344 Op0BO->getName());
5345 Op0BO->setName("");
5346 InsertNewInstBefore(NewShift, I);
5347
5348 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
5349 NewRHS);
5350 }
5351 }
5352 }
5353 }
5354
Chris Lattnereb372a02006-01-06 07:52:12 +00005355 // Find out if this is a shift of a shift by a constant.
5356 ShiftInst *ShiftOp = 0;
Chris Lattner14553932006-01-06 07:12:35 +00005357 if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0))
Chris Lattnereb372a02006-01-06 07:52:12 +00005358 ShiftOp = Op0SI;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005359 else if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
5360 // If this is a noop-integer cast of a shift instruction, use the shift.
5361 if (isa<ShiftInst>(CI->getOperand(0))) {
Chris Lattnereb372a02006-01-06 07:52:12 +00005362 ShiftOp = cast<ShiftInst>(CI->getOperand(0));
5363 }
5364 }
5365
Reid Spencere0fc4df2006-10-20 07:07:24 +00005366 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Chris Lattnereb372a02006-01-06 07:52:12 +00005367 // Find the operands and properties of the input shift. Note that the
5368 // signedness of the input shift may differ from the current shift if there
5369 // is a noop cast between the two.
5370 bool isShiftOfLeftShift = ShiftOp->getOpcode() == Instruction::Shl;
Reid Spencerfdff9382006-11-08 06:47:33 +00005371 bool isShiftOfSignedShift = isShiftOfLeftShift ?
5372 ShiftOp->getType()->isSigned() :
5373 ShiftOp->getOpcode() == Instruction::AShr;
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005374 bool isShiftOfUnsignedShift = !isShiftOfSignedShift;
Chris Lattnereb372a02006-01-06 07:52:12 +00005375
Reid Spencere0fc4df2006-10-20 07:07:24 +00005376 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Chris Lattnereb372a02006-01-06 07:52:12 +00005377
Reid Spencere0fc4df2006-10-20 07:07:24 +00005378 unsigned ShiftAmt1 = (unsigned)ShiftAmt1C->getZExtValue();
5379 unsigned ShiftAmt2 = (unsigned)Op1->getZExtValue();
Chris Lattnereb372a02006-01-06 07:52:12 +00005380
5381 // Check for (A << c1) << c2 and (A >> c1) >> c2.
5382 if (isLeftShift == isShiftOfLeftShift) {
5383 // Do not fold these shifts if the first one is signed and the second one
5384 // is unsigned and this is a right shift. Further, don't do any folding
5385 // on them.
5386 if (isShiftOfSignedShift && isUnsignedShift && !isLeftShift)
5387 return 0;
Chris Lattner14553932006-01-06 07:12:35 +00005388
Chris Lattnereb372a02006-01-06 07:52:12 +00005389 unsigned Amt = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
5390 if (Amt > Op0->getType()->getPrimitiveSizeInBits())
5391 Amt = Op0->getType()->getPrimitiveSizeInBits();
Chris Lattner14553932006-01-06 07:12:35 +00005392
Chris Lattnereb372a02006-01-06 07:52:12 +00005393 Value *Op = ShiftOp->getOperand(0);
5394 if (isShiftOfSignedShift != isSignedShift)
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005395 Op = InsertNewInstBefore(
5396 CastInst::createInferredCast(Op, I.getType(), "tmp"), I);
5397 ShiftInst *ShiftResult = new ShiftInst(I.getOpcode(), Op,
Reid Spencere0fc4df2006-10-20 07:07:24 +00005398 ConstantInt::get(Type::UByteTy, Amt));
Reid Spencerfdff9382006-11-08 06:47:33 +00005399 if (I.getType() == ShiftResult->getType())
5400 return ShiftResult;
5401 InsertNewInstBefore(ShiftResult, I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005402 return CastInst::create(Instruction::BitCast, ShiftResult, I.getType());
Chris Lattnereb372a02006-01-06 07:52:12 +00005403 }
5404
5405 // Check for (A << c1) >> c2 or (A >> c1) << c2. If we are dealing with
5406 // signed types, we can only support the (A >> c1) << c2 configuration,
5407 // because it can not turn an arbitrary bit of A into a sign bit.
5408 if (isUnsignedShift || isLeftShift) {
5409 // Calculate bitmask for what gets shifted off the edge.
5410 Constant *C = ConstantIntegral::getAllOnesValue(I.getType());
5411 if (isLeftShift)
5412 C = ConstantExpr::getShl(C, ShiftAmt1C);
5413 else
Reid Spencerfdff9382006-11-08 06:47:33 +00005414 C = ConstantExpr::getLShr(C, ShiftAmt1C);
Chris Lattnereb372a02006-01-06 07:52:12 +00005415
5416 Value *Op = ShiftOp->getOperand(0);
Reid Spencerfdff9382006-11-08 06:47:33 +00005417 if (Op->getType() != C->getType())
Reid Spencer13bc5d72006-12-12 09:18:51 +00005418 Op = InsertCastBefore(Instruction::BitCast, Op, I.getType(), I);
Chris Lattnereb372a02006-01-06 07:52:12 +00005419
5420 Instruction *Mask =
5421 BinaryOperator::createAnd(Op, C, Op->getName()+".mask");
5422 InsertNewInstBefore(Mask, I);
5423
5424 // Figure out what flavor of shift we should use...
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005425 if (ShiftAmt1 == ShiftAmt2) {
Chris Lattnereb372a02006-01-06 07:52:12 +00005426 return ReplaceInstUsesWith(I, Mask); // (A << c) >> c === A & c2
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005427 } else if (ShiftAmt1 < ShiftAmt2) {
Chris Lattnereb372a02006-01-06 07:52:12 +00005428 return new ShiftInst(I.getOpcode(), Mask,
Reid Spencere0fc4df2006-10-20 07:07:24 +00005429 ConstantInt::get(Type::UByteTy, ShiftAmt2-ShiftAmt1));
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005430 } else if (isShiftOfUnsignedShift || isShiftOfLeftShift) {
5431 if (isShiftOfUnsignedShift && !isShiftOfLeftShift && isSignedShift) {
Reid Spencerfdff9382006-11-08 06:47:33 +00005432 return new ShiftInst(Instruction::LShr, Mask,
5433 ConstantInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005434 } else {
5435 return new ShiftInst(ShiftOp->getOpcode(), Mask,
Reid Spencere0fc4df2006-10-20 07:07:24 +00005436 ConstantInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005437 }
5438 } else {
5439 // (X >>s C1) << C2 where C1 > C2 === (X >>s (C1-C2)) & mask
Reid Spencer13bc5d72006-12-12 09:18:51 +00005440 Op = InsertCastBefore(Instruction::BitCast, Mask,
5441 I.getType()->getSignedVersion(), I);
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005442 Instruction *Shift =
5443 new ShiftInst(ShiftOp->getOpcode(), Op,
Reid Spencere0fc4df2006-10-20 07:07:24 +00005444 ConstantInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005445 InsertNewInstBefore(Shift, I);
5446
5447 C = ConstantIntegral::getAllOnesValue(Shift->getType());
5448 C = ConstantExpr::getShl(C, Op1);
5449 Mask = BinaryOperator::createAnd(Shift, C, Op->getName()+".mask");
5450 InsertNewInstBefore(Mask, I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005451 return CastInst::create(Instruction::BitCast, Mask, I.getType());
Chris Lattnereb372a02006-01-06 07:52:12 +00005452 }
5453 } else {
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005454 // We can handle signed (X << C1) >>s C2 if it's a sign extend. In
Chris Lattnereb372a02006-01-06 07:52:12 +00005455 // this case, C1 == C2 and C1 is 8, 16, or 32.
5456 if (ShiftAmt1 == ShiftAmt2) {
5457 const Type *SExtType = 0;
Chris Lattner655d08f2006-04-28 22:21:41 +00005458 switch (Op0->getType()->getPrimitiveSizeInBits() - ShiftAmt1) {
Chris Lattnereb372a02006-01-06 07:52:12 +00005459 case 8 : SExtType = Type::SByteTy; break;
5460 case 16: SExtType = Type::ShortTy; break;
5461 case 32: SExtType = Type::IntTy; break;
5462 }
5463
5464 if (SExtType) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005465 Instruction *NewTrunc =
5466 new TruncInst(ShiftOp->getOperand(0), SExtType, "sext");
Chris Lattnereb372a02006-01-06 07:52:12 +00005467 InsertNewInstBefore(NewTrunc, I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005468 return new SExtInst(NewTrunc, I.getType());
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00005469 }
Chris Lattner27cb9db2005-09-18 05:12:10 +00005470 }
Chris Lattner86102b82005-01-01 16:22:27 +00005471 }
Chris Lattnereb372a02006-01-06 07:52:12 +00005472 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005473 return 0;
5474}
5475
Chris Lattner48a44f72002-05-02 17:06:02 +00005476
Chris Lattner8f663e82005-10-29 04:36:15 +00005477/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
5478/// expression. If so, decompose it, returning some value X, such that Val is
5479/// X*Scale+Offset.
5480///
5481static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
5482 unsigned &Offset) {
5483 assert(Val->getType() == Type::UIntTy && "Unexpected allocation size type!");
Reid Spencere0fc4df2006-10-20 07:07:24 +00005484 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
5485 if (CI->getType()->isUnsigned()) {
5486 Offset = CI->getZExtValue();
5487 Scale = 1;
5488 return ConstantInt::get(Type::UIntTy, 0);
5489 }
Chris Lattner8f663e82005-10-29 04:36:15 +00005490 } else if (Instruction *I = dyn_cast<Instruction>(Val)) {
5491 if (I->getNumOperands() == 2) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00005492 if (ConstantInt *CUI = dyn_cast<ConstantInt>(I->getOperand(1))) {
5493 if (CUI->getType()->isUnsigned()) {
5494 if (I->getOpcode() == Instruction::Shl) {
5495 // This is a value scaled by '1 << the shift amt'.
5496 Scale = 1U << CUI->getZExtValue();
5497 Offset = 0;
5498 return I->getOperand(0);
5499 } else if (I->getOpcode() == Instruction::Mul) {
5500 // This value is scaled by 'CUI'.
5501 Scale = CUI->getZExtValue();
5502 Offset = 0;
5503 return I->getOperand(0);
5504 } else if (I->getOpcode() == Instruction::Add) {
5505 // We have X+C. Check to see if we really have (X*C2)+C1,
5506 // where C1 is divisible by C2.
5507 unsigned SubScale;
5508 Value *SubVal =
5509 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
5510 Offset += CUI->getZExtValue();
5511 if (SubScale > 1 && (Offset % SubScale == 0)) {
5512 Scale = SubScale;
5513 return SubVal;
5514 }
Chris Lattner8f663e82005-10-29 04:36:15 +00005515 }
5516 }
5517 }
5518 }
5519 }
5520
5521 // Otherwise, we can't look past this.
5522 Scale = 1;
5523 Offset = 0;
5524 return Val;
5525}
5526
5527
Chris Lattner216be912005-10-24 06:03:58 +00005528/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
5529/// try to eliminate the cast by moving the type information into the alloc.
5530Instruction *InstCombiner::PromoteCastOfAllocation(CastInst &CI,
5531 AllocationInst &AI) {
5532 const PointerType *PTy = dyn_cast<PointerType>(CI.getType());
Chris Lattnerbb171802005-10-27 05:53:56 +00005533 if (!PTy) return 0; // Not casting the allocation to a pointer type.
Chris Lattner216be912005-10-24 06:03:58 +00005534
Chris Lattnerac87beb2005-10-24 06:22:12 +00005535 // Remove any uses of AI that are dead.
5536 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
5537 std::vector<Instruction*> DeadUsers;
5538 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
5539 Instruction *User = cast<Instruction>(*UI++);
5540 if (isInstructionTriviallyDead(User)) {
5541 while (UI != E && *UI == User)
5542 ++UI; // If this instruction uses AI more than once, don't break UI.
5543
5544 // Add operands to the worklist.
5545 AddUsesToWorkList(*User);
5546 ++NumDeadInst;
Bill Wendling5dbf43c2006-11-26 09:46:52 +00005547 DOUT << "IC: DCE: " << *User;
Chris Lattnerac87beb2005-10-24 06:22:12 +00005548
5549 User->eraseFromParent();
5550 removeFromWorkList(User);
5551 }
5552 }
5553
Chris Lattner216be912005-10-24 06:03:58 +00005554 // Get the type really allocated and the type casted to.
5555 const Type *AllocElTy = AI.getAllocatedType();
5556 const Type *CastElTy = PTy->getElementType();
5557 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner355ecc02005-10-24 06:26:18 +00005558
Chris Lattner7d190672006-10-01 19:40:58 +00005559 unsigned AllocElTyAlign = TD->getTypeAlignment(AllocElTy);
5560 unsigned CastElTyAlign = TD->getTypeAlignment(CastElTy);
Chris Lattner355ecc02005-10-24 06:26:18 +00005561 if (CastElTyAlign < AllocElTyAlign) return 0;
5562
Chris Lattner46705b22005-10-24 06:35:18 +00005563 // If the allocation has multiple uses, only promote it if we are strictly
5564 // increasing the alignment of the resultant allocation. If we keep it the
5565 // same, we open the door to infinite loops of various kinds.
5566 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
5567
Chris Lattner216be912005-10-24 06:03:58 +00005568 uint64_t AllocElTySize = TD->getTypeSize(AllocElTy);
5569 uint64_t CastElTySize = TD->getTypeSize(CastElTy);
Chris Lattnerbb171802005-10-27 05:53:56 +00005570 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner355ecc02005-10-24 06:26:18 +00005571
Chris Lattner8270c332005-10-29 03:19:53 +00005572 // See if we can satisfy the modulus by pulling a scale out of the array
5573 // size argument.
Chris Lattner8f663e82005-10-29 04:36:15 +00005574 unsigned ArraySizeScale, ArrayOffset;
5575 Value *NumElements = // See if the array size is a decomposable linear expr.
5576 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
5577
Chris Lattner8270c332005-10-29 03:19:53 +00005578 // If we can now satisfy the modulus, by using a non-1 scale, we really can
5579 // do the xform.
Chris Lattner8f663e82005-10-29 04:36:15 +00005580 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
5581 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattnerb3ecf962005-10-27 06:12:00 +00005582
Chris Lattner8270c332005-10-29 03:19:53 +00005583 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
5584 Value *Amt = 0;
5585 if (Scale == 1) {
5586 Amt = NumElements;
5587 } else {
Reid Spencere0fc4df2006-10-20 07:07:24 +00005588 // If the allocation size is constant, form a constant mul expression
5589 Amt = ConstantInt::get(Type::UIntTy, Scale);
5590 if (isa<ConstantInt>(NumElements) && NumElements->getType()->isUnsigned())
5591 Amt = ConstantExpr::getMul(
5592 cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
5593 // otherwise multiply the amount and the number of elements
Chris Lattner8270c332005-10-29 03:19:53 +00005594 else if (Scale != 1) {
5595 Instruction *Tmp = BinaryOperator::createMul(Amt, NumElements, "tmp");
5596 Amt = InsertNewInstBefore(Tmp, AI);
Chris Lattnerb3ecf962005-10-27 06:12:00 +00005597 }
Chris Lattnerbb171802005-10-27 05:53:56 +00005598 }
5599
Chris Lattner8f663e82005-10-29 04:36:15 +00005600 if (unsigned Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00005601 Value *Off = ConstantInt::get(Type::UIntTy, Offset);
Chris Lattner8f663e82005-10-29 04:36:15 +00005602 Instruction *Tmp = BinaryOperator::createAdd(Amt, Off, "tmp");
5603 Amt = InsertNewInstBefore(Tmp, AI);
5604 }
5605
Chris Lattner216be912005-10-24 06:03:58 +00005606 std::string Name = AI.getName(); AI.setName("");
5607 AllocationInst *New;
5608 if (isa<MallocInst>(AI))
Nate Begeman848622f2005-11-05 09:21:28 +00005609 New = new MallocInst(CastElTy, Amt, AI.getAlignment(), Name);
Chris Lattner216be912005-10-24 06:03:58 +00005610 else
Nate Begeman848622f2005-11-05 09:21:28 +00005611 New = new AllocaInst(CastElTy, Amt, AI.getAlignment(), Name);
Chris Lattner216be912005-10-24 06:03:58 +00005612 InsertNewInstBefore(New, AI);
Chris Lattner46705b22005-10-24 06:35:18 +00005613
5614 // If the allocation has multiple uses, insert a cast and change all things
5615 // that used it to use the new cast. This will also hack on CI, but it will
5616 // die soon.
5617 if (!AI.hasOneUse()) {
5618 AddUsesToWorkList(AI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005619 // New is the allocation instruction, pointer typed. AI is the original
5620 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
5621 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
Chris Lattner46705b22005-10-24 06:35:18 +00005622 InsertNewInstBefore(NewCast, AI);
5623 AI.replaceAllUsesWith(NewCast);
5624 }
Chris Lattner216be912005-10-24 06:03:58 +00005625 return ReplaceInstUsesWith(CI, New);
5626}
5627
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005628/// CanEvaluateInDifferentType - Return true if we can take the specified value
5629/// and return it without inserting any new casts. This is used by code that
5630/// tries to decide whether promoting or shrinking integer operations to wider
5631/// or smaller types will allow us to eliminate a truncate or extend.
5632static bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
5633 int &NumCastsRemoved) {
5634 if (isa<Constant>(V)) return true;
5635
5636 Instruction *I = dyn_cast<Instruction>(V);
5637 if (!I || !I->hasOneUse()) return false;
5638
5639 switch (I->getOpcode()) {
5640 case Instruction::And:
5641 case Instruction::Or:
5642 case Instruction::Xor:
5643 // These operators can all arbitrarily be extended or truncated.
5644 return CanEvaluateInDifferentType(I->getOperand(0), Ty, NumCastsRemoved) &&
5645 CanEvaluateInDifferentType(I->getOperand(1), Ty, NumCastsRemoved);
Chris Lattner960acb02006-11-29 07:18:39 +00005646 case Instruction::AShr:
5647 case Instruction::LShr:
5648 case Instruction::Shl:
5649 // If this is just a bitcast changing the sign of the operation, we can
5650 // convert if the operand can be converted.
5651 if (V->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
5652 return CanEvaluateInDifferentType(I->getOperand(0), Ty, NumCastsRemoved);
5653 break;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005654 case Instruction::Trunc:
5655 case Instruction::ZExt:
5656 case Instruction::SExt:
5657 case Instruction::BitCast:
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005658 // If this is a cast from the destination type, we can trivially eliminate
5659 // it, and this will remove a cast overall.
5660 if (I->getOperand(0)->getType() == Ty) {
Chris Lattner3fda3862006-06-28 17:34:50 +00005661 // If the first operand is itself a cast, and is eliminable, do not count
5662 // this as an eliminable cast. We would prefer to eliminate those two
5663 // casts first.
Reid Spencerde46e482006-11-02 20:25:50 +00005664 if (isa<CastInst>(I->getOperand(0)))
Chris Lattner3fda3862006-06-28 17:34:50 +00005665 return true;
5666
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005667 ++NumCastsRemoved;
5668 return true;
5669 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005670 break;
5671 default:
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005672 // TODO: Can handle more cases here.
5673 break;
5674 }
5675
5676 return false;
5677}
5678
5679/// EvaluateInDifferentType - Given an expression that
5680/// CanEvaluateInDifferentType returns true for, actually insert the code to
5681/// evaluate the expression.
5682Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty) {
5683 if (Constant *C = dyn_cast<Constant>(V))
5684 return ConstantExpr::getCast(C, Ty);
5685
5686 // Otherwise, it must be an instruction.
5687 Instruction *I = cast<Instruction>(V);
Chris Lattnerd0622b62006-05-20 23:14:03 +00005688 Instruction *Res = 0;
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005689 switch (I->getOpcode()) {
5690 case Instruction::And:
5691 case Instruction::Or:
5692 case Instruction::Xor: {
5693 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty);
5694 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty);
5695 Res = BinaryOperator::create((Instruction::BinaryOps)I->getOpcode(),
5696 LHS, RHS, I->getName());
5697 break;
5698 }
Chris Lattner960acb02006-11-29 07:18:39 +00005699 case Instruction::AShr:
5700 case Instruction::LShr:
5701 case Instruction::Shl: {
5702 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty);
5703 Res = new ShiftInst((Instruction::OtherOps)I->getOpcode(), LHS,
5704 I->getOperand(1), I->getName());
5705 break;
5706 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005707 case Instruction::Trunc:
5708 case Instruction::ZExt:
5709 case Instruction::SExt:
5710 case Instruction::BitCast:
5711 // If the source type of the cast is the type we're trying for then we can
5712 // just return the source. There's no need to insert it because its not new.
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005713 if (I->getOperand(0)->getType() == Ty)
5714 return I->getOperand(0);
5715
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005716 // Some other kind of cast, which shouldn't happen, so just ..
5717 // FALL THROUGH
5718 default:
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005719 // TODO: Can handle more cases here.
5720 assert(0 && "Unreachable!");
5721 break;
5722 }
5723
5724 return InsertNewInstBefore(Res, *I);
5725}
5726
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005727/// @brief Implement the transforms common to all CastInst visitors.
5728Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
Chris Lattner55d4bda2003-06-23 21:59:52 +00005729 Value *Src = CI.getOperand(0);
5730
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005731 // Casting undef to anything results in undef so might as just replace it and
5732 // get rid of the cast.
Chris Lattner81a7a232004-10-16 18:11:37 +00005733 if (isa<UndefValue>(Src)) // cast undef -> undef
5734 return ReplaceInstUsesWith(CI, UndefValue::get(CI.getType()));
5735
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005736 // Many cases of "cast of a cast" are eliminable. If its eliminable we just
5737 // eliminate it now.
Chris Lattner86102b82005-01-01 16:22:27 +00005738 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005739 if (Instruction::CastOps opc =
5740 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
5741 // The first cast (CSrc) is eliminable so we need to fix up or replace
5742 // the second cast (CI). CSrc will then have a good chance of being dead.
5743 return CastInst::create(opc, CSrc->getOperand(0), CI.getType());
Chris Lattner650b6da2002-08-02 20:00:25 +00005744 }
5745 }
Chris Lattner03841652004-05-25 04:29:21 +00005746
Chris Lattnerd0d51602003-06-21 23:12:02 +00005747 // If casting the result of a getelementptr instruction with no offset, turn
5748 // this into a cast of the original pointer!
5749 //
Chris Lattner55d4bda2003-06-23 21:59:52 +00005750 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattnerd0d51602003-06-21 23:12:02 +00005751 bool AllZeroOperands = true;
5752 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
5753 if (!isa<Constant>(GEP->getOperand(i)) ||
5754 !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
5755 AllZeroOperands = false;
5756 break;
5757 }
5758 if (AllZeroOperands) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005759 // Changing the cast operand is usually not a good idea but it is safe
5760 // here because the pointer operand is being replaced with another
5761 // pointer operand so the opcode doesn't need to change.
Chris Lattnerd0d51602003-06-21 23:12:02 +00005762 CI.setOperand(0, GEP->getOperand(0));
5763 return &CI;
5764 }
5765 }
Chris Lattnerec45a4c2006-11-21 17:05:13 +00005766
Chris Lattnerf4ad1652003-11-02 05:57:39 +00005767 // If we are casting a malloc or alloca to a pointer to a type of the same
5768 // size, rewrite the allocation instruction to allocate the "right" type.
Chris Lattnerf4ad1652003-11-02 05:57:39 +00005769 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
Chris Lattner216be912005-10-24 06:03:58 +00005770 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
5771 return V;
Chris Lattnerf4ad1652003-11-02 05:57:39 +00005772
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005773 // If we are casting a select then fold the cast into the select
Chris Lattner86102b82005-01-01 16:22:27 +00005774 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
5775 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
5776 return NV;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005777
5778 // If we are casting a PHI then fold the cast into the PHI
Chris Lattner6a4adcd2004-09-29 05:07:12 +00005779 if (isa<PHINode>(Src))
5780 if (Instruction *NV = FoldOpIntoPhi(CI))
5781 return NV;
Chris Lattnerb19a5c62006-04-12 18:09:35 +00005782
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005783 return 0;
5784}
5785
5786/// Only the TRUNC, ZEXT, SEXT, and BITCONVERT can have both operands as
5787/// integers. This function implements the common transforms for all those
5788/// cases.
5789/// @brief Implement the transforms common to CastInst with integer operands
5790Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
5791 if (Instruction *Result = commonCastTransforms(CI))
5792 return Result;
5793
5794 Value *Src = CI.getOperand(0);
5795 const Type *SrcTy = Src->getType();
5796 const Type *DestTy = CI.getType();
5797 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
5798 unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
5799
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005800 // See if we can simplify any instructions used by the LHS whose sole
5801 // purpose is to compute bits we don't care about.
5802 uint64_t KnownZero = 0, KnownOne = 0;
5803 if (SimplifyDemandedBits(&CI, DestTy->getIntegralTypeMask(),
5804 KnownZero, KnownOne))
5805 return &CI;
5806
5807 // If the source isn't an instruction or has more than one use then we
5808 // can't do anything more.
5809 if (!isa<Instruction>(Src) || !Src->hasOneUse())
5810 return 0;
5811
5812 // Attempt to propagate the cast into the instruction.
5813 Instruction *SrcI = cast<Instruction>(Src);
5814 int NumCastsRemoved = 0;
5815 if (CanEvaluateInDifferentType(SrcI, DestTy, NumCastsRemoved)) {
5816 // If this cast is a truncate, evaluting in a different type always
5817 // eliminates the cast, so it is always a win. If this is a noop-cast
5818 // this just removes a noop cast which isn't pointful, but simplifies
5819 // the code. If this is a zero-extension, we need to do an AND to
5820 // maintain the clear top-part of the computation, so we require that
5821 // the input have eliminated at least one cast. If this is a sign
5822 // extension, we insert two new casts (to do the extension) so we
5823 // require that two casts have been eliminated.
5824 bool DoXForm = CI.isNoopCast(TD->getIntPtrType());
5825 if (!DoXForm) {
5826 switch (CI.getOpcode()) {
5827 case Instruction::Trunc:
5828 DoXForm = true;
5829 break;
5830 case Instruction::ZExt:
5831 DoXForm = NumCastsRemoved >= 1;
5832 break;
5833 case Instruction::SExt:
5834 DoXForm = NumCastsRemoved >= 2;
5835 break;
5836 case Instruction::BitCast:
5837 DoXForm = false;
5838 break;
5839 default:
5840 // All the others use floating point so we shouldn't actually
5841 // get here because of the check above.
5842 assert(!"Unknown cast type .. unreachable");
5843 break;
5844 }
5845 }
5846
5847 if (DoXForm) {
5848 Value *Res = EvaluateInDifferentType(SrcI, DestTy);
5849 assert(Res->getType() == DestTy);
5850 switch (CI.getOpcode()) {
5851 default: assert(0 && "Unknown cast type!");
5852 case Instruction::Trunc:
5853 case Instruction::BitCast:
5854 // Just replace this cast with the result.
5855 return ReplaceInstUsesWith(CI, Res);
5856 case Instruction::ZExt: {
5857 // We need to emit an AND to clear the high bits.
5858 assert(SrcBitSize < DestBitSize && "Not a zext?");
5859 Constant *C =
5860 ConstantInt::get(Type::ULongTy, (1ULL << SrcBitSize)-1);
5861 if (DestBitSize < 64)
5862 C = ConstantExpr::getTrunc(C, DestTy);
5863 else {
5864 assert(DestBitSize == 64);
5865 C = ConstantExpr::getBitCast(C, DestTy);
5866 }
5867 return BinaryOperator::createAnd(Res, C);
5868 }
5869 case Instruction::SExt:
5870 // We need to emit a cast to truncate, then a cast to sext.
5871 return CastInst::create(Instruction::SExt,
Reid Spencer13bc5d72006-12-12 09:18:51 +00005872 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
5873 CI), DestTy);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005874 }
5875 }
5876 }
5877
5878 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
5879 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
5880
5881 switch (SrcI->getOpcode()) {
5882 case Instruction::Add:
5883 case Instruction::Mul:
5884 case Instruction::And:
5885 case Instruction::Or:
5886 case Instruction::Xor:
5887 // If we are discarding information, or just changing the sign,
5888 // rewrite.
5889 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
5890 // Don't insert two casts if they cannot be eliminated. We allow
5891 // two casts to be inserted if the sizes are the same. This could
5892 // only be converting signedness, which is a noop.
5893 if (DestBitSize == SrcBitSize ||
5894 !ValueRequiresCast(Op1, DestTy,TD) ||
5895 !ValueRequiresCast(Op0, DestTy, TD)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00005896 unsigned Op0BitSize = Op0->getType()->getPrimitiveSizeInBits();
5897 Instruction::CastOps opcode =
5898 (Op0BitSize > DestBitSize ? Instruction::Trunc :
5899 (Op0BitSize == DestBitSize ? Instruction::BitCast :
5900 Op0->getType()->isSigned() ? Instruction::SExt :Instruction::ZExt));
5901 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
5902 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
5903 return BinaryOperator::create(
5904 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005905 }
5906 }
5907
5908 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
5909 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
5910 SrcI->getOpcode() == Instruction::Xor &&
5911 Op1 == ConstantBool::getTrue() &&
5912 (!Op0->hasOneUse() || !isa<SetCondInst>(Op0))) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00005913 Value *New = InsertOperandCastBefore(Instruction::ZExt, Op0, DestTy, &CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005914 return BinaryOperator::createXor(New, ConstantInt::get(CI.getType(), 1));
5915 }
5916 break;
5917 case Instruction::SDiv:
5918 case Instruction::UDiv:
5919 case Instruction::SRem:
5920 case Instruction::URem:
5921 // If we are just changing the sign, rewrite.
5922 if (DestBitSize == SrcBitSize) {
5923 // Don't insert two casts if they cannot be eliminated. We allow
5924 // two casts to be inserted if the sizes are the same. This could
5925 // only be converting signedness, which is a noop.
5926 if (!ValueRequiresCast(Op1, DestTy,TD) ||
5927 !ValueRequiresCast(Op0, DestTy, TD)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00005928 Value *Op0c = InsertOperandCastBefore(Instruction::BitCast,
5929 Op0, DestTy, SrcI);
5930 Value *Op1c = InsertOperandCastBefore(Instruction::BitCast,
5931 Op1, DestTy, SrcI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005932 return BinaryOperator::create(
5933 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
5934 }
5935 }
5936 break;
5937
5938 case Instruction::Shl:
5939 // Allow changing the sign of the source operand. Do not allow
5940 // changing the size of the shift, UNLESS the shift amount is a
5941 // constant. We must not change variable sized shifts to a smaller
5942 // size, because it is undefined to shift more bits out than exist
5943 // in the value.
5944 if (DestBitSize == SrcBitSize ||
5945 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00005946 Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
5947 Instruction::BitCast : Instruction::Trunc);
5948 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00005949 return new ShiftInst(Instruction::Shl, Op0c, Op1);
5950 }
5951 break;
5952 case Instruction::AShr:
5953 // If this is a signed shr, and if all bits shifted in are about to be
5954 // truncated off, turn it into an unsigned shr to allow greater
5955 // simplifications.
5956 if (DestBitSize < SrcBitSize &&
5957 isa<ConstantInt>(Op1)) {
5958 unsigned ShiftAmt = cast<ConstantInt>(Op1)->getZExtValue();
5959 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
5960 // Insert the new logical shift right.
5961 return new ShiftInst(Instruction::LShr, Op0, Op1);
5962 }
5963 }
5964 break;
5965
5966 case Instruction::SetEQ:
5967 case Instruction::SetNE:
5968 // If we are just checking for a seteq of a single bit and casting it
5969 // to an integer. If so, shift the bit to the appropriate place then
5970 // cast to integer to avoid the comparison.
5971 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
5972 uint64_t Op1CV = Op1C->getZExtValue();
5973 // cast (X == 0) to int --> X^1 iff X has only the low bit set.
5974 // cast (X == 0) to int --> (X>>1)^1 iff X has only the 2nd bit set.
5975 // cast (X == 1) to int --> X iff X has only the low bit set.
5976 // cast (X == 2) to int --> X>>1 iff X has only the 2nd bit set.
5977 // cast (X != 0) to int --> X iff X has only the low bit set.
5978 // cast (X != 0) to int --> X>>1 iff X has only the 2nd bit set.
5979 // cast (X != 1) to int --> X^1 iff X has only the low bit set.
5980 // cast (X != 2) to int --> (X>>1)^1 iff X has only the 2nd bit set.
5981 if (Op1CV == 0 || isPowerOf2_64(Op1CV)) {
5982 // If Op1C some other power of two, convert:
5983 uint64_t KnownZero, KnownOne;
5984 uint64_t TypeMask = Op1->getType()->getIntegralTypeMask();
5985 ComputeMaskedBits(Op0, TypeMask, KnownZero, KnownOne);
5986
5987 if (isPowerOf2_64(KnownZero^TypeMask)) { // Exactly 1 possible 1?
5988 bool isSetNE = SrcI->getOpcode() == Instruction::SetNE;
5989 if (Op1CV && (Op1CV != (KnownZero^TypeMask))) {
5990 // (X&4) == 2 --> false
5991 // (X&4) != 2 --> true
5992 Constant *Res = ConstantBool::get(isSetNE);
5993 Res = ConstantExpr::getZeroExtend(Res, CI.getType());
5994 return ReplaceInstUsesWith(CI, Res);
5995 }
5996
5997 unsigned ShiftAmt = Log2_64(KnownZero^TypeMask);
5998 Value *In = Op0;
5999 if (ShiftAmt) {
6000 // Perform a logical shr by shiftamt.
6001 // Insert the shift to put the result in the low bit.
6002 In = InsertNewInstBefore(
6003 new ShiftInst(Instruction::LShr, In,
6004 ConstantInt::get(Type::UByteTy, ShiftAmt),
6005 In->getName()+".lobit"), CI);
6006 }
6007
6008 if ((Op1CV != 0) == isSetNE) { // Toggle the low bit.
6009 Constant *One = ConstantInt::get(In->getType(), 1);
6010 In = BinaryOperator::createXor(In, One, "tmp");
6011 InsertNewInstBefore(cast<Instruction>(In), CI);
6012 }
6013
6014 if (CI.getType() == In->getType())
6015 return ReplaceInstUsesWith(CI, In);
6016 else
6017 return CastInst::createInferredCast(In, CI.getType());
6018 }
6019 }
6020 }
6021 break;
6022 }
6023 return 0;
6024}
6025
6026Instruction *InstCombiner::visitTrunc(CastInst &CI) {
Chris Lattnerd747f012006-11-29 07:04:07 +00006027 if (Instruction *Result = commonIntCastTransforms(CI))
6028 return Result;
6029
6030 Value *Src = CI.getOperand(0);
6031 const Type *Ty = CI.getType();
6032 unsigned DestBitWidth = Ty->getPrimitiveSizeInBits();
6033
6034 if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
6035 switch (SrcI->getOpcode()) {
6036 default: break;
6037 case Instruction::LShr:
6038 // We can shrink lshr to something smaller if we know the bits shifted in
6039 // are already zeros.
6040 if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
6041 unsigned ShAmt = ShAmtV->getZExtValue();
6042
6043 // Get a mask for the bits shifting in.
6044 uint64_t Mask = (~0ULL >> (64-ShAmt)) << DestBitWidth;
Reid Spencer13bc5d72006-12-12 09:18:51 +00006045 Value* SrcIOp0 = SrcI->getOperand(0);
6046 if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
Chris Lattnerd747f012006-11-29 07:04:07 +00006047 if (ShAmt >= DestBitWidth) // All zeros.
6048 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
6049
6050 // Okay, we can shrink this. Truncate the input, then return a new
6051 // shift.
Reid Spencer13bc5d72006-12-12 09:18:51 +00006052 Instruction::CastOps opcode =
6053 (SrcIOp0->getType()->getPrimitiveSizeInBits() ==
6054 Ty->getPrimitiveSizeInBits() ? Instruction::BitCast :
6055 Instruction::Trunc);
6056 Value *V = InsertCastBefore(opcode, SrcIOp0, Ty, CI);
Chris Lattnerd747f012006-11-29 07:04:07 +00006057 return new ShiftInst(Instruction::LShr, V, SrcI->getOperand(1));
6058 }
Chris Lattnerc209b582006-12-05 01:26:29 +00006059 } else { // This is a variable shr.
6060
6061 // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'. This is
6062 // more LLVM instructions, but allows '1 << Y' to be hoisted if
6063 // loop-invariant and CSE'd.
6064 if (CI.getType() == Type::BoolTy && SrcI->hasOneUse()) {
6065 Value *One = ConstantInt::get(SrcI->getType(), 1);
6066
6067 Value *V = InsertNewInstBefore(new ShiftInst(Instruction::Shl, One,
6068 SrcI->getOperand(1),
6069 "tmp"), CI);
6070 V = InsertNewInstBefore(BinaryOperator::createAnd(V,
6071 SrcI->getOperand(0),
6072 "tmp"), CI);
6073 Value *Zero = Constant::getNullValue(V->getType());
6074 return BinaryOperator::createSetNE(V, Zero);
6075 }
Chris Lattnerd747f012006-11-29 07:04:07 +00006076 }
6077 break;
6078 }
6079 }
6080
6081 return 0;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006082}
6083
6084Instruction *InstCombiner::visitZExt(CastInst &CI) {
6085 // If one of the common conversion will work ..
6086 if (Instruction *Result = commonIntCastTransforms(CI))
6087 return Result;
6088
6089 Value *Src = CI.getOperand(0);
6090
6091 // If this is a cast of a cast
6092 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
6093 // If the operand of the ZEXT is a TRUNC then we are dealing with integral
6094 // types and we can convert this to a logical AND if the sizes are just
6095 // right. This will be much cheaper than the pair of casts.
6096 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
6097 // types and if the sizes are just right we can convert this into a logical
6098 // 'and' which will be much cheaper than the pair of casts.
6099 if (isa<TruncInst>(CSrc)) {
6100 // Get the sizes of the types involved
6101 Value *A = CSrc->getOperand(0);
6102 unsigned SrcSize = A->getType()->getPrimitiveSizeInBits();
6103 unsigned MidSize = CSrc->getType()->getPrimitiveSizeInBits();
6104 unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
6105 // If we're actually extending zero bits and the trunc is a no-op
6106 if (MidSize < DstSize && SrcSize == DstSize) {
6107 // Replace both of the casts with an And of the type mask.
6108 uint64_t AndValue = CSrc->getType()->getIntegralTypeMask();
6109 Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
6110 Instruction *And =
6111 BinaryOperator::createAnd(CSrc->getOperand(0), AndConst);
6112 // Unfortunately, if the type changed, we need to cast it back.
6113 if (And->getType() != CI.getType()) {
6114 And->setName(CSrc->getName()+".mask");
6115 InsertNewInstBefore(And, CI);
6116 And = CastInst::createInferredCast(And, CI.getType());
6117 }
6118 return And;
6119 }
6120 }
6121 }
6122
6123 return 0;
6124}
6125
6126Instruction *InstCombiner::visitSExt(CastInst &CI) {
6127 return commonIntCastTransforms(CI);
6128}
6129
6130Instruction *InstCombiner::visitFPTrunc(CastInst &CI) {
6131 return commonCastTransforms(CI);
6132}
6133
6134Instruction *InstCombiner::visitFPExt(CastInst &CI) {
6135 return commonCastTransforms(CI);
6136}
6137
6138Instruction *InstCombiner::visitFPToUI(CastInst &CI) {
Reid Spencerad05ee92006-11-30 23:13:36 +00006139 return commonCastTransforms(CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006140}
6141
6142Instruction *InstCombiner::visitFPToSI(CastInst &CI) {
Reid Spencerad05ee92006-11-30 23:13:36 +00006143 return commonCastTransforms(CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006144}
6145
6146Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
6147 return commonCastTransforms(CI);
6148}
6149
6150Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
6151 return commonCastTransforms(CI);
6152}
6153
6154Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
Reid Spencerad05ee92006-11-30 23:13:36 +00006155 return commonCastTransforms(CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006156}
6157
6158Instruction *InstCombiner::visitIntToPtr(CastInst &CI) {
6159 return commonCastTransforms(CI);
6160}
6161
6162Instruction *InstCombiner::visitBitCast(CastInst &CI) {
6163
6164 // If the operands are integer typed then apply the integer transforms,
6165 // otherwise just apply the common ones.
6166 Value *Src = CI.getOperand(0);
6167 const Type *SrcTy = Src->getType();
6168 const Type *DestTy = CI.getType();
6169
6170 if (SrcTy->isInteger() && DestTy->isInteger()) {
6171 if (Instruction *Result = commonIntCastTransforms(CI))
6172 return Result;
6173 } else {
6174 if (Instruction *Result = commonCastTransforms(CI))
6175 return Result;
6176 }
6177
6178
6179 // Get rid of casts from one type to the same type. These are useless and can
6180 // be replaced by the operand.
6181 if (DestTy == Src->getType())
6182 return ReplaceInstUsesWith(CI, Src);
6183
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006184 // If the source and destination are pointers, and this cast is equivalent to
6185 // a getelementptr X, 0, 0, 0... turn it into the appropriate getelementptr.
6186 // This can enhance SROA and other transforms that want type-safe pointers.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006187 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
6188 if (const PointerType *SrcPTy = dyn_cast<PointerType>(SrcTy)) {
6189 const Type *DstElTy = DstPTy->getElementType();
6190 const Type *SrcElTy = SrcPTy->getElementType();
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006191
6192 Constant *ZeroUInt = Constant::getNullValue(Type::UIntTy);
6193 unsigned NumZeros = 0;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006194 while (SrcElTy != DstElTy &&
6195 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
6196 SrcElTy->getNumContainedTypes() /* not "{}" */) {
6197 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006198 ++NumZeros;
6199 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00006200
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006201 // If we found a path from the src to dest, create the getelementptr now.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006202 if (SrcElTy == DstElTy) {
Chris Lattnerb19a5c62006-04-12 18:09:35 +00006203 std::vector<Value*> Idxs(NumZeros+1, ZeroUInt);
6204 return new GetElementPtrInst(Src, Idxs);
6205 }
6206 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006207 }
Chris Lattnerdfae8be2003-07-24 17:35:25 +00006208
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006209 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
6210 if (SVI->hasOneUse()) {
6211 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
6212 // a bitconvert to a vector with the same # elts.
6213 if (isa<PackedType>(DestTy) &&
6214 cast<PackedType>(DestTy)->getNumElements() ==
6215 SVI->getType()->getNumElements()) {
6216 CastInst *Tmp;
6217 // If either of the operands is a cast from CI.getType(), then
6218 // evaluating the shuffle in the casted destination's type will allow
6219 // us to eliminate at least one cast.
6220 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
6221 Tmp->getOperand(0)->getType() == DestTy) ||
6222 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
6223 Tmp->getOperand(0)->getType() == DestTy)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00006224 Value *LHS = InsertOperandCastBefore(Instruction::BitCast,
6225 SVI->getOperand(0), DestTy, &CI);
6226 Value *RHS = InsertOperandCastBefore(Instruction::BitCast,
6227 SVI->getOperand(1), DestTy, &CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006228 // Return a new shuffle vector. Use the same element ID's, as we
6229 // know the vector types match #elts.
6230 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner99155be2006-05-25 23:24:33 +00006231 }
6232 }
6233 }
6234 }
Chris Lattner260ab202002-04-18 17:39:14 +00006235 return 0;
Chris Lattnerca081252001-12-14 16:52:21 +00006236}
6237
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006238/// GetSelectFoldableOperands - We want to turn code that looks like this:
6239/// %C = or %A, %B
6240/// %D = select %cond, %C, %A
6241/// into:
6242/// %C = select %cond, %B, 0
6243/// %D = or %A, %C
6244///
6245/// Assuming that the specified instruction is an operand to the select, return
6246/// a bitmask indicating which operands of this instruction are foldable if they
6247/// equal the other incoming value of the select.
6248///
6249static unsigned GetSelectFoldableOperands(Instruction *I) {
6250 switch (I->getOpcode()) {
6251 case Instruction::Add:
6252 case Instruction::Mul:
6253 case Instruction::And:
6254 case Instruction::Or:
6255 case Instruction::Xor:
6256 return 3; // Can fold through either operand.
6257 case Instruction::Sub: // Can only fold on the amount subtracted.
6258 case Instruction::Shl: // Can only fold on the shift amount.
Reid Spencerfdff9382006-11-08 06:47:33 +00006259 case Instruction::LShr:
6260 case Instruction::AShr:
Misha Brukmanb1c93172005-04-21 23:48:37 +00006261 return 1;
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006262 default:
6263 return 0; // Cannot fold
6264 }
6265}
6266
6267/// GetSelectFoldableConstant - For the same transformation as the previous
6268/// function, return the identity constant that goes into the select.
6269static Constant *GetSelectFoldableConstant(Instruction *I) {
6270 switch (I->getOpcode()) {
6271 default: assert(0 && "This cannot happen!"); abort();
6272 case Instruction::Add:
6273 case Instruction::Sub:
6274 case Instruction::Or:
6275 case Instruction::Xor:
6276 return Constant::getNullValue(I->getType());
6277 case Instruction::Shl:
Reid Spencerfdff9382006-11-08 06:47:33 +00006278 case Instruction::LShr:
6279 case Instruction::AShr:
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006280 return Constant::getNullValue(Type::UByteTy);
6281 case Instruction::And:
6282 return ConstantInt::getAllOnesValue(I->getType());
6283 case Instruction::Mul:
6284 return ConstantInt::get(I->getType(), 1);
6285 }
6286}
6287
Chris Lattner411336f2005-01-19 21:50:18 +00006288/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
6289/// have the same opcode and only one use each. Try to simplify this.
6290Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
6291 Instruction *FI) {
6292 if (TI->getNumOperands() == 1) {
6293 // If this is a non-volatile load or a cast from the same type,
6294 // merge.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006295 if (TI->isCast()) {
Chris Lattner411336f2005-01-19 21:50:18 +00006296 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
6297 return 0;
6298 } else {
6299 return 0; // unknown unary op.
6300 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00006301
Chris Lattner411336f2005-01-19 21:50:18 +00006302 // Fold this by inserting a select from the input values.
6303 SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
6304 FI->getOperand(0), SI.getName()+".v");
6305 InsertNewInstBefore(NewSI, SI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006306 return CastInst::create(Instruction::CastOps(TI->getOpcode()), NewSI,
6307 TI->getType());
Chris Lattner411336f2005-01-19 21:50:18 +00006308 }
6309
6310 // Only handle binary operators here.
6311 if (!isa<ShiftInst>(TI) && !isa<BinaryOperator>(TI))
6312 return 0;
6313
6314 // Figure out if the operations have any operands in common.
6315 Value *MatchOp, *OtherOpT, *OtherOpF;
6316 bool MatchIsOpZero;
6317 if (TI->getOperand(0) == FI->getOperand(0)) {
6318 MatchOp = TI->getOperand(0);
6319 OtherOpT = TI->getOperand(1);
6320 OtherOpF = FI->getOperand(1);
6321 MatchIsOpZero = true;
6322 } else if (TI->getOperand(1) == FI->getOperand(1)) {
6323 MatchOp = TI->getOperand(1);
6324 OtherOpT = TI->getOperand(0);
6325 OtherOpF = FI->getOperand(0);
6326 MatchIsOpZero = false;
6327 } else if (!TI->isCommutative()) {
6328 return 0;
6329 } else if (TI->getOperand(0) == FI->getOperand(1)) {
6330 MatchOp = TI->getOperand(0);
6331 OtherOpT = TI->getOperand(1);
6332 OtherOpF = FI->getOperand(0);
6333 MatchIsOpZero = true;
6334 } else if (TI->getOperand(1) == FI->getOperand(0)) {
6335 MatchOp = TI->getOperand(1);
6336 OtherOpT = TI->getOperand(0);
6337 OtherOpF = FI->getOperand(1);
6338 MatchIsOpZero = true;
6339 } else {
6340 return 0;
6341 }
6342
6343 // If we reach here, they do have operations in common.
6344 SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
6345 OtherOpF, SI.getName()+".v");
6346 InsertNewInstBefore(NewSI, SI);
6347
6348 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
6349 if (MatchIsOpZero)
6350 return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
6351 else
6352 return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
6353 } else {
6354 if (MatchIsOpZero)
6355 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), MatchOp, NewSI);
6356 else
6357 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), NewSI, MatchOp);
6358 }
6359}
6360
Chris Lattnerb909e8b2004-03-12 05:52:32 +00006361Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattner533bc492004-03-30 19:37:13 +00006362 Value *CondVal = SI.getCondition();
6363 Value *TrueVal = SI.getTrueValue();
6364 Value *FalseVal = SI.getFalseValue();
6365
6366 // select true, X, Y -> X
6367 // select false, X, Y -> Y
6368 if (ConstantBool *C = dyn_cast<ConstantBool>(CondVal))
Chris Lattner6ab03f62006-09-28 23:35:22 +00006369 return ReplaceInstUsesWith(SI, C->getValue() ? TrueVal : FalseVal);
Chris Lattner533bc492004-03-30 19:37:13 +00006370
6371 // select C, X, X -> X
6372 if (TrueVal == FalseVal)
6373 return ReplaceInstUsesWith(SI, TrueVal);
6374
Chris Lattner81a7a232004-10-16 18:11:37 +00006375 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
6376 return ReplaceInstUsesWith(SI, FalseVal);
6377 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
6378 return ReplaceInstUsesWith(SI, TrueVal);
6379 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
6380 if (isa<Constant>(TrueVal))
6381 return ReplaceInstUsesWith(SI, TrueVal);
6382 else
6383 return ReplaceInstUsesWith(SI, FalseVal);
6384 }
6385
Chris Lattner1c631e82004-04-08 04:43:23 +00006386 if (SI.getType() == Type::BoolTy)
6387 if (ConstantBool *C = dyn_cast<ConstantBool>(TrueVal)) {
Chris Lattner6ab03f62006-09-28 23:35:22 +00006388 if (C->getValue()) {
Chris Lattner1c631e82004-04-08 04:43:23 +00006389 // Change: A = select B, true, C --> A = or B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00006390 return BinaryOperator::createOr(CondVal, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00006391 } else {
6392 // Change: A = select B, false, C --> A = and !B, C
6393 Value *NotCond =
6394 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
6395 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00006396 return BinaryOperator::createAnd(NotCond, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00006397 }
6398 } else if (ConstantBool *C = dyn_cast<ConstantBool>(FalseVal)) {
Chris Lattner6ab03f62006-09-28 23:35:22 +00006399 if (C->getValue() == false) {
Chris Lattner1c631e82004-04-08 04:43:23 +00006400 // Change: A = select B, C, false --> A = and B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00006401 return BinaryOperator::createAnd(CondVal, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00006402 } else {
6403 // Change: A = select B, C, true --> A = or !B, C
6404 Value *NotCond =
6405 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
6406 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00006407 return BinaryOperator::createOr(NotCond, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00006408 }
6409 }
6410
Chris Lattner183b3362004-04-09 19:05:30 +00006411 // Selecting between two integer constants?
6412 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
6413 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
6414 // select C, 1, 0 -> cast C to int
Reid Spencere0fc4df2006-10-20 07:07:24 +00006415 if (FalseValC->isNullValue() && TrueValC->getZExtValue() == 1) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006416 return CastInst::create(Instruction::ZExt, CondVal, SI.getType());
Reid Spencere0fc4df2006-10-20 07:07:24 +00006417 } else if (TrueValC->isNullValue() && FalseValC->getZExtValue() == 1) {
Chris Lattner183b3362004-04-09 19:05:30 +00006418 // select C, 0, 1 -> cast !C to int
6419 Value *NotCond =
6420 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
Chris Lattnercf7baf32004-04-09 18:19:44 +00006421 "not."+CondVal->getName()), SI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006422 return CastInst::create(Instruction::ZExt, NotCond, SI.getType());
Chris Lattnercf7baf32004-04-09 18:19:44 +00006423 }
Chris Lattner35167c32004-06-09 07:59:58 +00006424
Chris Lattner380c7e92006-09-20 04:44:59 +00006425 if (SetCondInst *IC = dyn_cast<SetCondInst>(SI.getCondition())) {
6426
6427 // (x <s 0) ? -1 : 0 -> sra x, 31
6428 // (x >u 2147483647) ? -1 : 0 -> sra x, 31
6429 if (TrueValC->isAllOnesValue() && FalseValC->isNullValue())
6430 if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
6431 bool CanXForm = false;
6432 if (CmpCst->getType()->isSigned())
6433 CanXForm = CmpCst->isNullValue() &&
6434 IC->getOpcode() == Instruction::SetLT;
6435 else {
6436 unsigned Bits = CmpCst->getType()->getPrimitiveSizeInBits();
Reid Spencere0fc4df2006-10-20 07:07:24 +00006437 CanXForm = (CmpCst->getZExtValue() == ~0ULL >> (64-Bits+1)) &&
Chris Lattner380c7e92006-09-20 04:44:59 +00006438 IC->getOpcode() == Instruction::SetGT;
6439 }
6440
6441 if (CanXForm) {
6442 // The comparison constant and the result are not neccessarily the
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006443 // same width. Make an all-ones value by inserting a AShr.
Chris Lattner380c7e92006-09-20 04:44:59 +00006444 Value *X = IC->getOperand(0);
Chris Lattner380c7e92006-09-20 04:44:59 +00006445 unsigned Bits = X->getType()->getPrimitiveSizeInBits();
Reid Spencere0fc4df2006-10-20 07:07:24 +00006446 Constant *ShAmt = ConstantInt::get(Type::UByteTy, Bits-1);
Reid Spencerfdff9382006-11-08 06:47:33 +00006447 Instruction *SRA = new ShiftInst(Instruction::AShr, X,
Chris Lattner380c7e92006-09-20 04:44:59 +00006448 ShAmt, "ones");
6449 InsertNewInstBefore(SRA, SI);
6450
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006451 // Finally, convert to the type of the select RHS. We figure out
6452 // if this requires a SExt, Trunc or BitCast based on the sizes.
6453 Instruction::CastOps opc = Instruction::BitCast;
6454 unsigned SRASize = SRA->getType()->getPrimitiveSizeInBits();
6455 unsigned SISize = SI.getType()->getPrimitiveSizeInBits();
6456 if (SRASize < SISize)
6457 opc = Instruction::SExt;
6458 else if (SRASize > SISize)
6459 opc = Instruction::Trunc;
6460 return CastInst::create(opc, SRA, SI.getType());
Chris Lattner380c7e92006-09-20 04:44:59 +00006461 }
6462 }
6463
6464
6465 // If one of the constants is zero (we know they can't both be) and we
6466 // have a setcc instruction with zero, and we have an 'and' with the
6467 // non-constant value, eliminate this whole mess. This corresponds to
6468 // cases like this: ((X & 27) ? 27 : 0)
6469 if (TrueValC->isNullValue() || FalseValC->isNullValue())
Chris Lattnerb3f24c92006-09-18 04:22:48 +00006470 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner35167c32004-06-09 07:59:58 +00006471 cast<Constant>(IC->getOperand(1))->isNullValue())
6472 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
6473 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00006474 isa<ConstantInt>(ICA->getOperand(1)) &&
6475 (ICA->getOperand(1) == TrueValC ||
6476 ICA->getOperand(1) == FalseValC) &&
Chris Lattner35167c32004-06-09 07:59:58 +00006477 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
6478 // Okay, now we know that everything is set up, we just don't
6479 // know whether we have a setne or seteq and whether the true or
6480 // false val is the zero.
6481 bool ShouldNotVal = !TrueValC->isNullValue();
6482 ShouldNotVal ^= IC->getOpcode() == Instruction::SetNE;
6483 Value *V = ICA;
6484 if (ShouldNotVal)
6485 V = InsertNewInstBefore(BinaryOperator::create(
6486 Instruction::Xor, V, ICA->getOperand(1)), SI);
6487 return ReplaceInstUsesWith(SI, V);
6488 }
Chris Lattner380c7e92006-09-20 04:44:59 +00006489 }
Chris Lattner533bc492004-03-30 19:37:13 +00006490 }
Chris Lattner623fba12004-04-10 22:21:27 +00006491
6492 // See if we are selecting two values based on a comparison of the two values.
6493 if (SetCondInst *SCI = dyn_cast<SetCondInst>(CondVal)) {
6494 if (SCI->getOperand(0) == TrueVal && SCI->getOperand(1) == FalseVal) {
6495 // Transform (X == Y) ? X : Y -> Y
6496 if (SCI->getOpcode() == Instruction::SetEQ)
6497 return ReplaceInstUsesWith(SI, FalseVal);
6498 // Transform (X != Y) ? X : Y -> X
6499 if (SCI->getOpcode() == Instruction::SetNE)
6500 return ReplaceInstUsesWith(SI, TrueVal);
6501 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6502
6503 } else if (SCI->getOperand(0) == FalseVal && SCI->getOperand(1) == TrueVal){
6504 // Transform (X == Y) ? Y : X -> X
6505 if (SCI->getOpcode() == Instruction::SetEQ)
Chris Lattner24cf0202004-04-11 01:39:19 +00006506 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattner623fba12004-04-10 22:21:27 +00006507 // Transform (X != Y) ? Y : X -> Y
6508 if (SCI->getOpcode() == Instruction::SetNE)
Chris Lattner24cf0202004-04-11 01:39:19 +00006509 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattner623fba12004-04-10 22:21:27 +00006510 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6511 }
6512 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00006513
Chris Lattnera04c9042005-01-13 22:52:24 +00006514 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
6515 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
6516 if (TI->hasOneUse() && FI->hasOneUse()) {
Chris Lattnera04c9042005-01-13 22:52:24 +00006517 Instruction *AddOp = 0, *SubOp = 0;
6518
Chris Lattner411336f2005-01-19 21:50:18 +00006519 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
6520 if (TI->getOpcode() == FI->getOpcode())
6521 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
6522 return IV;
6523
6524 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
6525 // even legal for FP.
Chris Lattnera04c9042005-01-13 22:52:24 +00006526 if (TI->getOpcode() == Instruction::Sub &&
6527 FI->getOpcode() == Instruction::Add) {
6528 AddOp = FI; SubOp = TI;
6529 } else if (FI->getOpcode() == Instruction::Sub &&
6530 TI->getOpcode() == Instruction::Add) {
6531 AddOp = TI; SubOp = FI;
6532 }
6533
6534 if (AddOp) {
6535 Value *OtherAddOp = 0;
6536 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
6537 OtherAddOp = AddOp->getOperand(1);
6538 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
6539 OtherAddOp = AddOp->getOperand(0);
6540 }
6541
6542 if (OtherAddOp) {
Chris Lattnerb580d262006-02-24 18:05:58 +00006543 // So at this point we know we have (Y -> OtherAddOp):
6544 // select C, (add X, Y), (sub X, Z)
6545 Value *NegVal; // Compute -Z
6546 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
6547 NegVal = ConstantExpr::getNeg(C);
6548 } else {
6549 NegVal = InsertNewInstBefore(
6550 BinaryOperator::createNeg(SubOp->getOperand(1), "tmp"), SI);
Chris Lattnera04c9042005-01-13 22:52:24 +00006551 }
Chris Lattnerb580d262006-02-24 18:05:58 +00006552
6553 Value *NewTrueOp = OtherAddOp;
6554 Value *NewFalseOp = NegVal;
6555 if (AddOp != TI)
6556 std::swap(NewTrueOp, NewFalseOp);
6557 Instruction *NewSel =
6558 new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
6559
6560 NewSel = InsertNewInstBefore(NewSel, SI);
6561 return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
Chris Lattnera04c9042005-01-13 22:52:24 +00006562 }
6563 }
6564 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00006565
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006566 // See if we can fold the select into one of our operands.
6567 if (SI.getType()->isInteger()) {
6568 // See the comment above GetSelectFoldableOperands for a description of the
6569 // transformation we are doing here.
6570 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
6571 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
6572 !isa<Constant>(FalseVal))
6573 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
6574 unsigned OpToFold = 0;
6575 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
6576 OpToFold = 1;
6577 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
6578 OpToFold = 2;
6579 }
6580
6581 if (OpToFold) {
6582 Constant *C = GetSelectFoldableConstant(TVI);
6583 std::string Name = TVI->getName(); TVI->setName("");
6584 Instruction *NewSel =
6585 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C,
6586 Name);
6587 InsertNewInstBefore(NewSel, SI);
6588 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
6589 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
6590 else if (ShiftInst *SI = dyn_cast<ShiftInst>(TVI))
6591 return new ShiftInst(SI->getOpcode(), FalseVal, NewSel);
6592 else {
6593 assert(0 && "Unknown instruction!!");
6594 }
6595 }
6596 }
Chris Lattner6862fbd2004-09-29 17:40:11 +00006597
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006598 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
6599 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
6600 !isa<Constant>(TrueVal))
6601 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
6602 unsigned OpToFold = 0;
6603 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
6604 OpToFold = 1;
6605 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
6606 OpToFold = 2;
6607 }
6608
6609 if (OpToFold) {
6610 Constant *C = GetSelectFoldableConstant(FVI);
6611 std::string Name = FVI->getName(); FVI->setName("");
6612 Instruction *NewSel =
6613 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold),
6614 Name);
6615 InsertNewInstBefore(NewSel, SI);
6616 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
6617 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
6618 else if (ShiftInst *SI = dyn_cast<ShiftInst>(FVI))
6619 return new ShiftInst(SI->getOpcode(), TrueVal, NewSel);
6620 else {
6621 assert(0 && "Unknown instruction!!");
6622 }
6623 }
6624 }
6625 }
Chris Lattnerd6f636a2005-04-24 07:30:14 +00006626
6627 if (BinaryOperator::isNot(CondVal)) {
6628 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
6629 SI.setOperand(1, FalseVal);
6630 SI.setOperand(2, TrueVal);
6631 return &SI;
6632 }
6633
Chris Lattnerb909e8b2004-03-12 05:52:32 +00006634 return 0;
6635}
6636
Chris Lattner82f2ef22006-03-06 20:18:44 +00006637/// GetKnownAlignment - If the specified pointer has an alignment that we can
6638/// determine, return it, otherwise return 0.
6639static unsigned GetKnownAlignment(Value *V, TargetData *TD) {
6640 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
6641 unsigned Align = GV->getAlignment();
6642 if (Align == 0 && TD)
6643 Align = TD->getTypeAlignment(GV->getType()->getElementType());
6644 return Align;
6645 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
6646 unsigned Align = AI->getAlignment();
6647 if (Align == 0 && TD) {
6648 if (isa<AllocaInst>(AI))
6649 Align = TD->getTypeAlignment(AI->getType()->getElementType());
6650 else if (isa<MallocInst>(AI)) {
6651 // Malloc returns maximally aligned memory.
6652 Align = TD->getTypeAlignment(AI->getType()->getElementType());
6653 Align = std::max(Align, (unsigned)TD->getTypeAlignment(Type::DoubleTy));
6654 Align = std::max(Align, (unsigned)TD->getTypeAlignment(Type::LongTy));
6655 }
6656 }
6657 return Align;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006658 } else if (isa<BitCastInst>(V) ||
Chris Lattner53ef5a02006-03-07 01:28:57 +00006659 (isa<ConstantExpr>(V) &&
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006660 cast<ConstantExpr>(V)->getOpcode() == Instruction::BitCast)) {
Chris Lattner53ef5a02006-03-07 01:28:57 +00006661 User *CI = cast<User>(V);
Chris Lattner82f2ef22006-03-06 20:18:44 +00006662 if (isa<PointerType>(CI->getOperand(0)->getType()))
6663 return GetKnownAlignment(CI->getOperand(0), TD);
6664 return 0;
Chris Lattner53ef5a02006-03-07 01:28:57 +00006665 } else if (isa<GetElementPtrInst>(V) ||
6666 (isa<ConstantExpr>(V) &&
6667 cast<ConstantExpr>(V)->getOpcode()==Instruction::GetElementPtr)) {
6668 User *GEPI = cast<User>(V);
Chris Lattner82f2ef22006-03-06 20:18:44 +00006669 unsigned BaseAlignment = GetKnownAlignment(GEPI->getOperand(0), TD);
6670 if (BaseAlignment == 0) return 0;
6671
6672 // If all indexes are zero, it is just the alignment of the base pointer.
6673 bool AllZeroOperands = true;
6674 for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
6675 if (!isa<Constant>(GEPI->getOperand(i)) ||
6676 !cast<Constant>(GEPI->getOperand(i))->isNullValue()) {
6677 AllZeroOperands = false;
6678 break;
6679 }
6680 if (AllZeroOperands)
6681 return BaseAlignment;
6682
6683 // Otherwise, if the base alignment is >= the alignment we expect for the
6684 // base pointer type, then we know that the resultant pointer is aligned at
6685 // least as much as its type requires.
6686 if (!TD) return 0;
6687
6688 const Type *BasePtrTy = GEPI->getOperand(0)->getType();
6689 if (TD->getTypeAlignment(cast<PointerType>(BasePtrTy)->getElementType())
Chris Lattner53ef5a02006-03-07 01:28:57 +00006690 <= BaseAlignment) {
6691 const Type *GEPTy = GEPI->getType();
6692 return TD->getTypeAlignment(cast<PointerType>(GEPTy)->getElementType());
6693 }
Chris Lattner82f2ef22006-03-06 20:18:44 +00006694 return 0;
6695 }
6696 return 0;
6697}
6698
Chris Lattnerb909e8b2004-03-12 05:52:32 +00006699
Chris Lattnerc66b2232006-01-13 20:11:04 +00006700/// visitCallInst - CallInst simplification. This mostly only handles folding
6701/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
6702/// the heavy lifting.
6703///
Chris Lattner970c33a2003-06-19 17:00:31 +00006704Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattnerc66b2232006-01-13 20:11:04 +00006705 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
6706 if (!II) return visitCallSite(&CI);
6707
Chris Lattner51ea1272004-02-28 05:22:00 +00006708 // Intrinsics cannot occur in an invoke, so handle them here instead of in
6709 // visitCallSite.
Chris Lattnerc66b2232006-01-13 20:11:04 +00006710 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner00648e12004-10-12 04:52:52 +00006711 bool Changed = false;
6712
6713 // memmove/cpy/set of zero bytes is a noop.
6714 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
6715 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
6716
Chris Lattner00648e12004-10-12 04:52:52 +00006717 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencere0fc4df2006-10-20 07:07:24 +00006718 if (CI->getZExtValue() == 1) {
Chris Lattner00648e12004-10-12 04:52:52 +00006719 // Replace the instruction with just byte operations. We would
6720 // transform other cases to loads/stores, but we don't know if
6721 // alignment is sufficient.
6722 }
Chris Lattner51ea1272004-02-28 05:22:00 +00006723 }
6724
Chris Lattner00648e12004-10-12 04:52:52 +00006725 // If we have a memmove and the source operation is a constant global,
6726 // then the source and dest pointers can't alias, so we can change this
6727 // into a call to memcpy.
Chris Lattner82f2ef22006-03-06 20:18:44 +00006728 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(II)) {
Chris Lattner00648e12004-10-12 04:52:52 +00006729 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
6730 if (GVSrc->isConstant()) {
6731 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner681ef2f2006-03-03 01:34:17 +00006732 const char *Name;
Andrew Lenharth0ebb0b02006-11-03 22:45:50 +00006733 if (CI.getCalledFunction()->getFunctionType()->getParamType(2) ==
Chris Lattner681ef2f2006-03-03 01:34:17 +00006734 Type::UIntTy)
6735 Name = "llvm.memcpy.i32";
6736 else
6737 Name = "llvm.memcpy.i64";
6738 Function *MemCpy = M->getOrInsertFunction(Name,
Chris Lattner00648e12004-10-12 04:52:52 +00006739 CI.getCalledFunction()->getFunctionType());
6740 CI.setOperand(0, MemCpy);
6741 Changed = true;
6742 }
Chris Lattner82f2ef22006-03-06 20:18:44 +00006743 }
Chris Lattner00648e12004-10-12 04:52:52 +00006744
Chris Lattner82f2ef22006-03-06 20:18:44 +00006745 // If we can determine a pointer alignment that is bigger than currently
6746 // set, update the alignment.
6747 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
6748 unsigned Alignment1 = GetKnownAlignment(MI->getOperand(1), TD);
6749 unsigned Alignment2 = GetKnownAlignment(MI->getOperand(2), TD);
6750 unsigned Align = std::min(Alignment1, Alignment2);
Reid Spencere0fc4df2006-10-20 07:07:24 +00006751 if (MI->getAlignment()->getZExtValue() < Align) {
6752 MI->setAlignment(ConstantInt::get(Type::UIntTy, Align));
Chris Lattner82f2ef22006-03-06 20:18:44 +00006753 Changed = true;
6754 }
6755 } else if (isa<MemSetInst>(MI)) {
6756 unsigned Alignment = GetKnownAlignment(MI->getDest(), TD);
Reid Spencere0fc4df2006-10-20 07:07:24 +00006757 if (MI->getAlignment()->getZExtValue() < Alignment) {
6758 MI->setAlignment(ConstantInt::get(Type::UIntTy, Alignment));
Chris Lattner82f2ef22006-03-06 20:18:44 +00006759 Changed = true;
6760 }
6761 }
6762
Chris Lattnerc66b2232006-01-13 20:11:04 +00006763 if (Changed) return II;
Chris Lattner503221f2006-01-13 21:28:09 +00006764 } else {
6765 switch (II->getIntrinsicID()) {
6766 default: break;
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00006767 case Intrinsic::ppc_altivec_lvx:
6768 case Intrinsic::ppc_altivec_lvxl:
Chris Lattner36dd7c92006-04-17 22:26:56 +00006769 case Intrinsic::x86_sse_loadu_ps:
6770 case Intrinsic::x86_sse2_loadu_pd:
6771 case Intrinsic::x86_sse2_loadu_dq:
6772 // Turn PPC lvx -> load if the pointer is known aligned.
6773 // Turn X86 loadups -> load if the pointer is known aligned.
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00006774 if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00006775 Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(1),
Chris Lattnere79d2492006-04-06 19:19:17 +00006776 PointerType::get(II->getType()), CI);
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00006777 return new LoadInst(Ptr);
6778 }
6779 break;
6780 case Intrinsic::ppc_altivec_stvx:
6781 case Intrinsic::ppc_altivec_stvxl:
6782 // Turn stvx -> store if the pointer is known aligned.
6783 if (GetKnownAlignment(II->getOperand(2), TD) >= 16) {
Chris Lattnere79d2492006-04-06 19:19:17 +00006784 const Type *OpPtrTy = PointerType::get(II->getOperand(1)->getType());
Reid Spencer13bc5d72006-12-12 09:18:51 +00006785 Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(2),
6786 OpPtrTy, CI);
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00006787 return new StoreInst(II->getOperand(1), Ptr);
6788 }
6789 break;
Chris Lattner36dd7c92006-04-17 22:26:56 +00006790 case Intrinsic::x86_sse_storeu_ps:
6791 case Intrinsic::x86_sse2_storeu_pd:
6792 case Intrinsic::x86_sse2_storeu_dq:
6793 case Intrinsic::x86_sse2_storel_dq:
6794 // Turn X86 storeu -> store if the pointer is known aligned.
6795 if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
6796 const Type *OpPtrTy = PointerType::get(II->getOperand(2)->getType());
Reid Spencer13bc5d72006-12-12 09:18:51 +00006797 Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(1),
6798 OpPtrTy, CI);
Chris Lattner36dd7c92006-04-17 22:26:56 +00006799 return new StoreInst(II->getOperand(2), Ptr);
6800 }
6801 break;
Chris Lattner2deeaea2006-10-05 06:55:50 +00006802
6803 case Intrinsic::x86_sse_cvttss2si: {
6804 // These intrinsics only demands the 0th element of its input vector. If
6805 // we can simplify the input based on that, do so now.
6806 uint64_t UndefElts;
6807 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1,
6808 UndefElts)) {
6809 II->setOperand(1, V);
6810 return II;
6811 }
6812 break;
6813 }
6814
Chris Lattnere79d2492006-04-06 19:19:17 +00006815 case Intrinsic::ppc_altivec_vperm:
6816 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
6817 if (ConstantPacked *Mask = dyn_cast<ConstantPacked>(II->getOperand(3))) {
6818 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
6819
6820 // Check that all of the elements are integer constants or undefs.
6821 bool AllEltsOk = true;
6822 for (unsigned i = 0; i != 16; ++i) {
6823 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
6824 !isa<UndefValue>(Mask->getOperand(i))) {
6825 AllEltsOk = false;
6826 break;
6827 }
6828 }
6829
6830 if (AllEltsOk) {
6831 // Cast the input vectors to byte vectors.
Reid Spencer13bc5d72006-12-12 09:18:51 +00006832 Value *Op0 = InsertCastBefore(Instruction::BitCast,
6833 II->getOperand(1), Mask->getType(), CI);
6834 Value *Op1 = InsertCastBefore(Instruction::BitCast,
6835 II->getOperand(2), Mask->getType(), CI);
Chris Lattnere79d2492006-04-06 19:19:17 +00006836 Value *Result = UndefValue::get(Op0->getType());
6837
6838 // Only extract each element once.
6839 Value *ExtractedElts[32];
6840 memset(ExtractedElts, 0, sizeof(ExtractedElts));
6841
6842 for (unsigned i = 0; i != 16; ++i) {
6843 if (isa<UndefValue>(Mask->getOperand(i)))
6844 continue;
Reid Spencere0fc4df2006-10-20 07:07:24 +00006845 unsigned Idx =cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
Chris Lattnere79d2492006-04-06 19:19:17 +00006846 Idx &= 31; // Match the hardware behavior.
6847
6848 if (ExtractedElts[Idx] == 0) {
6849 Instruction *Elt =
Chris Lattner2deeaea2006-10-05 06:55:50 +00006850 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
Chris Lattnere79d2492006-04-06 19:19:17 +00006851 InsertNewInstBefore(Elt, CI);
6852 ExtractedElts[Idx] = Elt;
6853 }
6854
6855 // Insert this value into the result vector.
Chris Lattner2deeaea2006-10-05 06:55:50 +00006856 Result = new InsertElementInst(Result, ExtractedElts[Idx], i,"tmp");
Chris Lattnere79d2492006-04-06 19:19:17 +00006857 InsertNewInstBefore(cast<Instruction>(Result), CI);
6858 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006859 return CastInst::create(Instruction::BitCast, Result, CI.getType());
Chris Lattnere79d2492006-04-06 19:19:17 +00006860 }
6861 }
6862 break;
6863
Chris Lattner503221f2006-01-13 21:28:09 +00006864 case Intrinsic::stackrestore: {
6865 // If the save is right next to the restore, remove the restore. This can
6866 // happen when variable allocas are DCE'd.
6867 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
6868 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
6869 BasicBlock::iterator BI = SS;
6870 if (&*++BI == II)
6871 return EraseInstFromFunction(CI);
6872 }
6873 }
6874
6875 // If the stack restore is in a return/unwind block and if there are no
6876 // allocas or calls between the restore and the return, nuke the restore.
6877 TerminatorInst *TI = II->getParent()->getTerminator();
6878 if (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)) {
6879 BasicBlock::iterator BI = II;
6880 bool CannotRemove = false;
6881 for (++BI; &*BI != TI; ++BI) {
6882 if (isa<AllocaInst>(BI) ||
6883 (isa<CallInst>(BI) && !isa<IntrinsicInst>(BI))) {
6884 CannotRemove = true;
6885 break;
6886 }
6887 }
6888 if (!CannotRemove)
6889 return EraseInstFromFunction(CI);
6890 }
6891 break;
6892 }
6893 }
Chris Lattner00648e12004-10-12 04:52:52 +00006894 }
6895
Chris Lattnerc66b2232006-01-13 20:11:04 +00006896 return visitCallSite(II);
Chris Lattner970c33a2003-06-19 17:00:31 +00006897}
6898
6899// InvokeInst simplification
6900//
6901Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattneraec3d942003-10-07 22:32:43 +00006902 return visitCallSite(&II);
Chris Lattner970c33a2003-06-19 17:00:31 +00006903}
6904
Chris Lattneraec3d942003-10-07 22:32:43 +00006905// visitCallSite - Improvements for call and invoke instructions.
6906//
6907Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner75b4d1d2003-10-07 22:54:13 +00006908 bool Changed = false;
6909
6910 // If the callee is a constexpr cast of a function, attempt to move the cast
6911 // to the arguments of the call/invoke.
Chris Lattneraec3d942003-10-07 22:32:43 +00006912 if (transformConstExprCastCall(CS)) return 0;
6913
Chris Lattner75b4d1d2003-10-07 22:54:13 +00006914 Value *Callee = CS.getCalledValue();
Chris Lattner81a7a232004-10-16 18:11:37 +00006915
Chris Lattner61d9d812005-05-13 07:09:09 +00006916 if (Function *CalleeF = dyn_cast<Function>(Callee))
6917 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
6918 Instruction *OldCall = CS.getInstruction();
6919 // If the call and callee calling conventions don't match, this call must
6920 // be unreachable, as the call is undefined.
Chris Lattner6ab03f62006-09-28 23:35:22 +00006921 new StoreInst(ConstantBool::getTrue(),
Chris Lattner61d9d812005-05-13 07:09:09 +00006922 UndefValue::get(PointerType::get(Type::BoolTy)), OldCall);
6923 if (!OldCall->use_empty())
6924 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
6925 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
6926 return EraseInstFromFunction(*OldCall);
6927 return 0;
6928 }
6929
Chris Lattner8ba9ec92004-10-18 02:59:09 +00006930 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
6931 // This instruction is not reachable, just remove it. We insert a store to
6932 // undef so that we know that this code is not reachable, despite the fact
6933 // that we can't modify the CFG here.
Chris Lattner6ab03f62006-09-28 23:35:22 +00006934 new StoreInst(ConstantBool::getTrue(),
Chris Lattner8ba9ec92004-10-18 02:59:09 +00006935 UndefValue::get(PointerType::get(Type::BoolTy)),
6936 CS.getInstruction());
6937
6938 if (!CS.getInstruction()->use_empty())
6939 CS.getInstruction()->
6940 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
6941
6942 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
6943 // Don't break the CFG, insert a dummy cond branch.
6944 new BranchInst(II->getNormalDest(), II->getUnwindDest(),
Chris Lattner6ab03f62006-09-28 23:35:22 +00006945 ConstantBool::getTrue(), II);
Chris Lattner81a7a232004-10-16 18:11:37 +00006946 }
Chris Lattner8ba9ec92004-10-18 02:59:09 +00006947 return EraseInstFromFunction(*CS.getInstruction());
6948 }
Chris Lattner81a7a232004-10-16 18:11:37 +00006949
Chris Lattner75b4d1d2003-10-07 22:54:13 +00006950 const PointerType *PTy = cast<PointerType>(Callee->getType());
6951 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
6952 if (FTy->isVarArg()) {
6953 // See if we can optimize any arguments passed through the varargs area of
6954 // the call.
6955 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
6956 E = CS.arg_end(); I != E; ++I)
6957 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
6958 // If this cast does not effect the value passed through the varargs
6959 // area, we can eliminate the use of the cast.
6960 Value *Op = CI->getOperand(0);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006961 if (CI->isLosslessCast()) {
Chris Lattner75b4d1d2003-10-07 22:54:13 +00006962 *I = Op;
6963 Changed = true;
6964 }
6965 }
6966 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00006967
Chris Lattner75b4d1d2003-10-07 22:54:13 +00006968 return Changed ? CS.getInstruction() : 0;
Chris Lattneraec3d942003-10-07 22:32:43 +00006969}
6970
Chris Lattner970c33a2003-06-19 17:00:31 +00006971// transformConstExprCastCall - If the callee is a constexpr cast of a function,
6972// attempt to move the cast to the arguments of the call/invoke.
6973//
6974bool InstCombiner::transformConstExprCastCall(CallSite CS) {
6975 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
6976 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006977 if (CE->getOpcode() != Instruction::BitCast ||
6978 !isa<Function>(CE->getOperand(0)))
Chris Lattner970c33a2003-06-19 17:00:31 +00006979 return false;
Reid Spencer87436872004-07-18 00:38:32 +00006980 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner970c33a2003-06-19 17:00:31 +00006981 Instruction *Caller = CS.getInstruction();
6982
6983 // Okay, this is a cast from a function to a different type. Unless doing so
6984 // would cause a type conversion of one of our arguments, change this call to
6985 // be a direct call with arguments casted to the appropriate types.
6986 //
6987 const FunctionType *FT = Callee->getFunctionType();
6988 const Type *OldRetTy = Caller->getType();
6989
Chris Lattner1f7942f2004-01-14 06:06:08 +00006990 // Check to see if we are changing the return type...
6991 if (OldRetTy != FT->getReturnType()) {
6992 if (Callee->isExternal() &&
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006993 !Caller->use_empty() &&
6994 !(OldRetTy->canLosslesslyBitCastTo(FT->getReturnType()) ||
Andrew Lenharth61eae292006-04-20 14:56:47 +00006995 (isa<PointerType>(FT->getReturnType()) &&
Reid Spencer6c38f0b2006-11-27 01:05:10 +00006996 TD->getIntPtrType()->canLosslesslyBitCastTo(OldRetTy)))
6997 )
Chris Lattner1f7942f2004-01-14 06:06:08 +00006998 return false; // Cannot transform this return value...
6999
7000 // If the callsite is an invoke instruction, and the return value is used by
7001 // a PHI node in a successor, we cannot change the return type of the call
7002 // because there is no place to put the cast instruction (without breaking
7003 // the critical edge). Bail out in this case.
7004 if (!Caller->use_empty())
7005 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
7006 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
7007 UI != E; ++UI)
7008 if (PHINode *PN = dyn_cast<PHINode>(*UI))
7009 if (PN->getParent() == II->getNormalDest() ||
Chris Lattnerfae8ab32004-02-08 21:44:31 +00007010 PN->getParent() == II->getUnwindDest())
Chris Lattner1f7942f2004-01-14 06:06:08 +00007011 return false;
7012 }
Chris Lattner970c33a2003-06-19 17:00:31 +00007013
7014 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
7015 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanb1c93172005-04-21 23:48:37 +00007016
Chris Lattner970c33a2003-06-19 17:00:31 +00007017 CallSite::arg_iterator AI = CS.arg_begin();
7018 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
7019 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthebfa24e2006-06-28 01:01:52 +00007020 const Type *ActTy = (*AI)->getType();
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007021 ConstantInt *c = dyn_cast<ConstantInt>(*AI);
Andrew Lenharthebfa24e2006-06-28 01:01:52 +00007022 //Either we can cast directly, or we can upconvert the argument
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007023 bool isConvertible = ActTy->canLosslesslyBitCastTo(ParamTy) ||
Andrew Lenharthebfa24e2006-06-28 01:01:52 +00007024 (ParamTy->isIntegral() && ActTy->isIntegral() &&
7025 ParamTy->isSigned() == ActTy->isSigned() &&
7026 ParamTy->getPrimitiveSize() >= ActTy->getPrimitiveSize()) ||
7027 (c && ParamTy->getPrimitiveSize() >= ActTy->getPrimitiveSize() &&
Reid Spencere0fc4df2006-10-20 07:07:24 +00007028 c->getSExtValue() > 0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00007029 if (Callee->isExternal() && !isConvertible) return false;
Chris Lattner970c33a2003-06-19 17:00:31 +00007030 }
7031
7032 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
7033 Callee->isExternal())
7034 return false; // Do not delete arguments unless we have a function body...
7035
7036 // Okay, we decided that this is a safe thing to do: go ahead and start
7037 // inserting cast instructions as necessary...
7038 std::vector<Value*> Args;
7039 Args.reserve(NumActualArgs);
7040
7041 AI = CS.arg_begin();
7042 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
7043 const Type *ParamTy = FT->getParamType(i);
7044 if ((*AI)->getType() == ParamTy) {
7045 Args.push_back(*AI);
7046 } else {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007047 CastInst *NewCast = CastInst::createInferredCast(*AI, ParamTy, "tmp");
7048 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
Chris Lattner970c33a2003-06-19 17:00:31 +00007049 }
7050 }
7051
7052 // If the function takes more arguments than the call was taking, add them
7053 // now...
7054 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
7055 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
7056
7057 // If we are removing arguments to the function, emit an obnoxious warning...
7058 if (FT->getNumParams() < NumActualArgs)
7059 if (!FT->isVarArg()) {
Bill Wendlingf3baad32006-12-07 01:30:32 +00007060 cerr << "WARNING: While resolving call to function '"
7061 << Callee->getName() << "' arguments were dropped!\n";
Chris Lattner970c33a2003-06-19 17:00:31 +00007062 } else {
7063 // Add all of the arguments in their promoted form to the arg list...
7064 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
7065 const Type *PTy = getPromotedType((*AI)->getType());
7066 if (PTy != (*AI)->getType()) {
7067 // Must promote to pass through va_arg area!
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007068 Instruction *Cast = CastInst::createInferredCast(*AI, PTy, "tmp");
Chris Lattner970c33a2003-06-19 17:00:31 +00007069 InsertNewInstBefore(Cast, *Caller);
7070 Args.push_back(Cast);
7071 } else {
7072 Args.push_back(*AI);
7073 }
7074 }
7075 }
7076
7077 if (FT->getReturnType() == Type::VoidTy)
7078 Caller->setName(""); // Void type should not have a name...
7079
7080 Instruction *NC;
7081 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Chris Lattnerfae8ab32004-02-08 21:44:31 +00007082 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
Chris Lattner970c33a2003-06-19 17:00:31 +00007083 Args, Caller->getName(), Caller);
Chris Lattner05c703e2005-05-14 12:25:32 +00007084 cast<InvokeInst>(II)->setCallingConv(II->getCallingConv());
Chris Lattner970c33a2003-06-19 17:00:31 +00007085 } else {
7086 NC = new CallInst(Callee, Args, Caller->getName(), Caller);
Chris Lattner6aacb0f2005-05-06 06:48:21 +00007087 if (cast<CallInst>(Caller)->isTailCall())
7088 cast<CallInst>(NC)->setTailCall();
Chris Lattner05c703e2005-05-14 12:25:32 +00007089 cast<CallInst>(NC)->setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Chris Lattner970c33a2003-06-19 17:00:31 +00007090 }
7091
7092 // Insert a cast of the return type as necessary...
7093 Value *NV = NC;
7094 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
7095 if (NV->getType() != Type::VoidTy) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007096 NV = NC = CastInst::createInferredCast(NC, Caller->getType(), "tmp");
Chris Lattner686767f2003-10-30 00:46:41 +00007097
7098 // If this is an invoke instruction, we should insert it after the first
7099 // non-phi, instruction in the normal successor block.
7100 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
7101 BasicBlock::iterator I = II->getNormalDest()->begin();
7102 while (isa<PHINode>(I)) ++I;
7103 InsertNewInstBefore(NC, *I);
7104 } else {
7105 // Otherwise, it's a call, just insert cast right after the call instr
7106 InsertNewInstBefore(NC, *Caller);
7107 }
Chris Lattner51ea1272004-02-28 05:22:00 +00007108 AddUsersToWorkList(*Caller);
Chris Lattner970c33a2003-06-19 17:00:31 +00007109 } else {
Chris Lattnere29d6342004-10-17 21:22:38 +00007110 NV = UndefValue::get(Caller->getType());
Chris Lattner970c33a2003-06-19 17:00:31 +00007111 }
7112 }
7113
7114 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
7115 Caller->replaceAllUsesWith(NV);
7116 Caller->getParent()->getInstList().erase(Caller);
7117 removeFromWorkList(Caller);
7118 return true;
7119}
7120
Chris Lattnercadac0c2006-11-01 04:51:18 +00007121/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
7122/// and if a/b/c/d and the add's all have a single use, turn this into two phi's
7123/// and a single binop.
7124Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
7125 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Chris Lattnereebea432006-11-01 07:43:41 +00007126 assert(isa<BinaryOperator>(FirstInst) || isa<ShiftInst>(FirstInst) ||
7127 isa<GetElementPtrInst>(FirstInst));
Chris Lattnercadac0c2006-11-01 04:51:18 +00007128 unsigned Opc = FirstInst->getOpcode();
Chris Lattnercd62f112006-11-08 19:29:23 +00007129 Value *LHSVal = FirstInst->getOperand(0);
7130 Value *RHSVal = FirstInst->getOperand(1);
7131
7132 const Type *LHSType = LHSVal->getType();
7133 const Type *RHSType = RHSVal->getType();
Chris Lattnercadac0c2006-11-01 04:51:18 +00007134
7135 // Scan to see if all operands are the same opcode, all have one use, and all
7136 // kill their operands (i.e. the operands have one use).
Chris Lattnerdc826fc2006-11-01 04:55:47 +00007137 for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
Chris Lattnercadac0c2006-11-01 04:51:18 +00007138 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Chris Lattnerdc826fc2006-11-01 04:55:47 +00007139 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
7140 // Verify type of the LHS matches so we don't fold setcc's of different
Chris Lattnereebea432006-11-01 07:43:41 +00007141 // types or GEP's with different index types.
7142 I->getOperand(0)->getType() != LHSType ||
7143 I->getOperand(1)->getType() != RHSType)
Chris Lattnercadac0c2006-11-01 04:51:18 +00007144 return 0;
Chris Lattnercd62f112006-11-08 19:29:23 +00007145
7146 // Keep track of which operand needs a phi node.
7147 if (I->getOperand(0) != LHSVal) LHSVal = 0;
7148 if (I->getOperand(1) != RHSVal) RHSVal = 0;
Chris Lattnercadac0c2006-11-01 04:51:18 +00007149 }
7150
Chris Lattner4f218d52006-11-08 19:42:28 +00007151 // Otherwise, this is safe to transform, determine if it is profitable.
7152
7153 // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
7154 // Indexes are often folded into load/store instructions, so we don't want to
7155 // hide them behind a phi.
7156 if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
7157 return 0;
7158
Chris Lattnercadac0c2006-11-01 04:51:18 +00007159 Value *InLHS = FirstInst->getOperand(0);
Chris Lattnercadac0c2006-11-01 04:51:18 +00007160 Value *InRHS = FirstInst->getOperand(1);
Chris Lattner4f218d52006-11-08 19:42:28 +00007161 PHINode *NewLHS = 0, *NewRHS = 0;
Chris Lattnercd62f112006-11-08 19:29:23 +00007162 if (LHSVal == 0) {
7163 NewLHS = new PHINode(LHSType, FirstInst->getOperand(0)->getName()+".pn");
7164 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
7165 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
Chris Lattnereebea432006-11-01 07:43:41 +00007166 InsertNewInstBefore(NewLHS, PN);
7167 LHSVal = NewLHS;
7168 }
Chris Lattnercd62f112006-11-08 19:29:23 +00007169
7170 if (RHSVal == 0) {
7171 NewRHS = new PHINode(RHSType, FirstInst->getOperand(1)->getName()+".pn");
7172 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
7173 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
Chris Lattnereebea432006-11-01 07:43:41 +00007174 InsertNewInstBefore(NewRHS, PN);
7175 RHSVal = NewRHS;
7176 }
7177
Chris Lattnercd62f112006-11-08 19:29:23 +00007178 // Add all operands to the new PHIs.
7179 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7180 if (NewLHS) {
7181 Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
7182 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
7183 }
7184 if (NewRHS) {
7185 Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
7186 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
7187 }
7188 }
7189
Chris Lattnercadac0c2006-11-01 04:51:18 +00007190 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattnereebea432006-11-01 07:43:41 +00007191 return BinaryOperator::create(BinOp->getOpcode(), LHSVal, RHSVal);
7192 else if (ShiftInst *SI = dyn_cast<ShiftInst>(FirstInst))
7193 return new ShiftInst(SI->getOpcode(), LHSVal, RHSVal);
7194 else {
7195 assert(isa<GetElementPtrInst>(FirstInst));
7196 return new GetElementPtrInst(LHSVal, RHSVal);
7197 }
Chris Lattnercadac0c2006-11-01 04:51:18 +00007198}
7199
Chris Lattner14f82c72006-11-01 07:13:54 +00007200/// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
7201/// of the block that defines it. This means that it must be obvious the value
7202/// of the load is not changed from the point of the load to the end of the
7203/// block it is in.
7204static bool isSafeToSinkLoad(LoadInst *L) {
7205 BasicBlock::iterator BBI = L, E = L->getParent()->end();
7206
7207 for (++BBI; BBI != E; ++BBI)
7208 if (BBI->mayWriteToMemory())
7209 return false;
7210 return true;
7211}
7212
Chris Lattner970c33a2003-06-19 17:00:31 +00007213
Chris Lattner7515cab2004-11-14 19:13:23 +00007214// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
7215// operator and they all are only used by the PHI, PHI together their
7216// inputs, and do the operation once, to the result of the PHI.
7217Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
7218 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
7219
7220 // Scan the instruction, looking for input operations that can be folded away.
7221 // If all input operands to the phi are the same instruction (e.g. a cast from
7222 // the same type or "+42") we can pull the operation through the PHI, reducing
7223 // code size and simplifying code.
7224 Constant *ConstantOp = 0;
7225 const Type *CastSrcTy = 0;
Chris Lattner14f82c72006-11-01 07:13:54 +00007226 bool isVolatile = false;
Chris Lattner7515cab2004-11-14 19:13:23 +00007227 if (isa<CastInst>(FirstInst)) {
7228 CastSrcTy = FirstInst->getOperand(0)->getType();
7229 } else if (isa<BinaryOperator>(FirstInst) || isa<ShiftInst>(FirstInst)) {
Chris Lattnercadac0c2006-11-01 04:51:18 +00007230 // Can fold binop or shift here if the RHS is a constant, otherwise call
7231 // FoldPHIArgBinOpIntoPHI.
Chris Lattner7515cab2004-11-14 19:13:23 +00007232 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Chris Lattnercadac0c2006-11-01 04:51:18 +00007233 if (ConstantOp == 0)
7234 return FoldPHIArgBinOpIntoPHI(PN);
Chris Lattner14f82c72006-11-01 07:13:54 +00007235 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
7236 isVolatile = LI->isVolatile();
7237 // We can't sink the load if the loaded value could be modified between the
7238 // load and the PHI.
7239 if (LI->getParent() != PN.getIncomingBlock(0) ||
7240 !isSafeToSinkLoad(LI))
7241 return 0;
Chris Lattnereebea432006-11-01 07:43:41 +00007242 } else if (isa<GetElementPtrInst>(FirstInst)) {
Chris Lattner4f218d52006-11-08 19:42:28 +00007243 if (FirstInst->getNumOperands() == 2)
Chris Lattnereebea432006-11-01 07:43:41 +00007244 return FoldPHIArgBinOpIntoPHI(PN);
7245 // Can't handle general GEPs yet.
7246 return 0;
Chris Lattner7515cab2004-11-14 19:13:23 +00007247 } else {
7248 return 0; // Cannot fold this operation.
7249 }
7250
7251 // Check to see if all arguments are the same operation.
7252 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7253 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
7254 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
7255 if (!I->hasOneUse() || I->getOpcode() != FirstInst->getOpcode())
7256 return 0;
7257 if (CastSrcTy) {
7258 if (I->getOperand(0)->getType() != CastSrcTy)
7259 return 0; // Cast operation must match.
Chris Lattner14f82c72006-11-01 07:13:54 +00007260 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
7261 // We can't sink the load if the loaded value could be modified between the
7262 // load and the PHI.
7263 if (LI->isVolatile() != isVolatile ||
7264 LI->getParent() != PN.getIncomingBlock(i) ||
7265 !isSafeToSinkLoad(LI))
7266 return 0;
Chris Lattner7515cab2004-11-14 19:13:23 +00007267 } else if (I->getOperand(1) != ConstantOp) {
7268 return 0;
7269 }
7270 }
7271
7272 // Okay, they are all the same operation. Create a new PHI node of the
7273 // correct type, and PHI together all of the LHS's of the instructions.
7274 PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
7275 PN.getName()+".in");
Chris Lattnerd8e20182005-01-29 00:39:08 +00007276 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattner46dd5a62004-11-14 19:29:34 +00007277
7278 Value *InVal = FirstInst->getOperand(0);
7279 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattner7515cab2004-11-14 19:13:23 +00007280
7281 // Add all operands to the new PHI.
Chris Lattner46dd5a62004-11-14 19:29:34 +00007282 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7283 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
7284 if (NewInVal != InVal)
7285 InVal = 0;
7286 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
7287 }
7288
7289 Value *PhiVal;
7290 if (InVal) {
7291 // The new PHI unions all of the same values together. This is really
7292 // common, so we handle it intelligently here for compile-time speed.
7293 PhiVal = InVal;
7294 delete NewPN;
7295 } else {
7296 InsertNewInstBefore(NewPN, PN);
7297 PhiVal = NewPN;
7298 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00007299
Chris Lattner7515cab2004-11-14 19:13:23 +00007300 // Insert and return the new operation.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007301 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
7302 return CastInst::create(FirstCI->getOpcode(), PhiVal, PN.getType());
Reid Spencerde46e482006-11-02 20:25:50 +00007303 else if (isa<LoadInst>(FirstInst))
Chris Lattner14f82c72006-11-01 07:13:54 +00007304 return new LoadInst(PhiVal, "", isVolatile);
Chris Lattner7515cab2004-11-14 19:13:23 +00007305 else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattner46dd5a62004-11-14 19:29:34 +00007306 return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattner7515cab2004-11-14 19:13:23 +00007307 else
7308 return new ShiftInst(cast<ShiftInst>(FirstInst)->getOpcode(),
Chris Lattner46dd5a62004-11-14 19:29:34 +00007309 PhiVal, ConstantOp);
Chris Lattner7515cab2004-11-14 19:13:23 +00007310}
Chris Lattner48a44f72002-05-02 17:06:02 +00007311
Chris Lattner71536432005-01-17 05:10:15 +00007312/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
7313/// that is dead.
7314static bool DeadPHICycle(PHINode *PN, std::set<PHINode*> &PotentiallyDeadPHIs) {
7315 if (PN->use_empty()) return true;
7316 if (!PN->hasOneUse()) return false;
7317
7318 // Remember this node, and if we find the cycle, return.
7319 if (!PotentiallyDeadPHIs.insert(PN).second)
7320 return true;
7321
7322 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
7323 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanb1c93172005-04-21 23:48:37 +00007324
Chris Lattner71536432005-01-17 05:10:15 +00007325 return false;
7326}
7327
Chris Lattnerbbbdd852002-05-06 18:06:38 +00007328// PHINode simplification
7329//
Chris Lattner113f4f42002-06-25 16:13:24 +00007330Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonbbf89902006-07-10 22:15:25 +00007331 // If LCSSA is around, don't mess with Phi nodes
7332 if (mustPreserveAnalysisID(LCSSAID)) return 0;
Owen Andersona6968f82006-07-10 19:03:49 +00007333
Owen Andersonae8aa642006-07-10 22:03:18 +00007334 if (Value *V = PN.hasConstantValue())
7335 return ReplaceInstUsesWith(PN, V);
7336
Owen Andersonae8aa642006-07-10 22:03:18 +00007337 // If all PHI operands are the same operation, pull them through the PHI,
7338 // reducing code size.
7339 if (isa<Instruction>(PN.getIncomingValue(0)) &&
7340 PN.getIncomingValue(0)->hasOneUse())
7341 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
7342 return Result;
7343
7344 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
7345 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
7346 // PHI)... break the cycle.
7347 if (PN.hasOneUse())
7348 if (PHINode *PU = dyn_cast<PHINode>(PN.use_back())) {
7349 std::set<PHINode*> PotentiallyDeadPHIs;
7350 PotentiallyDeadPHIs.insert(&PN);
7351 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
7352 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
7353 }
7354
Chris Lattner91daeb52003-12-19 05:58:40 +00007355 return 0;
Chris Lattnerbbbdd852002-05-06 18:06:38 +00007356}
7357
Reid Spencer13bc5d72006-12-12 09:18:51 +00007358static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
7359 Instruction *InsertPoint,
7360 InstCombiner *IC) {
7361 unsigned PtrSize = IC->getTargetData().getPointerSize();
7362 unsigned VTySize = V->getType()->getPrimitiveSize();
7363 // We must cast correctly to the pointer type. Ensure that we
7364 // sign extend the integer value if it is smaller as this is
7365 // used for address computation.
7366 Instruction::CastOps opcode =
7367 (VTySize < PtrSize ? Instruction::SExt :
7368 (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
7369 return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
Chris Lattner69193f92004-04-05 01:30:19 +00007370}
7371
Chris Lattner48a44f72002-05-02 17:06:02 +00007372
Chris Lattner113f4f42002-06-25 16:13:24 +00007373Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner5f667a62004-05-07 22:09:22 +00007374 Value *PtrOp = GEP.getOperand(0);
Chris Lattner471bd762003-05-22 19:07:21 +00007375 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
Chris Lattner113f4f42002-06-25 16:13:24 +00007376 // If so, eliminate the noop.
Chris Lattner8d0bacb2004-02-22 05:25:17 +00007377 if (GEP.getNumOperands() == 1)
Chris Lattner5f667a62004-05-07 22:09:22 +00007378 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner8d0bacb2004-02-22 05:25:17 +00007379
Chris Lattner81a7a232004-10-16 18:11:37 +00007380 if (isa<UndefValue>(GEP.getOperand(0)))
7381 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
7382
Chris Lattner8d0bacb2004-02-22 05:25:17 +00007383 bool HasZeroPointerIndex = false;
7384 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
7385 HasZeroPointerIndex = C->isNullValue();
7386
7387 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner5f667a62004-05-07 22:09:22 +00007388 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner48a44f72002-05-02 17:06:02 +00007389
Chris Lattner69193f92004-04-05 01:30:19 +00007390 // Eliminate unneeded casts for indices.
7391 bool MadeChange = false;
Chris Lattner2b2412d2004-04-07 18:38:20 +00007392 gep_type_iterator GTI = gep_type_begin(GEP);
7393 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI)
7394 if (isa<SequentialType>(*GTI)) {
7395 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
7396 Value *Src = CI->getOperand(0);
7397 const Type *SrcTy = Src->getType();
7398 const Type *DestTy = CI->getType();
7399 if (Src->getType()->isInteger()) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00007400 if (SrcTy->getPrimitiveSizeInBits() ==
7401 DestTy->getPrimitiveSizeInBits()) {
Chris Lattner2b2412d2004-04-07 18:38:20 +00007402 // We can always eliminate a cast from ulong or long to the other.
7403 // We can always eliminate a cast from uint to int or the other on
7404 // 32-bit pointer platforms.
Chris Lattnerd1f46d32005-04-24 06:59:08 +00007405 if (DestTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()){
Chris Lattner2b2412d2004-04-07 18:38:20 +00007406 MadeChange = true;
7407 GEP.setOperand(i, Src);
7408 }
7409 } else if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
7410 SrcTy->getPrimitiveSize() == 4) {
7411 // We can always eliminate a cast from int to [u]long. We can
7412 // eliminate a cast from uint to [u]long iff the target is a 32-bit
7413 // pointer target.
Misha Brukmanb1c93172005-04-21 23:48:37 +00007414 if (SrcTy->isSigned() ||
Chris Lattnerd1f46d32005-04-24 06:59:08 +00007415 SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
Chris Lattner2b2412d2004-04-07 18:38:20 +00007416 MadeChange = true;
7417 GEP.setOperand(i, Src);
7418 }
Chris Lattner69193f92004-04-05 01:30:19 +00007419 }
7420 }
7421 }
Chris Lattner2b2412d2004-04-07 18:38:20 +00007422 // If we are using a wider index than needed for this platform, shrink it
7423 // to what we need. If the incoming value needs a cast instruction,
7424 // insert it. This explicit cast can make subsequent optimizations more
7425 // obvious.
7426 Value *Op = GEP.getOperand(i);
7427 if (Op->getType()->getPrimitiveSize() > TD->getPointerSize())
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00007428 if (Constant *C = dyn_cast<Constant>(Op)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00007429 GEP.setOperand(i, ConstantExpr::getTrunc(C,
Chris Lattner44d0b952004-07-20 01:48:15 +00007430 TD->getIntPtrType()->getSignedVersion()));
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00007431 MadeChange = true;
7432 } else {
Reid Spencer13bc5d72006-12-12 09:18:51 +00007433 Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
7434 GEP);
Chris Lattner2b2412d2004-04-07 18:38:20 +00007435 GEP.setOperand(i, Op);
7436 MadeChange = true;
7437 }
Chris Lattner44d0b952004-07-20 01:48:15 +00007438
7439 // If this is a constant idx, make sure to canonicalize it to be a signed
7440 // operand, otherwise CSE and other optimizations are pessimized.
Reid Spencere0fc4df2006-10-20 07:07:24 +00007441 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op))
7442 if (CUI->getType()->isUnsigned()) {
7443 GEP.setOperand(i,
Reid Spencer13bc5d72006-12-12 09:18:51 +00007444 ConstantExpr::getBitCast(CUI, CUI->getType()->getSignedVersion()));
Reid Spencere0fc4df2006-10-20 07:07:24 +00007445 MadeChange = true;
7446 }
Chris Lattner69193f92004-04-05 01:30:19 +00007447 }
7448 if (MadeChange) return &GEP;
7449
Chris Lattnerae7a0d32002-08-02 19:29:35 +00007450 // Combine Indices - If the source pointer to this getelementptr instruction
7451 // is a getelementptr instruction, combine the indices of the two
7452 // getelementptr instructions into a single instruction.
7453 //
Chris Lattner57c67b02004-03-25 22:59:29 +00007454 std::vector<Value*> SrcGEPOperands;
Chris Lattner0798af32005-01-13 20:14:25 +00007455 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattner57c67b02004-03-25 22:59:29 +00007456 SrcGEPOperands.assign(Src->op_begin(), Src->op_end());
Chris Lattner57c67b02004-03-25 22:59:29 +00007457
7458 if (!SrcGEPOperands.empty()) {
Chris Lattner5f667a62004-05-07 22:09:22 +00007459 // Note that if our source is a gep chain itself that we wait for that
7460 // chain to be resolved before we perform this transformation. This
7461 // avoids us creating a TON of code in some cases.
7462 //
7463 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
7464 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
7465 return 0; // Wait until our source is folded to completion.
7466
Chris Lattnerae7a0d32002-08-02 19:29:35 +00007467 std::vector<Value *> Indices;
Chris Lattner5f667a62004-05-07 22:09:22 +00007468
7469 // Find out whether the last index in the source GEP is a sequential idx.
7470 bool EndsWithSequential = false;
7471 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
7472 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattner8ec5f882004-05-08 22:41:42 +00007473 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00007474
Chris Lattnerae7a0d32002-08-02 19:29:35 +00007475 // Can we combine the two pointer arithmetics offsets?
Chris Lattner5f667a62004-05-07 22:09:22 +00007476 if (EndsWithSequential) {
Chris Lattner235af562003-03-05 22:33:14 +00007477 // Replace: gep (gep %P, long B), long A, ...
7478 // With: T = long A+B; gep %P, T, ...
7479 //
Chris Lattner5f667a62004-05-07 22:09:22 +00007480 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner69193f92004-04-05 01:30:19 +00007481 if (SO1 == Constant::getNullValue(SO1->getType())) {
7482 Sum = GO1;
7483 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
7484 Sum = SO1;
7485 } else {
7486 // If they aren't the same type, convert both to an integer of the
7487 // target's pointer size.
7488 if (SO1->getType() != GO1->getType()) {
7489 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00007490 SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
Chris Lattner69193f92004-04-05 01:30:19 +00007491 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00007492 GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
Chris Lattner69193f92004-04-05 01:30:19 +00007493 } else {
7494 unsigned PS = TD->getPointerSize();
Chris Lattner69193f92004-04-05 01:30:19 +00007495 if (SO1->getType()->getPrimitiveSize() == PS) {
7496 // Convert GO1 to SO1's type.
Reid Spencer13bc5d72006-12-12 09:18:51 +00007497 GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
Chris Lattner69193f92004-04-05 01:30:19 +00007498
7499 } else if (GO1->getType()->getPrimitiveSize() == PS) {
7500 // Convert SO1 to GO1's type.
Reid Spencer13bc5d72006-12-12 09:18:51 +00007501 SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
Chris Lattner69193f92004-04-05 01:30:19 +00007502 } else {
7503 const Type *PT = TD->getIntPtrType();
Reid Spencer13bc5d72006-12-12 09:18:51 +00007504 SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
7505 GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
Chris Lattner69193f92004-04-05 01:30:19 +00007506 }
7507 }
7508 }
Chris Lattner5f667a62004-05-07 22:09:22 +00007509 if (isa<Constant>(SO1) && isa<Constant>(GO1))
7510 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
7511 else {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00007512 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
7513 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner5f667a62004-05-07 22:09:22 +00007514 }
Chris Lattner69193f92004-04-05 01:30:19 +00007515 }
Chris Lattner5f667a62004-05-07 22:09:22 +00007516
7517 // Recycle the GEP we already have if possible.
7518 if (SrcGEPOperands.size() == 2) {
7519 GEP.setOperand(0, SrcGEPOperands[0]);
7520 GEP.setOperand(1, Sum);
7521 return &GEP;
7522 } else {
7523 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
7524 SrcGEPOperands.end()-1);
7525 Indices.push_back(Sum);
7526 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
7527 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00007528 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner69193f92004-04-05 01:30:19 +00007529 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00007530 SrcGEPOperands.size() != 1) {
Chris Lattnerae7a0d32002-08-02 19:29:35 +00007531 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattner57c67b02004-03-25 22:59:29 +00007532 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
7533 SrcGEPOperands.end());
Chris Lattnerae7a0d32002-08-02 19:29:35 +00007534 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
7535 }
7536
7537 if (!Indices.empty())
Chris Lattner57c67b02004-03-25 22:59:29 +00007538 return new GetElementPtrInst(SrcGEPOperands[0], Indices, GEP.getName());
Chris Lattnerc59af1d2002-08-17 22:21:59 +00007539
Chris Lattner5f667a62004-05-07 22:09:22 +00007540 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattnerc59af1d2002-08-17 22:21:59 +00007541 // GEP of global variable. If all of the indices for this GEP are
7542 // constants, we can promote this to a constexpr instead of an instruction.
7543
7544 // Scan for nonconstants...
7545 std::vector<Constant*> Indices;
7546 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
7547 for (; I != E && isa<Constant>(*I); ++I)
7548 Indices.push_back(cast<Constant>(*I));
7549
7550 if (I == E) { // If they are all constants...
Chris Lattnerf3edc492004-07-18 18:59:44 +00007551 Constant *CE = ConstantExpr::getGetElementPtr(GV, Indices);
Chris Lattnerc59af1d2002-08-17 22:21:59 +00007552
7553 // Replace all uses of the GEP with the new constexpr...
7554 return ReplaceInstUsesWith(GEP, CE);
7555 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007556 } else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast?
Chris Lattner567b81f2005-09-13 00:40:14 +00007557 if (!isa<PointerType>(X->getType())) {
7558 // Not interesting. Source pointer must be a cast from pointer.
7559 } else if (HasZeroPointerIndex) {
7560 // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
7561 // into : GEP [10 x ubyte]* X, long 0, ...
7562 //
7563 // This occurs when the program declares an array extern like "int X[];"
7564 //
7565 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
7566 const PointerType *XTy = cast<PointerType>(X->getType());
7567 if (const ArrayType *XATy =
7568 dyn_cast<ArrayType>(XTy->getElementType()))
7569 if (const ArrayType *CATy =
7570 dyn_cast<ArrayType>(CPTy->getElementType()))
7571 if (CATy->getElementType() == XATy->getElementType()) {
7572 // At this point, we know that the cast source type is a pointer
7573 // to an array of the same type as the destination pointer
7574 // array. Because the array type is never stepped over (there
7575 // is a leading zero) we can fold the cast into this GEP.
7576 GEP.setOperand(0, X);
7577 return &GEP;
7578 }
7579 } else if (GEP.getNumOperands() == 2) {
7580 // Transform things like:
Chris Lattner2a893292005-09-13 18:36:04 +00007581 // %t = getelementptr ubyte* cast ([2 x int]* %str to uint*), uint %V
7582 // into: %t1 = getelementptr [2 x int*]* %str, int 0, uint %V; cast
Chris Lattner567b81f2005-09-13 00:40:14 +00007583 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
7584 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
7585 if (isa<ArrayType>(SrcElTy) &&
7586 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
7587 TD->getTypeSize(ResElTy)) {
7588 Value *V = InsertNewInstBefore(
7589 new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
7590 GEP.getOperand(1), GEP.getName()), GEP);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007591 // V and GEP are both pointer types --> BitCast
7592 return new BitCastInst(V, GEP.getType());
Chris Lattner8d0bacb2004-02-22 05:25:17 +00007593 }
Chris Lattner2a893292005-09-13 18:36:04 +00007594
7595 // Transform things like:
7596 // getelementptr sbyte* cast ([100 x double]* X to sbyte*), int %tmp
7597 // (where tmp = 8*tmp2) into:
7598 // getelementptr [100 x double]* %arr, int 0, int %tmp.2
7599
7600 if (isa<ArrayType>(SrcElTy) &&
7601 (ResElTy == Type::SByteTy || ResElTy == Type::UByteTy)) {
7602 uint64_t ArrayEltSize =
7603 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType());
7604
7605 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
7606 // allow either a mul, shift, or constant here.
7607 Value *NewIdx = 0;
7608 ConstantInt *Scale = 0;
7609 if (ArrayEltSize == 1) {
7610 NewIdx = GEP.getOperand(1);
7611 Scale = ConstantInt::get(NewIdx->getType(), 1);
7612 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Chris Lattnera393e4d2005-09-14 17:32:56 +00007613 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner2a893292005-09-13 18:36:04 +00007614 Scale = CI;
7615 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
7616 if (Inst->getOpcode() == Instruction::Shl &&
7617 isa<ConstantInt>(Inst->getOperand(1))) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00007618 unsigned ShAmt =
7619 cast<ConstantInt>(Inst->getOperand(1))->getZExtValue();
Chris Lattner2a893292005-09-13 18:36:04 +00007620 if (Inst->getType()->isSigned())
Reid Spencere0fc4df2006-10-20 07:07:24 +00007621 Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmt);
Chris Lattner2a893292005-09-13 18:36:04 +00007622 else
Reid Spencere0fc4df2006-10-20 07:07:24 +00007623 Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmt);
Chris Lattner2a893292005-09-13 18:36:04 +00007624 NewIdx = Inst->getOperand(0);
7625 } else if (Inst->getOpcode() == Instruction::Mul &&
7626 isa<ConstantInt>(Inst->getOperand(1))) {
7627 Scale = cast<ConstantInt>(Inst->getOperand(1));
7628 NewIdx = Inst->getOperand(0);
7629 }
7630 }
7631
7632 // If the index will be to exactly the right offset with the scale taken
7633 // out, perform the transformation.
Reid Spencere0fc4df2006-10-20 07:07:24 +00007634 if (Scale && Scale->getZExtValue() % ArrayEltSize == 0) {
Reid Spencerde46e482006-11-02 20:25:50 +00007635 if (isa<ConstantInt>(Scale))
Reid Spencere0fc4df2006-10-20 07:07:24 +00007636 Scale = ConstantInt::get(Scale->getType(),
7637 Scale->getZExtValue() / ArrayEltSize);
7638 if (Scale->getZExtValue() != 1) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00007639 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
7640 true /*SExt*/);
Chris Lattner2a893292005-09-13 18:36:04 +00007641 Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
7642 NewIdx = InsertNewInstBefore(Sc, GEP);
7643 }
7644
7645 // Insert the new GEP instruction.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007646 Instruction *NewGEP =
Chris Lattner2a893292005-09-13 18:36:04 +00007647 new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
7648 NewIdx, GEP.getName());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007649 NewGEP = InsertNewInstBefore(NewGEP, GEP);
7650 // The NewGEP must be pointer typed, so must the old one -> BitCast
7651 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner2a893292005-09-13 18:36:04 +00007652 }
7653 }
Chris Lattner8d0bacb2004-02-22 05:25:17 +00007654 }
Chris Lattnerca081252001-12-14 16:52:21 +00007655 }
7656
Chris Lattnerca081252001-12-14 16:52:21 +00007657 return 0;
7658}
7659
Chris Lattner1085bdf2002-11-04 16:18:53 +00007660Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
7661 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
7662 if (AI.isArrayAllocation()) // Check C != 1
Reid Spencere0fc4df2006-10-20 07:07:24 +00007663 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
7664 const Type *NewTy =
7665 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Chris Lattnera2620ac2002-11-09 00:49:43 +00007666 AllocationInst *New = 0;
Chris Lattner1085bdf2002-11-04 16:18:53 +00007667
7668 // Create and insert the replacement instruction...
7669 if (isa<MallocInst>(AI))
Nate Begeman848622f2005-11-05 09:21:28 +00007670 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00007671 else {
7672 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Nate Begeman848622f2005-11-05 09:21:28 +00007673 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00007674 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00007675
7676 InsertNewInstBefore(New, AI);
Misha Brukmanb1c93172005-04-21 23:48:37 +00007677
Chris Lattner1085bdf2002-11-04 16:18:53 +00007678 // Scan to the end of the allocation instructions, to skip over a block of
7679 // allocas if possible...
7680 //
7681 BasicBlock::iterator It = New;
7682 while (isa<AllocationInst>(*It)) ++It;
7683
7684 // Now that I is pointing to the first non-allocation-inst in the block,
7685 // insert our getelementptr instruction...
7686 //
Chris Lattner809dfac2005-05-04 19:10:26 +00007687 Value *NullIdx = Constant::getNullValue(Type::IntTy);
7688 Value *V = new GetElementPtrInst(New, NullIdx, NullIdx,
7689 New->getName()+".sub", It);
Chris Lattner1085bdf2002-11-04 16:18:53 +00007690
7691 // Now make everything use the getelementptr instead of the original
7692 // allocation.
Chris Lattnerabb77c92004-03-19 06:08:10 +00007693 return ReplaceInstUsesWith(AI, V);
Chris Lattner81a7a232004-10-16 18:11:37 +00007694 } else if (isa<UndefValue>(AI.getArraySize())) {
7695 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner1085bdf2002-11-04 16:18:53 +00007696 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00007697
7698 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
7699 // Note that we only do this for alloca's, because malloc should allocate and
7700 // return a unique pointer, even for a zero byte allocation.
Misha Brukmanb1c93172005-04-21 23:48:37 +00007701 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
Chris Lattner49df6ce2004-07-02 22:55:47 +00007702 TD->getTypeSize(AI.getAllocatedType()) == 0)
Chris Lattnerabb77c92004-03-19 06:08:10 +00007703 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
7704
Chris Lattner1085bdf2002-11-04 16:18:53 +00007705 return 0;
7706}
7707
Chris Lattner8427bff2003-12-07 01:24:23 +00007708Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
7709 Value *Op = FI.getOperand(0);
7710
7711 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
7712 if (CastInst *CI = dyn_cast<CastInst>(Op))
7713 if (isa<PointerType>(CI->getOperand(0)->getType())) {
7714 FI.setOperand(0, CI->getOperand(0));
7715 return &FI;
7716 }
7717
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007718 // free undef -> unreachable.
7719 if (isa<UndefValue>(Op)) {
7720 // Insert a new store to null because we cannot modify the CFG here.
Chris Lattner6ab03f62006-09-28 23:35:22 +00007721 new StoreInst(ConstantBool::getTrue(),
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007722 UndefValue::get(PointerType::get(Type::BoolTy)), &FI);
7723 return EraseInstFromFunction(FI);
7724 }
7725
Chris Lattnerf3a36602004-02-28 04:57:37 +00007726 // If we have 'free null' delete the instruction. This can happen in stl code
7727 // when lots of inlining happens.
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007728 if (isa<ConstantPointerNull>(Op))
Chris Lattner51ea1272004-02-28 05:22:00 +00007729 return EraseInstFromFunction(FI);
Chris Lattnerf3a36602004-02-28 04:57:37 +00007730
Chris Lattner8427bff2003-12-07 01:24:23 +00007731 return 0;
7732}
7733
7734
Chris Lattner72684fe2005-01-31 05:51:45 +00007735/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Chris Lattner35e24772004-07-13 01:49:43 +00007736static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
7737 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00007738 Value *CastOp = CI->getOperand(0);
Chris Lattner35e24772004-07-13 01:49:43 +00007739
7740 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00007741 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Chris Lattner35e24772004-07-13 01:49:43 +00007742 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00007743
Chris Lattnerebca4762006-04-02 05:37:12 +00007744 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
7745 isa<PackedType>(DestPTy)) {
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00007746 // If the source is an array, the code below will not succeed. Check to
7747 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
7748 // constants.
7749 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
7750 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
7751 if (ASrcTy->getNumElements() != 0) {
7752 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
7753 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
7754 SrcTy = cast<PointerType>(CastOp->getType());
7755 SrcPTy = SrcTy->getElementType();
7756 }
7757
Chris Lattnerebca4762006-04-02 05:37:12 +00007758 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
7759 isa<PackedType>(SrcPTy)) &&
Chris Lattnerecfa9b52005-03-29 06:37:47 +00007760 // Do not allow turning this into a load of an integer, which is then
7761 // casted to a pointer, this pessimizes pointer analysis a lot.
7762 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00007763 IC.getTargetData().getTypeSize(SrcPTy) ==
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00007764 IC.getTargetData().getTypeSize(DestPTy)) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00007765
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00007766 // Okay, we are casting from one integer or pointer type to another of
7767 // the same size. Instead of casting the pointer before the load, cast
7768 // the result of the loaded value.
7769 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
7770 CI->getName(),
7771 LI.isVolatile()),LI);
7772 // Now cast the result of the load.
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007773 return CastInst::createInferredCast(NewLoad, LI.getType());
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00007774 }
Chris Lattner35e24772004-07-13 01:49:43 +00007775 }
7776 }
7777 return 0;
7778}
7779
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00007780/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattnere6f13092004-09-19 19:18:10 +00007781/// from this value cannot trap. If it is not obviously safe to load from the
7782/// specified pointer, we do a quick local scan of the basic block containing
7783/// ScanFrom, to determine if the address is already accessed.
7784static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
7785 // If it is an alloca or global variable, it is always safe to load from.
7786 if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
7787
7788 // Otherwise, be a little bit agressive by scanning the local block where we
7789 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00007790 // from/to. If so, the previous load or store would have already trapped,
7791 // so there is no harm doing an extra load (also, CSE will later eliminate
7792 // the load entirely).
Chris Lattnere6f13092004-09-19 19:18:10 +00007793 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
7794
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00007795 while (BBI != E) {
Chris Lattnere6f13092004-09-19 19:18:10 +00007796 --BBI;
7797
7798 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
7799 if (LI->getOperand(0) == V) return true;
7800 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
7801 if (SI->getOperand(1) == V) return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +00007802
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00007803 }
Chris Lattnere6f13092004-09-19 19:18:10 +00007804 return false;
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00007805}
7806
Chris Lattner0f1d8a32003-06-26 05:06:25 +00007807Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
7808 Value *Op = LI.getOperand(0);
Chris Lattner7e8af382004-01-12 04:13:56 +00007809
Chris Lattnera9d84e32005-05-01 04:24:53 +00007810 // load (cast X) --> cast (load X) iff safe
Reid Spencerde46e482006-11-02 20:25:50 +00007811 if (isa<CastInst>(Op))
Chris Lattnera9d84e32005-05-01 04:24:53 +00007812 if (Instruction *Res = InstCombineLoadCast(*this, LI))
7813 return Res;
7814
7815 // None of the following transforms are legal for volatile loads.
7816 if (LI.isVolatile()) return 0;
Chris Lattnerb990f7d2005-09-12 22:00:15 +00007817
Chris Lattnerb990f7d2005-09-12 22:00:15 +00007818 if (&LI.getParent()->front() != &LI) {
7819 BasicBlock::iterator BBI = &LI; --BBI;
Chris Lattnere0bfdf12005-09-12 22:21:03 +00007820 // If the instruction immediately before this is a store to the same
7821 // address, do a simple form of store->load forwarding.
Chris Lattnerb990f7d2005-09-12 22:00:15 +00007822 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
7823 if (SI->getOperand(1) == LI.getOperand(0))
7824 return ReplaceInstUsesWith(LI, SI->getOperand(0));
Chris Lattnere0bfdf12005-09-12 22:21:03 +00007825 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
7826 if (LIB->getOperand(0) == LI.getOperand(0))
7827 return ReplaceInstUsesWith(LI, LIB);
Chris Lattnerb990f7d2005-09-12 22:00:15 +00007828 }
Chris Lattnera9d84e32005-05-01 04:24:53 +00007829
7830 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op))
7831 if (isa<ConstantPointerNull>(GEPI->getOperand(0)) ||
7832 isa<UndefValue>(GEPI->getOperand(0))) {
7833 // Insert a new store to null instruction before the load to indicate
7834 // that this code is not reachable. We do this instead of inserting
7835 // an unreachable instruction directly because we cannot modify the
7836 // CFG.
7837 new StoreInst(UndefValue::get(LI.getType()),
7838 Constant::getNullValue(Op->getType()), &LI);
7839 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
7840 }
7841
Chris Lattner81a7a232004-10-16 18:11:37 +00007842 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattnera9d84e32005-05-01 04:24:53 +00007843 // load null/undef -> undef
7844 if ((C->isNullValue() || isa<UndefValue>(C))) {
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007845 // Insert a new store to null instruction before the load to indicate that
7846 // this code is not reachable. We do this instead of inserting an
7847 // unreachable instruction directly because we cannot modify the CFG.
Chris Lattnera9d84e32005-05-01 04:24:53 +00007848 new StoreInst(UndefValue::get(LI.getType()),
7849 Constant::getNullValue(Op->getType()), &LI);
Chris Lattner81a7a232004-10-16 18:11:37 +00007850 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007851 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00007852
Chris Lattner81a7a232004-10-16 18:11:37 +00007853 // Instcombine load (constant global) into the value loaded.
7854 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
7855 if (GV->isConstant() && !GV->isExternal())
7856 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanb1c93172005-04-21 23:48:37 +00007857
Chris Lattner81a7a232004-10-16 18:11:37 +00007858 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
7859 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
7860 if (CE->getOpcode() == Instruction::GetElementPtr) {
7861 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
7862 if (GV->isConstant() && !GV->isExternal())
Chris Lattner0b011ec2005-09-26 05:28:06 +00007863 if (Constant *V =
7864 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
Chris Lattner81a7a232004-10-16 18:11:37 +00007865 return ReplaceInstUsesWith(LI, V);
Chris Lattnera9d84e32005-05-01 04:24:53 +00007866 if (CE->getOperand(0)->isNullValue()) {
7867 // Insert a new store to null instruction before the load to indicate
7868 // that this code is not reachable. We do this instead of inserting
7869 // an unreachable instruction directly because we cannot modify the
7870 // CFG.
7871 new StoreInst(UndefValue::get(LI.getType()),
7872 Constant::getNullValue(Op->getType()), &LI);
7873 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
7874 }
7875
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007876 } else if (CE->isCast()) {
Chris Lattner81a7a232004-10-16 18:11:37 +00007877 if (Instruction *Res = InstCombineLoadCast(*this, LI))
7878 return Res;
7879 }
7880 }
Chris Lattnere228ee52004-04-08 20:39:49 +00007881
Chris Lattnera9d84e32005-05-01 04:24:53 +00007882 if (Op->hasOneUse()) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00007883 // Change select and PHI nodes to select values instead of addresses: this
7884 // helps alias analysis out a lot, allows many others simplifications, and
7885 // exposes redundancy in the code.
7886 //
7887 // Note that we cannot do the transformation unless we know that the
7888 // introduced loads cannot trap! Something like this is valid as long as
7889 // the condition is always false: load (select bool %C, int* null, int* %G),
7890 // but it would not be valid if we transformed it to load from null
7891 // unconditionally.
7892 //
7893 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
7894 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattnere6f13092004-09-19 19:18:10 +00007895 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
7896 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00007897 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner42618552004-09-20 10:15:10 +00007898 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00007899 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner42618552004-09-20 10:15:10 +00007900 SI->getOperand(2)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00007901 return new SelectInst(SI->getCondition(), V1, V2);
7902 }
7903
Chris Lattnerbdcf41a2004-09-23 15:46:00 +00007904 // load (select (cond, null, P)) -> load P
7905 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
7906 if (C->isNullValue()) {
7907 LI.setOperand(0, SI->getOperand(2));
7908 return &LI;
7909 }
7910
7911 // load (select (cond, P, null)) -> load P
7912 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
7913 if (C->isNullValue()) {
7914 LI.setOperand(0, SI->getOperand(1));
7915 return &LI;
7916 }
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00007917 }
7918 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00007919 return 0;
7920}
7921
Chris Lattner72684fe2005-01-31 05:51:45 +00007922/// InstCombineStoreToCast - Fold 'store V, (cast P)' -> store (cast V), P'
7923/// when possible.
7924static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
7925 User *CI = cast<User>(SI.getOperand(1));
7926 Value *CastOp = CI->getOperand(0);
7927
7928 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
7929 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
7930 const Type *SrcPTy = SrcTy->getElementType();
7931
7932 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
7933 // If the source is an array, the code below will not succeed. Check to
7934 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
7935 // constants.
7936 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
7937 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
7938 if (ASrcTy->getNumElements() != 0) {
7939 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
7940 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
7941 SrcTy = cast<PointerType>(CastOp->getType());
7942 SrcPTy = SrcTy->getElementType();
7943 }
7944
7945 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00007946 IC.getTargetData().getTypeSize(SrcPTy) ==
Chris Lattner72684fe2005-01-31 05:51:45 +00007947 IC.getTargetData().getTypeSize(DestPTy)) {
7948
7949 // Okay, we are casting from one integer or pointer type to another of
7950 // the same size. Instead of casting the pointer before the store, cast
7951 // the value to be stored.
7952 Value *NewCast;
7953 if (Constant *C = dyn_cast<Constant>(SI.getOperand(0)))
7954 NewCast = ConstantExpr::getCast(C, SrcPTy);
7955 else
Reid Spencer6c38f0b2006-11-27 01:05:10 +00007956 NewCast = IC.InsertNewInstBefore(
7957 CastInst::createInferredCast(SI.getOperand(0), SrcPTy,
7958 SI.getOperand(0)->getName()+".c"), SI);
Chris Lattner72684fe2005-01-31 05:51:45 +00007959
7960 return new StoreInst(NewCast, CastOp);
7961 }
7962 }
7963 }
7964 return 0;
7965}
7966
Chris Lattner31f486c2005-01-31 05:36:43 +00007967Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
7968 Value *Val = SI.getOperand(0);
7969 Value *Ptr = SI.getOperand(1);
7970
7971 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner5997cf92006-02-08 03:25:32 +00007972 EraseInstFromFunction(SI);
Chris Lattner31f486c2005-01-31 05:36:43 +00007973 ++NumCombined;
7974 return 0;
7975 }
7976
Chris Lattner5997cf92006-02-08 03:25:32 +00007977 // Do really simple DSE, to catch cases where there are several consequtive
7978 // stores to the same location, separated by a few arithmetic operations. This
7979 // situation often occurs with bitfield accesses.
7980 BasicBlock::iterator BBI = &SI;
7981 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
7982 --ScanInsts) {
7983 --BBI;
7984
7985 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
7986 // Prev store isn't volatile, and stores to the same location?
7987 if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
7988 ++NumDeadStore;
7989 ++BBI;
7990 EraseInstFromFunction(*PrevSI);
7991 continue;
7992 }
7993 break;
7994 }
7995
Chris Lattnerdab43b22006-05-26 19:19:20 +00007996 // If this is a load, we have to stop. However, if the loaded value is from
7997 // the pointer we're loading and is producing the pointer we're storing,
7998 // then *this* store is dead (X = load P; store X -> P).
7999 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
8000 if (LI == Val && LI->getOperand(0) == Ptr) {
8001 EraseInstFromFunction(SI);
8002 ++NumCombined;
8003 return 0;
8004 }
8005 // Otherwise, this is a load from some other location. Stores before it
8006 // may not be dead.
8007 break;
8008 }
8009
Chris Lattner5997cf92006-02-08 03:25:32 +00008010 // Don't skip over loads or things that can modify memory.
Chris Lattnerdab43b22006-05-26 19:19:20 +00008011 if (BBI->mayWriteToMemory())
Chris Lattner5997cf92006-02-08 03:25:32 +00008012 break;
8013 }
8014
8015
8016 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner31f486c2005-01-31 05:36:43 +00008017
8018 // store X, null -> turns into 'unreachable' in SimplifyCFG
8019 if (isa<ConstantPointerNull>(Ptr)) {
8020 if (!isa<UndefValue>(Val)) {
8021 SI.setOperand(0, UndefValue::get(Val->getType()));
8022 if (Instruction *U = dyn_cast<Instruction>(Val))
8023 WorkList.push_back(U); // Dropped a use.
8024 ++NumCombined;
8025 }
8026 return 0; // Do not modify these!
8027 }
8028
8029 // store undef, Ptr -> noop
8030 if (isa<UndefValue>(Val)) {
Chris Lattner5997cf92006-02-08 03:25:32 +00008031 EraseInstFromFunction(SI);
Chris Lattner31f486c2005-01-31 05:36:43 +00008032 ++NumCombined;
8033 return 0;
8034 }
8035
Chris Lattner72684fe2005-01-31 05:51:45 +00008036 // If the pointer destination is a cast, see if we can fold the cast into the
8037 // source instead.
Reid Spencerde46e482006-11-02 20:25:50 +00008038 if (isa<CastInst>(Ptr))
Chris Lattner72684fe2005-01-31 05:51:45 +00008039 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
8040 return Res;
8041 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
Reid Spencer6c38f0b2006-11-27 01:05:10 +00008042 if (CE->isCast())
Chris Lattner72684fe2005-01-31 05:51:45 +00008043 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
8044 return Res;
8045
Chris Lattner219175c2005-09-12 23:23:25 +00008046
8047 // If this store is the last instruction in the basic block, and if the block
8048 // ends with an unconditional branch, try to move it to the successor block.
Chris Lattner5997cf92006-02-08 03:25:32 +00008049 BBI = &SI; ++BBI;
Chris Lattner219175c2005-09-12 23:23:25 +00008050 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
8051 if (BI->isUnconditional()) {
8052 // Check to see if the successor block has exactly two incoming edges. If
8053 // so, see if the other predecessor contains a store to the same location.
8054 // if so, insert a PHI node (if needed) and move the stores down.
8055 BasicBlock *Dest = BI->getSuccessor(0);
8056
8057 pred_iterator PI = pred_begin(Dest);
8058 BasicBlock *Other = 0;
8059 if (*PI != BI->getParent())
8060 Other = *PI;
8061 ++PI;
8062 if (PI != pred_end(Dest)) {
8063 if (*PI != BI->getParent())
8064 if (Other)
8065 Other = 0;
8066 else
8067 Other = *PI;
8068 if (++PI != pred_end(Dest))
8069 Other = 0;
8070 }
8071 if (Other) { // If only one other pred...
8072 BBI = Other->getTerminator();
8073 // Make sure this other block ends in an unconditional branch and that
8074 // there is an instruction before the branch.
8075 if (isa<BranchInst>(BBI) && cast<BranchInst>(BBI)->isUnconditional() &&
8076 BBI != Other->begin()) {
8077 --BBI;
8078 StoreInst *OtherStore = dyn_cast<StoreInst>(BBI);
8079
8080 // If this instruction is a store to the same location.
8081 if (OtherStore && OtherStore->getOperand(1) == SI.getOperand(1)) {
8082 // Okay, we know we can perform this transformation. Insert a PHI
8083 // node now if we need it.
8084 Value *MergedVal = OtherStore->getOperand(0);
8085 if (MergedVal != SI.getOperand(0)) {
8086 PHINode *PN = new PHINode(MergedVal->getType(), "storemerge");
8087 PN->reserveOperandSpace(2);
8088 PN->addIncoming(SI.getOperand(0), SI.getParent());
8089 PN->addIncoming(OtherStore->getOperand(0), Other);
8090 MergedVal = InsertNewInstBefore(PN, Dest->front());
8091 }
8092
8093 // Advance to a place where it is safe to insert the new store and
8094 // insert it.
8095 BBI = Dest->begin();
8096 while (isa<PHINode>(BBI)) ++BBI;
8097 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
8098 OtherStore->isVolatile()), *BBI);
8099
8100 // Nuke the old stores.
Chris Lattner5997cf92006-02-08 03:25:32 +00008101 EraseInstFromFunction(SI);
8102 EraseInstFromFunction(*OtherStore);
Chris Lattner219175c2005-09-12 23:23:25 +00008103 ++NumCombined;
8104 return 0;
8105 }
8106 }
8107 }
8108 }
8109
Chris Lattner31f486c2005-01-31 05:36:43 +00008110 return 0;
8111}
8112
8113
Chris Lattner9eef8a72003-06-04 04:46:00 +00008114Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
8115 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4fdd96c2005-06-18 17:37:34 +00008116 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00008117 BasicBlock *TrueDest;
8118 BasicBlock *FalseDest;
8119 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
8120 !isa<Constant>(X)) {
8121 // Swap Destinations and condition...
8122 BI.setCondition(X);
8123 BI.setSuccessor(0, FalseDest);
8124 BI.setSuccessor(1, TrueDest);
8125 return &BI;
8126 }
8127
8128 // Cannonicalize setne -> seteq
8129 Instruction::BinaryOps Op; Value *Y;
8130 if (match(&BI, m_Br(m_SetCond(Op, m_Value(X), m_Value(Y)),
8131 TrueDest, FalseDest)))
8132 if ((Op == Instruction::SetNE || Op == Instruction::SetLE ||
8133 Op == Instruction::SetGE) && BI.getCondition()->hasOneUse()) {
8134 SetCondInst *I = cast<SetCondInst>(BI.getCondition());
8135 std::string Name = I->getName(); I->setName("");
8136 Instruction::BinaryOps NewOpcode = SetCondInst::getInverseCondition(Op);
8137 Value *NewSCC = BinaryOperator::create(NewOpcode, X, Y, Name, I);
Chris Lattnere967b342003-06-04 05:10:11 +00008138 // Swap Destinations and condition...
Chris Lattnerd4252a72004-07-30 07:50:03 +00008139 BI.setCondition(NewSCC);
Chris Lattnere967b342003-06-04 05:10:11 +00008140 BI.setSuccessor(0, FalseDest);
8141 BI.setSuccessor(1, TrueDest);
Chris Lattnerd4252a72004-07-30 07:50:03 +00008142 removeFromWorkList(I);
8143 I->getParent()->getInstList().erase(I);
8144 WorkList.push_back(cast<Instruction>(NewSCC));
Chris Lattnere967b342003-06-04 05:10:11 +00008145 return &BI;
8146 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00008147
Chris Lattner9eef8a72003-06-04 04:46:00 +00008148 return 0;
8149}
Chris Lattner1085bdf2002-11-04 16:18:53 +00008150
Chris Lattner4c9c20a2004-07-03 00:26:11 +00008151Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
8152 Value *Cond = SI.getCondition();
8153 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
8154 if (I->getOpcode() == Instruction::Add)
8155 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
8156 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
8157 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattner81a7a232004-10-16 18:11:37 +00008158 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner4c9c20a2004-07-03 00:26:11 +00008159 AddRHS));
8160 SI.setOperand(0, I->getOperand(0));
8161 WorkList.push_back(I);
8162 return &SI;
8163 }
8164 }
8165 return 0;
8166}
8167
Chris Lattner6bc98652006-03-05 00:22:33 +00008168/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
8169/// is to leave as a vector operation.
8170static bool CheapToScalarize(Value *V, bool isConstant) {
8171 if (isa<ConstantAggregateZero>(V))
8172 return true;
8173 if (ConstantPacked *C = dyn_cast<ConstantPacked>(V)) {
8174 if (isConstant) return true;
8175 // If all elts are the same, we can extract.
8176 Constant *Op0 = C->getOperand(0);
8177 for (unsigned i = 1; i < C->getNumOperands(); ++i)
8178 if (C->getOperand(i) != Op0)
8179 return false;
8180 return true;
8181 }
8182 Instruction *I = dyn_cast<Instruction>(V);
8183 if (!I) return false;
8184
8185 // Insert element gets simplified to the inserted element or is deleted if
8186 // this is constant idx extract element and its a constant idx insertelt.
8187 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
8188 isa<ConstantInt>(I->getOperand(2)))
8189 return true;
8190 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
8191 return true;
8192 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
8193 if (BO->hasOneUse() &&
8194 (CheapToScalarize(BO->getOperand(0), isConstant) ||
8195 CheapToScalarize(BO->getOperand(1), isConstant)))
8196 return true;
8197
8198 return false;
8199}
8200
Chris Lattner12249be2006-05-25 23:48:38 +00008201/// getShuffleMask - Read and decode a shufflevector mask. It turns undef
8202/// elements into values that are larger than the #elts in the input.
8203static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
8204 unsigned NElts = SVI->getType()->getNumElements();
8205 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
8206 return std::vector<unsigned>(NElts, 0);
8207 if (isa<UndefValue>(SVI->getOperand(2)))
8208 return std::vector<unsigned>(NElts, 2*NElts);
8209
8210 std::vector<unsigned> Result;
8211 const ConstantPacked *CP = cast<ConstantPacked>(SVI->getOperand(2));
8212 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
8213 if (isa<UndefValue>(CP->getOperand(i)))
8214 Result.push_back(NElts*2); // undef -> 8
8215 else
Reid Spencere0fc4df2006-10-20 07:07:24 +00008216 Result.push_back(cast<ConstantInt>(CP->getOperand(i))->getZExtValue());
Chris Lattner12249be2006-05-25 23:48:38 +00008217 return Result;
8218}
8219
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008220/// FindScalarElement - Given a vector and an element number, see if the scalar
8221/// value is already around as a register, for example if it were inserted then
8222/// extracted from the vector.
8223static Value *FindScalarElement(Value *V, unsigned EltNo) {
8224 assert(isa<PackedType>(V->getType()) && "Not looking at a vector?");
8225 const PackedType *PTy = cast<PackedType>(V->getType());
Chris Lattner2d37f922006-04-10 23:06:36 +00008226 unsigned Width = PTy->getNumElements();
8227 if (EltNo >= Width) // Out of range access.
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008228 return UndefValue::get(PTy->getElementType());
8229
8230 if (isa<UndefValue>(V))
8231 return UndefValue::get(PTy->getElementType());
8232 else if (isa<ConstantAggregateZero>(V))
8233 return Constant::getNullValue(PTy->getElementType());
8234 else if (ConstantPacked *CP = dyn_cast<ConstantPacked>(V))
8235 return CP->getOperand(EltNo);
8236 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
8237 // If this is an insert to a variable element, we don't know what it is.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008238 if (!isa<ConstantInt>(III->getOperand(2)))
8239 return 0;
8240 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008241
8242 // If this is an insert to the element we are looking for, return the
8243 // inserted value.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008244 if (EltNo == IIElt)
8245 return III->getOperand(1);
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008246
8247 // Otherwise, the insertelement doesn't modify the value, recurse on its
8248 // vector input.
8249 return FindScalarElement(III->getOperand(0), EltNo);
Chris Lattner2d37f922006-04-10 23:06:36 +00008250 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Chris Lattner12249be2006-05-25 23:48:38 +00008251 unsigned InEl = getShuffleMask(SVI)[EltNo];
8252 if (InEl < Width)
8253 return FindScalarElement(SVI->getOperand(0), InEl);
8254 else if (InEl < Width*2)
8255 return FindScalarElement(SVI->getOperand(1), InEl - Width);
8256 else
8257 return UndefValue::get(PTy->getElementType());
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008258 }
8259
8260 // Otherwise, we don't know.
8261 return 0;
8262}
8263
Robert Bocchinoa8352962006-01-13 22:48:06 +00008264Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008265
Chris Lattner92346c32006-03-31 18:25:14 +00008266 // If packed val is undef, replace extract with scalar undef.
8267 if (isa<UndefValue>(EI.getOperand(0)))
8268 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
8269
8270 // If packed val is constant 0, replace extract with scalar 0.
8271 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
8272 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
8273
Robert Bocchinoa8352962006-01-13 22:48:06 +00008274 if (ConstantPacked *C = dyn_cast<ConstantPacked>(EI.getOperand(0))) {
8275 // If packed val is constant with uniform operands, replace EI
8276 // with that operand
Chris Lattner6bc98652006-03-05 00:22:33 +00008277 Constant *op0 = C->getOperand(0);
Robert Bocchinoa8352962006-01-13 22:48:06 +00008278 for (unsigned i = 1; i < C->getNumOperands(); ++i)
Chris Lattner6bc98652006-03-05 00:22:33 +00008279 if (C->getOperand(i) != op0) {
8280 op0 = 0;
8281 break;
8282 }
8283 if (op0)
8284 return ReplaceInstUsesWith(EI, op0);
Robert Bocchinoa8352962006-01-13 22:48:06 +00008285 }
Chris Lattner6bc98652006-03-05 00:22:33 +00008286
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008287 // If extracting a specified index from the vector, see if we can recursively
8288 // find a previously computed scalar that was inserted into the vector.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008289 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Chris Lattner2deeaea2006-10-05 06:55:50 +00008290 // This instruction only demands the single element from the input vector.
8291 // If the input vector has a single use, simplify it based on this use
8292 // property.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008293 uint64_t IndexVal = IdxC->getZExtValue();
Chris Lattner2deeaea2006-10-05 06:55:50 +00008294 if (EI.getOperand(0)->hasOneUse()) {
8295 uint64_t UndefElts;
8296 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Reid Spencere0fc4df2006-10-20 07:07:24 +00008297 1 << IndexVal,
Chris Lattner2deeaea2006-10-05 06:55:50 +00008298 UndefElts)) {
8299 EI.setOperand(0, V);
8300 return &EI;
8301 }
8302 }
8303
Reid Spencere0fc4df2006-10-20 07:07:24 +00008304 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008305 return ReplaceInstUsesWith(EI, Elt);
Chris Lattner2d37f922006-04-10 23:06:36 +00008306 }
Chris Lattner8d1d8d32006-03-31 23:01:56 +00008307
Chris Lattner83f65782006-05-25 22:53:38 +00008308 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Robert Bocchinoa8352962006-01-13 22:48:06 +00008309 if (I->hasOneUse()) {
8310 // Push extractelement into predecessor operation if legal and
8311 // profitable to do so
8312 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Chris Lattner6bc98652006-03-05 00:22:33 +00008313 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
8314 if (CheapToScalarize(BO, isConstantElt)) {
8315 ExtractElementInst *newEI0 =
8316 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
8317 EI.getName()+".lhs");
8318 ExtractElementInst *newEI1 =
8319 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
8320 EI.getName()+".rhs");
8321 InsertNewInstBefore(newEI0, EI);
8322 InsertNewInstBefore(newEI1, EI);
8323 return BinaryOperator::create(BO->getOpcode(), newEI0, newEI1);
8324 }
Reid Spencerde46e482006-11-02 20:25:50 +00008325 } else if (isa<LoadInst>(I)) {
Reid Spencer13bc5d72006-12-12 09:18:51 +00008326 Value *Ptr = InsertCastBefore(Instruction::BitCast, I->getOperand(0),
Robert Bocchinoa8352962006-01-13 22:48:06 +00008327 PointerType::get(EI.getType()), EI);
8328 GetElementPtrInst *GEP =
Reid Spencera736fdf2006-11-29 01:11:01 +00008329 new GetElementPtrInst(Ptr, EI.getOperand(1), I->getName() + ".gep");
Robert Bocchinoa8352962006-01-13 22:48:06 +00008330 InsertNewInstBefore(GEP, EI);
8331 return new LoadInst(GEP);
Chris Lattner83f65782006-05-25 22:53:38 +00008332 }
8333 }
8334 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
8335 // Extracting the inserted element?
8336 if (IE->getOperand(2) == EI.getOperand(1))
8337 return ReplaceInstUsesWith(EI, IE->getOperand(1));
8338 // If the inserted and extracted elements are constants, they must not
8339 // be the same value, extract from the pre-inserted value instead.
8340 if (isa<Constant>(IE->getOperand(2)) &&
8341 isa<Constant>(EI.getOperand(1))) {
8342 AddUsesToWorkList(EI);
8343 EI.setOperand(0, IE->getOperand(0));
8344 return &EI;
8345 }
8346 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
8347 // If this is extracting an element from a shufflevector, figure out where
8348 // it came from and extract from the appropriate input element instead.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008349 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
8350 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
Chris Lattner12249be2006-05-25 23:48:38 +00008351 Value *Src;
8352 if (SrcIdx < SVI->getType()->getNumElements())
8353 Src = SVI->getOperand(0);
8354 else if (SrcIdx < SVI->getType()->getNumElements()*2) {
8355 SrcIdx -= SVI->getType()->getNumElements();
8356 Src = SVI->getOperand(1);
8357 } else {
8358 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattner612fa8e2006-03-30 22:02:40 +00008359 }
Chris Lattner2deeaea2006-10-05 06:55:50 +00008360 return new ExtractElementInst(Src, SrcIdx);
Robert Bocchinoa8352962006-01-13 22:48:06 +00008361 }
8362 }
Chris Lattner83f65782006-05-25 22:53:38 +00008363 }
Robert Bocchinoa8352962006-01-13 22:48:06 +00008364 return 0;
8365}
8366
Chris Lattner90951862006-04-16 00:51:47 +00008367/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
8368/// elements from either LHS or RHS, return the shuffle mask and true.
8369/// Otherwise, return false.
8370static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
8371 std::vector<Constant*> &Mask) {
8372 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
8373 "Invalid CollectSingleShuffleElements");
8374 unsigned NumElts = cast<PackedType>(V->getType())->getNumElements();
8375
8376 if (isa<UndefValue>(V)) {
8377 Mask.assign(NumElts, UndefValue::get(Type::UIntTy));
8378 return true;
8379 } else if (V == LHS) {
8380 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencere0fc4df2006-10-20 07:07:24 +00008381 Mask.push_back(ConstantInt::get(Type::UIntTy, i));
Chris Lattner90951862006-04-16 00:51:47 +00008382 return true;
8383 } else if (V == RHS) {
8384 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencere0fc4df2006-10-20 07:07:24 +00008385 Mask.push_back(ConstantInt::get(Type::UIntTy, i+NumElts));
Chris Lattner90951862006-04-16 00:51:47 +00008386 return true;
8387 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
8388 // If this is an insert of an extract from some other vector, include it.
8389 Value *VecOp = IEI->getOperand(0);
8390 Value *ScalarOp = IEI->getOperand(1);
8391 Value *IdxOp = IEI->getOperand(2);
8392
Chris Lattnerb6cb64b2006-04-27 21:14:21 +00008393 if (!isa<ConstantInt>(IdxOp))
8394 return false;
Reid Spencere0fc4df2006-10-20 07:07:24 +00008395 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerb6cb64b2006-04-27 21:14:21 +00008396
8397 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
8398 // Okay, we can handle this if the vector we are insertinting into is
8399 // transitively ok.
8400 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
8401 // If so, update the mask to reflect the inserted undef.
8402 Mask[InsertedIdx] = UndefValue::get(Type::UIntTy);
8403 return true;
8404 }
8405 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
8406 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner90951862006-04-16 00:51:47 +00008407 EI->getOperand(0)->getType() == V->getType()) {
8408 unsigned ExtractedIdx =
Reid Spencere0fc4df2006-10-20 07:07:24 +00008409 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattner90951862006-04-16 00:51:47 +00008410
8411 // This must be extracting from either LHS or RHS.
8412 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
8413 // Okay, we can handle this if the vector we are insertinting into is
8414 // transitively ok.
8415 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
8416 // If so, update the mask to reflect the inserted value.
8417 if (EI->getOperand(0) == LHS) {
8418 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencere0fc4df2006-10-20 07:07:24 +00008419 ConstantInt::get(Type::UIntTy, ExtractedIdx);
Chris Lattner90951862006-04-16 00:51:47 +00008420 } else {
8421 assert(EI->getOperand(0) == RHS);
8422 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencere0fc4df2006-10-20 07:07:24 +00008423 ConstantInt::get(Type::UIntTy, ExtractedIdx+NumElts);
Chris Lattner90951862006-04-16 00:51:47 +00008424
8425 }
8426 return true;
8427 }
8428 }
8429 }
8430 }
8431 }
8432 // TODO: Handle shufflevector here!
8433
8434 return false;
8435}
8436
8437/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
8438/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
8439/// that computes V and the LHS value of the shuffle.
Chris Lattner39fac442006-04-15 01:39:45 +00008440static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Chris Lattner90951862006-04-16 00:51:47 +00008441 Value *&RHS) {
8442 assert(isa<PackedType>(V->getType()) &&
8443 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattner39fac442006-04-15 01:39:45 +00008444 "Invalid shuffle!");
8445 unsigned NumElts = cast<PackedType>(V->getType())->getNumElements();
8446
8447 if (isa<UndefValue>(V)) {
8448 Mask.assign(NumElts, UndefValue::get(Type::UIntTy));
8449 return V;
8450 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00008451 Mask.assign(NumElts, ConstantInt::get(Type::UIntTy, 0));
Chris Lattner39fac442006-04-15 01:39:45 +00008452 return V;
8453 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
8454 // If this is an insert of an extract from some other vector, include it.
8455 Value *VecOp = IEI->getOperand(0);
8456 Value *ScalarOp = IEI->getOperand(1);
8457 Value *IdxOp = IEI->getOperand(2);
8458
8459 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
8460 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
8461 EI->getOperand(0)->getType() == V->getType()) {
8462 unsigned ExtractedIdx =
Reid Spencere0fc4df2006-10-20 07:07:24 +00008463 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
8464 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattner39fac442006-04-15 01:39:45 +00008465
8466 // Either the extracted from or inserted into vector must be RHSVec,
8467 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner90951862006-04-16 00:51:47 +00008468 if (EI->getOperand(0) == RHS || RHS == 0) {
8469 RHS = EI->getOperand(0);
8470 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
Chris Lattner39fac442006-04-15 01:39:45 +00008471 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencere0fc4df2006-10-20 07:07:24 +00008472 ConstantInt::get(Type::UIntTy, NumElts+ExtractedIdx);
Chris Lattner39fac442006-04-15 01:39:45 +00008473 return V;
8474 }
8475
Chris Lattner90951862006-04-16 00:51:47 +00008476 if (VecOp == RHS) {
8477 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
Chris Lattner39fac442006-04-15 01:39:45 +00008478 // Everything but the extracted element is replaced with the RHS.
8479 for (unsigned i = 0; i != NumElts; ++i) {
8480 if (i != InsertedIdx)
Reid Spencere0fc4df2006-10-20 07:07:24 +00008481 Mask[i] = ConstantInt::get(Type::UIntTy, NumElts+i);
Chris Lattner39fac442006-04-15 01:39:45 +00008482 }
8483 return V;
8484 }
Chris Lattner90951862006-04-16 00:51:47 +00008485
8486 // If this insertelement is a chain that comes from exactly these two
8487 // vectors, return the vector and the effective shuffle.
8488 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
8489 return EI->getOperand(0);
8490
Chris Lattner39fac442006-04-15 01:39:45 +00008491 }
8492 }
8493 }
Chris Lattner90951862006-04-16 00:51:47 +00008494 // TODO: Handle shufflevector here!
Chris Lattner39fac442006-04-15 01:39:45 +00008495
8496 // Otherwise, can't do anything fancy. Return an identity vector.
8497 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencere0fc4df2006-10-20 07:07:24 +00008498 Mask.push_back(ConstantInt::get(Type::UIntTy, i));
Chris Lattner39fac442006-04-15 01:39:45 +00008499 return V;
8500}
8501
8502Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
8503 Value *VecOp = IE.getOperand(0);
8504 Value *ScalarOp = IE.getOperand(1);
8505 Value *IdxOp = IE.getOperand(2);
8506
8507 // If the inserted element was extracted from some other vector, and if the
8508 // indexes are constant, try to turn this into a shufflevector operation.
8509 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
8510 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
8511 EI->getOperand(0)->getType() == IE.getType()) {
8512 unsigned NumVectorElts = IE.getType()->getNumElements();
Reid Spencere0fc4df2006-10-20 07:07:24 +00008513 unsigned ExtractedIdx=cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
8514 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattner39fac442006-04-15 01:39:45 +00008515
8516 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
8517 return ReplaceInstUsesWith(IE, VecOp);
8518
8519 if (InsertedIdx >= NumVectorElts) // Out of range insert.
8520 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
8521
8522 // If we are extracting a value from a vector, then inserting it right
8523 // back into the same place, just use the input vector.
8524 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
8525 return ReplaceInstUsesWith(IE, VecOp);
8526
8527 // We could theoretically do this for ANY input. However, doing so could
8528 // turn chains of insertelement instructions into a chain of shufflevector
8529 // instructions, and right now we do not merge shufflevectors. As such,
8530 // only do this in a situation where it is clear that there is benefit.
8531 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
8532 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
8533 // the values of VecOp, except then one read from EIOp0.
8534 // Build a new shuffle mask.
8535 std::vector<Constant*> Mask;
8536 if (isa<UndefValue>(VecOp))
8537 Mask.assign(NumVectorElts, UndefValue::get(Type::UIntTy));
8538 else {
8539 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
Reid Spencere0fc4df2006-10-20 07:07:24 +00008540 Mask.assign(NumVectorElts, ConstantInt::get(Type::UIntTy,
Chris Lattner39fac442006-04-15 01:39:45 +00008541 NumVectorElts));
8542 }
Reid Spencere0fc4df2006-10-20 07:07:24 +00008543 Mask[InsertedIdx] = ConstantInt::get(Type::UIntTy, ExtractedIdx);
Chris Lattner39fac442006-04-15 01:39:45 +00008544 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
8545 ConstantPacked::get(Mask));
8546 }
8547
8548 // If this insertelement isn't used by some other insertelement, turn it
8549 // (and any insertelements it points to), into one big shuffle.
8550 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
8551 std::vector<Constant*> Mask;
Chris Lattner90951862006-04-16 00:51:47 +00008552 Value *RHS = 0;
8553 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
8554 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
8555 // We now have a shuffle of LHS, RHS, Mask.
8556 return new ShuffleVectorInst(LHS, RHS, ConstantPacked::get(Mask));
Chris Lattner39fac442006-04-15 01:39:45 +00008557 }
8558 }
8559 }
8560
8561 return 0;
8562}
8563
8564
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008565Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
8566 Value *LHS = SVI.getOperand(0);
8567 Value *RHS = SVI.getOperand(1);
Chris Lattner12249be2006-05-25 23:48:38 +00008568 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008569
8570 bool MadeChange = false;
8571
Chris Lattner2deeaea2006-10-05 06:55:50 +00008572 // Undefined shuffle mask -> undefined value.
Chris Lattner12249be2006-05-25 23:48:38 +00008573 if (isa<UndefValue>(SVI.getOperand(2)))
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008574 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
8575
Chris Lattner39fac442006-04-15 01:39:45 +00008576 // TODO: If we have shuffle(x, undef, mask) and any elements of mask refer to
8577 // the undef, change them to undefs.
8578
Chris Lattner12249be2006-05-25 23:48:38 +00008579 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
8580 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
8581 if (LHS == RHS || isa<UndefValue>(LHS)) {
8582 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008583 // shuffle(undef,undef,mask) -> undef.
8584 return ReplaceInstUsesWith(SVI, LHS);
8585 }
8586
Chris Lattner12249be2006-05-25 23:48:38 +00008587 // Remap any references to RHS to use LHS.
8588 std::vector<Constant*> Elts;
8589 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner0e477162006-05-26 00:29:06 +00008590 if (Mask[i] >= 2*e)
Chris Lattner12249be2006-05-25 23:48:38 +00008591 Elts.push_back(UndefValue::get(Type::UIntTy));
Chris Lattner0e477162006-05-26 00:29:06 +00008592 else {
8593 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
8594 (Mask[i] < e && isa<UndefValue>(LHS)))
8595 Mask[i] = 2*e; // Turn into undef.
8596 else
8597 Mask[i] &= (e-1); // Force to LHS.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008598 Elts.push_back(ConstantInt::get(Type::UIntTy, Mask[i]));
Chris Lattner0e477162006-05-26 00:29:06 +00008599 }
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008600 }
Chris Lattner12249be2006-05-25 23:48:38 +00008601 SVI.setOperand(0, SVI.getOperand(1));
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008602 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Chris Lattner12249be2006-05-25 23:48:38 +00008603 SVI.setOperand(2, ConstantPacked::get(Elts));
Chris Lattner0e477162006-05-26 00:29:06 +00008604 LHS = SVI.getOperand(0);
8605 RHS = SVI.getOperand(1);
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008606 MadeChange = true;
8607 }
8608
Chris Lattner0e477162006-05-26 00:29:06 +00008609 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner12249be2006-05-25 23:48:38 +00008610 bool isLHSID = true, isRHSID = true;
Chris Lattner34cebe72006-04-16 00:03:56 +00008611
Chris Lattner12249be2006-05-25 23:48:38 +00008612 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
8613 if (Mask[i] >= e*2) continue; // Ignore undef values.
8614 // Is this an identity shuffle of the LHS value?
8615 isLHSID &= (Mask[i] == i);
8616
8617 // Is this an identity shuffle of the RHS value?
8618 isRHSID &= (Mask[i]-e == i);
Chris Lattner34cebe72006-04-16 00:03:56 +00008619 }
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008620
Chris Lattner12249be2006-05-25 23:48:38 +00008621 // Eliminate identity shuffles.
8622 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
8623 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008624
Chris Lattner0e477162006-05-26 00:29:06 +00008625 // If the LHS is a shufflevector itself, see if we can combine it with this
8626 // one without producing an unusual shuffle. Here we are really conservative:
8627 // we are absolutely afraid of producing a shuffle mask not in the input
8628 // program, because the code gen may not be smart enough to turn a merged
8629 // shuffle into two specific shuffles: it may produce worse code. As such,
8630 // we only merge two shuffles if the result is one of the two input shuffle
8631 // masks. In this case, merging the shuffles just removes one instruction,
8632 // which we know is safe. This is good for things like turning:
8633 // (splat(splat)) -> splat.
8634 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
8635 if (isa<UndefValue>(RHS)) {
8636 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
8637
8638 std::vector<unsigned> NewMask;
8639 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
8640 if (Mask[i] >= 2*e)
8641 NewMask.push_back(2*e);
8642 else
8643 NewMask.push_back(LHSMask[Mask[i]]);
8644
8645 // If the result mask is equal to the src shuffle or this shuffle mask, do
8646 // the replacement.
8647 if (NewMask == LHSMask || NewMask == Mask) {
8648 std::vector<Constant*> Elts;
8649 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
8650 if (NewMask[i] >= e*2) {
8651 Elts.push_back(UndefValue::get(Type::UIntTy));
8652 } else {
Reid Spencere0fc4df2006-10-20 07:07:24 +00008653 Elts.push_back(ConstantInt::get(Type::UIntTy, NewMask[i]));
Chris Lattner0e477162006-05-26 00:29:06 +00008654 }
8655 }
8656 return new ShuffleVectorInst(LHSSVI->getOperand(0),
8657 LHSSVI->getOperand(1),
8658 ConstantPacked::get(Elts));
8659 }
8660 }
8661 }
8662
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008663 return MadeChange ? &SVI : 0;
8664}
8665
8666
Robert Bocchinoa8352962006-01-13 22:48:06 +00008667
Chris Lattner99f48c62002-09-02 04:59:56 +00008668void InstCombiner::removeFromWorkList(Instruction *I) {
8669 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
8670 WorkList.end());
8671}
8672
Chris Lattner39c98bb2004-12-08 23:43:58 +00008673
8674/// TryToSinkInstruction - Try to move the specified instruction from its
8675/// current block into the beginning of DestBlock, which can only happen if it's
8676/// safe to move the instruction past all of the instructions between it and the
8677/// end of its block.
8678static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
8679 assert(I->hasOneUse() && "Invariants didn't hold!");
8680
Chris Lattnerc4f67e62005-10-27 17:13:11 +00008681 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
8682 if (isa<PHINode>(I) || I->mayWriteToMemory()) return false;
Misha Brukmanb1c93172005-04-21 23:48:37 +00008683
Chris Lattner39c98bb2004-12-08 23:43:58 +00008684 // Do not sink alloca instructions out of the entry block.
8685 if (isa<AllocaInst>(I) && I->getParent() == &DestBlock->getParent()->front())
8686 return false;
8687
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00008688 // We can only sink load instructions if there is nothing between the load and
8689 // the end of block that could change the value.
8690 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00008691 for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
8692 Scan != E; ++Scan)
8693 if (Scan->mayWriteToMemory())
8694 return false;
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00008695 }
Chris Lattner39c98bb2004-12-08 23:43:58 +00008696
8697 BasicBlock::iterator InsertPos = DestBlock->begin();
8698 while (isa<PHINode>(InsertPos)) ++InsertPos;
8699
Chris Lattner9f269e42005-08-08 19:11:57 +00008700 I->moveBefore(InsertPos);
Chris Lattner39c98bb2004-12-08 23:43:58 +00008701 ++NumSunkInst;
8702 return true;
8703}
8704
Chris Lattner1443bc52006-05-11 17:11:52 +00008705/// OptimizeConstantExpr - Given a constant expression and target data layout
Reid Spencer13bc5d72006-12-12 09:18:51 +00008706/// information, symbolically evaluate the constant expr to something simpler
Chris Lattner1443bc52006-05-11 17:11:52 +00008707/// if possible.
8708static Constant *OptimizeConstantExpr(ConstantExpr *CE, const TargetData *TD) {
8709 if (!TD) return CE;
8710
8711 Constant *Ptr = CE->getOperand(0);
8712 if (CE->getOpcode() == Instruction::GetElementPtr && Ptr->isNullValue() &&
8713 cast<PointerType>(Ptr->getType())->getElementType()->isSized()) {
8714 // If this is a constant expr gep that is effectively computing an
8715 // "offsetof", fold it into 'cast int Size to T*' instead of 'gep 0, 0, 12'
8716 bool isFoldableGEP = true;
8717 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
8718 if (!isa<ConstantInt>(CE->getOperand(i)))
8719 isFoldableGEP = false;
8720 if (isFoldableGEP) {
8721 std::vector<Value*> Ops(CE->op_begin()+1, CE->op_end());
8722 uint64_t Offset = TD->getIndexedOffset(Ptr->getType(), Ops);
Reid Spencere0fc4df2006-10-20 07:07:24 +00008723 Constant *C = ConstantInt::get(Type::ULongTy, Offset);
Reid Spencer13bc5d72006-12-12 09:18:51 +00008724 C = ConstantExpr::getIntegerCast(C, TD->getIntPtrType(), true /*SExt*/);
8725 return ConstantExpr::getIntToPtr(C, CE->getType());
Chris Lattner1443bc52006-05-11 17:11:52 +00008726 }
8727 }
8728
8729 return CE;
8730}
8731
Chris Lattnera36ee4e2006-05-10 19:00:36 +00008732
8733/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
8734/// all reachable code to the worklist.
8735///
8736/// This has a couple of tricks to make the code faster and more powerful. In
8737/// particular, we constant fold and DCE instructions as we go, to avoid adding
8738/// them to the worklist (this significantly speeds up instcombine on code where
8739/// many instructions are dead or constant). Additionally, if we find a branch
8740/// whose condition is a known constant, we only visit the reachable successors.
8741///
8742static void AddReachableCodeToWorklist(BasicBlock *BB,
8743 std::set<BasicBlock*> &Visited,
Chris Lattner1443bc52006-05-11 17:11:52 +00008744 std::vector<Instruction*> &WorkList,
8745 const TargetData *TD) {
Chris Lattnera36ee4e2006-05-10 19:00:36 +00008746 // We have now visited this block! If we've already been here, bail out.
8747 if (!Visited.insert(BB).second) return;
8748
8749 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
8750 Instruction *Inst = BBI++;
8751
8752 // DCE instruction if trivially dead.
8753 if (isInstructionTriviallyDead(Inst)) {
8754 ++NumDeadInst;
Bill Wendling5dbf43c2006-11-26 09:46:52 +00008755 DOUT << "IC: DCE: " << *Inst;
Chris Lattnera36ee4e2006-05-10 19:00:36 +00008756 Inst->eraseFromParent();
8757 continue;
8758 }
8759
8760 // ConstantProp instruction if trivially constant.
8761 if (Constant *C = ConstantFoldInstruction(Inst)) {
Chris Lattner1443bc52006-05-11 17:11:52 +00008762 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
8763 C = OptimizeConstantExpr(CE, TD);
Bill Wendling5dbf43c2006-11-26 09:46:52 +00008764 DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
Chris Lattnera36ee4e2006-05-10 19:00:36 +00008765 Inst->replaceAllUsesWith(C);
8766 ++NumConstProp;
8767 Inst->eraseFromParent();
8768 continue;
8769 }
8770
8771 WorkList.push_back(Inst);
8772 }
8773
8774 // Recursively visit successors. If this is a branch or switch on a constant,
8775 // only visit the reachable successor.
8776 TerminatorInst *TI = BB->getTerminator();
8777 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
8778 if (BI->isConditional() && isa<ConstantBool>(BI->getCondition())) {
8779 bool CondVal = cast<ConstantBool>(BI->getCondition())->getValue();
Chris Lattner1443bc52006-05-11 17:11:52 +00008780 AddReachableCodeToWorklist(BI->getSuccessor(!CondVal), Visited, WorkList,
8781 TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00008782 return;
8783 }
8784 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
8785 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
8786 // See if this is an explicit destination.
8787 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
8788 if (SI->getCaseValue(i) == Cond) {
Chris Lattner1443bc52006-05-11 17:11:52 +00008789 AddReachableCodeToWorklist(SI->getSuccessor(i), Visited, WorkList,TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00008790 return;
8791 }
8792
8793 // Otherwise it is the default destination.
Chris Lattner1443bc52006-05-11 17:11:52 +00008794 AddReachableCodeToWorklist(SI->getSuccessor(0), Visited, WorkList, TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00008795 return;
8796 }
8797 }
8798
8799 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
Chris Lattner1443bc52006-05-11 17:11:52 +00008800 AddReachableCodeToWorklist(TI->getSuccessor(i), Visited, WorkList, TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00008801}
8802
Chris Lattner113f4f42002-06-25 16:13:24 +00008803bool InstCombiner::runOnFunction(Function &F) {
Chris Lattner260ab202002-04-18 17:39:14 +00008804 bool Changed = false;
Chris Lattnerf4ad1652003-11-02 05:57:39 +00008805 TD = &getAnalysis<TargetData>();
Chris Lattnerca081252001-12-14 16:52:21 +00008806
Chris Lattner4ed40f72005-07-07 20:40:38 +00008807 {
Chris Lattnera36ee4e2006-05-10 19:00:36 +00008808 // Do a depth-first traversal of the function, populate the worklist with
8809 // the reachable instructions. Ignore blocks that are not reachable. Keep
8810 // track of which blocks we visit.
Chris Lattner4ed40f72005-07-07 20:40:38 +00008811 std::set<BasicBlock*> Visited;
Chris Lattner1443bc52006-05-11 17:11:52 +00008812 AddReachableCodeToWorklist(F.begin(), Visited, WorkList, TD);
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00008813
Chris Lattner4ed40f72005-07-07 20:40:38 +00008814 // Do a quick scan over the function. If we find any blocks that are
8815 // unreachable, remove any instructions inside of them. This prevents
8816 // the instcombine code from having to deal with some bad special cases.
8817 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
8818 if (!Visited.count(BB)) {
8819 Instruction *Term = BB->getTerminator();
8820 while (Term != BB->begin()) { // Remove instrs bottom-up
8821 BasicBlock::iterator I = Term; --I;
Chris Lattner2d3a7a62004-04-27 15:13:33 +00008822
Bill Wendling5dbf43c2006-11-26 09:46:52 +00008823 DOUT << "IC: DCE: " << *I;
Chris Lattner4ed40f72005-07-07 20:40:38 +00008824 ++NumDeadInst;
8825
8826 if (!I->use_empty())
8827 I->replaceAllUsesWith(UndefValue::get(I->getType()));
8828 I->eraseFromParent();
8829 }
8830 }
8831 }
Chris Lattnerca081252001-12-14 16:52:21 +00008832
8833 while (!WorkList.empty()) {
8834 Instruction *I = WorkList.back(); // Get an instruction from the worklist
8835 WorkList.pop_back();
8836
Chris Lattner1443bc52006-05-11 17:11:52 +00008837 // Check to see if we can DCE the instruction.
Chris Lattner99f48c62002-09-02 04:59:56 +00008838 if (isInstructionTriviallyDead(I)) {
Chris Lattner1443bc52006-05-11 17:11:52 +00008839 // Add operands to the worklist.
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00008840 if (I->getNumOperands() < 4)
Chris Lattner51ea1272004-02-28 05:22:00 +00008841 AddUsesToWorkList(*I);
Chris Lattner99f48c62002-09-02 04:59:56 +00008842 ++NumDeadInst;
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00008843
Bill Wendling5dbf43c2006-11-26 09:46:52 +00008844 DOUT << "IC: DCE: " << *I;
Chris Lattnercd517ff2005-01-28 19:32:01 +00008845
8846 I->eraseFromParent();
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00008847 removeFromWorkList(I);
8848 continue;
8849 }
Chris Lattner99f48c62002-09-02 04:59:56 +00008850
Chris Lattner1443bc52006-05-11 17:11:52 +00008851 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattner99f48c62002-09-02 04:59:56 +00008852 if (Constant *C = ConstantFoldInstruction(I)) {
Chris Lattner1443bc52006-05-11 17:11:52 +00008853 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
8854 C = OptimizeConstantExpr(CE, TD);
Bill Wendling5dbf43c2006-11-26 09:46:52 +00008855 DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
Chris Lattnercd517ff2005-01-28 19:32:01 +00008856
Chris Lattner1443bc52006-05-11 17:11:52 +00008857 // Add operands to the worklist.
Chris Lattner51ea1272004-02-28 05:22:00 +00008858 AddUsesToWorkList(*I);
Chris Lattnerc6509f42002-12-05 22:41:53 +00008859 ReplaceInstUsesWith(*I, C);
8860
Chris Lattner99f48c62002-09-02 04:59:56 +00008861 ++NumConstProp;
Chris Lattnera36ee4e2006-05-10 19:00:36 +00008862 I->eraseFromParent();
Chris Lattner800aaaf2003-10-07 15:17:02 +00008863 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00008864 continue;
Chris Lattner99f48c62002-09-02 04:59:56 +00008865 }
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00008866
Chris Lattner39c98bb2004-12-08 23:43:58 +00008867 // See if we can trivially sink this instruction to a successor basic block.
8868 if (I->hasOneUse()) {
8869 BasicBlock *BB = I->getParent();
8870 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
8871 if (UserParent != BB) {
8872 bool UserIsSuccessor = false;
8873 // See if the user is one of our successors.
8874 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
8875 if (*SI == UserParent) {
8876 UserIsSuccessor = true;
8877 break;
8878 }
8879
8880 // If the user is one of our immediate successors, and if that successor
8881 // only has us as a predecessors (we'd have to split the critical edge
8882 // otherwise), we can keep going.
8883 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
8884 next(pred_begin(UserParent)) == pred_end(UserParent))
8885 // Okay, the CFG is simple enough, try to sink this instruction.
8886 Changed |= TryToSinkInstruction(I, UserParent);
8887 }
8888 }
8889
Chris Lattnerca081252001-12-14 16:52:21 +00008890 // Now that we have an instruction, try combining it to simplify it...
Chris Lattnerae7a0d32002-08-02 19:29:35 +00008891 if (Instruction *Result = visit(*I)) {
Chris Lattner0b18c1d2002-05-10 15:38:35 +00008892 ++NumCombined;
Chris Lattner260ab202002-04-18 17:39:14 +00008893 // Should we replace the old instruction with a new one?
Chris Lattner053c0932002-05-14 15:24:07 +00008894 if (Result != I) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +00008895 DOUT << "IC: Old = " << *I
8896 << " New = " << *Result;
Chris Lattner7d2a5392004-03-13 23:54:27 +00008897
Chris Lattner396dbfe2004-06-09 05:08:07 +00008898 // Everything uses the new instruction now.
8899 I->replaceAllUsesWith(Result);
8900
8901 // Push the new instruction and any users onto the worklist.
8902 WorkList.push_back(Result);
8903 AddUsersToWorkList(*Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00008904
8905 // Move the name to the new instruction first...
8906 std::string OldName = I->getName(); I->setName("");
Chris Lattner950fc782003-10-07 22:58:41 +00008907 Result->setName(OldName);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00008908
8909 // Insert the new instruction into the basic block...
8910 BasicBlock *InstParent = I->getParent();
Chris Lattner7515cab2004-11-14 19:13:23 +00008911 BasicBlock::iterator InsertPos = I;
8912
8913 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
8914 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
8915 ++InsertPos;
8916
8917 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00008918
Chris Lattner63d75af2004-05-01 23:27:23 +00008919 // Make sure that we reprocess all operands now that we reduced their
8920 // use counts.
Chris Lattnerb643a9e2004-05-01 23:19:52 +00008921 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
8922 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
8923 WorkList.push_back(OpI);
8924
Chris Lattner396dbfe2004-06-09 05:08:07 +00008925 // Instructions can end up on the worklist more than once. Make sure
8926 // we do not process an instruction that has been deleted.
8927 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00008928
8929 // Erase the old instruction.
8930 InstParent->getInstList().erase(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00008931 } else {
Bill Wendling5dbf43c2006-11-26 09:46:52 +00008932 DOUT << "IC: MOD = " << *I;
Chris Lattner7d2a5392004-03-13 23:54:27 +00008933
Chris Lattnerae7a0d32002-08-02 19:29:35 +00008934 // If the instruction was modified, it's possible that it is now dead.
8935 // if so, remove it.
Chris Lattner63d75af2004-05-01 23:27:23 +00008936 if (isInstructionTriviallyDead(I)) {
8937 // Make sure we process all operands now that we are reducing their
8938 // use counts.
8939 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
8940 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
8941 WorkList.push_back(OpI);
Misha Brukmanb1c93172005-04-21 23:48:37 +00008942
Chris Lattner63d75af2004-05-01 23:27:23 +00008943 // Instructions may end up in the worklist more than once. Erase all
Robert Bocchinoa8352962006-01-13 22:48:06 +00008944 // occurrences of this instruction.
Chris Lattner99f48c62002-09-02 04:59:56 +00008945 removeFromWorkList(I);
Chris Lattner31f486c2005-01-31 05:36:43 +00008946 I->eraseFromParent();
Chris Lattner396dbfe2004-06-09 05:08:07 +00008947 } else {
8948 WorkList.push_back(Result);
8949 AddUsersToWorkList(*Result);
Chris Lattnerae7a0d32002-08-02 19:29:35 +00008950 }
Chris Lattner053c0932002-05-14 15:24:07 +00008951 }
Chris Lattner260ab202002-04-18 17:39:14 +00008952 Changed = true;
Chris Lattnerca081252001-12-14 16:52:21 +00008953 }
8954 }
8955
Chris Lattner260ab202002-04-18 17:39:14 +00008956 return Changed;
Chris Lattner04805fa2002-02-26 21:46:54 +00008957}
8958
Brian Gaeke38b79e82004-07-27 17:43:21 +00008959FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattner260ab202002-04-18 17:39:14 +00008960 return new InstCombiner();
Chris Lattner04805fa2002-02-26 21:46:54 +00008961}
Brian Gaeke960707c2003-11-11 22:41:34 +00008962