blob: b9ce08697c84b8275eef7a22a2deacdd6d03d5f4 [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 Lattnerc597b8a2006-01-22 23:32:06 +000055#include <iostream>
Chris Lattner8427bff2003-12-07 01:24:23 +000056using namespace llvm;
Chris Lattnerd4252a72004-07-30 07:50:03 +000057using namespace llvm::PatternMatch;
Brian Gaeke960707c2003-11-11 22:41:34 +000058
Chris Lattner260ab202002-04-18 17:39:14 +000059namespace {
Chris Lattnerbf3a0992002-10-01 22:38:41 +000060 Statistic<> NumCombined ("instcombine", "Number of insts combined");
61 Statistic<> NumConstProp("instcombine", "Number of constant folds");
62 Statistic<> NumDeadInst ("instcombine", "Number of dead inst eliminated");
Chris Lattner5997cf92006-02-08 03:25:32 +000063 Statistic<> NumDeadStore("instcombine", "Number of dead stores eliminated");
Chris Lattner39c98bb2004-12-08 23:43:58 +000064 Statistic<> NumSunkInst ("instcombine", "Number of instructions sunk");
Chris Lattnerbf3a0992002-10-01 22:38:41 +000065
Chris Lattner4a4c7fe2006-06-28 22:08:15 +000066 class VISIBILITY_HIDDEN InstCombiner
67 : public FunctionPass,
68 public InstVisitor<InstCombiner, Instruction*> {
Chris Lattner260ab202002-04-18 17:39:14 +000069 // Worklist of all of the instructions that need to be simplified.
70 std::vector<Instruction*> WorkList;
Chris Lattnerf4ad1652003-11-02 05:57:39 +000071 TargetData *TD;
Chris Lattner260ab202002-04-18 17:39:14 +000072
Chris Lattner51ea1272004-02-28 05:22:00 +000073 /// AddUsersToWorkList - When an instruction is simplified, add all users of
74 /// the instruction to the work lists because they might get more simplified
75 /// now.
76 ///
Chris Lattner2590e512006-02-07 06:56:34 +000077 void AddUsersToWorkList(Value &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +000078 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
Chris Lattner260ab202002-04-18 17:39:14 +000079 UI != UE; ++UI)
80 WorkList.push_back(cast<Instruction>(*UI));
81 }
82
Chris Lattner51ea1272004-02-28 05:22:00 +000083 /// AddUsesToWorkList - When an instruction is simplified, add operands to
84 /// the work lists because they might get more simplified now.
85 ///
86 void AddUsesToWorkList(Instruction &I) {
87 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
88 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i)))
89 WorkList.push_back(Op);
90 }
Chris Lattner2deeaea2006-10-05 06:55:50 +000091
92 /// AddSoonDeadInstToWorklist - The specified instruction is about to become
93 /// dead. Add all of its operands to the worklist, turning them into
94 /// undef's to reduce the number of uses of those instructions.
95 ///
96 /// Return the specified operand before it is turned into an undef.
97 ///
98 Value *AddSoonDeadInstToWorklist(Instruction &I, unsigned op) {
99 Value *R = I.getOperand(op);
100
101 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
102 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i))) {
103 WorkList.push_back(Op);
104 // Set the operand to undef to drop the use.
105 I.setOperand(i, UndefValue::get(Op->getType()));
106 }
107
108 return R;
109 }
Chris Lattner51ea1272004-02-28 05:22:00 +0000110
Chris Lattner99f48c62002-09-02 04:59:56 +0000111 // removeFromWorkList - remove all instances of I from the worklist.
112 void removeFromWorkList(Instruction *I);
Chris Lattner260ab202002-04-18 17:39:14 +0000113 public:
Chris Lattner113f4f42002-06-25 16:13:24 +0000114 virtual bool runOnFunction(Function &F);
Chris Lattner260ab202002-04-18 17:39:14 +0000115
Chris Lattnerf12cc842002-04-28 21:27:06 +0000116 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnerf4ad1652003-11-02 05:57:39 +0000117 AU.addRequired<TargetData>();
Owen Andersona6968f82006-07-10 19:03:49 +0000118 AU.addPreservedID(LCSSAID);
Chris Lattner820d9712002-10-21 20:00:28 +0000119 AU.setPreservesCFG();
Chris Lattnerf12cc842002-04-28 21:27:06 +0000120 }
121
Chris Lattner69193f92004-04-05 01:30:19 +0000122 TargetData &getTargetData() const { return *TD; }
123
Chris Lattner260ab202002-04-18 17:39:14 +0000124 // Visitation implementation - Implement instruction combining for different
125 // instruction types. The semantics are as follows:
126 // Return Value:
127 // null - No change was made
Chris Lattnere6794492002-08-12 21:17:25 +0000128 // I - Change was made, I is still valid, I may be dead though
Chris Lattner260ab202002-04-18 17:39:14 +0000129 // otherwise - Change was made, replace I with returned instruction
Misha Brukmanb1c93172005-04-21 23:48:37 +0000130 //
Chris Lattner113f4f42002-06-25 16:13:24 +0000131 Instruction *visitAdd(BinaryOperator &I);
132 Instruction *visitSub(BinaryOperator &I);
133 Instruction *visitMul(BinaryOperator &I);
Reid Spencer7e80b0b2006-10-26 06:15:43 +0000134 Instruction *commonDivTransforms(BinaryOperator &I);
135 Instruction *commonIDivTransforms(BinaryOperator &I);
136 Instruction *visitUDiv(BinaryOperator &I);
137 Instruction *visitSDiv(BinaryOperator &I);
138 Instruction *visitFDiv(BinaryOperator &I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000139 Instruction *visitRem(BinaryOperator &I);
140 Instruction *visitAnd(BinaryOperator &I);
141 Instruction *visitOr (BinaryOperator &I);
142 Instruction *visitXor(BinaryOperator &I);
Chris Lattnerd1f46d32005-04-24 06:59:08 +0000143 Instruction *visitSetCondInst(SetCondInst &I);
144 Instruction *visitSetCondInstWithCastAndCast(SetCondInst &SCI);
145
Chris Lattner0798af32005-01-13 20:14:25 +0000146 Instruction *FoldGEPSetCC(User *GEPLHS, Value *RHS,
147 Instruction::BinaryOps Cond, Instruction &I);
Chris Lattnere8d6c602003-03-10 19:16:08 +0000148 Instruction *visitShiftInst(ShiftInst &I);
Reid Spencere0fc4df2006-10-20 07:07:24 +0000149 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Chris Lattner14553932006-01-06 07:12:35 +0000150 ShiftInst &I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000151 Instruction *visitCastInst(CastInst &CI);
Chris Lattner411336f2005-01-19 21:50:18 +0000152 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
153 Instruction *FI);
Chris Lattnerb909e8b2004-03-12 05:52:32 +0000154 Instruction *visitSelectInst(SelectInst &CI);
Chris Lattner970c33a2003-06-19 17:00:31 +0000155 Instruction *visitCallInst(CallInst &CI);
156 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner113f4f42002-06-25 16:13:24 +0000157 Instruction *visitPHINode(PHINode &PN);
158 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Chris Lattner1085bdf2002-11-04 16:18:53 +0000159 Instruction *visitAllocationInst(AllocationInst &AI);
Chris Lattner8427bff2003-12-07 01:24:23 +0000160 Instruction *visitFreeInst(FreeInst &FI);
Chris Lattner0f1d8a32003-06-26 05:06:25 +0000161 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattner31f486c2005-01-31 05:36:43 +0000162 Instruction *visitStoreInst(StoreInst &SI);
Chris Lattner9eef8a72003-06-04 04:46:00 +0000163 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner4c9c20a2004-07-03 00:26:11 +0000164 Instruction *visitSwitchInst(SwitchInst &SI);
Chris Lattner39fac442006-04-15 01:39:45 +0000165 Instruction *visitInsertElementInst(InsertElementInst &IE);
Robert Bocchinoa8352962006-01-13 22:48:06 +0000166 Instruction *visitExtractElementInst(ExtractElementInst &EI);
Chris Lattnerfbb77a42006-04-10 22:45:52 +0000167 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
Chris Lattner260ab202002-04-18 17:39:14 +0000168
169 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner113f4f42002-06-25 16:13:24 +0000170 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000171
Chris Lattner970c33a2003-06-19 17:00:31 +0000172 private:
Chris Lattneraec3d942003-10-07 22:32:43 +0000173 Instruction *visitCallSite(CallSite CS);
Chris Lattner970c33a2003-06-19 17:00:31 +0000174 bool transformConstExprCastCall(CallSite CS);
175
Chris Lattner69193f92004-04-05 01:30:19 +0000176 public:
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000177 // InsertNewInstBefore - insert an instruction New before instruction Old
178 // in the program. Add the new instruction to the worklist.
179 //
Chris Lattner623826c2004-09-28 21:48:02 +0000180 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattner65217ff2002-08-23 18:32:43 +0000181 assert(New && New->getParent() == 0 &&
182 "New instruction already inserted into a basic block!");
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000183 BasicBlock *BB = Old.getParent();
184 BB->getInstList().insert(&Old, New); // Insert inst
185 WorkList.push_back(New); // Add to worklist
Chris Lattnere79e8542004-02-23 06:38:22 +0000186 return New;
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000187 }
188
Chris Lattner7e794272004-09-24 15:21:34 +0000189 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
190 /// This also adds the cast to the worklist. Finally, this returns the
191 /// cast.
192 Value *InsertCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
193 if (V->getType() == Ty) return V;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000194
Chris Lattnere79d2492006-04-06 19:19:17 +0000195 if (Constant *CV = dyn_cast<Constant>(V))
196 return ConstantExpr::getCast(CV, Ty);
197
Chris Lattner7e794272004-09-24 15:21:34 +0000198 Instruction *C = new CastInst(V, Ty, V->getName(), &Pos);
199 WorkList.push_back(C);
200 return C;
201 }
202
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000203 // ReplaceInstUsesWith - This method is to be used when an instruction is
204 // found to be dead, replacable with another preexisting expression. Here
205 // we add all uses of I to the worklist, replace all uses of I with the new
206 // value, then return I, so that the inst combiner will know that I was
207 // modified.
208 //
209 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattner51ea1272004-02-28 05:22:00 +0000210 AddUsersToWorkList(I); // Add all modified instrs to worklist
Chris Lattner8953b902004-04-05 02:10:19 +0000211 if (&I != V) {
212 I.replaceAllUsesWith(V);
213 return &I;
214 } else {
215 // If we are replacing the instruction with itself, this must be in a
216 // segment of unreachable code, so just clobber the instruction.
Chris Lattner8ba9ec92004-10-18 02:59:09 +0000217 I.replaceAllUsesWith(UndefValue::get(I.getType()));
Chris Lattner8953b902004-04-05 02:10:19 +0000218 return &I;
219 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000220 }
Chris Lattner51ea1272004-02-28 05:22:00 +0000221
Chris Lattner2590e512006-02-07 06:56:34 +0000222 // UpdateValueUsesWith - This method is to be used when an value is
223 // found to be replacable with another preexisting expression or was
224 // updated. Here we add all uses of I to the worklist, replace all uses of
225 // I with the new value (unless the instruction was just updated), then
226 // return true, so that the inst combiner will know that I was modified.
227 //
228 bool UpdateValueUsesWith(Value *Old, Value *New) {
229 AddUsersToWorkList(*Old); // Add all modified instrs to worklist
230 if (Old != New)
231 Old->replaceAllUsesWith(New);
232 if (Instruction *I = dyn_cast<Instruction>(Old))
233 WorkList.push_back(I);
Chris Lattner5b2edb12006-02-12 08:02:11 +0000234 if (Instruction *I = dyn_cast<Instruction>(New))
235 WorkList.push_back(I);
Chris Lattner2590e512006-02-07 06:56:34 +0000236 return true;
237 }
238
Chris Lattner51ea1272004-02-28 05:22:00 +0000239 // EraseInstFromFunction - When dealing with an instruction that has side
240 // effects or produces a void value, we can't rely on DCE to delete the
241 // instruction. Instead, visit methods should return the value returned by
242 // this function.
243 Instruction *EraseInstFromFunction(Instruction &I) {
244 assert(I.use_empty() && "Cannot erase instruction that is used!");
245 AddUsesToWorkList(I);
246 removeFromWorkList(&I);
Chris Lattner95307542004-11-18 21:41:39 +0000247 I.eraseFromParent();
Chris Lattner51ea1272004-02-28 05:22:00 +0000248 return 0; // Don't do anything with FI
249 }
250
Chris Lattner3ac7c262003-08-13 20:16:26 +0000251 private:
Chris Lattnerdfae8be2003-07-24 17:35:25 +0000252 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
253 /// InsertBefore instruction. This is specialized a bit to avoid inserting
254 /// casts that are known to not do anything...
255 ///
256 Value *InsertOperandCastBefore(Value *V, const Type *DestTy,
257 Instruction *InsertBefore);
258
Chris Lattner7fb29e12003-03-11 00:12:48 +0000259 // SimplifyCommutative - This performs a few simplifications for commutative
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000260 // operators.
Chris Lattner7fb29e12003-03-11 00:12:48 +0000261 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerba1cb382003-09-19 17:17:26 +0000262
Chris Lattner0157e7f2006-02-11 09:31:47 +0000263 bool SimplifyDemandedBits(Value *V, uint64_t Mask,
264 uint64_t &KnownZero, uint64_t &KnownOne,
265 unsigned Depth = 0);
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000266
Chris Lattner2deeaea2006-10-05 06:55:50 +0000267 Value *SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
268 uint64_t &UndefElts, unsigned Depth = 0);
269
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000270 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
271 // PHI node as operand #0, see if we can fold the instruction into the PHI
272 // (which is only possible if all operands to the PHI are constants).
273 Instruction *FoldOpIntoPhi(Instruction &I);
274
Chris Lattner7515cab2004-11-14 19:13:23 +0000275 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
276 // operator and they all are only used by the PHI, PHI together their
277 // inputs, and do the operation once, to the result of the PHI.
278 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
Chris Lattnercadac0c2006-11-01 04:51:18 +0000279 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
280
281
Chris Lattnerba1cb382003-09-19 17:17:26 +0000282 Instruction *OptAndOp(Instruction *Op, ConstantIntegral *OpRHS,
283 ConstantIntegral *AndRHS, BinaryOperator &TheAnd);
Chris Lattneraf517572005-09-18 04:24:45 +0000284
285 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantIntegral *Mask,
286 bool isSub, Instruction &I);
Chris Lattner6862fbd2004-09-29 17:40:11 +0000287 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
288 bool Inside, Instruction &IB);
Chris Lattner216be912005-10-24 06:03:58 +0000289 Instruction *PromoteCastOfAllocation(CastInst &CI, AllocationInst &AI);
Chris Lattnerc482a9e2006-06-15 19:07:26 +0000290 Instruction *MatchBSwap(BinaryOperator &I);
291
Chris Lattner1ebbe6a2006-05-13 02:06:03 +0000292 Value *EvaluateInDifferentType(Value *V, const Type *Ty);
Chris Lattner260ab202002-04-18 17:39:14 +0000293 };
Chris Lattnerb28b6802002-07-23 18:06:35 +0000294
Chris Lattnerc2d3d312006-08-27 22:42:52 +0000295 RegisterPass<InstCombiner> X("instcombine", "Combine redundant instructions");
Chris Lattner260ab202002-04-18 17:39:14 +0000296}
297
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000298// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattner81a7a232004-10-16 18:11:37 +0000299// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000300static unsigned getComplexity(Value *V) {
301 if (isa<Instruction>(V)) {
302 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
Chris Lattner81a7a232004-10-16 18:11:37 +0000303 return 3;
304 return 4;
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000305 }
Chris Lattner81a7a232004-10-16 18:11:37 +0000306 if (isa<Argument>(V)) return 3;
307 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000308}
Chris Lattner260ab202002-04-18 17:39:14 +0000309
Chris Lattner7fb29e12003-03-11 00:12:48 +0000310// isOnlyUse - Return true if this instruction will be deleted if we stop using
311// it.
312static bool isOnlyUse(Value *V) {
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000313 return V->hasOneUse() || isa<Constant>(V);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000314}
315
Chris Lattnere79e8542004-02-23 06:38:22 +0000316// getPromotedType - Return the specified type promoted as it would be to pass
317// though a va_arg area...
318static const Type *getPromotedType(const Type *Ty) {
Chris Lattner97bfcea2004-06-17 18:16:02 +0000319 switch (Ty->getTypeID()) {
Chris Lattnere79e8542004-02-23 06:38:22 +0000320 case Type::SByteTyID:
321 case Type::ShortTyID: return Type::IntTy;
322 case Type::UByteTyID:
323 case Type::UShortTyID: return Type::UIntTy;
324 case Type::FloatTyID: return Type::DoubleTy;
325 default: return Ty;
326 }
327}
328
Chris Lattner567b81f2005-09-13 00:40:14 +0000329/// isCast - If the specified operand is a CastInst or a constant expr cast,
330/// return the operand value, otherwise return null.
331static Value *isCast(Value *V) {
332 if (CastInst *I = dyn_cast<CastInst>(V))
333 return I->getOperand(0);
334 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
335 if (CE->getOpcode() == Instruction::Cast)
336 return CE->getOperand(0);
337 return 0;
338}
339
Chris Lattner1d441ad2006-05-06 09:00:16 +0000340enum CastType {
341 Noop = 0,
342 Truncate = 1,
343 Signext = 2,
344 Zeroext = 3
345};
346
347/// getCastType - In the future, we will split the cast instruction into these
348/// various types. Until then, we have to do the analysis here.
349static CastType getCastType(const Type *Src, const Type *Dest) {
350 assert(Src->isIntegral() && Dest->isIntegral() &&
351 "Only works on integral types!");
352 unsigned SrcSize = Src->getPrimitiveSizeInBits();
353 unsigned DestSize = Dest->getPrimitiveSizeInBits();
354
355 if (SrcSize == DestSize) return Noop;
356 if (SrcSize > DestSize) return Truncate;
357 if (Src->isSigned()) return Signext;
358 return Zeroext;
359}
360
361
362// isEliminableCastOfCast - Return true if it is valid to eliminate the CI
363// instruction.
364//
365static bool isEliminableCastOfCast(const Type *SrcTy, const Type *MidTy,
366 const Type *DstTy, TargetData *TD) {
367
368 // It is legal to eliminate the instruction if casting A->B->A if the sizes
369 // are identical and the bits don't get reinterpreted (for example
370 // int->float->int would not be allowed).
371 if (SrcTy == DstTy && SrcTy->isLosslesslyConvertibleTo(MidTy))
372 return true;
373
374 // If we are casting between pointer and integer types, treat pointers as
375 // integers of the appropriate size for the code below.
376 if (isa<PointerType>(SrcTy)) SrcTy = TD->getIntPtrType();
377 if (isa<PointerType>(MidTy)) MidTy = TD->getIntPtrType();
378 if (isa<PointerType>(DstTy)) DstTy = TD->getIntPtrType();
379
380 // Allow free casting and conversion of sizes as long as the sign doesn't
381 // change...
382 if (SrcTy->isIntegral() && MidTy->isIntegral() && DstTy->isIntegral()) {
383 CastType FirstCast = getCastType(SrcTy, MidTy);
384 CastType SecondCast = getCastType(MidTy, DstTy);
385
386 // Capture the effect of these two casts. If the result is a legal cast,
387 // the CastType is stored here, otherwise a special code is used.
388 static const unsigned CastResult[] = {
389 // First cast is noop
390 0, 1, 2, 3,
391 // First cast is a truncate
392 1, 1, 4, 4, // trunc->extend is not safe to eliminate
393 // First cast is a sign ext
394 2, 5, 2, 4, // signext->zeroext never ok
395 // First cast is a zero ext
396 3, 5, 3, 3,
397 };
398
399 unsigned Result = CastResult[FirstCast*4+SecondCast];
400 switch (Result) {
401 default: assert(0 && "Illegal table value!");
402 case 0:
403 case 1:
404 case 2:
405 case 3:
406 // FIXME: in the future, when LLVM has explicit sign/zeroextends and
407 // truncates, we could eliminate more casts.
408 return (unsigned)getCastType(SrcTy, DstTy) == Result;
409 case 4:
410 return false; // Not possible to eliminate this here.
411 case 5:
412 // Sign or zero extend followed by truncate is always ok if the result
413 // is a truncate or noop.
414 CastType ResultCast = getCastType(SrcTy, DstTy);
415 if (ResultCast == Noop || ResultCast == Truncate)
416 return true;
417 // Otherwise we are still growing the value, we are only safe if the
418 // result will match the sign/zeroextendness of the result.
419 return ResultCast == FirstCast;
420 }
421 }
422
423 // If this is a cast from 'float -> double -> integer', cast from
424 // 'float -> integer' directly, as the value isn't changed by the
425 // float->double conversion.
426 if (SrcTy->isFloatingPoint() && MidTy->isFloatingPoint() &&
427 DstTy->isIntegral() &&
428 SrcTy->getPrimitiveSize() < MidTy->getPrimitiveSize())
429 return true;
430
431 // Packed type conversions don't modify bits.
432 if (isa<PackedType>(SrcTy) && isa<PackedType>(MidTy) &&isa<PackedType>(DstTy))
433 return true;
434
435 return false;
436}
437
438/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
439/// in any code being generated. It does not require codegen if V is simple
440/// enough or if the cast can be folded into other casts.
441static bool ValueRequiresCast(const Value *V, const Type *Ty, TargetData *TD) {
442 if (V->getType() == Ty || isa<Constant>(V)) return false;
443
444 // If this is a noop cast, it isn't real codegen.
445 if (V->getType()->isLosslesslyConvertibleTo(Ty))
446 return false;
447
Chris Lattner99155be2006-05-25 23:24:33 +0000448 // If this is another cast that can be eliminated, it isn't codegen either.
Chris Lattner1d441ad2006-05-06 09:00:16 +0000449 if (const CastInst *CI = dyn_cast<CastInst>(V))
450 if (isEliminableCastOfCast(CI->getOperand(0)->getType(), CI->getType(), Ty,
451 TD))
452 return false;
453 return true;
454}
455
456/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
457/// InsertBefore instruction. This is specialized a bit to avoid inserting
458/// casts that are known to not do anything...
459///
460Value *InstCombiner::InsertOperandCastBefore(Value *V, const Type *DestTy,
461 Instruction *InsertBefore) {
462 if (V->getType() == DestTy) return V;
463 if (Constant *C = dyn_cast<Constant>(V))
464 return ConstantExpr::getCast(C, DestTy);
465
Reid Spencer00c482b2006-10-26 19:19:06 +0000466 return InsertCastBefore(V, DestTy, *InsertBefore);
Chris Lattner1d441ad2006-05-06 09:00:16 +0000467}
468
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000469// SimplifyCommutative - This performs a few simplifications for commutative
470// operators:
Chris Lattner260ab202002-04-18 17:39:14 +0000471//
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000472// 1. Order operands such that they are listed from right (least complex) to
473// left (most complex). This puts constants before unary operators before
474// binary operators.
475//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000476// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
477// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000478//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000479bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000480 bool Changed = false;
481 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
482 Changed = !I.swapOperands();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000483
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000484 if (!I.isAssociative()) return Changed;
485 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattner7fb29e12003-03-11 00:12:48 +0000486 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
487 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
488 if (isa<Constant>(I.getOperand(1))) {
Chris Lattner34428442003-05-27 16:40:51 +0000489 Constant *Folded = ConstantExpr::get(I.getOpcode(),
490 cast<Constant>(I.getOperand(1)),
491 cast<Constant>(Op->getOperand(1)));
Chris Lattner7fb29e12003-03-11 00:12:48 +0000492 I.setOperand(0, Op->getOperand(0));
493 I.setOperand(1, Folded);
494 return true;
495 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
496 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
497 isOnlyUse(Op) && isOnlyUse(Op1)) {
498 Constant *C1 = cast<Constant>(Op->getOperand(1));
499 Constant *C2 = cast<Constant>(Op1->getOperand(1));
500
501 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner34428442003-05-27 16:40:51 +0000502 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000503 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
504 Op1->getOperand(0),
505 Op1->getName(), &I);
506 WorkList.push_back(New);
507 I.setOperand(0, New);
508 I.setOperand(1, Folded);
509 return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000510 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000511 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000512 return Changed;
Chris Lattner260ab202002-04-18 17:39:14 +0000513}
Chris Lattnerca081252001-12-14 16:52:21 +0000514
Chris Lattnerbb74e222003-03-10 23:06:50 +0000515// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
516// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattner9fa53de2002-05-06 16:49:18 +0000517//
Chris Lattnerbb74e222003-03-10 23:06:50 +0000518static inline Value *dyn_castNegVal(Value *V) {
519 if (BinaryOperator::isNeg(V))
Chris Lattnerd6f636a2005-04-24 07:30:14 +0000520 return BinaryOperator::getNegArgument(V);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000521
Chris Lattner9ad0d552004-12-14 20:08:06 +0000522 // Constants can be considered to be negated values if they can be folded.
523 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
524 return ConstantExpr::getNeg(C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000525 return 0;
Chris Lattner9fa53de2002-05-06 16:49:18 +0000526}
527
Chris Lattnerbb74e222003-03-10 23:06:50 +0000528static inline Value *dyn_castNotVal(Value *V) {
529 if (BinaryOperator::isNot(V))
Chris Lattnerd6f636a2005-04-24 07:30:14 +0000530 return BinaryOperator::getNotArgument(V);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000531
532 // Constants can be considered to be not'ed values...
Chris Lattnerdd65d862003-04-30 22:34:06 +0000533 if (ConstantIntegral *C = dyn_cast<ConstantIntegral>(V))
Chris Lattnerc8e7e292004-06-10 02:12:35 +0000534 return ConstantExpr::getNot(C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000535 return 0;
536}
537
Chris Lattner7fb29e12003-03-11 00:12:48 +0000538// dyn_castFoldableMul - If this value is a multiply that can be folded into
539// other computations (because it has a constant operand), return the
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000540// non-constant operand of the multiply, and set CST to point to the multiplier.
541// Otherwise, return null.
Chris Lattner7fb29e12003-03-11 00:12:48 +0000542//
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000543static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000544 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000545 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattner7fb29e12003-03-11 00:12:48 +0000546 if (I->getOpcode() == Instruction::Mul)
Chris Lattner970136362004-11-15 05:54:07 +0000547 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattner7fb29e12003-03-11 00:12:48 +0000548 return I->getOperand(0);
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000549 if (I->getOpcode() == Instruction::Shl)
Chris Lattner970136362004-11-15 05:54:07 +0000550 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000551 // The multiplier is really 1 << CST.
552 Constant *One = ConstantInt::get(V->getType(), 1);
553 CST = cast<ConstantInt>(ConstantExpr::getShl(One, CST));
554 return I->getOperand(0);
555 }
556 }
Chris Lattner7fb29e12003-03-11 00:12:48 +0000557 return 0;
Chris Lattner3082c5a2003-02-18 19:28:33 +0000558}
Chris Lattner31ae8632002-08-14 17:51:49 +0000559
Chris Lattner0798af32005-01-13 20:14:25 +0000560/// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
561/// expression, return it.
562static User *dyn_castGetElementPtr(Value *V) {
563 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
564 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
565 if (CE->getOpcode() == Instruction::GetElementPtr)
566 return cast<User>(V);
567 return false;
568}
569
Chris Lattner623826c2004-09-28 21:48:02 +0000570// AddOne, SubOne - Add or subtract a constant one from an integer constant...
Chris Lattner6862fbd2004-09-29 17:40:11 +0000571static ConstantInt *AddOne(ConstantInt *C) {
572 return cast<ConstantInt>(ConstantExpr::getAdd(C,
573 ConstantInt::get(C->getType(), 1)));
Chris Lattner623826c2004-09-28 21:48:02 +0000574}
Chris Lattner6862fbd2004-09-29 17:40:11 +0000575static ConstantInt *SubOne(ConstantInt *C) {
576 return cast<ConstantInt>(ConstantExpr::getSub(C,
577 ConstantInt::get(C->getType(), 1)));
Chris Lattner623826c2004-09-28 21:48:02 +0000578}
579
Chris Lattner0157e7f2006-02-11 09:31:47 +0000580/// GetConstantInType - Return a ConstantInt with the specified type and value.
581///
Chris Lattneree0f2802006-02-12 02:07:56 +0000582static ConstantIntegral *GetConstantInType(const Type *Ty, uint64_t Val) {
Reid Spencere0fc4df2006-10-20 07:07:24 +0000583 if (Ty->isUnsigned())
584 return ConstantInt::get(Ty, Val);
Chris Lattneree0f2802006-02-12 02:07:56 +0000585 else if (Ty->getTypeID() == Type::BoolTyID)
586 return ConstantBool::get(Val);
Chris Lattner0157e7f2006-02-11 09:31:47 +0000587 int64_t SVal = Val;
588 SVal <<= 64-Ty->getPrimitiveSizeInBits();
589 SVal >>= 64-Ty->getPrimitiveSizeInBits();
Reid Spencere0fc4df2006-10-20 07:07:24 +0000590 return ConstantInt::get(Ty, SVal);
Chris Lattner0157e7f2006-02-11 09:31:47 +0000591}
592
593
Chris Lattner4534dd592006-02-09 07:38:58 +0000594/// ComputeMaskedBits - Determine which of the bits specified in Mask are
595/// known to be either zero or one and return them in the KnownZero/KnownOne
596/// bitsets. This code only analyzes bits in Mask, in order to short-circuit
597/// processing.
598static void ComputeMaskedBits(Value *V, uint64_t Mask, uint64_t &KnownZero,
599 uint64_t &KnownOne, unsigned Depth = 0) {
Chris Lattner0b3557f2005-09-24 23:43:33 +0000600 // Note, we cannot consider 'undef' to be "IsZero" here. The problem is that
601 // we cannot optimize based on the assumption that it is zero without changing
Chris Lattnerc3ebf402006-02-07 07:27:52 +0000602 // it to be an explicit zero. If we don't change it to zero, other code could
Chris Lattner0b3557f2005-09-24 23:43:33 +0000603 // optimized based on the contradictory assumption that it is non-zero.
604 // Because instcombine aggressively folds operations with undef args anyway,
605 // this won't lose us code quality.
Chris Lattner4534dd592006-02-09 07:38:58 +0000606 if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(V)) {
607 // We know all of the bits for a constant!
Chris Lattner0157e7f2006-02-11 09:31:47 +0000608 KnownOne = CI->getZExtValue() & Mask;
Chris Lattner4534dd592006-02-09 07:38:58 +0000609 KnownZero = ~KnownOne & Mask;
610 return;
611 }
612
613 KnownZero = KnownOne = 0; // Don't know anything.
Chris Lattner92a68652006-02-07 08:05:22 +0000614 if (Depth == 6 || Mask == 0)
Chris Lattner4534dd592006-02-09 07:38:58 +0000615 return; // Limit search depth.
616
617 uint64_t KnownZero2, KnownOne2;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000618 Instruction *I = dyn_cast<Instruction>(V);
619 if (!I) return;
620
Chris Lattnerfb296922006-05-04 17:33:35 +0000621 Mask &= V->getType()->getIntegralTypeMask();
622
Chris Lattner0157e7f2006-02-11 09:31:47 +0000623 switch (I->getOpcode()) {
624 case Instruction::And:
625 // If either the LHS or the RHS are Zero, the result is zero.
626 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
627 Mask &= ~KnownZero;
628 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
629 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
630 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
631
632 // Output known-1 bits are only known if set in both the LHS & RHS.
633 KnownOne &= KnownOne2;
634 // Output known-0 are known to be clear if zero in either the LHS | RHS.
635 KnownZero |= KnownZero2;
636 return;
637 case Instruction::Or:
638 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
639 Mask &= ~KnownOne;
640 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
641 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
642 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
643
644 // Output known-0 bits are only known if clear in both the LHS & RHS.
645 KnownZero &= KnownZero2;
646 // Output known-1 are known to be set if set in either the LHS | RHS.
647 KnownOne |= KnownOne2;
648 return;
649 case Instruction::Xor: {
650 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
651 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
652 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
653 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
654
655 // Output known-0 bits are known if clear or set in both the LHS & RHS.
656 uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
657 // Output known-1 are known to be set if set in only one of the LHS, RHS.
658 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
659 KnownZero = KnownZeroOut;
660 return;
661 }
662 case Instruction::Select:
663 ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
664 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
665 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
666 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
667
668 // Only known if known in both the LHS and RHS.
669 KnownOne &= KnownOne2;
670 KnownZero &= KnownZero2;
671 return;
672 case Instruction::Cast: {
673 const Type *SrcTy = I->getOperand(0)->getType();
674 if (!SrcTy->isIntegral()) return;
675
676 // If this is an integer truncate or noop, just look in the input.
677 if (SrcTy->getPrimitiveSizeInBits() >=
678 I->getType()->getPrimitiveSizeInBits()) {
679 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
Chris Lattner4534dd592006-02-09 07:38:58 +0000680 return;
681 }
Chris Lattner4534dd592006-02-09 07:38:58 +0000682
Chris Lattner0157e7f2006-02-11 09:31:47 +0000683 // Sign or Zero extension. Compute the bits in the result that are not
684 // present in the input.
685 uint64_t NotIn = ~SrcTy->getIntegralTypeMask();
686 uint64_t NewBits = I->getType()->getIntegralTypeMask() & NotIn;
Chris Lattner62010c42005-10-09 06:36:35 +0000687
Chris Lattner0157e7f2006-02-11 09:31:47 +0000688 // Handle zero extension.
689 if (!SrcTy->isSigned()) {
690 Mask &= SrcTy->getIntegralTypeMask();
691 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
692 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
693 // The top bits are known to be zero.
694 KnownZero |= NewBits;
695 } else {
696 // Sign extension.
697 Mask &= SrcTy->getIntegralTypeMask();
698 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
699 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattner92a68652006-02-07 08:05:22 +0000700
Chris Lattner0157e7f2006-02-11 09:31:47 +0000701 // If the sign bit of the input is known set or clear, then we know the
702 // top bits of the result.
703 uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
704 if (KnownZero & InSignBit) { // Input sign bit known zero
Chris Lattner4534dd592006-02-09 07:38:58 +0000705 KnownZero |= NewBits;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000706 KnownOne &= ~NewBits;
707 } else if (KnownOne & InSignBit) { // Input sign bit known set
708 KnownOne |= NewBits;
709 KnownZero &= ~NewBits;
710 } else { // Input sign bit unknown
711 KnownZero &= ~NewBits;
712 KnownOne &= ~NewBits;
713 }
714 }
715 return;
716 }
717 case Instruction::Shl:
718 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
Reid Spencere0fc4df2006-10-20 07:07:24 +0000719 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
720 uint64_t ShiftAmt = SA->getZExtValue();
721 Mask >>= ShiftAmt;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000722 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
723 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Reid Spencere0fc4df2006-10-20 07:07:24 +0000724 KnownZero <<= ShiftAmt;
725 KnownOne <<= ShiftAmt;
726 KnownZero |= (1ULL << ShiftAmt)-1; // low bits known zero.
Chris Lattner0157e7f2006-02-11 09:31:47 +0000727 return;
728 }
729 break;
730 case Instruction::Shr:
731 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
Reid Spencere0fc4df2006-10-20 07:07:24 +0000732 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Chris Lattner0157e7f2006-02-11 09:31:47 +0000733 // Compute the new bits that are at the top now.
Reid Spencere0fc4df2006-10-20 07:07:24 +0000734 uint64_t ShiftAmt = SA->getZExtValue();
735 uint64_t HighBits = (1ULL << ShiftAmt)-1;
736 HighBits <<= I->getType()->getPrimitiveSizeInBits()-ShiftAmt;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000737
738 if (I->getType()->isUnsigned()) { // Unsigned shift right.
Reid Spencere0fc4df2006-10-20 07:07:24 +0000739 Mask <<= ShiftAmt;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000740 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
741 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
Reid Spencere0fc4df2006-10-20 07:07:24 +0000742 KnownZero >>= ShiftAmt;
743 KnownOne >>= ShiftAmt;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000744 KnownZero |= HighBits; // high bits known zero.
Chris Lattner4534dd592006-02-09 07:38:58 +0000745 } else {
Reid Spencere0fc4df2006-10-20 07:07:24 +0000746 Mask <<= ShiftAmt;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000747 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
748 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
Reid Spencere0fc4df2006-10-20 07:07:24 +0000749 KnownZero >>= ShiftAmt;
750 KnownOne >>= ShiftAmt;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000751
752 // Handle the sign bits.
753 uint64_t SignBit = 1ULL << (I->getType()->getPrimitiveSizeInBits()-1);
Reid Spencere0fc4df2006-10-20 07:07:24 +0000754 SignBit >>= ShiftAmt; // Adjust to where it is now in the mask.
Chris Lattner0157e7f2006-02-11 09:31:47 +0000755
756 if (KnownZero & SignBit) { // New bits are known zero.
757 KnownZero |= HighBits;
758 } else if (KnownOne & SignBit) { // New bits are known one.
759 KnownOne |= HighBits;
Chris Lattner4534dd592006-02-09 07:38:58 +0000760 }
761 }
762 return;
Chris Lattner62010c42005-10-09 06:36:35 +0000763 }
Chris Lattner0157e7f2006-02-11 09:31:47 +0000764 break;
Chris Lattner0b3557f2005-09-24 23:43:33 +0000765 }
Chris Lattner92a68652006-02-07 08:05:22 +0000766}
767
768/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
769/// this predicate to simplify operations downstream. Mask is known to be zero
770/// for bits that V cannot have.
771static bool MaskedValueIsZero(Value *V, uint64_t Mask, unsigned Depth = 0) {
Chris Lattner4534dd592006-02-09 07:38:58 +0000772 uint64_t KnownZero, KnownOne;
773 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
774 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
775 return (KnownZero & Mask) == Mask;
Chris Lattner0b3557f2005-09-24 23:43:33 +0000776}
777
Chris Lattner0157e7f2006-02-11 09:31:47 +0000778/// ShrinkDemandedConstant - Check to see if the specified operand of the
779/// specified instruction is a constant integer. If so, check to see if there
780/// are any bits set in the constant that are not demanded. If so, shrink the
781/// constant and return true.
782static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
783 uint64_t Demanded) {
784 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
785 if (!OpC) return false;
786
787 // If there are no bits set that aren't demanded, nothing to do.
788 if ((~Demanded & OpC->getZExtValue()) == 0)
789 return false;
790
791 // This is producing any bits that are not needed, shrink the RHS.
792 uint64_t Val = Demanded & OpC->getZExtValue();
793 I->setOperand(OpNo, GetConstantInType(OpC->getType(), Val));
794 return true;
795}
796
Chris Lattneree0f2802006-02-12 02:07:56 +0000797// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
798// set of known zero and one bits, compute the maximum and minimum values that
799// could have the specified known zero and known one bits, returning them in
800// min/max.
801static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
802 uint64_t KnownZero,
803 uint64_t KnownOne,
804 int64_t &Min, int64_t &Max) {
805 uint64_t TypeBits = Ty->getIntegralTypeMask();
806 uint64_t UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
807
808 uint64_t SignBit = 1ULL << (Ty->getPrimitiveSizeInBits()-1);
809
810 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
811 // bit if it is unknown.
812 Min = KnownOne;
813 Max = KnownOne|UnknownBits;
814
815 if (SignBit & UnknownBits) { // Sign bit is unknown
816 Min |= SignBit;
817 Max &= ~SignBit;
818 }
819
820 // Sign extend the min/max values.
821 int ShAmt = 64-Ty->getPrimitiveSizeInBits();
822 Min = (Min << ShAmt) >> ShAmt;
823 Max = (Max << ShAmt) >> ShAmt;
824}
825
826// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
827// a set of known zero and one bits, compute the maximum and minimum values that
828// could have the specified known zero and known one bits, returning them in
829// min/max.
830static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
831 uint64_t KnownZero,
832 uint64_t KnownOne,
833 uint64_t &Min,
834 uint64_t &Max) {
835 uint64_t TypeBits = Ty->getIntegralTypeMask();
836 uint64_t UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
837
838 // The minimum value is when the unknown bits are all zeros.
839 Min = KnownOne;
840 // The maximum value is when the unknown bits are all ones.
841 Max = KnownOne|UnknownBits;
842}
Chris Lattner0157e7f2006-02-11 09:31:47 +0000843
844
845/// SimplifyDemandedBits - Look at V. At this point, we know that only the
846/// DemandedMask bits of the result of V are ever used downstream. If we can
847/// use this information to simplify V, do so and return true. Otherwise,
848/// analyze the expression and return a mask of KnownOne and KnownZero bits for
849/// the expression (used to simplify the caller). The KnownZero/One bits may
850/// only be accurate for those bits in the DemandedMask.
851bool InstCombiner::SimplifyDemandedBits(Value *V, uint64_t DemandedMask,
852 uint64_t &KnownZero, uint64_t &KnownOne,
Chris Lattner2590e512006-02-07 06:56:34 +0000853 unsigned Depth) {
Chris Lattner0157e7f2006-02-11 09:31:47 +0000854 if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(V)) {
855 // We know all of the bits for a constant!
856 KnownOne = CI->getZExtValue() & DemandedMask;
857 KnownZero = ~KnownOne & DemandedMask;
858 return false;
859 }
860
861 KnownZero = KnownOne = 0;
Chris Lattner2590e512006-02-07 06:56:34 +0000862 if (!V->hasOneUse()) { // Other users may use these bits.
Chris Lattner0157e7f2006-02-11 09:31:47 +0000863 if (Depth != 0) { // Not at the root.
864 // Just compute the KnownZero/KnownOne bits to simplify things downstream.
865 ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
Chris Lattner2590e512006-02-07 06:56:34 +0000866 return false;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000867 }
Chris Lattner2590e512006-02-07 06:56:34 +0000868 // If this is the root being simplified, allow it to have multiple uses,
Chris Lattner0157e7f2006-02-11 09:31:47 +0000869 // just set the DemandedMask to all bits.
870 DemandedMask = V->getType()->getIntegralTypeMask();
871 } else if (DemandedMask == 0) { // Not demanding any bits from V.
Chris Lattner92a68652006-02-07 08:05:22 +0000872 if (V != UndefValue::get(V->getType()))
873 return UpdateValueUsesWith(V, UndefValue::get(V->getType()));
874 return false;
Chris Lattner2590e512006-02-07 06:56:34 +0000875 } else if (Depth == 6) { // Limit search depth.
876 return false;
877 }
878
879 Instruction *I = dyn_cast<Instruction>(V);
880 if (!I) return false; // Only analyze instructions.
881
Chris Lattnerfb296922006-05-04 17:33:35 +0000882 DemandedMask &= V->getType()->getIntegralTypeMask();
883
Chris Lattner0157e7f2006-02-11 09:31:47 +0000884 uint64_t KnownZero2, KnownOne2;
Chris Lattner2590e512006-02-07 06:56:34 +0000885 switch (I->getOpcode()) {
886 default: break;
887 case Instruction::And:
Chris Lattner0157e7f2006-02-11 09:31:47 +0000888 // If either the LHS or the RHS are Zero, the result is zero.
889 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
890 KnownZero, KnownOne, Depth+1))
891 return true;
892 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
893
894 // If something is known zero on the RHS, the bits aren't demanded on the
895 // LHS.
896 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownZero,
897 KnownZero2, KnownOne2, Depth+1))
898 return true;
899 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
900
901 // If all of the demanded bits are known one on one side, return the other.
902 // These bits cannot contribute to the result of the 'and'.
903 if ((DemandedMask & ~KnownZero2 & KnownOne) == (DemandedMask & ~KnownZero2))
904 return UpdateValueUsesWith(I, I->getOperand(0));
905 if ((DemandedMask & ~KnownZero & KnownOne2) == (DemandedMask & ~KnownZero))
906 return UpdateValueUsesWith(I, I->getOperand(1));
Chris Lattner5b2edb12006-02-12 08:02:11 +0000907
908 // If all of the demanded bits in the inputs are known zeros, return zero.
909 if ((DemandedMask & (KnownZero|KnownZero2)) == DemandedMask)
910 return UpdateValueUsesWith(I, Constant::getNullValue(I->getType()));
911
Chris Lattner0157e7f2006-02-11 09:31:47 +0000912 // If the RHS is a constant, see if we can simplify it.
Chris Lattner5b2edb12006-02-12 08:02:11 +0000913 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~KnownZero2))
Chris Lattner0157e7f2006-02-11 09:31:47 +0000914 return UpdateValueUsesWith(I, I);
915
916 // Output known-1 bits are only known if set in both the LHS & RHS.
917 KnownOne &= KnownOne2;
918 // Output known-0 are known to be clear if zero in either the LHS | RHS.
919 KnownZero |= KnownZero2;
920 break;
921 case Instruction::Or:
922 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
923 KnownZero, KnownOne, Depth+1))
924 return true;
925 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
926 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownOne,
927 KnownZero2, KnownOne2, Depth+1))
928 return true;
929 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
930
931 // If all of the demanded bits are known zero on one side, return the other.
932 // These bits cannot contribute to the result of the 'or'.
Jeff Cohen0add83e2006-02-18 03:20:33 +0000933 if ((DemandedMask & ~KnownOne2 & KnownZero) == (DemandedMask & ~KnownOne2))
Chris Lattner0157e7f2006-02-11 09:31:47 +0000934 return UpdateValueUsesWith(I, I->getOperand(0));
Jeff Cohen0add83e2006-02-18 03:20:33 +0000935 if ((DemandedMask & ~KnownOne & KnownZero2) == (DemandedMask & ~KnownOne))
Chris Lattner0157e7f2006-02-11 09:31:47 +0000936 return UpdateValueUsesWith(I, I->getOperand(1));
Chris Lattner5b2edb12006-02-12 08:02:11 +0000937
938 // If all of the potentially set bits on one side are known to be set on
939 // the other side, just use the 'other' side.
940 if ((DemandedMask & (~KnownZero) & KnownOne2) ==
941 (DemandedMask & (~KnownZero)))
942 return UpdateValueUsesWith(I, I->getOperand(0));
Nate Begeman8a77efe2006-02-16 21:11:51 +0000943 if ((DemandedMask & (~KnownZero2) & KnownOne) ==
944 (DemandedMask & (~KnownZero2)))
945 return UpdateValueUsesWith(I, I->getOperand(1));
Chris Lattner0157e7f2006-02-11 09:31:47 +0000946
947 // If the RHS is a constant, see if we can simplify it.
948 if (ShrinkDemandedConstant(I, 1, DemandedMask))
949 return UpdateValueUsesWith(I, I);
950
951 // Output known-0 bits are only known if clear in both the LHS & RHS.
952 KnownZero &= KnownZero2;
953 // Output known-1 are known to be set if set in either the LHS | RHS.
954 KnownOne |= KnownOne2;
955 break;
956 case Instruction::Xor: {
957 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
958 KnownZero, KnownOne, Depth+1))
959 return true;
960 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
961 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
962 KnownZero2, KnownOne2, Depth+1))
963 return true;
964 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
965
966 // If all of the demanded bits are known zero on one side, return the other.
967 // These bits cannot contribute to the result of the 'xor'.
968 if ((DemandedMask & KnownZero) == DemandedMask)
969 return UpdateValueUsesWith(I, I->getOperand(0));
970 if ((DemandedMask & KnownZero2) == DemandedMask)
971 return UpdateValueUsesWith(I, I->getOperand(1));
972
973 // Output known-0 bits are known if clear or set in both the LHS & RHS.
974 uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
975 // Output known-1 are known to be set if set in only one of the LHS, RHS.
976 uint64_t KnownOneOut = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
977
978 // If all of the unknown bits are known to be zero on one side or the other
979 // (but not both) turn this into an *inclusive* or.
Chris Lattner5b2edb12006-02-12 08:02:11 +0000980 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattner0157e7f2006-02-11 09:31:47 +0000981 if (uint64_t UnknownBits = DemandedMask & ~(KnownZeroOut|KnownOneOut)) {
982 if ((UnknownBits & (KnownZero|KnownZero2)) == UnknownBits) {
983 Instruction *Or =
984 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
985 I->getName());
986 InsertNewInstBefore(Or, *I);
987 return UpdateValueUsesWith(I, Or);
Chris Lattner2590e512006-02-07 06:56:34 +0000988 }
989 }
Chris Lattner0157e7f2006-02-11 09:31:47 +0000990
Chris Lattner5b2edb12006-02-12 08:02:11 +0000991 // If all of the demanded bits on one side are known, and all of the set
992 // bits on that side are also known to be set on the other side, turn this
993 // into an AND, as we know the bits will be cleared.
994 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
995 if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask) { // all known
996 if ((KnownOne & KnownOne2) == KnownOne) {
997 Constant *AndC = GetConstantInType(I->getType(),
998 ~KnownOne & DemandedMask);
999 Instruction *And =
1000 BinaryOperator::createAnd(I->getOperand(0), AndC, "tmp");
1001 InsertNewInstBefore(And, *I);
1002 return UpdateValueUsesWith(I, And);
1003 }
1004 }
1005
Chris Lattner0157e7f2006-02-11 09:31:47 +00001006 // If the RHS is a constant, see if we can simplify it.
1007 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1008 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1009 return UpdateValueUsesWith(I, I);
1010
1011 KnownZero = KnownZeroOut;
1012 KnownOne = KnownOneOut;
1013 break;
1014 }
1015 case Instruction::Select:
1016 if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
1017 KnownZero, KnownOne, Depth+1))
1018 return true;
1019 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1020 KnownZero2, KnownOne2, Depth+1))
1021 return true;
1022 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1023 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1024
1025 // If the operands are constants, see if we can simplify them.
1026 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1027 return UpdateValueUsesWith(I, I);
1028 if (ShrinkDemandedConstant(I, 2, DemandedMask))
1029 return UpdateValueUsesWith(I, I);
1030
1031 // Only known if known in both the LHS and RHS.
1032 KnownOne &= KnownOne2;
1033 KnownZero &= KnownZero2;
1034 break;
Chris Lattner2590e512006-02-07 06:56:34 +00001035 case Instruction::Cast: {
1036 const Type *SrcTy = I->getOperand(0)->getType();
Chris Lattner0157e7f2006-02-11 09:31:47 +00001037 if (!SrcTy->isIntegral()) return false;
Chris Lattner2590e512006-02-07 06:56:34 +00001038
Chris Lattner0157e7f2006-02-11 09:31:47 +00001039 // If this is an integer truncate or noop, just look in the input.
1040 if (SrcTy->getPrimitiveSizeInBits() >=
1041 I->getType()->getPrimitiveSizeInBits()) {
Chris Lattner850465d2006-09-16 03:14:10 +00001042 // Cast to bool is a comparison against 0, which demands all bits. We
1043 // can't propagate anything useful up.
1044 if (I->getType() == Type::BoolTy)
1045 break;
1046
Chris Lattner0157e7f2006-02-11 09:31:47 +00001047 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1048 KnownZero, KnownOne, Depth+1))
1049 return true;
1050 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1051 break;
1052 }
1053
1054 // Sign or Zero extension. Compute the bits in the result that are not
1055 // present in the input.
1056 uint64_t NotIn = ~SrcTy->getIntegralTypeMask();
1057 uint64_t NewBits = I->getType()->getIntegralTypeMask() & NotIn;
1058
1059 // Handle zero extension.
1060 if (!SrcTy->isSigned()) {
1061 DemandedMask &= SrcTy->getIntegralTypeMask();
1062 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1063 KnownZero, KnownOne, Depth+1))
1064 return true;
1065 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1066 // The top bits are known to be zero.
1067 KnownZero |= NewBits;
1068 } else {
1069 // Sign extension.
Chris Lattner7d852282006-02-13 22:41:07 +00001070 uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
1071 int64_t InputDemandedBits = DemandedMask & SrcTy->getIntegralTypeMask();
1072
1073 // If any of the sign extended bits are demanded, we know that the sign
1074 // bit is demanded.
1075 if (NewBits & DemandedMask)
1076 InputDemandedBits |= InSignBit;
1077
1078 if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
Chris Lattner0157e7f2006-02-11 09:31:47 +00001079 KnownZero, KnownOne, Depth+1))
1080 return true;
1081 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1082
1083 // If the sign bit of the input is known set or clear, then we know the
1084 // top bits of the result.
Chris Lattner2590e512006-02-07 06:56:34 +00001085
Chris Lattner0157e7f2006-02-11 09:31:47 +00001086 // If the input sign bit is known zero, or if the NewBits are not demanded
1087 // convert this into a zero extension.
1088 if ((KnownZero & InSignBit) || (NewBits & ~DemandedMask) == NewBits) {
Chris Lattner2590e512006-02-07 06:56:34 +00001089 // Convert to unsigned first.
Reid Spencer00c482b2006-10-26 19:19:06 +00001090 Value *NewVal =
1091 InsertCastBefore(I->getOperand(0), SrcTy->getUnsignedVersion(), *I);
Chris Lattner0157e7f2006-02-11 09:31:47 +00001092 // Then cast that to the destination type.
Chris Lattner44314822006-02-07 19:07:40 +00001093 NewVal = new CastInst(NewVal, I->getType(), I->getName());
Reid Spencer00c482b2006-10-26 19:19:06 +00001094 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
Chris Lattner2590e512006-02-07 06:56:34 +00001095 return UpdateValueUsesWith(I, NewVal);
Chris Lattner0157e7f2006-02-11 09:31:47 +00001096 } else if (KnownOne & InSignBit) { // Input sign bit known set
1097 KnownOne |= NewBits;
1098 KnownZero &= ~NewBits;
1099 } else { // Input sign bit unknown
1100 KnownZero &= ~NewBits;
1101 KnownOne &= ~NewBits;
Chris Lattner2590e512006-02-07 06:56:34 +00001102 }
Chris Lattner2590e512006-02-07 06:56:34 +00001103 }
Chris Lattner0157e7f2006-02-11 09:31:47 +00001104 break;
Chris Lattner2590e512006-02-07 06:56:34 +00001105 }
Chris Lattner2590e512006-02-07 06:56:34 +00001106 case Instruction::Shl:
Reid Spencere0fc4df2006-10-20 07:07:24 +00001107 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1108 uint64_t ShiftAmt = SA->getZExtValue();
1109 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask >> ShiftAmt,
Chris Lattner0157e7f2006-02-11 09:31:47 +00001110 KnownZero, KnownOne, Depth+1))
1111 return true;
1112 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Reid Spencere0fc4df2006-10-20 07:07:24 +00001113 KnownZero <<= ShiftAmt;
1114 KnownOne <<= ShiftAmt;
1115 KnownZero |= (1ULL << ShiftAmt) - 1; // low bits known zero.
Chris Lattner0157e7f2006-02-11 09:31:47 +00001116 }
Chris Lattner2590e512006-02-07 06:56:34 +00001117 break;
1118 case Instruction::Shr:
Chris Lattner420c4bc2006-09-18 04:31:40 +00001119 // If this is an arithmetic shift right and only the low-bit is set, we can
1120 // always convert this into a logical shr, even if the shift amount is
1121 // variable. The low bit of the shift cannot be an input sign bit unless
1122 // the shift amount is >= the size of the datatype, which is undefined.
1123 if (DemandedMask == 1 && I->getType()->isSigned()) {
1124 // Convert the input to unsigned.
Reid Spencer00c482b2006-10-26 19:19:06 +00001125 Value *NewVal = InsertCastBefore(I->getOperand(0),
1126 I->getType()->getUnsignedVersion(), *I);
Chris Lattner420c4bc2006-09-18 04:31:40 +00001127 // Perform the unsigned shift right.
1128 NewVal = new ShiftInst(Instruction::Shr, NewVal, I->getOperand(1),
1129 I->getName());
Reid Spencer00c482b2006-10-26 19:19:06 +00001130 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
Chris Lattner420c4bc2006-09-18 04:31:40 +00001131 // Then cast that to the destination type.
1132 NewVal = new CastInst(NewVal, I->getType(), I->getName());
Reid Spencer00c482b2006-10-26 19:19:06 +00001133 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
Chris Lattner420c4bc2006-09-18 04:31:40 +00001134 return UpdateValueUsesWith(I, NewVal);
1135 }
1136
Reid Spencere0fc4df2006-10-20 07:07:24 +00001137 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1138 unsigned ShiftAmt = SA->getZExtValue();
Chris Lattner0157e7f2006-02-11 09:31:47 +00001139
1140 // Compute the new bits that are at the top now.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001141 uint64_t HighBits = (1ULL << ShiftAmt)-1;
1142 HighBits <<= I->getType()->getPrimitiveSizeInBits() - ShiftAmt;
Chris Lattner68e74752006-02-13 06:09:08 +00001143 uint64_t TypeMask = I->getType()->getIntegralTypeMask();
Chris Lattner0157e7f2006-02-11 09:31:47 +00001144 if (I->getType()->isUnsigned()) { // Unsigned shift right.
Chris Lattner68e74752006-02-13 06:09:08 +00001145 if (SimplifyDemandedBits(I->getOperand(0),
Reid Spencere0fc4df2006-10-20 07:07:24 +00001146 (DemandedMask << ShiftAmt) & TypeMask,
Chris Lattner0157e7f2006-02-11 09:31:47 +00001147 KnownZero, KnownOne, Depth+1))
1148 return true;
1149 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattner68e74752006-02-13 06:09:08 +00001150 KnownZero &= TypeMask;
1151 KnownOne &= TypeMask;
Reid Spencere0fc4df2006-10-20 07:07:24 +00001152 KnownZero >>= ShiftAmt;
1153 KnownOne >>= ShiftAmt;
Chris Lattner0157e7f2006-02-11 09:31:47 +00001154 KnownZero |= HighBits; // high bits known zero.
1155 } else { // Signed shift right.
Chris Lattner68e74752006-02-13 06:09:08 +00001156 if (SimplifyDemandedBits(I->getOperand(0),
Reid Spencere0fc4df2006-10-20 07:07:24 +00001157 (DemandedMask << ShiftAmt) & TypeMask,
Chris Lattner0157e7f2006-02-11 09:31:47 +00001158 KnownZero, KnownOne, Depth+1))
1159 return true;
1160 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattner68e74752006-02-13 06:09:08 +00001161 KnownZero &= TypeMask;
1162 KnownOne &= TypeMask;
Reid Spencere0fc4df2006-10-20 07:07:24 +00001163 KnownZero >>= ShiftAmt;
1164 KnownOne >>= ShiftAmt;
Chris Lattner0157e7f2006-02-11 09:31:47 +00001165
1166 // Handle the sign bits.
1167 uint64_t SignBit = 1ULL << (I->getType()->getPrimitiveSizeInBits()-1);
Reid Spencere0fc4df2006-10-20 07:07:24 +00001168 SignBit >>= ShiftAmt; // Adjust to where it is now in the mask.
Chris Lattner0157e7f2006-02-11 09:31:47 +00001169
1170 // If the input sign bit is known to be zero, or if none of the top bits
1171 // are demanded, turn this into an unsigned shift right.
1172 if ((KnownZero & SignBit) || (HighBits & ~DemandedMask) == HighBits) {
1173 // Convert the input to unsigned.
Reid Spencer00c482b2006-10-26 19:19:06 +00001174 Value *NewVal = InsertCastBefore(I->getOperand(0),
1175 I->getType()->getUnsignedVersion(), *I);
Chris Lattner0157e7f2006-02-11 09:31:47 +00001176 // Perform the unsigned shift right.
1177 NewVal = new ShiftInst(Instruction::Shr, NewVal, SA, I->getName());
Reid Spencer00c482b2006-10-26 19:19:06 +00001178 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
Chris Lattner0157e7f2006-02-11 09:31:47 +00001179 // Then cast that to the destination type.
1180 NewVal = new CastInst(NewVal, I->getType(), I->getName());
Reid Spencer00c482b2006-10-26 19:19:06 +00001181 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
Chris Lattner0157e7f2006-02-11 09:31:47 +00001182 return UpdateValueUsesWith(I, NewVal);
1183 } else if (KnownOne & SignBit) { // New bits are known one.
1184 KnownOne |= HighBits;
1185 }
Chris Lattner2590e512006-02-07 06:56:34 +00001186 }
Chris Lattner0157e7f2006-02-11 09:31:47 +00001187 }
Chris Lattner2590e512006-02-07 06:56:34 +00001188 break;
1189 }
Chris Lattner0157e7f2006-02-11 09:31:47 +00001190
1191 // If the client is only demanding bits that we know, return the known
1192 // constant.
1193 if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask)
1194 return UpdateValueUsesWith(I, GetConstantInType(I->getType(), KnownOne));
Chris Lattner2590e512006-02-07 06:56:34 +00001195 return false;
1196}
1197
Chris Lattner2deeaea2006-10-05 06:55:50 +00001198
1199/// SimplifyDemandedVectorElts - The specified value producecs a vector with
1200/// 64 or fewer elements. DemandedElts contains the set of elements that are
1201/// actually used by the caller. This method analyzes which elements of the
1202/// operand are undef and returns that information in UndefElts.
1203///
1204/// If the information about demanded elements can be used to simplify the
1205/// operation, the operation is simplified, then the resultant value is
1206/// returned. This returns null if no change was made.
1207Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1208 uint64_t &UndefElts,
1209 unsigned Depth) {
1210 unsigned VWidth = cast<PackedType>(V->getType())->getNumElements();
1211 assert(VWidth <= 64 && "Vector too wide to analyze!");
1212 uint64_t EltMask = ~0ULL >> (64-VWidth);
1213 assert(DemandedElts != EltMask && (DemandedElts & ~EltMask) == 0 &&
1214 "Invalid DemandedElts!");
1215
1216 if (isa<UndefValue>(V)) {
1217 // If the entire vector is undefined, just return this info.
1218 UndefElts = EltMask;
1219 return 0;
1220 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1221 UndefElts = EltMask;
1222 return UndefValue::get(V->getType());
1223 }
1224
1225 UndefElts = 0;
1226 if (ConstantPacked *CP = dyn_cast<ConstantPacked>(V)) {
1227 const Type *EltTy = cast<PackedType>(V->getType())->getElementType();
1228 Constant *Undef = UndefValue::get(EltTy);
1229
1230 std::vector<Constant*> Elts;
1231 for (unsigned i = 0; i != VWidth; ++i)
1232 if (!(DemandedElts & (1ULL << i))) { // If not demanded, set to undef.
1233 Elts.push_back(Undef);
1234 UndefElts |= (1ULL << i);
1235 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1236 Elts.push_back(Undef);
1237 UndefElts |= (1ULL << i);
1238 } else { // Otherwise, defined.
1239 Elts.push_back(CP->getOperand(i));
1240 }
1241
1242 // If we changed the constant, return it.
1243 Constant *NewCP = ConstantPacked::get(Elts);
1244 return NewCP != CP ? NewCP : 0;
1245 } else if (isa<ConstantAggregateZero>(V)) {
1246 // Simplify the CAZ to a ConstantPacked where the non-demanded elements are
1247 // set to undef.
1248 const Type *EltTy = cast<PackedType>(V->getType())->getElementType();
1249 Constant *Zero = Constant::getNullValue(EltTy);
1250 Constant *Undef = UndefValue::get(EltTy);
1251 std::vector<Constant*> Elts;
1252 for (unsigned i = 0; i != VWidth; ++i)
1253 Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1254 UndefElts = DemandedElts ^ EltMask;
1255 return ConstantPacked::get(Elts);
1256 }
1257
1258 if (!V->hasOneUse()) { // Other users may use these bits.
1259 if (Depth != 0) { // Not at the root.
1260 // TODO: Just compute the UndefElts information recursively.
1261 return false;
1262 }
1263 return false;
1264 } else if (Depth == 10) { // Limit search depth.
1265 return false;
1266 }
1267
1268 Instruction *I = dyn_cast<Instruction>(V);
1269 if (!I) return false; // Only analyze instructions.
1270
1271 bool MadeChange = false;
1272 uint64_t UndefElts2;
1273 Value *TmpV;
1274 switch (I->getOpcode()) {
1275 default: break;
1276
1277 case Instruction::InsertElement: {
1278 // If this is a variable index, we don't know which element it overwrites.
1279 // demand exactly the same input as we produce.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001280 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
Chris Lattner2deeaea2006-10-05 06:55:50 +00001281 if (Idx == 0) {
1282 // Note that we can't propagate undef elt info, because we don't know
1283 // which elt is getting updated.
1284 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1285 UndefElts2, Depth+1);
1286 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1287 break;
1288 }
1289
1290 // If this is inserting an element that isn't demanded, remove this
1291 // insertelement.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001292 unsigned IdxNo = Idx->getZExtValue();
Chris Lattner2deeaea2006-10-05 06:55:50 +00001293 if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1294 return AddSoonDeadInstToWorklist(*I, 0);
1295
1296 // Otherwise, the element inserted overwrites whatever was there, so the
1297 // input demanded set is simpler than the output set.
1298 TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1299 DemandedElts & ~(1ULL << IdxNo),
1300 UndefElts, Depth+1);
1301 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1302
1303 // The inserted element is defined.
1304 UndefElts |= 1ULL << IdxNo;
1305 break;
1306 }
1307
1308 case Instruction::And:
1309 case Instruction::Or:
1310 case Instruction::Xor:
1311 case Instruction::Add:
1312 case Instruction::Sub:
1313 case Instruction::Mul:
1314 // div/rem demand all inputs, because they don't want divide by zero.
1315 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1316 UndefElts, Depth+1);
1317 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1318 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1319 UndefElts2, Depth+1);
1320 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1321
1322 // Output elements are undefined if both are undefined. Consider things
1323 // like undef&0. The result is known zero, not undef.
1324 UndefElts &= UndefElts2;
1325 break;
1326
1327 case Instruction::Call: {
1328 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1329 if (!II) break;
1330 switch (II->getIntrinsicID()) {
1331 default: break;
1332
1333 // Binary vector operations that work column-wise. A dest element is a
1334 // function of the corresponding input elements from the two inputs.
1335 case Intrinsic::x86_sse_sub_ss:
1336 case Intrinsic::x86_sse_mul_ss:
1337 case Intrinsic::x86_sse_min_ss:
1338 case Intrinsic::x86_sse_max_ss:
1339 case Intrinsic::x86_sse2_sub_sd:
1340 case Intrinsic::x86_sse2_mul_sd:
1341 case Intrinsic::x86_sse2_min_sd:
1342 case Intrinsic::x86_sse2_max_sd:
1343 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1344 UndefElts, Depth+1);
1345 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1346 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1347 UndefElts2, Depth+1);
1348 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1349
1350 // If only the low elt is demanded and this is a scalarizable intrinsic,
1351 // scalarize it now.
1352 if (DemandedElts == 1) {
1353 switch (II->getIntrinsicID()) {
1354 default: break;
1355 case Intrinsic::x86_sse_sub_ss:
1356 case Intrinsic::x86_sse_mul_ss:
1357 case Intrinsic::x86_sse2_sub_sd:
1358 case Intrinsic::x86_sse2_mul_sd:
1359 // TODO: Lower MIN/MAX/ABS/etc
1360 Value *LHS = II->getOperand(1);
1361 Value *RHS = II->getOperand(2);
1362 // Extract the element as scalars.
1363 LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1364 RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1365
1366 switch (II->getIntrinsicID()) {
1367 default: assert(0 && "Case stmts out of sync!");
1368 case Intrinsic::x86_sse_sub_ss:
1369 case Intrinsic::x86_sse2_sub_sd:
1370 TmpV = InsertNewInstBefore(BinaryOperator::createSub(LHS, RHS,
1371 II->getName()), *II);
1372 break;
1373 case Intrinsic::x86_sse_mul_ss:
1374 case Intrinsic::x86_sse2_mul_sd:
1375 TmpV = InsertNewInstBefore(BinaryOperator::createMul(LHS, RHS,
1376 II->getName()), *II);
1377 break;
1378 }
1379
1380 Instruction *New =
1381 new InsertElementInst(UndefValue::get(II->getType()), TmpV, 0U,
1382 II->getName());
1383 InsertNewInstBefore(New, *II);
1384 AddSoonDeadInstToWorklist(*II, 0);
1385 return New;
1386 }
1387 }
1388
1389 // Output elements are undefined if both are undefined. Consider things
1390 // like undef&0. The result is known zero, not undef.
1391 UndefElts &= UndefElts2;
1392 break;
1393 }
1394 break;
1395 }
1396 }
1397 return MadeChange ? I : 0;
1398}
1399
Chris Lattner623826c2004-09-28 21:48:02 +00001400// isTrueWhenEqual - Return true if the specified setcondinst instruction is
1401// true when both operands are equal...
1402//
1403static bool isTrueWhenEqual(Instruction &I) {
1404 return I.getOpcode() == Instruction::SetEQ ||
1405 I.getOpcode() == Instruction::SetGE ||
1406 I.getOpcode() == Instruction::SetLE;
1407}
Chris Lattnerb8b97502003-08-13 19:01:45 +00001408
1409/// AssociativeOpt - Perform an optimization on an associative operator. This
1410/// function is designed to check a chain of associative operators for a
1411/// potential to apply a certain optimization. Since the optimization may be
1412/// applicable if the expression was reassociated, this checks the chain, then
1413/// reassociates the expression as necessary to expose the optimization
1414/// opportunity. This makes use of a special Functor, which must define
1415/// 'shouldApply' and 'apply' methods.
1416///
1417template<typename Functor>
1418Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1419 unsigned Opcode = Root.getOpcode();
1420 Value *LHS = Root.getOperand(0);
1421
1422 // Quick check, see if the immediate LHS matches...
1423 if (F.shouldApply(LHS))
1424 return F.apply(Root);
1425
1426 // Otherwise, if the LHS is not of the same opcode as the root, return.
1427 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001428 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattnerb8b97502003-08-13 19:01:45 +00001429 // Should we apply this transform to the RHS?
1430 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1431
1432 // If not to the RHS, check to see if we should apply to the LHS...
1433 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1434 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1435 ShouldApply = true;
1436 }
1437
1438 // If the functor wants to apply the optimization to the RHS of LHSI,
1439 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1440 if (ShouldApply) {
1441 BasicBlock *BB = Root.getParent();
Misha Brukmanb1c93172005-04-21 23:48:37 +00001442
Chris Lattnerb8b97502003-08-13 19:01:45 +00001443 // Now all of the instructions are in the current basic block, go ahead
1444 // and perform the reassociation.
1445 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1446
1447 // First move the selected RHS to the LHS of the root...
1448 Root.setOperand(0, LHSI->getOperand(1));
1449
1450 // Make what used to be the LHS of the root be the user of the root...
1451 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner284d3b02004-04-16 18:08:07 +00001452 if (&Root == TmpLHSI) {
Chris Lattner8953b902004-04-05 02:10:19 +00001453 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1454 return 0;
1455 }
Chris Lattner284d3b02004-04-16 18:08:07 +00001456 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattnerb8b97502003-08-13 19:01:45 +00001457 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner284d3b02004-04-16 18:08:07 +00001458 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
1459 BasicBlock::iterator ARI = &Root; ++ARI;
1460 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
1461 ARI = Root;
Chris Lattnerb8b97502003-08-13 19:01:45 +00001462
1463 // Now propagate the ExtraOperand down the chain of instructions until we
1464 // get to LHSI.
1465 while (TmpLHSI != LHSI) {
1466 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner284d3b02004-04-16 18:08:07 +00001467 // Move the instruction to immediately before the chain we are
1468 // constructing to avoid breaking dominance properties.
1469 NextLHSI->getParent()->getInstList().remove(NextLHSI);
1470 BB->getInstList().insert(ARI, NextLHSI);
1471 ARI = NextLHSI;
1472
Chris Lattnerb8b97502003-08-13 19:01:45 +00001473 Value *NextOp = NextLHSI->getOperand(1);
1474 NextLHSI->setOperand(1, ExtraOperand);
1475 TmpLHSI = NextLHSI;
1476 ExtraOperand = NextOp;
1477 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001478
Chris Lattnerb8b97502003-08-13 19:01:45 +00001479 // Now that the instructions are reassociated, have the functor perform
1480 // the transformation...
1481 return F.apply(Root);
1482 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001483
Chris Lattnerb8b97502003-08-13 19:01:45 +00001484 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1485 }
1486 return 0;
1487}
1488
1489
1490// AddRHS - Implements: X + X --> X << 1
1491struct AddRHS {
1492 Value *RHS;
1493 AddRHS(Value *rhs) : RHS(rhs) {}
1494 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1495 Instruction *apply(BinaryOperator &Add) const {
1496 return new ShiftInst(Instruction::Shl, Add.getOperand(0),
1497 ConstantInt::get(Type::UByteTy, 1));
1498 }
1499};
1500
1501// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1502// iff C1&C2 == 0
1503struct AddMaskingAnd {
1504 Constant *C2;
1505 AddMaskingAnd(Constant *c) : C2(c) {}
1506 bool shouldApply(Value *LHS) const {
Chris Lattnerd4252a72004-07-30 07:50:03 +00001507 ConstantInt *C1;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001508 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Chris Lattnerd4252a72004-07-30 07:50:03 +00001509 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattnerb8b97502003-08-13 19:01:45 +00001510 }
1511 Instruction *apply(BinaryOperator &Add) const {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001512 return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattnerb8b97502003-08-13 19:01:45 +00001513 }
1514};
1515
Chris Lattner86102b82005-01-01 16:22:27 +00001516static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner183b3362004-04-09 19:05:30 +00001517 InstCombiner *IC) {
Chris Lattner86102b82005-01-01 16:22:27 +00001518 if (isa<CastInst>(I)) {
1519 if (Constant *SOC = dyn_cast<Constant>(SO))
1520 return ConstantExpr::getCast(SOC, I.getType());
Misha Brukmanb1c93172005-04-21 23:48:37 +00001521
Chris Lattner86102b82005-01-01 16:22:27 +00001522 return IC->InsertNewInstBefore(new CastInst(SO, I.getType(),
1523 SO->getName() + ".cast"), I);
1524 }
1525
Chris Lattner183b3362004-04-09 19:05:30 +00001526 // Figure out if the constant is the left or the right argument.
Chris Lattner86102b82005-01-01 16:22:27 +00001527 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1528 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattnerb8b97502003-08-13 19:01:45 +00001529
Chris Lattner183b3362004-04-09 19:05:30 +00001530 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1531 if (ConstIsRHS)
Chris Lattner86102b82005-01-01 16:22:27 +00001532 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1533 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner183b3362004-04-09 19:05:30 +00001534 }
1535
1536 Value *Op0 = SO, *Op1 = ConstOperand;
1537 if (!ConstIsRHS)
1538 std::swap(Op0, Op1);
1539 Instruction *New;
Chris Lattner86102b82005-01-01 16:22:27 +00001540 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1541 New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
1542 else if (ShiftInst *SI = dyn_cast<ShiftInst>(&I))
1543 New = new ShiftInst(SI->getOpcode(), Op0, Op1, SO->getName()+".sh");
Chris Lattnerf9d96652004-04-10 19:15:56 +00001544 else {
Chris Lattner183b3362004-04-09 19:05:30 +00001545 assert(0 && "Unknown binary instruction type!");
Chris Lattnerf9d96652004-04-10 19:15:56 +00001546 abort();
1547 }
Chris Lattner86102b82005-01-01 16:22:27 +00001548 return IC->InsertNewInstBefore(New, I);
1549}
1550
1551// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1552// constant as the other operand, try to fold the binary operator into the
1553// select arguments. This also works for Cast instructions, which obviously do
1554// not have a second operand.
1555static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1556 InstCombiner *IC) {
1557 // Don't modify shared select instructions
1558 if (!SI->hasOneUse()) return 0;
1559 Value *TV = SI->getOperand(1);
1560 Value *FV = SI->getOperand(2);
1561
1562 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner374e6592005-04-21 05:43:13 +00001563 // Bool selects with constant operands can be folded to logical ops.
1564 if (SI->getType() == Type::BoolTy) return 0;
1565
Chris Lattner86102b82005-01-01 16:22:27 +00001566 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1567 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1568
1569 return new SelectInst(SI->getCondition(), SelectTrueVal,
1570 SelectFalseVal);
1571 }
1572 return 0;
Chris Lattner183b3362004-04-09 19:05:30 +00001573}
1574
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001575
1576/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1577/// node as operand #0, see if we can fold the instruction into the PHI (which
1578/// is only possible if all operands to the PHI are constants).
1579Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1580 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattner7515cab2004-11-14 19:13:23 +00001581 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner04689872006-09-09 22:02:56 +00001582 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001583
Chris Lattner04689872006-09-09 22:02:56 +00001584 // Check to see if all of the operands of the PHI are constants. If there is
1585 // one non-constant value, remember the BB it is. If there is more than one
1586 // bail out.
1587 BasicBlock *NonConstBB = 0;
1588 for (unsigned i = 0; i != NumPHIValues; ++i)
1589 if (!isa<Constant>(PN->getIncomingValue(i))) {
1590 if (NonConstBB) return 0; // More than one non-const value.
1591 NonConstBB = PN->getIncomingBlock(i);
1592
1593 // If the incoming non-constant value is in I's block, we have an infinite
1594 // loop.
1595 if (NonConstBB == I.getParent())
1596 return 0;
1597 }
1598
1599 // If there is exactly one non-constant value, we can insert a copy of the
1600 // operation in that block. However, if this is a critical edge, we would be
1601 // inserting the computation one some other paths (e.g. inside a loop). Only
1602 // do this if the pred block is unconditionally branching into the phi block.
1603 if (NonConstBB) {
1604 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1605 if (!BI || !BI->isUnconditional()) return 0;
1606 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001607
1608 // Okay, we can do the transformation: create the new PHI node.
1609 PHINode *NewPN = new PHINode(I.getType(), I.getName());
1610 I.setName("");
Chris Lattnerd8e20182005-01-29 00:39:08 +00001611 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001612 InsertNewInstBefore(NewPN, *PN);
1613
1614 // Next, add all of the operands to the PHI.
1615 if (I.getNumOperands() == 2) {
1616 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattner7515cab2004-11-14 19:13:23 +00001617 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner04689872006-09-09 22:02:56 +00001618 Value *InV;
1619 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1620 InV = ConstantExpr::get(I.getOpcode(), InC, C);
1621 } else {
1622 assert(PN->getIncomingBlock(i) == NonConstBB);
1623 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1624 InV = BinaryOperator::create(BO->getOpcode(),
1625 PN->getIncomingValue(i), C, "phitmp",
1626 NonConstBB->getTerminator());
1627 else if (ShiftInst *SI = dyn_cast<ShiftInst>(&I))
1628 InV = new ShiftInst(SI->getOpcode(),
1629 PN->getIncomingValue(i), C, "phitmp",
1630 NonConstBB->getTerminator());
1631 else
1632 assert(0 && "Unknown binop!");
1633
1634 WorkList.push_back(cast<Instruction>(InV));
1635 }
1636 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001637 }
1638 } else {
1639 assert(isa<CastInst>(I) && "Unary op should be a cast!");
1640 const Type *RetTy = I.getType();
Chris Lattner7515cab2004-11-14 19:13:23 +00001641 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner04689872006-09-09 22:02:56 +00001642 Value *InV;
1643 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1644 InV = ConstantExpr::getCast(InC, RetTy);
1645 } else {
1646 assert(PN->getIncomingBlock(i) == NonConstBB);
1647 InV = new CastInst(PN->getIncomingValue(i), I.getType(), "phitmp",
1648 NonConstBB->getTerminator());
1649 WorkList.push_back(cast<Instruction>(InV));
1650 }
1651 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001652 }
1653 }
1654 return ReplaceInstUsesWith(I, NewPN);
1655}
1656
Chris Lattner113f4f42002-06-25 16:13:24 +00001657Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001658 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00001659 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattner9fa53de2002-05-06 16:49:18 +00001660
Chris Lattnercf4a9962004-04-10 22:01:55 +00001661 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattner81a7a232004-10-16 18:11:37 +00001662 // X + undef -> undef
1663 if (isa<UndefValue>(RHS))
1664 return ReplaceInstUsesWith(I, RHS);
1665
Chris Lattnercf4a9962004-04-10 22:01:55 +00001666 // X + 0 --> X
Chris Lattner7fde91e2005-10-17 17:56:38 +00001667 if (!I.getType()->isFloatingPoint()) { // NOTE: -0 + +0 = +0.
1668 if (RHSC->isNullValue())
1669 return ReplaceInstUsesWith(I, LHS);
Chris Lattnerda1b1522005-10-17 20:18:38 +00001670 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
1671 if (CFP->isExactlyValue(-0.0))
1672 return ReplaceInstUsesWith(I, LHS);
Chris Lattner7fde91e2005-10-17 17:56:38 +00001673 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001674
Chris Lattnercf4a9962004-04-10 22:01:55 +00001675 // X + (signbit) --> X ^ signbit
1676 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattner92a68652006-02-07 08:05:22 +00001677 uint64_t Val = CI->getZExtValue();
Chris Lattner77defba2006-02-07 07:00:41 +00001678 if (Val == (1ULL << (CI->getType()->getPrimitiveSizeInBits()-1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001679 return BinaryOperator::createXor(LHS, RHS);
Chris Lattnercf4a9962004-04-10 22:01:55 +00001680 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001681
1682 if (isa<PHINode>(LHS))
1683 if (Instruction *NV = FoldOpIntoPhi(I))
1684 return NV;
Chris Lattner0b3557f2005-09-24 23:43:33 +00001685
Chris Lattner330628a2006-01-06 17:59:59 +00001686 ConstantInt *XorRHS = 0;
1687 Value *XorLHS = 0;
Chris Lattner0b3557f2005-09-24 23:43:33 +00001688 if (match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
1689 unsigned TySizeBits = I.getType()->getPrimitiveSizeInBits();
1690 int64_t RHSSExt = cast<ConstantInt>(RHSC)->getSExtValue();
1691 uint64_t RHSZExt = cast<ConstantInt>(RHSC)->getZExtValue();
1692
1693 uint64_t C0080Val = 1ULL << 31;
1694 int64_t CFF80Val = -C0080Val;
1695 unsigned Size = 32;
1696 do {
1697 if (TySizeBits > Size) {
1698 bool Found = false;
1699 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
1700 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
1701 if (RHSSExt == CFF80Val) {
1702 if (XorRHS->getZExtValue() == C0080Val)
1703 Found = true;
1704 } else if (RHSZExt == C0080Val) {
1705 if (XorRHS->getSExtValue() == CFF80Val)
1706 Found = true;
1707 }
1708 if (Found) {
1709 // This is a sign extend if the top bits are known zero.
Chris Lattner4534dd592006-02-09 07:38:58 +00001710 uint64_t Mask = ~0ULL;
Chris Lattnerc3ebf402006-02-07 07:27:52 +00001711 Mask <<= 64-(TySizeBits-Size);
Chris Lattner4534dd592006-02-09 07:38:58 +00001712 Mask &= XorLHS->getType()->getIntegralTypeMask();
Chris Lattnerc3ebf402006-02-07 07:27:52 +00001713 if (!MaskedValueIsZero(XorLHS, Mask))
Chris Lattner0b3557f2005-09-24 23:43:33 +00001714 Size = 0; // Not a sign ext, but can't be any others either.
1715 goto FoundSExt;
1716 }
1717 }
1718 Size >>= 1;
1719 C0080Val >>= Size;
1720 CFF80Val >>= Size;
1721 } while (Size >= 8);
1722
1723FoundSExt:
1724 const Type *MiddleType = 0;
1725 switch (Size) {
1726 default: break;
1727 case 32: MiddleType = Type::IntTy; break;
1728 case 16: MiddleType = Type::ShortTy; break;
1729 case 8: MiddleType = Type::SByteTy; break;
1730 }
1731 if (MiddleType) {
1732 Instruction *NewTrunc = new CastInst(XorLHS, MiddleType, "sext");
1733 InsertNewInstBefore(NewTrunc, I);
1734 return new CastInst(NewTrunc, I.getType());
1735 }
1736 }
Chris Lattnercf4a9962004-04-10 22:01:55 +00001737 }
Chris Lattner9fa53de2002-05-06 16:49:18 +00001738
Chris Lattnerb8b97502003-08-13 19:01:45 +00001739 // X + X --> X << 1
Robert Bocchino7b5b86c2004-07-27 21:02:21 +00001740 if (I.getType()->isInteger()) {
Chris Lattnerb8b97502003-08-13 19:01:45 +00001741 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Chris Lattner47060462005-04-07 17:14:51 +00001742
1743 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
1744 if (RHSI->getOpcode() == Instruction::Sub)
1745 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
1746 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
1747 }
1748 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
1749 if (LHSI->getOpcode() == Instruction::Sub)
1750 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
1751 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
1752 }
Robert Bocchino7b5b86c2004-07-27 21:02:21 +00001753 }
Chris Lattnerede3fe02003-08-13 04:18:28 +00001754
Chris Lattner147e9752002-05-08 22:46:53 +00001755 // -A + B --> B - A
Chris Lattnerbb74e222003-03-10 23:06:50 +00001756 if (Value *V = dyn_castNegVal(LHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001757 return BinaryOperator::createSub(RHS, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +00001758
1759 // A + -B --> A - B
Chris Lattnerbb74e222003-03-10 23:06:50 +00001760 if (!isa<Constant>(RHS))
1761 if (Value *V = dyn_castNegVal(RHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001762 return BinaryOperator::createSub(LHS, V);
Chris Lattner260ab202002-04-18 17:39:14 +00001763
Misha Brukmanb1c93172005-04-21 23:48:37 +00001764
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001765 ConstantInt *C2;
1766 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
1767 if (X == RHS) // X*C + X --> X * (C+1)
1768 return BinaryOperator::createMul(RHS, AddOne(C2));
1769
1770 // X*C1 + X*C2 --> X * (C1+C2)
1771 ConstantInt *C1;
1772 if (X == dyn_castFoldableMul(RHS, C1))
1773 return BinaryOperator::createMul(X, ConstantExpr::getAdd(C1, C2));
Chris Lattner57c8d992003-02-18 19:57:07 +00001774 }
1775
1776 // X + X*C --> X * (C+1)
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001777 if (dyn_castFoldableMul(RHS, C2) == LHS)
1778 return BinaryOperator::createMul(LHS, AddOne(C2));
1779
Chris Lattner57c8d992003-02-18 19:57:07 +00001780
Chris Lattnerb8b97502003-08-13 19:01:45 +00001781 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattnerd4252a72004-07-30 07:50:03 +00001782 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattnerb8b97502003-08-13 19:01:45 +00001783 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2))) return R;
Chris Lattner7fb29e12003-03-11 00:12:48 +00001784
Chris Lattnerb9cde762003-10-02 15:11:26 +00001785 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner330628a2006-01-06 17:59:59 +00001786 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00001787 if (match(LHS, m_Not(m_Value(X)))) { // ~X + C --> (C-1) - X
1788 Constant *C= ConstantExpr::getSub(CRHS, ConstantInt::get(I.getType(), 1));
1789 return BinaryOperator::createSub(C, X);
Chris Lattnerb9cde762003-10-02 15:11:26 +00001790 }
Chris Lattnerd4252a72004-07-30 07:50:03 +00001791
Chris Lattnerbff91d92004-10-08 05:07:56 +00001792 // (X & FF00) + xx00 -> (X+xx00) & FF00
1793 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
1794 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
1795 if (Anded == CRHS) {
1796 // See if all bits from the first bit set in the Add RHS up are included
1797 // in the mask. First, get the rightmost bit.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001798 uint64_t AddRHSV = CRHS->getZExtValue();
Chris Lattnerbff91d92004-10-08 05:07:56 +00001799
1800 // Form a mask of all bits from the lowest bit added through the top.
1801 uint64_t AddRHSHighBits = ~((AddRHSV & -AddRHSV)-1);
Chris Lattner77defba2006-02-07 07:00:41 +00001802 AddRHSHighBits &= C2->getType()->getIntegralTypeMask();
Chris Lattnerbff91d92004-10-08 05:07:56 +00001803
1804 // See if the and mask includes all of these bits.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001805 uint64_t AddRHSHighBitsAnd = AddRHSHighBits & C2->getZExtValue();
Misha Brukmanb1c93172005-04-21 23:48:37 +00001806
Chris Lattnerbff91d92004-10-08 05:07:56 +00001807 if (AddRHSHighBits == AddRHSHighBitsAnd) {
1808 // Okay, the xform is safe. Insert the new add pronto.
1809 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
1810 LHS->getName()), I);
1811 return BinaryOperator::createAnd(NewAdd, C2);
1812 }
1813 }
1814 }
1815
Chris Lattnerd4252a72004-07-30 07:50:03 +00001816 // Try to fold constant add into select arguments.
1817 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner86102b82005-01-01 16:22:27 +00001818 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattnerd4252a72004-07-30 07:50:03 +00001819 return R;
Chris Lattnerb9cde762003-10-02 15:11:26 +00001820 }
1821
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001822 // add (cast *A to intptrtype) B ->
1823 // cast (GEP (cast *A to sbyte*) B) ->
1824 // intptrtype
Andrew Lenharth4f339be2006-09-19 18:24:51 +00001825 {
1826 CastInst* CI = dyn_cast<CastInst>(LHS);
1827 Value* Other = RHS;
1828 if (!CI) {
1829 CI = dyn_cast<CastInst>(RHS);
1830 Other = LHS;
1831 }
Andrew Lenharth44cb67a2006-09-20 15:37:57 +00001832 if (CI && CI->getType()->isSized() &&
1833 (CI->getType()->getPrimitiveSize() ==
1834 TD->getIntPtrType()->getPrimitiveSize())
1835 && isa<PointerType>(CI->getOperand(0)->getType())) {
1836 Value* I2 = InsertCastBefore(CI->getOperand(0),
1837 PointerType::get(Type::SByteTy), I);
1838 I2 = InsertNewInstBefore(new GetElementPtrInst(I2, Other, "ctg2"), I);
1839 return new CastInst(I2, CI->getType());
Andrew Lenharth4f339be2006-09-19 18:24:51 +00001840 }
1841 }
1842
Chris Lattner113f4f42002-06-25 16:13:24 +00001843 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +00001844}
1845
Chris Lattnerbdb0ce02003-07-22 21:46:59 +00001846// isSignBit - Return true if the value represented by the constant only has the
1847// highest order bit set.
1848static bool isSignBit(ConstantInt *CI) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001849 unsigned NumBits = CI->getType()->getPrimitiveSizeInBits();
Reid Spencere0fc4df2006-10-20 07:07:24 +00001850 return (CI->getZExtValue() & (~0ULL >> (64-NumBits))) == (1ULL << (NumBits-1));
Chris Lattnerbdb0ce02003-07-22 21:46:59 +00001851}
1852
Chris Lattner022167f2004-03-13 00:11:49 +00001853/// RemoveNoopCast - Strip off nonconverting casts from the value.
1854///
1855static Value *RemoveNoopCast(Value *V) {
1856 if (CastInst *CI = dyn_cast<CastInst>(V)) {
1857 const Type *CTy = CI->getType();
1858 const Type *OpTy = CI->getOperand(0)->getType();
1859 if (CTy->isInteger() && OpTy->isInteger()) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001860 if (CTy->getPrimitiveSizeInBits() == OpTy->getPrimitiveSizeInBits())
Chris Lattner022167f2004-03-13 00:11:49 +00001861 return RemoveNoopCast(CI->getOperand(0));
1862 } else if (isa<PointerType>(CTy) && isa<PointerType>(OpTy))
1863 return RemoveNoopCast(CI->getOperand(0));
1864 }
1865 return V;
1866}
1867
Chris Lattner113f4f42002-06-25 16:13:24 +00001868Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +00001869 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001870
Chris Lattnere6794492002-08-12 21:17:25 +00001871 if (Op0 == Op1) // sub X, X -> 0
1872 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner260ab202002-04-18 17:39:14 +00001873
Chris Lattnere6794492002-08-12 21:17:25 +00001874 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattnerbb74e222003-03-10 23:06:50 +00001875 if (Value *V = dyn_castNegVal(Op1))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001876 return BinaryOperator::createAdd(Op0, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +00001877
Chris Lattner81a7a232004-10-16 18:11:37 +00001878 if (isa<UndefValue>(Op0))
1879 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
1880 if (isa<UndefValue>(Op1))
1881 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
1882
Chris Lattner8f2f5982003-11-05 01:06:05 +00001883 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
1884 // Replace (-1 - A) with (~A)...
Chris Lattner3082c5a2003-02-18 19:28:33 +00001885 if (C->isAllOnesValue())
1886 return BinaryOperator::createNot(Op1);
Chris Lattnerad3c4952002-05-09 01:29:19 +00001887
Chris Lattner8f2f5982003-11-05 01:06:05 +00001888 // C - ~X == X + (1+C)
Reid Spencer4fdd96c2005-06-18 17:37:34 +00001889 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00001890 if (match(Op1, m_Not(m_Value(X))))
1891 return BinaryOperator::createAdd(X,
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001892 ConstantExpr::getAdd(C, ConstantInt::get(I.getType(), 1)));
Chris Lattner92295c52004-03-12 23:53:13 +00001893 // -((uint)X >> 31) -> ((int)X >> 31)
1894 // -((int)X >> 31) -> ((uint)X >> 31)
Chris Lattner022167f2004-03-13 00:11:49 +00001895 if (C->isNullValue()) {
1896 Value *NoopCastedRHS = RemoveNoopCast(Op1);
1897 if (ShiftInst *SI = dyn_cast<ShiftInst>(NoopCastedRHS))
Chris Lattner92295c52004-03-12 23:53:13 +00001898 if (SI->getOpcode() == Instruction::Shr)
Reid Spencere0fc4df2006-10-20 07:07:24 +00001899 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
Chris Lattner92295c52004-03-12 23:53:13 +00001900 const Type *NewTy;
Chris Lattner022167f2004-03-13 00:11:49 +00001901 if (SI->getType()->isSigned())
Chris Lattner97bfcea2004-06-17 18:16:02 +00001902 NewTy = SI->getType()->getUnsignedVersion();
Chris Lattner92295c52004-03-12 23:53:13 +00001903 else
Chris Lattner97bfcea2004-06-17 18:16:02 +00001904 NewTy = SI->getType()->getSignedVersion();
Chris Lattner92295c52004-03-12 23:53:13 +00001905 // Check to see if we are shifting out everything but the sign bit.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001906 if (CU->getZExtValue() ==
1907 SI->getType()->getPrimitiveSizeInBits()-1) {
Chris Lattner92295c52004-03-12 23:53:13 +00001908 // Ok, the transformation is safe. Insert a cast of the incoming
1909 // value, then the new shift, then the new cast.
Reid Spencer00c482b2006-10-26 19:19:06 +00001910 Value *InV = InsertCastBefore(SI->getOperand(0), NewTy, I);
1911 Instruction *NewShift = new ShiftInst(Instruction::Shr, InV,
Chris Lattner92295c52004-03-12 23:53:13 +00001912 CU, SI->getName());
Chris Lattner022167f2004-03-13 00:11:49 +00001913 if (NewShift->getType() == I.getType())
1914 return NewShift;
1915 else {
Reid Spencer00c482b2006-10-26 19:19:06 +00001916 InsertNewInstBefore(NewShift, I);
Chris Lattner022167f2004-03-13 00:11:49 +00001917 return new CastInst(NewShift, I.getType());
1918 }
Chris Lattner92295c52004-03-12 23:53:13 +00001919 }
1920 }
Chris Lattner022167f2004-03-13 00:11:49 +00001921 }
Chris Lattner183b3362004-04-09 19:05:30 +00001922
1923 // Try to fold constant sub into select arguments.
1924 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner86102b82005-01-01 16:22:27 +00001925 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00001926 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001927
1928 if (isa<PHINode>(Op0))
1929 if (Instruction *NV = FoldOpIntoPhi(I))
1930 return NV;
Chris Lattner8f2f5982003-11-05 01:06:05 +00001931 }
1932
Chris Lattnera9be4492005-04-07 16:15:25 +00001933 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
1934 if (Op1I->getOpcode() == Instruction::Add &&
1935 !Op0->getType()->isFloatingPoint()) {
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00001936 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Chris Lattnera9be4492005-04-07 16:15:25 +00001937 return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00001938 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Chris Lattnera9be4492005-04-07 16:15:25 +00001939 return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00001940 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
1941 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
1942 // C1-(X+C2) --> (C1-C2)-X
1943 return BinaryOperator::createSub(ConstantExpr::getSub(CI1, CI2),
1944 Op1I->getOperand(0));
1945 }
Chris Lattnera9be4492005-04-07 16:15:25 +00001946 }
1947
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001948 if (Op1I->hasOneUse()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00001949 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
1950 // is not used by anyone else...
1951 //
Chris Lattnerc2f0aa52004-02-02 20:09:56 +00001952 if (Op1I->getOpcode() == Instruction::Sub &&
1953 !Op1I->getType()->isFloatingPoint()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00001954 // Swap the two operands of the subexpr...
1955 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
1956 Op1I->setOperand(0, IIOp1);
1957 Op1I->setOperand(1, IIOp0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001958
Chris Lattner3082c5a2003-02-18 19:28:33 +00001959 // Create the new top level add instruction...
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001960 return BinaryOperator::createAdd(Op0, Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001961 }
1962
1963 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
1964 //
1965 if (Op1I->getOpcode() == Instruction::And &&
1966 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
1967 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
1968
Chris Lattner396dbfe2004-06-09 05:08:07 +00001969 Value *NewNot =
1970 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001971 return BinaryOperator::createAnd(Op0, NewNot);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001972 }
Chris Lattner57c8d992003-02-18 19:57:07 +00001973
Reid Spencer3c514952006-10-16 23:08:08 +00001974 // 0 - (X sdiv C) -> (X sdiv -C)
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001975 if (Op1I->getOpcode() == Instruction::SDiv)
Reid Spencere0fc4df2006-10-20 07:07:24 +00001976 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001977 if (CSI->isNullValue())
Chris Lattner0aee4b72004-10-06 15:08:25 +00001978 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001979 return BinaryOperator::createSDiv(Op1I->getOperand(0),
Chris Lattner0aee4b72004-10-06 15:08:25 +00001980 ConstantExpr::getNeg(DivRHS));
1981
Chris Lattner57c8d992003-02-18 19:57:07 +00001982 // X - X*C --> X * (1-C)
Reid Spencer4fdd96c2005-06-18 17:37:34 +00001983 ConstantInt *C2 = 0;
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001984 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00001985 Constant *CP1 =
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001986 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1), C2);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001987 return BinaryOperator::createMul(Op0, CP1);
Chris Lattner57c8d992003-02-18 19:57:07 +00001988 }
Chris Lattnerad3c4952002-05-09 01:29:19 +00001989 }
Chris Lattnera9be4492005-04-07 16:15:25 +00001990 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00001991
Chris Lattner47060462005-04-07 17:14:51 +00001992 if (!Op0->getType()->isFloatingPoint())
1993 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
1994 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner411336f2005-01-19 21:50:18 +00001995 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
1996 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
1997 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
1998 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner47060462005-04-07 17:14:51 +00001999 } else if (Op0I->getOpcode() == Instruction::Sub) {
2000 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
2001 return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
Chris Lattner411336f2005-01-19 21:50:18 +00002002 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002003
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002004 ConstantInt *C1;
2005 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2006 if (X == Op1) { // X*C - X --> X * (C-1)
2007 Constant *CP1 = ConstantExpr::getSub(C1, ConstantInt::get(I.getType(),1));
2008 return BinaryOperator::createMul(Op1, CP1);
2009 }
Chris Lattner57c8d992003-02-18 19:57:07 +00002010
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002011 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
2012 if (X == dyn_castFoldableMul(Op1, C2))
2013 return BinaryOperator::createMul(Op1, ConstantExpr::getSub(C1, C2));
2014 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002015 return 0;
Chris Lattner260ab202002-04-18 17:39:14 +00002016}
2017
Chris Lattnere79e8542004-02-23 06:38:22 +00002018/// isSignBitCheck - Given an exploded setcc instruction, return true if it is
2019/// really just returns true if the most significant (sign) bit is set.
2020static bool isSignBitCheck(unsigned Opcode, Value *LHS, ConstantInt *RHS) {
2021 if (RHS->getType()->isSigned()) {
2022 // True if source is LHS < 0 or LHS <= -1
2023 return Opcode == Instruction::SetLT && RHS->isNullValue() ||
2024 Opcode == Instruction::SetLE && RHS->isAllOnesValue();
2025 } else {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002026 ConstantInt *RHSC = cast<ConstantInt>(RHS);
Chris Lattnere79e8542004-02-23 06:38:22 +00002027 // True if source is LHS > 127 or LHS >= 128, where the constants depend on
2028 // the size of the integer type.
2029 if (Opcode == Instruction::SetGE)
Reid Spencere0fc4df2006-10-20 07:07:24 +00002030 return RHSC->getZExtValue() ==
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002031 1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1);
Chris Lattnere79e8542004-02-23 06:38:22 +00002032 if (Opcode == Instruction::SetGT)
Reid Spencere0fc4df2006-10-20 07:07:24 +00002033 return RHSC->getZExtValue() ==
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002034 (1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1))-1;
Chris Lattnere79e8542004-02-23 06:38:22 +00002035 }
2036 return false;
2037}
2038
Chris Lattner113f4f42002-06-25 16:13:24 +00002039Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00002040 bool Changed = SimplifyCommutative(I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002041 Value *Op0 = I.getOperand(0);
Chris Lattner260ab202002-04-18 17:39:14 +00002042
Chris Lattner81a7a232004-10-16 18:11:37 +00002043 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
2044 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2045
Chris Lattnere6794492002-08-12 21:17:25 +00002046 // Simplify mul instructions with a constant RHS...
Chris Lattner3082c5a2003-02-18 19:28:33 +00002047 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2048 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerede3fe02003-08-13 04:18:28 +00002049
2050 // ((X << C1)*C2) == (X * (C2 << C1))
2051 if (ShiftInst *SI = dyn_cast<ShiftInst>(Op0))
2052 if (SI->getOpcode() == Instruction::Shl)
2053 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002054 return BinaryOperator::createMul(SI->getOperand(0),
2055 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanb1c93172005-04-21 23:48:37 +00002056
Chris Lattnercce81be2003-09-11 22:24:54 +00002057 if (CI->isNullValue())
2058 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2059 if (CI->equalsInt(1)) // X * 1 == X
2060 return ReplaceInstUsesWith(I, Op0);
2061 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Chris Lattner35236d82003-06-25 17:09:20 +00002062 return BinaryOperator::createNeg(Op0, I.getName());
Chris Lattner31ba1292002-04-29 22:24:47 +00002063
Reid Spencere0fc4df2006-10-20 07:07:24 +00002064 int64_t Val = (int64_t)cast<ConstantInt>(CI)->getZExtValue();
Chris Lattner22d00a82005-08-02 19:16:58 +00002065 if (isPowerOf2_64(Val)) { // Replace X*(2^C) with X << C
2066 uint64_t C = Log2_64(Val);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002067 return new ShiftInst(Instruction::Shl, Op0,
Reid Spencere0fc4df2006-10-20 07:07:24 +00002068 ConstantInt::get(Type::UByteTy, C));
Chris Lattner22d00a82005-08-02 19:16:58 +00002069 }
Robert Bocchino7b5b86c2004-07-27 21:02:21 +00002070 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00002071 if (Op1F->isNullValue())
2072 return ReplaceInstUsesWith(I, Op1);
Chris Lattner31ba1292002-04-29 22:24:47 +00002073
Chris Lattner3082c5a2003-02-18 19:28:33 +00002074 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2075 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2076 if (Op1F->getValue() == 1.0)
2077 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
2078 }
Chris Lattner32c01df2006-03-04 06:04:02 +00002079
2080 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2081 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2082 isa<ConstantInt>(Op0I->getOperand(1))) {
2083 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2084 Instruction *Add = BinaryOperator::createMul(Op0I->getOperand(0),
2085 Op1, "tmp");
2086 InsertNewInstBefore(Add, I);
2087 Value *C1C2 = ConstantExpr::getMul(Op1,
2088 cast<Constant>(Op0I->getOperand(1)));
2089 return BinaryOperator::createAdd(Add, C1C2);
2090
2091 }
Chris Lattner183b3362004-04-09 19:05:30 +00002092
2093 // Try to fold constant mul into select arguments.
2094 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00002095 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00002096 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002097
2098 if (isa<PHINode>(Op0))
2099 if (Instruction *NV = FoldOpIntoPhi(I))
2100 return NV;
Chris Lattner260ab202002-04-18 17:39:14 +00002101 }
2102
Chris Lattner934a64cf2003-03-10 23:23:04 +00002103 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
2104 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002105 return BinaryOperator::createMul(Op0v, Op1v);
Chris Lattner934a64cf2003-03-10 23:23:04 +00002106
Chris Lattner2635b522004-02-23 05:39:21 +00002107 // If one of the operands of the multiply is a cast from a boolean value, then
2108 // we know the bool is either zero or one, so this is a 'masking' multiply.
2109 // See if we can simplify things based on how the boolean was originally
2110 // formed.
2111 CastInst *BoolCast = 0;
2112 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(0)))
2113 if (CI->getOperand(0)->getType() == Type::BoolTy)
2114 BoolCast = CI;
2115 if (!BoolCast)
2116 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(1)))
2117 if (CI->getOperand(0)->getType() == Type::BoolTy)
2118 BoolCast = CI;
2119 if (BoolCast) {
2120 if (SetCondInst *SCI = dyn_cast<SetCondInst>(BoolCast->getOperand(0))) {
2121 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2122 const Type *SCOpTy = SCIOp0->getType();
2123
Chris Lattnere79e8542004-02-23 06:38:22 +00002124 // If the setcc is true iff the sign bit of X is set, then convert this
2125 // multiply into a shift/and combination.
2126 if (isa<ConstantInt>(SCIOp1) &&
2127 isSignBitCheck(SCI->getOpcode(), SCIOp0, cast<ConstantInt>(SCIOp1))) {
Chris Lattner2635b522004-02-23 05:39:21 +00002128 // Shift the X value right to turn it into "all signbits".
Reid Spencere0fc4df2006-10-20 07:07:24 +00002129 Constant *Amt = ConstantInt::get(Type::UByteTy,
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002130 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattnere79e8542004-02-23 06:38:22 +00002131 if (SCIOp0->getType()->isUnsigned()) {
Chris Lattner97bfcea2004-06-17 18:16:02 +00002132 const Type *NewTy = SCIOp0->getType()->getSignedVersion();
Reid Spencer00c482b2006-10-26 19:19:06 +00002133 SCIOp0 = InsertCastBefore(SCIOp0, NewTy, I);
Chris Lattnere79e8542004-02-23 06:38:22 +00002134 }
2135
2136 Value *V =
2137 InsertNewInstBefore(new ShiftInst(Instruction::Shr, SCIOp0, Amt,
2138 BoolCast->getOperand(0)->getName()+
2139 ".mask"), I);
Chris Lattner2635b522004-02-23 05:39:21 +00002140
2141 // If the multiply type is not the same as the source type, sign extend
2142 // or truncate to the multiply type.
2143 if (I.getType() != V->getType())
Reid Spencer00c482b2006-10-26 19:19:06 +00002144 V = InsertCastBefore(V, I.getType(), I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002145
Chris Lattner2635b522004-02-23 05:39:21 +00002146 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002147 return BinaryOperator::createAnd(V, OtherOp);
Chris Lattner2635b522004-02-23 05:39:21 +00002148 }
2149 }
2150 }
2151
Chris Lattner113f4f42002-06-25 16:13:24 +00002152 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +00002153}
2154
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002155/// This function implements the transforms on div instructions that work
2156/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2157/// used by the visitors to those instructions.
2158/// @brief Transforms common to all three div instructions
2159Instruction* InstCombiner::commonDivTransforms(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002160 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner81a7a232004-10-16 18:11:37 +00002161
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002162 // undef / X -> 0
2163 if (isa<UndefValue>(Op0))
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002164 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002165
2166 // X / undef -> undef
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002167 if (isa<UndefValue>(Op1))
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002168 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002169
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002170 // Handle cases involving: div X, (select Cond, Y, Z)
Chris Lattnerd79dc792006-09-09 20:26:32 +00002171 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2172 // div X, (Cond ? 0 : Y) -> div X, Y. If the div and the select are in the
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002173 // same basic block, then we replace the select with Y, and the condition
2174 // of the select with false (if the cond value is in the same BB). If the
Chris Lattnerd79dc792006-09-09 20:26:32 +00002175 // select has uses other than the div, this allows them to be simplified
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002176 // also. Note that div X, Y is just as good as div X, 0 (undef)
Chris Lattnerd79dc792006-09-09 20:26:32 +00002177 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2178 if (ST->isNullValue()) {
2179 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2180 if (CondI && CondI->getParent() == I.getParent())
Chris Lattner6ab03f62006-09-28 23:35:22 +00002181 UpdateValueUsesWith(CondI, ConstantBool::getFalse());
Chris Lattnerd79dc792006-09-09 20:26:32 +00002182 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2183 I.setOperand(1, SI->getOperand(2));
2184 else
2185 UpdateValueUsesWith(SI, SI->getOperand(2));
2186 return &I;
2187 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002188
Chris Lattnerd79dc792006-09-09 20:26:32 +00002189 // Likewise for: div X, (Cond ? Y : 0) -> div X, Y
2190 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2191 if (ST->isNullValue()) {
2192 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2193 if (CondI && CondI->getParent() == I.getParent())
Chris Lattner6ab03f62006-09-28 23:35:22 +00002194 UpdateValueUsesWith(CondI, ConstantBool::getTrue());
Chris Lattnerd79dc792006-09-09 20:26:32 +00002195 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2196 I.setOperand(1, SI->getOperand(1));
2197 else
2198 UpdateValueUsesWith(SI, SI->getOperand(1));
2199 return &I;
2200 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002201 }
Chris Lattnerd79dc792006-09-09 20:26:32 +00002202
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002203 return 0;
2204}
Misha Brukmanb1c93172005-04-21 23:48:37 +00002205
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002206/// This function implements the transforms common to both integer division
2207/// instructions (udiv and sdiv). It is called by the visitors to those integer
2208/// division instructions.
2209/// @brief Common integer divide transforms
2210Instruction* InstCombiner::commonIDivTransforms(BinaryOperator &I) {
2211 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2212
2213 if (Instruction *Common = commonDivTransforms(I))
2214 return Common;
2215
2216 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2217 // div X, 1 == X
2218 if (RHS->equalsInt(1))
2219 return ReplaceInstUsesWith(I, Op0);
2220
2221 // (X / C1) / C2 -> X / (C1*C2)
2222 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2223 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2224 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
2225 return BinaryOperator::create(I.getOpcode(), LHS->getOperand(0),
2226 ConstantExpr::getMul(RHS, LHSRHS));
Chris Lattner42362612005-04-08 04:03:26 +00002227 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002228
2229 if (!RHS->isNullValue()) { // avoid X udiv 0
2230 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2231 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2232 return R;
2233 if (isa<PHINode>(Op0))
2234 if (Instruction *NV = FoldOpIntoPhi(I))
2235 return NV;
2236 }
Chris Lattnerd79dc792006-09-09 20:26:32 +00002237 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002238
Chris Lattner3082c5a2003-02-18 19:28:33 +00002239 // 0 / X == 0, we don't need to preserve faults!
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002240 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattner3082c5a2003-02-18 19:28:33 +00002241 if (LHS->equalsInt(0))
2242 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2243
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002244 return 0;
2245}
2246
2247Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2248 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2249
2250 // Handle the integer div common cases
2251 if (Instruction *Common = commonIDivTransforms(I))
2252 return Common;
2253
2254 // X udiv C^2 -> X >> C
2255 // Check to see if this is an unsigned division with an exact power of 2,
2256 // if so, convert to a right shift.
2257 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
2258 if (uint64_t Val = C->getZExtValue()) // Don't break X / 0
2259 if (isPowerOf2_64(Val)) {
2260 uint64_t ShiftAmt = Log2_64(Val);
2261 Value* X = Op0;
2262 const Type* XTy = X->getType();
2263 bool isSigned = XTy->isSigned();
2264 if (isSigned)
2265 X = InsertCastBefore(X, XTy->getUnsignedVersion(), I);
2266 Instruction* Result =
2267 new ShiftInst(Instruction::Shr, X,
2268 ConstantInt::get(Type::UByteTy, ShiftAmt));
2269 if (!isSigned)
2270 return Result;
2271 InsertNewInstBefore(Result, I);
2272 return new CastInst(Result, XTy->getSignedVersion(), I.getName());
2273 }
2274 }
2275
2276 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
2277 if (ShiftInst *RHSI = dyn_cast<ShiftInst>(I.getOperand(1))) {
2278 if (RHSI->getOpcode() == Instruction::Shl &&
2279 isa<ConstantInt>(RHSI->getOperand(0))) {
2280 uint64_t C1 = cast<ConstantInt>(RHSI->getOperand(0))->getZExtValue();
2281 if (isPowerOf2_64(C1)) {
2282 Value *N = RHSI->getOperand(1);
2283 const Type* NTy = N->getType();
2284 bool isSigned = NTy->isSigned();
2285 if (uint64_t C2 = Log2_64(C1)) {
2286 if (isSigned) {
2287 NTy = NTy->getUnsignedVersion();
2288 N = InsertCastBefore(N, NTy, I);
Chris Lattner2e90b732006-02-05 07:54:04 +00002289 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002290 Constant *C2V = ConstantInt::get(NTy, C2);
2291 N = InsertNewInstBefore(BinaryOperator::createAdd(N, C2V, "tmp"), I);
Chris Lattner2e90b732006-02-05 07:54:04 +00002292 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002293 Instruction* Result = new ShiftInst(Instruction::Shr, Op0, N);
2294 if (!isSigned)
2295 return Result;
2296 InsertNewInstBefore(Result, I);
2297 return new CastInst(Result, NTy->getSignedVersion(), I.getName());
Chris Lattner2e90b732006-02-05 07:54:04 +00002298 }
2299 }
Chris Lattnerdd0c1742005-11-05 07:40:31 +00002300 }
2301
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002302 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
2303 // where C1&C2 are powers of two.
2304 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2305 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2306 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2)))
2307 if (!STO->isNullValue() && !STO->isNullValue()) {
2308 uint64_t TVA = STO->getZExtValue(), FVA = SFO->getZExtValue();
2309 if (isPowerOf2_64(TVA) && isPowerOf2_64(FVA)) {
2310 // Compute the shift amounts
2311 unsigned TSA = Log2_64(TVA), FSA = Log2_64(FVA);
2312 // Make sure we get the unsigned version of X
2313 Value* X = Op0;
2314 const Type* origXTy = X->getType();
2315 bool isSigned = origXTy->isSigned();
2316 if (isSigned)
2317 X = InsertCastBefore(X, X->getType()->getUnsignedVersion(), I);
2318 // Construct the "on true" case of the select
2319 Constant *TC = ConstantInt::get(Type::UByteTy, TSA);
2320 Instruction *TSI =
2321 new ShiftInst(Instruction::Shr, X, TC, SI->getName()+".t");
2322 TSI = InsertNewInstBefore(TSI, I);
2323
2324 // Construct the "on false" case of the select
2325 Constant *FC = ConstantInt::get(Type::UByteTy, FSA);
2326 Instruction *FSI =
2327 new ShiftInst(Instruction::Shr, X, FC, SI->getName()+".f");
2328 FSI = InsertNewInstBefore(FSI, I);
2329
2330 // construct the select instruction and return it.
2331 SelectInst* NewSI =
2332 new SelectInst(SI->getOperand(0), TSI, FSI, SI->getName());
2333 if (!isSigned)
2334 return NewSI;
2335 InsertNewInstBefore(NewSI, I);
2336 return new CastInst(NewSI, origXTy, NewSI->getName());
2337 }
2338 }
2339 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002340 return 0;
2341}
2342
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002343Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
2344 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2345
2346 // Handle the integer div common cases
2347 if (Instruction *Common = commonIDivTransforms(I))
2348 return Common;
2349
2350 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2351 // sdiv X, -1 == -X
2352 if (RHS->isAllOnesValue())
2353 return BinaryOperator::createNeg(Op0);
2354
2355 // -X/C -> X/-C
2356 if (Value *LHSNeg = dyn_castNegVal(Op0))
2357 return BinaryOperator::createSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
2358 }
2359
2360 // If the sign bits of both operands are zero (i.e. we can prove they are
2361 // unsigned inputs), turn this into a udiv.
2362 if (I.getType()->isInteger()) {
2363 uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
2364 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2365 return BinaryOperator::createUDiv(Op0, Op1, I.getName());
2366 }
2367 }
2368
2369 return 0;
2370}
2371
2372Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
2373 return commonDivTransforms(I);
2374}
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002375
Chris Lattner85dda9a2006-03-02 06:50:58 +00002376/// GetFactor - If we can prove that the specified value is at least a multiple
2377/// of some factor, return that factor.
2378static Constant *GetFactor(Value *V) {
2379 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
2380 return CI;
2381
2382 // Unless we can be tricky, we know this is a multiple of 1.
2383 Constant *Result = ConstantInt::get(V->getType(), 1);
2384
2385 Instruction *I = dyn_cast<Instruction>(V);
2386 if (!I) return Result;
2387
2388 if (I->getOpcode() == Instruction::Mul) {
2389 // Handle multiplies by a constant, etc.
2390 return ConstantExpr::getMul(GetFactor(I->getOperand(0)),
2391 GetFactor(I->getOperand(1)));
2392 } else if (I->getOpcode() == Instruction::Shl) {
2393 // (X<<C) -> X * (1 << C)
2394 if (Constant *ShRHS = dyn_cast<Constant>(I->getOperand(1))) {
2395 ShRHS = ConstantExpr::getShl(Result, ShRHS);
2396 return ConstantExpr::getMul(GetFactor(I->getOperand(0)), ShRHS);
2397 }
2398 } else if (I->getOpcode() == Instruction::And) {
2399 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
2400 // X & 0xFFF0 is known to be a multiple of 16.
2401 unsigned Zeros = CountTrailingZeros_64(RHS->getZExtValue());
2402 if (Zeros != V->getType()->getPrimitiveSizeInBits())
2403 return ConstantExpr::getShl(Result,
Reid Spencere0fc4df2006-10-20 07:07:24 +00002404 ConstantInt::get(Type::UByteTy, Zeros));
Chris Lattner85dda9a2006-03-02 06:50:58 +00002405 }
2406 } else if (I->getOpcode() == Instruction::Cast) {
2407 Value *Op = I->getOperand(0);
2408 // Only handle int->int casts.
2409 if (!Op->getType()->isInteger()) return Result;
2410 return ConstantExpr::getCast(GetFactor(Op), V->getType());
2411 }
2412 return Result;
2413}
2414
Chris Lattner113f4f42002-06-25 16:13:24 +00002415Instruction *InstCombiner::visitRem(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002416 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner0de4a8d2006-02-28 05:30:45 +00002417
2418 // 0 % X == 0, we don't need to preserve faults!
2419 if (Constant *LHS = dyn_cast<Constant>(Op0))
2420 if (LHS->isNullValue())
2421 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2422
2423 if (isa<UndefValue>(Op0)) // undef % X -> 0
2424 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2425 if (isa<UndefValue>(Op1))
2426 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
2427
Chris Lattnere9ff0ea2005-11-05 07:28:37 +00002428 if (I.getType()->isSigned()) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002429 if (Value *RHSNeg = dyn_castNegVal(Op1))
Reid Spencere0fc4df2006-10-20 07:07:24 +00002430 if (!isa<ConstantInt>(RHSNeg) || !RHSNeg->getType()->isSigned() ||
2431 cast<ConstantInt>(RHSNeg)->getSExtValue() > 0) {
Chris Lattner7fd5f072004-07-06 07:01:22 +00002432 // X % -Y -> X % Y
2433 AddUsesToWorkList(I);
2434 I.setOperand(1, RHSNeg);
2435 return &I;
2436 }
Chris Lattnere9ff0ea2005-11-05 07:28:37 +00002437
2438 // If the top bits of both operands are zero (i.e. we can prove they are
2439 // unsigned inputs), turn this into a urem.
Chris Lattnerc3ebf402006-02-07 07:27:52 +00002440 uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
2441 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
Chris Lattnere9ff0ea2005-11-05 07:28:37 +00002442 const Type *NTy = Op0->getType()->getUnsignedVersion();
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002443 Value *LHS = InsertCastBefore(Op0, NTy, I);
Chris Lattnere9ff0ea2005-11-05 07:28:37 +00002444 Value *RHS;
2445 if (Constant *R = dyn_cast<Constant>(Op1))
2446 RHS = ConstantExpr::getCast(R, NTy);
2447 else
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002448 RHS = InsertCastBefore(Op1, NTy, I);
Chris Lattnere9ff0ea2005-11-05 07:28:37 +00002449 Instruction *Rem = BinaryOperator::createRem(LHS, RHS, I.getName());
2450 InsertNewInstBefore(Rem, I);
2451 return new CastInst(Rem, I.getType());
2452 }
2453 }
Chris Lattner7fd5f072004-07-06 07:01:22 +00002454
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002455 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner0de4a8d2006-02-28 05:30:45 +00002456 // X % 0 == undef, we don't need to preserve faults!
2457 if (RHS->equalsInt(0))
2458 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2459
Chris Lattner3082c5a2003-02-18 19:28:33 +00002460 if (RHS->equalsInt(1)) // X % 1 == 0
2461 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2462
2463 // Check to see if this is an unsigned remainder with an exact power of 2,
2464 // if so, convert to a bitwise and.
Reid Spencere0fc4df2006-10-20 07:07:24 +00002465 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
2466 if (RHS->getType()->isUnsigned())
2467 if (isPowerOf2_64(C->getZExtValue()))
2468 return BinaryOperator::createAnd(Op0, SubOne(C));
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002469
Chris Lattnerb70f1412006-02-28 05:49:21 +00002470 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2471 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2472 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2473 return R;
2474 } else if (isa<PHINode>(Op0I)) {
2475 if (Instruction *NV = FoldOpIntoPhi(I))
2476 return NV;
Chris Lattnerb70f1412006-02-28 05:49:21 +00002477 }
Chris Lattner85dda9a2006-03-02 06:50:58 +00002478
2479 // X*C1%C2 --> 0 iff C1%C2 == 0
2480 if (ConstantExpr::getRem(GetFactor(Op0I), RHS)->isNullValue())
2481 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerb70f1412006-02-28 05:49:21 +00002482 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00002483 }
2484
Chris Lattner2e90b732006-02-05 07:54:04 +00002485 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
2486 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1) [urem only].
2487 if (I.getType()->isUnsigned() &&
2488 RHSI->getOpcode() == Instruction::Shl &&
Reid Spencere0fc4df2006-10-20 07:07:24 +00002489 isa<ConstantInt>(RHSI->getOperand(0)) &&
2490 RHSI->getOperand(0)->getType()->isUnsigned()) {
2491 unsigned C1 = cast<ConstantInt>(RHSI->getOperand(0))->getZExtValue();
Chris Lattner2e90b732006-02-05 07:54:04 +00002492 if (isPowerOf2_64(C1)) {
2493 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
2494 Value *Add = InsertNewInstBefore(BinaryOperator::createAdd(RHSI, N1,
2495 "tmp"), I);
2496 return BinaryOperator::createAnd(Op0, Add);
2497 }
2498 }
Chris Lattner0de4a8d2006-02-28 05:30:45 +00002499
2500 // If this is 'urem X, (Cond ? C1, C2)' where C1&C2 are powers of two,
2501 // transform this into: '(Cond ? (urem X, C1) : (urem X, C2))'.
Chris Lattnerd79dc792006-09-09 20:26:32 +00002502 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2503 // rem X, (Cond ? 0 : Y) -> rem X, Y. If the rem and the select are in
2504 // the same basic block, then we replace the select with Y, and the
2505 // condition of the select with false (if the cond value is in the same
2506 // BB). If the select has uses other than the div, this allows them to be
2507 // simplified also.
2508 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2509 if (ST->isNullValue()) {
2510 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2511 if (CondI && CondI->getParent() == I.getParent())
Chris Lattner6ab03f62006-09-28 23:35:22 +00002512 UpdateValueUsesWith(CondI, ConstantBool::getFalse());
Chris Lattnerd79dc792006-09-09 20:26:32 +00002513 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2514 I.setOperand(1, SI->getOperand(2));
2515 else
2516 UpdateValueUsesWith(SI, SI->getOperand(2));
2517 return &I;
2518 }
2519 // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
2520 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2521 if (ST->isNullValue()) {
2522 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2523 if (CondI && CondI->getParent() == I.getParent())
Chris Lattner6ab03f62006-09-28 23:35:22 +00002524 UpdateValueUsesWith(CondI, ConstantBool::getTrue());
Chris Lattnerd79dc792006-09-09 20:26:32 +00002525 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2526 I.setOperand(1, SI->getOperand(1));
2527 else
2528 UpdateValueUsesWith(SI, SI->getOperand(1));
2529 return &I;
2530 }
2531
2532
Reid Spencere0fc4df2006-10-20 07:07:24 +00002533 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2534 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2)))
2535 if (STO->getType()->isUnsigned() && SFO->getType()->isUnsigned()) {
2536 // STO == 0 and SFO == 0 handled above.
2537 if (isPowerOf2_64(STO->getZExtValue()) &&
2538 isPowerOf2_64(SFO->getZExtValue())) {
2539 Value *TrueAnd = InsertNewInstBefore(
2540 BinaryOperator::createAnd(Op0, SubOne(STO), SI->getName()+".t"),
2541 I);
2542 Value *FalseAnd = InsertNewInstBefore(
2543 BinaryOperator::createAnd(Op0, SubOne(SFO), SI->getName()+".f"),
2544 I);
2545 return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
2546 }
Chris Lattner0de4a8d2006-02-28 05:30:45 +00002547 }
Chris Lattnerd79dc792006-09-09 20:26:32 +00002548 }
Chris Lattner2e90b732006-02-05 07:54:04 +00002549 }
2550
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002551 return 0;
2552}
2553
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002554// isMaxValueMinusOne - return true if this is Max-1
Chris Lattnere6794492002-08-12 21:17:25 +00002555static bool isMaxValueMinusOne(const ConstantInt *C) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002556 if (C->getType()->isUnsigned())
2557 return C->getZExtValue() == C->getType()->getIntegralTypeMask()-1;
Misha Brukmanb1c93172005-04-21 23:48:37 +00002558
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002559 // Calculate 0111111111..11111
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002560 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002561 int64_t Val = INT64_MAX; // All ones
2562 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
Reid Spencere0fc4df2006-10-20 07:07:24 +00002563 return C->getSExtValue() == Val-1;
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002564}
2565
2566// isMinValuePlusOne - return true if this is Min+1
Chris Lattnere6794492002-08-12 21:17:25 +00002567static bool isMinValuePlusOne(const ConstantInt *C) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002568 if (C->getType()->isUnsigned())
2569 return C->getZExtValue() == 1;
Misha Brukmanb1c93172005-04-21 23:48:37 +00002570
2571 // Calculate 1111111111000000000000
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002572 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002573 int64_t Val = -1; // All ones
2574 Val <<= TypeBits-1; // Shift over to the right spot
Reid Spencere0fc4df2006-10-20 07:07:24 +00002575 return C->getSExtValue() == Val+1;
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002576}
2577
Chris Lattner35167c32004-06-09 07:59:58 +00002578// isOneBitSet - Return true if there is exactly one bit set in the specified
2579// constant.
2580static bool isOneBitSet(const ConstantInt *CI) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002581 uint64_t V = CI->getZExtValue();
Chris Lattner35167c32004-06-09 07:59:58 +00002582 return V && (V & (V-1)) == 0;
2583}
2584
Chris Lattner8fc5af42004-09-23 21:46:38 +00002585#if 0 // Currently unused
2586// isLowOnes - Return true if the constant is of the form 0+1+.
2587static bool isLowOnes(const ConstantInt *CI) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002588 uint64_t V = CI->getZExtValue();
Chris Lattner8fc5af42004-09-23 21:46:38 +00002589
2590 // There won't be bits set in parts that the type doesn't contain.
Reid Spencere0fc4df2006-10-20 07:07:24 +00002591 V &= ConstantInt::getAllOnesValue(CI->getType())->getZExtValue();
Chris Lattner8fc5af42004-09-23 21:46:38 +00002592
2593 uint64_t U = V+1; // If it is low ones, this should be a power of two.
2594 return U && V && (U & V) == 0;
2595}
2596#endif
2597
2598// isHighOnes - Return true if the constant is of the form 1+0+.
2599// This is the same as lowones(~X).
2600static bool isHighOnes(const ConstantInt *CI) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002601 uint64_t V = ~CI->getZExtValue();
Chris Lattner2c14cf72005-08-07 07:03:10 +00002602 if (~V == 0) return false; // 0's does not match "1+"
Chris Lattner8fc5af42004-09-23 21:46:38 +00002603
2604 // There won't be bits set in parts that the type doesn't contain.
Reid Spencere0fc4df2006-10-20 07:07:24 +00002605 V &= ConstantInt::getAllOnesValue(CI->getType())->getZExtValue();
Chris Lattner8fc5af42004-09-23 21:46:38 +00002606
2607 uint64_t U = V+1; // If it is low ones, this should be a power of two.
2608 return U && V && (U & V) == 0;
2609}
2610
2611
Chris Lattner3ac7c262003-08-13 20:16:26 +00002612/// getSetCondCode - Encode a setcc opcode into a three bit mask. These bits
2613/// are carefully arranged to allow folding of expressions such as:
2614///
2615/// (A < B) | (A > B) --> (A != B)
2616///
2617/// Bit value '4' represents that the comparison is true if A > B, bit value '2'
2618/// represents that the comparison is true if A == B, and bit value '1' is true
2619/// if A < B.
2620///
2621static unsigned getSetCondCode(const SetCondInst *SCI) {
2622 switch (SCI->getOpcode()) {
2623 // False -> 0
2624 case Instruction::SetGT: return 1;
2625 case Instruction::SetEQ: return 2;
2626 case Instruction::SetGE: return 3;
2627 case Instruction::SetLT: return 4;
2628 case Instruction::SetNE: return 5;
2629 case Instruction::SetLE: return 6;
2630 // True -> 7
2631 default:
2632 assert(0 && "Invalid SetCC opcode!");
2633 return 0;
2634 }
2635}
2636
2637/// getSetCCValue - This is the complement of getSetCondCode, which turns an
2638/// opcode and two operands into either a constant true or false, or a brand new
2639/// SetCC instruction.
2640static Value *getSetCCValue(unsigned Opcode, Value *LHS, Value *RHS) {
2641 switch (Opcode) {
Chris Lattner6ab03f62006-09-28 23:35:22 +00002642 case 0: return ConstantBool::getFalse();
Chris Lattner3ac7c262003-08-13 20:16:26 +00002643 case 1: return new SetCondInst(Instruction::SetGT, LHS, RHS);
2644 case 2: return new SetCondInst(Instruction::SetEQ, LHS, RHS);
2645 case 3: return new SetCondInst(Instruction::SetGE, LHS, RHS);
2646 case 4: return new SetCondInst(Instruction::SetLT, LHS, RHS);
2647 case 5: return new SetCondInst(Instruction::SetNE, LHS, RHS);
2648 case 6: return new SetCondInst(Instruction::SetLE, LHS, RHS);
Chris Lattner6ab03f62006-09-28 23:35:22 +00002649 case 7: return ConstantBool::getTrue();
Chris Lattner3ac7c262003-08-13 20:16:26 +00002650 default: assert(0 && "Illegal SetCCCode!"); return 0;
2651 }
2652}
2653
2654// FoldSetCCLogical - Implements (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
2655struct FoldSetCCLogical {
2656 InstCombiner &IC;
2657 Value *LHS, *RHS;
2658 FoldSetCCLogical(InstCombiner &ic, SetCondInst *SCI)
2659 : IC(ic), LHS(SCI->getOperand(0)), RHS(SCI->getOperand(1)) {}
2660 bool shouldApply(Value *V) const {
2661 if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
2662 return (SCI->getOperand(0) == LHS && SCI->getOperand(1) == RHS ||
2663 SCI->getOperand(0) == RHS && SCI->getOperand(1) == LHS);
2664 return false;
2665 }
2666 Instruction *apply(BinaryOperator &Log) const {
2667 SetCondInst *SCI = cast<SetCondInst>(Log.getOperand(0));
2668 if (SCI->getOperand(0) != LHS) {
2669 assert(SCI->getOperand(1) == LHS);
2670 SCI->swapOperands(); // Swap the LHS and RHS of the SetCC
2671 }
2672
2673 unsigned LHSCode = getSetCondCode(SCI);
2674 unsigned RHSCode = getSetCondCode(cast<SetCondInst>(Log.getOperand(1)));
2675 unsigned Code;
2676 switch (Log.getOpcode()) {
2677 case Instruction::And: Code = LHSCode & RHSCode; break;
2678 case Instruction::Or: Code = LHSCode | RHSCode; break;
2679 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner2caaaba2003-09-22 20:33:34 +00002680 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattner3ac7c262003-08-13 20:16:26 +00002681 }
2682
2683 Value *RV = getSetCCValue(Code, LHS, RHS);
2684 if (Instruction *I = dyn_cast<Instruction>(RV))
2685 return I;
2686 // Otherwise, it's a constant boolean value...
2687 return IC.ReplaceInstUsesWith(Log, RV);
2688 }
2689};
2690
Chris Lattnerba1cb382003-09-19 17:17:26 +00002691// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
2692// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
2693// guaranteed to be either a shift instruction or a binary operator.
2694Instruction *InstCombiner::OptAndOp(Instruction *Op,
2695 ConstantIntegral *OpRHS,
2696 ConstantIntegral *AndRHS,
2697 BinaryOperator &TheAnd) {
2698 Value *X = Op->getOperand(0);
Chris Lattnerfcf21a72004-01-12 19:47:05 +00002699 Constant *Together = 0;
2700 if (!isa<ShiftInst>(Op))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002701 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002702
Chris Lattnerba1cb382003-09-19 17:17:26 +00002703 switch (Op->getOpcode()) {
2704 case Instruction::Xor:
Chris Lattner86102b82005-01-01 16:22:27 +00002705 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00002706 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
2707 std::string OpName = Op->getName(); Op->setName("");
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002708 Instruction *And = BinaryOperator::createAnd(X, AndRHS, OpName);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002709 InsertNewInstBefore(And, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002710 return BinaryOperator::createXor(And, Together);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002711 }
2712 break;
2713 case Instruction::Or:
Chris Lattner86102b82005-01-01 16:22:27 +00002714 if (Together == AndRHS) // (X | C) & C --> C
2715 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002716
Chris Lattner86102b82005-01-01 16:22:27 +00002717 if (Op->hasOneUse() && Together != OpRHS) {
2718 // (X | C1) & C2 --> (X | (C1&C2)) & C2
2719 std::string Op0Name = Op->getName(); Op->setName("");
2720 Instruction *Or = BinaryOperator::createOr(X, Together, Op0Name);
2721 InsertNewInstBefore(Or, TheAnd);
2722 return BinaryOperator::createAnd(Or, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002723 }
2724 break;
2725 case Instruction::Add:
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002726 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00002727 // Adding a one to a single bit bit-field should be turned into an XOR
2728 // of the bit. First thing to check is to see if this AND is with a
2729 // single bit constant.
Reid Spencere0fc4df2006-10-20 07:07:24 +00002730 uint64_t AndRHSV = cast<ConstantInt>(AndRHS)->getZExtValue();
Chris Lattnerba1cb382003-09-19 17:17:26 +00002731
2732 // Clear bits that are not part of the constant.
Chris Lattner77defba2006-02-07 07:00:41 +00002733 AndRHSV &= AndRHS->getType()->getIntegralTypeMask();
Chris Lattnerba1cb382003-09-19 17:17:26 +00002734
2735 // If there is only one bit set...
Chris Lattner35167c32004-06-09 07:59:58 +00002736 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00002737 // Ok, at this point, we know that we are masking the result of the
2738 // ADD down to exactly one bit. If the constant we are adding has
2739 // no bits set below this bit, then we can eliminate the ADD.
Reid Spencere0fc4df2006-10-20 07:07:24 +00002740 uint64_t AddRHS = cast<ConstantInt>(OpRHS)->getZExtValue();
Misha Brukmanb1c93172005-04-21 23:48:37 +00002741
Chris Lattnerba1cb382003-09-19 17:17:26 +00002742 // Check to see if any bits below the one bit set in AndRHSV are set.
2743 if ((AddRHS & (AndRHSV-1)) == 0) {
2744 // If not, the only thing that can effect the output of the AND is
2745 // the bit specified by AndRHSV. If that bit is set, the effect of
2746 // the XOR is to toggle the bit. If it is clear, then the ADD has
2747 // no effect.
2748 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
2749 TheAnd.setOperand(0, X);
2750 return &TheAnd;
2751 } else {
2752 std::string Name = Op->getName(); Op->setName("");
2753 // Pull the XOR out of the AND.
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002754 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS, Name);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002755 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002756 return BinaryOperator::createXor(NewAnd, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002757 }
2758 }
2759 }
2760 }
2761 break;
Chris Lattner2da29172003-09-19 19:05:02 +00002762
2763 case Instruction::Shl: {
2764 // We know that the AND will not produce any of the bits shifted in, so if
2765 // the anded constant includes them, clear them now!
2766 //
2767 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner7e794272004-09-24 15:21:34 +00002768 Constant *ShlMask = ConstantExpr::getShl(AllOne, OpRHS);
2769 Constant *CI = ConstantExpr::getAnd(AndRHS, ShlMask);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002770
Chris Lattner7e794272004-09-24 15:21:34 +00002771 if (CI == ShlMask) { // Masking out bits that the shift already masks
2772 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
2773 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner2da29172003-09-19 19:05:02 +00002774 TheAnd.setOperand(1, CI);
2775 return &TheAnd;
2776 }
2777 break;
Misha Brukmanb1c93172005-04-21 23:48:37 +00002778 }
Chris Lattner2da29172003-09-19 19:05:02 +00002779 case Instruction::Shr:
2780 // We know that the AND will not produce any of the bits shifted in, so if
2781 // the anded constant includes them, clear them now! This only applies to
2782 // unsigned shifts, because a signed shr may bring in set bits!
2783 //
2784 if (AndRHS->getType()->isUnsigned()) {
2785 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner7e794272004-09-24 15:21:34 +00002786 Constant *ShrMask = ConstantExpr::getShr(AllOne, OpRHS);
2787 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
2788
2789 if (CI == ShrMask) { // Masking out bits that the shift already masks.
2790 return ReplaceInstUsesWith(TheAnd, Op);
2791 } else if (CI != AndRHS) {
2792 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
Chris Lattner2da29172003-09-19 19:05:02 +00002793 return &TheAnd;
2794 }
Chris Lattner7e794272004-09-24 15:21:34 +00002795 } else { // Signed shr.
2796 // See if this is shifting in some sign extension, then masking it out
2797 // with an and.
2798 if (Op->hasOneUse()) {
2799 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
2800 Constant *ShrMask = ConstantExpr::getUShr(AllOne, OpRHS);
2801 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
Chris Lattner5c3c21e2004-10-22 04:53:16 +00002802 if (CI == AndRHS) { // Masking out bits shifted in.
Chris Lattner7e794272004-09-24 15:21:34 +00002803 // Make the argument unsigned.
2804 Value *ShVal = Op->getOperand(0);
2805 ShVal = InsertCastBefore(ShVal,
2806 ShVal->getType()->getUnsignedVersion(),
2807 TheAnd);
2808 ShVal = InsertNewInstBefore(new ShiftInst(Instruction::Shr, ShVal,
2809 OpRHS, Op->getName()),
2810 TheAnd);
Chris Lattner70c20392004-10-27 05:57:15 +00002811 Value *AndRHS2 = ConstantExpr::getCast(AndRHS, ShVal->getType());
2812 ShVal = InsertNewInstBefore(BinaryOperator::createAnd(ShVal, AndRHS2,
2813 TheAnd.getName()),
2814 TheAnd);
Chris Lattner7e794272004-09-24 15:21:34 +00002815 return new CastInst(ShVal, Op->getType());
2816 }
2817 }
Chris Lattner2da29172003-09-19 19:05:02 +00002818 }
2819 break;
Chris Lattnerba1cb382003-09-19 17:17:26 +00002820 }
2821 return 0;
2822}
2823
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002824
Chris Lattner6862fbd2004-09-29 17:40:11 +00002825/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
2826/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
2827/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. IB is the location to
2828/// insert new instructions.
2829Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
2830 bool Inside, Instruction &IB) {
2831 assert(cast<ConstantBool>(ConstantExpr::getSetLE(Lo, Hi))->getValue() &&
2832 "Lo is not <= Hi in range emission code!");
2833 if (Inside) {
2834 if (Lo == Hi) // Trivially false.
2835 return new SetCondInst(Instruction::SetNE, V, V);
2836 if (cast<ConstantIntegral>(Lo)->isMinValue())
2837 return new SetCondInst(Instruction::SetLT, V, Hi);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002838
Chris Lattner6862fbd2004-09-29 17:40:11 +00002839 Constant *AddCST = ConstantExpr::getNeg(Lo);
2840 Instruction *Add = BinaryOperator::createAdd(V, AddCST,V->getName()+".off");
2841 InsertNewInstBefore(Add, IB);
2842 // Convert to unsigned for the comparison.
2843 const Type *UnsType = Add->getType()->getUnsignedVersion();
2844 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
2845 AddCST = ConstantExpr::getAdd(AddCST, Hi);
2846 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2847 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
2848 }
2849
2850 if (Lo == Hi) // Trivially true.
2851 return new SetCondInst(Instruction::SetEQ, V, V);
2852
2853 Hi = SubOne(cast<ConstantInt>(Hi));
Reid Spencere0fc4df2006-10-20 07:07:24 +00002854
2855 // V < 0 || V >= Hi ->'V > Hi-1'
2856 if (cast<ConstantIntegral>(Lo)->isMinValue())
Chris Lattner6862fbd2004-09-29 17:40:11 +00002857 return new SetCondInst(Instruction::SetGT, V, Hi);
2858
2859 // Emit X-Lo > Hi-Lo-1
2860 Constant *AddCST = ConstantExpr::getNeg(Lo);
2861 Instruction *Add = BinaryOperator::createAdd(V, AddCST, V->getName()+".off");
2862 InsertNewInstBefore(Add, IB);
2863 // Convert to unsigned for the comparison.
2864 const Type *UnsType = Add->getType()->getUnsignedVersion();
2865 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
2866 AddCST = ConstantExpr::getAdd(AddCST, Hi);
2867 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2868 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
2869}
2870
Chris Lattnerb4b25302005-09-18 07:22:02 +00002871// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
2872// any number of 0s on either side. The 1s are allowed to wrap from LSB to
2873// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
2874// not, since all 1s are not contiguous.
2875static bool isRunOfOnes(ConstantIntegral *Val, unsigned &MB, unsigned &ME) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002876 uint64_t V = Val->getZExtValue();
Chris Lattnerb4b25302005-09-18 07:22:02 +00002877 if (!isShiftedMask_64(V)) return false;
2878
2879 // look for the first zero bit after the run of ones
2880 MB = 64-CountLeadingZeros_64((V - 1) ^ V);
2881 // look for the first non-zero bit
2882 ME = 64-CountLeadingZeros_64(V);
2883 return true;
2884}
2885
2886
2887
2888/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
2889/// where isSub determines whether the operator is a sub. If we can fold one of
2890/// the following xforms:
Chris Lattneraf517572005-09-18 04:24:45 +00002891///
2892/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
2893/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
2894/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
2895///
2896/// return (A +/- B).
2897///
2898Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
2899 ConstantIntegral *Mask, bool isSub,
2900 Instruction &I) {
2901 Instruction *LHSI = dyn_cast<Instruction>(LHS);
2902 if (!LHSI || LHSI->getNumOperands() != 2 ||
2903 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
2904
2905 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
2906
2907 switch (LHSI->getOpcode()) {
2908 default: return 0;
2909 case Instruction::And:
Chris Lattnerb4b25302005-09-18 07:22:02 +00002910 if (ConstantExpr::getAnd(N, Mask) == Mask) {
2911 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Reid Spencere0fc4df2006-10-20 07:07:24 +00002912 if ((Mask->getZExtValue() & Mask->getZExtValue()+1) == 0)
Chris Lattnerb4b25302005-09-18 07:22:02 +00002913 break;
2914
2915 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
2916 // part, we don't need any explicit masks to take them out of A. If that
2917 // is all N is, ignore it.
2918 unsigned MB, ME;
2919 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Chris Lattnerc3ebf402006-02-07 07:27:52 +00002920 uint64_t Mask = RHS->getType()->getIntegralTypeMask();
2921 Mask >>= 64-MB+1;
2922 if (MaskedValueIsZero(RHS, Mask))
Chris Lattnerb4b25302005-09-18 07:22:02 +00002923 break;
2924 }
2925 }
Chris Lattneraf517572005-09-18 04:24:45 +00002926 return 0;
2927 case Instruction::Or:
2928 case Instruction::Xor:
Chris Lattnerb4b25302005-09-18 07:22:02 +00002929 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Reid Spencere0fc4df2006-10-20 07:07:24 +00002930 if ((Mask->getZExtValue() & Mask->getZExtValue()+1) == 0 &&
Chris Lattnerb4b25302005-09-18 07:22:02 +00002931 ConstantExpr::getAnd(N, Mask)->isNullValue())
Chris Lattneraf517572005-09-18 04:24:45 +00002932 break;
2933 return 0;
2934 }
2935
2936 Instruction *New;
2937 if (isSub)
2938 New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
2939 else
2940 New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
2941 return InsertNewInstBefore(New, I);
2942}
2943
Chris Lattner113f4f42002-06-25 16:13:24 +00002944Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00002945 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00002946 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002947
Chris Lattner81a7a232004-10-16 18:11:37 +00002948 if (isa<UndefValue>(Op1)) // X & undef -> 0
2949 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2950
Chris Lattner86102b82005-01-01 16:22:27 +00002951 // and X, X = X
2952 if (Op0 == Op1)
Chris Lattnere6794492002-08-12 21:17:25 +00002953 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002954
Chris Lattner5b2edb12006-02-12 08:02:11 +00002955 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner5997cf92006-02-08 03:25:32 +00002956 // purpose is to compute bits we don't care about.
Chris Lattner0157e7f2006-02-11 09:31:47 +00002957 uint64_t KnownZero, KnownOne;
Chris Lattnerd70d9f52006-03-25 21:58:26 +00002958 if (!isa<PackedType>(I.getType()) &&
2959 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
Chris Lattner0157e7f2006-02-11 09:31:47 +00002960 KnownZero, KnownOne))
Chris Lattner5997cf92006-02-08 03:25:32 +00002961 return &I;
2962
Chris Lattner86102b82005-01-01 16:22:27 +00002963 if (ConstantIntegral *AndRHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00002964 uint64_t AndRHSMask = AndRHS->getZExtValue();
2965 uint64_t TypeMask = Op0->getType()->getIntegralTypeMask();
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00002966 uint64_t NotAndRHS = AndRHSMask^TypeMask;
Chris Lattner86102b82005-01-01 16:22:27 +00002967
Chris Lattnerba1cb382003-09-19 17:17:26 +00002968 // Optimize a variety of ((val OP C1) & C2) combinations...
2969 if (isa<BinaryOperator>(Op0) || isa<ShiftInst>(Op0)) {
2970 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner86102b82005-01-01 16:22:27 +00002971 Value *Op0LHS = Op0I->getOperand(0);
2972 Value *Op0RHS = Op0I->getOperand(1);
2973 switch (Op0I->getOpcode()) {
2974 case Instruction::Xor:
2975 case Instruction::Or:
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00002976 // If the mask is only needed on one incoming arm, push it up.
2977 if (Op0I->hasOneUse()) {
2978 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
2979 // Not masking anything out for the LHS, move to RHS.
2980 Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
2981 Op0RHS->getName()+".masked");
2982 InsertNewInstBefore(NewRHS, I);
2983 return BinaryOperator::create(
2984 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002985 }
Chris Lattnerc3ebf402006-02-07 07:27:52 +00002986 if (!isa<Constant>(Op0RHS) &&
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00002987 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
2988 // Not masking anything out for the RHS, move to LHS.
2989 Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
2990 Op0LHS->getName()+".masked");
2991 InsertNewInstBefore(NewLHS, I);
2992 return BinaryOperator::create(
2993 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
2994 }
2995 }
2996
Chris Lattner86102b82005-01-01 16:22:27 +00002997 break;
Chris Lattneraf517572005-09-18 04:24:45 +00002998 case Instruction::Add:
Chris Lattnerb4b25302005-09-18 07:22:02 +00002999 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3000 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3001 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3002 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
3003 return BinaryOperator::createAnd(V, AndRHS);
3004 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
3005 return BinaryOperator::createAnd(V, AndRHS); // Add commutes
Chris Lattneraf517572005-09-18 04:24:45 +00003006 break;
3007
3008 case Instruction::Sub:
Chris Lattnerb4b25302005-09-18 07:22:02 +00003009 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3010 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3011 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3012 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
3013 return BinaryOperator::createAnd(V, AndRHS);
Chris Lattneraf517572005-09-18 04:24:45 +00003014 break;
Chris Lattner86102b82005-01-01 16:22:27 +00003015 }
3016
Chris Lattner16464b32003-07-23 19:25:52 +00003017 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner86102b82005-01-01 16:22:27 +00003018 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerba1cb382003-09-19 17:17:26 +00003019 return Res;
Chris Lattner86102b82005-01-01 16:22:27 +00003020 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3021 const Type *SrcTy = CI->getOperand(0)->getType();
3022
Chris Lattner2c14cf72005-08-07 07:03:10 +00003023 // If this is an integer truncation or change from signed-to-unsigned, and
3024 // if the source is an and/or with immediate, transform it. This
3025 // frequently occurs for bitfield accesses.
3026 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
3027 if (SrcTy->getPrimitiveSizeInBits() >=
3028 I.getType()->getPrimitiveSizeInBits() &&
3029 CastOp->getNumOperands() == 2)
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00003030 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1)))
Chris Lattner2c14cf72005-08-07 07:03:10 +00003031 if (CastOp->getOpcode() == Instruction::And) {
3032 // Change: and (cast (and X, C1) to T), C2
3033 // into : and (cast X to T), trunc(C1)&C2
3034 // This will folds the two ands together, which may allow other
3035 // simplifications.
3036 Instruction *NewCast =
3037 new CastInst(CastOp->getOperand(0), I.getType(),
3038 CastOp->getName()+".shrunk");
3039 NewCast = InsertNewInstBefore(NewCast, I);
3040
3041 Constant *C3=ConstantExpr::getCast(AndCI, I.getType());//trunc(C1)
3042 C3 = ConstantExpr::getAnd(C3, AndRHS); // trunc(C1)&C2
3043 return BinaryOperator::createAnd(NewCast, C3);
3044 } else if (CastOp->getOpcode() == Instruction::Or) {
3045 // Change: and (cast (or X, C1) to T), C2
3046 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
3047 Constant *C3=ConstantExpr::getCast(AndCI, I.getType());//trunc(C1)
3048 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
3049 return ReplaceInstUsesWith(I, AndRHS);
3050 }
3051 }
Chris Lattner33217db2003-07-23 19:36:21 +00003052 }
Chris Lattner183b3362004-04-09 19:05:30 +00003053
3054 // Try to fold constant and into select arguments.
3055 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00003056 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00003057 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00003058 if (isa<PHINode>(Op0))
3059 if (Instruction *NV = FoldOpIntoPhi(I))
3060 return NV;
Chris Lattner49b47ae2003-07-23 17:57:01 +00003061 }
3062
Chris Lattnerbb74e222003-03-10 23:06:50 +00003063 Value *Op0NotVal = dyn_castNotVal(Op0);
3064 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00003065
Chris Lattner023a4832004-06-18 06:07:51 +00003066 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
3067 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3068
Misha Brukman9c003d82004-07-30 12:50:08 +00003069 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattnerbb74e222003-03-10 23:06:50 +00003070 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003071 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
3072 I.getName()+".demorgan");
Chris Lattner49b47ae2003-07-23 17:57:01 +00003073 InsertNewInstBefore(Or, I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00003074 return BinaryOperator::createNot(Or);
3075 }
Chris Lattner8b10ab32006-02-13 23:07:23 +00003076
3077 {
3078 Value *A = 0, *B = 0;
3079 ConstantInt *C1 = 0, *C2 = 0;
3080 if (match(Op0, m_Or(m_Value(A), m_Value(B))))
3081 if (A == Op1 || B == Op1) // (A | ?) & A --> A
3082 return ReplaceInstUsesWith(I, Op1);
3083 if (match(Op1, m_Or(m_Value(A), m_Value(B))))
3084 if (A == Op0 || B == Op0) // A & (A | ?) --> A
3085 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerdcd07922006-04-01 08:03:55 +00003086
3087 if (Op0->hasOneUse() &&
3088 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3089 if (A == Op1) { // (A^B)&A -> A&(A^B)
3090 I.swapOperands(); // Simplify below
3091 std::swap(Op0, Op1);
3092 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
3093 cast<BinaryOperator>(Op0)->swapOperands();
3094 I.swapOperands(); // Simplify below
3095 std::swap(Op0, Op1);
3096 }
3097 }
3098 if (Op1->hasOneUse() &&
3099 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3100 if (B == Op0) { // B&(A^B) -> B&(B^A)
3101 cast<BinaryOperator>(Op1)->swapOperands();
3102 std::swap(A, B);
3103 }
3104 if (A == Op0) { // A&(A^B) -> A & ~B
3105 Instruction *NotB = BinaryOperator::createNot(B, "tmp");
3106 InsertNewInstBefore(NotB, I);
3107 return BinaryOperator::createAnd(A, NotB);
3108 }
3109 }
Chris Lattner8b10ab32006-02-13 23:07:23 +00003110 }
3111
Chris Lattner3082c5a2003-02-18 19:28:33 +00003112
Chris Lattner623826c2004-09-28 21:48:02 +00003113 if (SetCondInst *RHS = dyn_cast<SetCondInst>(Op1)) {
3114 // (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
Chris Lattner3ac7c262003-08-13 20:16:26 +00003115 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
3116 return R;
3117
Chris Lattner623826c2004-09-28 21:48:02 +00003118 Value *LHSVal, *RHSVal;
3119 ConstantInt *LHSCst, *RHSCst;
3120 Instruction::BinaryOps LHSCC, RHSCC;
3121 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3122 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3123 if (LHSVal == RHSVal && // Found (X setcc C1) & (X setcc C2)
3124 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
Misha Brukmanb1c93172005-04-21 23:48:37 +00003125 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
Chris Lattner623826c2004-09-28 21:48:02 +00003126 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
3127 // Ensure that the larger constant is on the RHS.
3128 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
3129 SetCondInst *LHS = cast<SetCondInst>(Op0);
3130 if (cast<ConstantBool>(Cmp)->getValue()) {
3131 std::swap(LHS, RHS);
3132 std::swap(LHSCst, RHSCst);
3133 std::swap(LHSCC, RHSCC);
3134 }
3135
3136 // At this point, we know we have have two setcc instructions
3137 // comparing a value against two constants and and'ing the result
3138 // together. Because of the above check, we know that we only have
3139 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
3140 // FoldSetCCLogical check above), that the two constants are not
3141 // equal.
3142 assert(LHSCst != RHSCst && "Compares not folded above?");
3143
3144 switch (LHSCC) {
3145 default: assert(0 && "Unknown integer condition code!");
3146 case Instruction::SetEQ:
3147 switch (RHSCC) {
3148 default: assert(0 && "Unknown integer condition code!");
3149 case Instruction::SetEQ: // (X == 13 & X == 15) -> false
3150 case Instruction::SetGT: // (X == 13 & X > 15) -> false
Chris Lattner6ab03f62006-09-28 23:35:22 +00003151 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattner623826c2004-09-28 21:48:02 +00003152 case Instruction::SetNE: // (X == 13 & X != 15) -> X == 13
3153 case Instruction::SetLT: // (X == 13 & X < 15) -> X == 13
3154 return ReplaceInstUsesWith(I, LHS);
3155 }
3156 case Instruction::SetNE:
3157 switch (RHSCC) {
3158 default: assert(0 && "Unknown integer condition code!");
3159 case Instruction::SetLT:
3160 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X < 14) -> X < 13
3161 return new SetCondInst(Instruction::SetLT, LHSVal, LHSCst);
3162 break; // (X != 13 & X < 15) -> no change
3163 case Instruction::SetEQ: // (X != 13 & X == 15) -> X == 15
3164 case Instruction::SetGT: // (X != 13 & X > 15) -> X > 15
3165 return ReplaceInstUsesWith(I, RHS);
3166 case Instruction::SetNE:
3167 if (LHSCst == SubOne(RHSCst)) {// (X != 13 & X != 14) -> X-13 >u 1
3168 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3169 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3170 LHSVal->getName()+".off");
3171 InsertNewInstBefore(Add, I);
3172 const Type *UnsType = Add->getType()->getUnsignedVersion();
3173 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
3174 AddCST = ConstantExpr::getSub(RHSCst, LHSCst);
3175 AddCST = ConstantExpr::getCast(AddCST, UnsType);
3176 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
3177 }
3178 break; // (X != 13 & X != 15) -> no change
3179 }
3180 break;
3181 case Instruction::SetLT:
3182 switch (RHSCC) {
3183 default: assert(0 && "Unknown integer condition code!");
3184 case Instruction::SetEQ: // (X < 13 & X == 15) -> false
3185 case Instruction::SetGT: // (X < 13 & X > 15) -> false
Chris Lattner6ab03f62006-09-28 23:35:22 +00003186 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattner623826c2004-09-28 21:48:02 +00003187 case Instruction::SetNE: // (X < 13 & X != 15) -> X < 13
3188 case Instruction::SetLT: // (X < 13 & X < 15) -> X < 13
3189 return ReplaceInstUsesWith(I, LHS);
3190 }
3191 case Instruction::SetGT:
3192 switch (RHSCC) {
3193 default: assert(0 && "Unknown integer condition code!");
3194 case Instruction::SetEQ: // (X > 13 & X == 15) -> X > 13
3195 return ReplaceInstUsesWith(I, LHS);
3196 case Instruction::SetGT: // (X > 13 & X > 15) -> X > 15
3197 return ReplaceInstUsesWith(I, RHS);
3198 case Instruction::SetNE:
3199 if (RHSCst == AddOne(LHSCst)) // (X > 13 & X != 14) -> X > 14
3200 return new SetCondInst(Instruction::SetGT, LHSVal, RHSCst);
3201 break; // (X > 13 & X != 15) -> no change
Chris Lattner6862fbd2004-09-29 17:40:11 +00003202 case Instruction::SetLT: // (X > 13 & X < 15) -> (X-14) <u 1
3203 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true, I);
Chris Lattner623826c2004-09-28 21:48:02 +00003204 }
3205 }
3206 }
3207 }
3208
Chris Lattner3af10532006-05-05 06:39:07 +00003209 // fold (and (cast A), (cast B)) -> (cast (and A, B))
3210 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattnere745c7d2006-05-05 20:51:30 +00003211 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner3af10532006-05-05 06:39:07 +00003212 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Chris Lattnere745c7d2006-05-05 20:51:30 +00003213 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegral() &&
Chris Lattner1d441ad2006-05-06 09:00:16 +00003214 // Only do this if the casts both really cause code to be generated.
3215 ValueRequiresCast(Op0C->getOperand(0), I.getType(), TD) &&
3216 ValueRequiresCast(Op1C->getOperand(0), I.getType(), TD)) {
Chris Lattner3af10532006-05-05 06:39:07 +00003217 Instruction *NewOp = BinaryOperator::createAnd(Op0C->getOperand(0),
3218 Op1C->getOperand(0),
3219 I.getName());
3220 InsertNewInstBefore(NewOp, I);
3221 return new CastInst(NewOp, I.getType());
3222 }
3223 }
3224
Chris Lattner113f4f42002-06-25 16:13:24 +00003225 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003226}
3227
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003228/// CollectBSwapParts - Look to see if the specified value defines a single byte
3229/// in the result. If it does, and if the specified byte hasn't been filled in
3230/// yet, fill it in and return false.
3231static bool CollectBSwapParts(Value *V, std::vector<Value*> &ByteValues) {
3232 Instruction *I = dyn_cast<Instruction>(V);
3233 if (I == 0) return true;
3234
3235 // If this is an or instruction, it is an inner node of the bswap.
3236 if (I->getOpcode() == Instruction::Or)
3237 return CollectBSwapParts(I->getOperand(0), ByteValues) ||
3238 CollectBSwapParts(I->getOperand(1), ByteValues);
3239
3240 // If this is a shift by a constant int, and it is "24", then its operand
3241 // defines a byte. We only handle unsigned types here.
3242 if (isa<ShiftInst>(I) && isa<ConstantInt>(I->getOperand(1))) {
3243 // Not shifting the entire input by N-1 bytes?
Reid Spencere0fc4df2006-10-20 07:07:24 +00003244 if (cast<ConstantInt>(I->getOperand(1))->getZExtValue() !=
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003245 8*(ByteValues.size()-1))
3246 return true;
3247
3248 unsigned DestNo;
3249 if (I->getOpcode() == Instruction::Shl) {
3250 // X << 24 defines the top byte with the lowest of the input bytes.
3251 DestNo = ByteValues.size()-1;
3252 } else {
3253 // X >>u 24 defines the low byte with the highest of the input bytes.
3254 DestNo = 0;
3255 }
3256
3257 // If the destination byte value is already defined, the values are or'd
3258 // together, which isn't a bswap (unless it's an or of the same bits).
3259 if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
3260 return true;
3261 ByteValues[DestNo] = I->getOperand(0);
3262 return false;
3263 }
3264
3265 // Otherwise, we can only handle and(shift X, imm), imm). Bail out of if we
3266 // don't have this.
3267 Value *Shift = 0, *ShiftLHS = 0;
3268 ConstantInt *AndAmt = 0, *ShiftAmt = 0;
3269 if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
3270 !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
3271 return true;
3272 Instruction *SI = cast<Instruction>(Shift);
3273
3274 // Make sure that the shift amount is by a multiple of 8 and isn't too big.
Reid Spencere0fc4df2006-10-20 07:07:24 +00003275 if (ShiftAmt->getZExtValue() & 7 ||
3276 ShiftAmt->getZExtValue() > 8*ByteValues.size())
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003277 return true;
3278
3279 // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
3280 unsigned DestByte;
3281 for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
Reid Spencere0fc4df2006-10-20 07:07:24 +00003282 if (AndAmt->getZExtValue() == uint64_t(0xFF) << 8*DestByte)
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003283 break;
3284 // Unknown mask for bswap.
3285 if (DestByte == ByteValues.size()) return true;
3286
Reid Spencere0fc4df2006-10-20 07:07:24 +00003287 unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003288 unsigned SrcByte;
3289 if (SI->getOpcode() == Instruction::Shl)
3290 SrcByte = DestByte - ShiftBytes;
3291 else
3292 SrcByte = DestByte + ShiftBytes;
3293
3294 // If the SrcByte isn't a bswapped value from the DestByte, reject it.
3295 if (SrcByte != ByteValues.size()-DestByte-1)
3296 return true;
3297
3298 // If the destination byte value is already defined, the values are or'd
3299 // together, which isn't a bswap (unless it's an or of the same bits).
3300 if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
3301 return true;
3302 ByteValues[DestByte] = SI->getOperand(0);
3303 return false;
3304}
3305
3306/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
3307/// If so, insert the new bswap intrinsic and return it.
3308Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
3309 // We can only handle bswap of unsigned integers, and cannot bswap one byte.
3310 if (!I.getType()->isUnsigned() || I.getType() == Type::UByteTy)
3311 return 0;
3312
3313 /// ByteValues - For each byte of the result, we keep track of which value
3314 /// defines each byte.
3315 std::vector<Value*> ByteValues;
3316 ByteValues.resize(I.getType()->getPrimitiveSize());
3317
3318 // Try to find all the pieces corresponding to the bswap.
3319 if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
3320 CollectBSwapParts(I.getOperand(1), ByteValues))
3321 return 0;
3322
3323 // Check to see if all of the bytes come from the same value.
3324 Value *V = ByteValues[0];
3325 if (V == 0) return 0; // Didn't find a byte? Must be zero.
3326
3327 // Check to make sure that all of the bytes come from the same value.
3328 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
3329 if (ByteValues[i] != V)
3330 return 0;
3331
3332 // If they do then *success* we can turn this into a bswap. Figure out what
3333 // bswap to make it into.
3334 Module *M = I.getParent()->getParent()->getParent();
Chris Lattner091b6ea2006-07-11 18:31:26 +00003335 const char *FnName = 0;
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003336 if (I.getType() == Type::UShortTy)
3337 FnName = "llvm.bswap.i16";
3338 else if (I.getType() == Type::UIntTy)
3339 FnName = "llvm.bswap.i32";
3340 else if (I.getType() == Type::ULongTy)
3341 FnName = "llvm.bswap.i64";
3342 else
3343 assert(0 && "Unknown integer type!");
3344 Function *F = M->getOrInsertFunction(FnName, I.getType(), I.getType(), NULL);
3345
3346 return new CallInst(F, V);
3347}
3348
3349
Chris Lattner113f4f42002-06-25 16:13:24 +00003350Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003351 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00003352 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003353
Chris Lattner81a7a232004-10-16 18:11:37 +00003354 if (isa<UndefValue>(Op1))
3355 return ReplaceInstUsesWith(I, // X | undef -> -1
3356 ConstantIntegral::getAllOnesValue(I.getType()));
3357
Chris Lattner5b2edb12006-02-12 08:02:11 +00003358 // or X, X = X
3359 if (Op0 == Op1)
Chris Lattnere6794492002-08-12 21:17:25 +00003360 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003361
Chris Lattner5b2edb12006-02-12 08:02:11 +00003362 // See if we can simplify any instructions used by the instruction whose sole
3363 // purpose is to compute bits we don't care about.
3364 uint64_t KnownZero, KnownOne;
Chris Lattnerd70d9f52006-03-25 21:58:26 +00003365 if (!isa<PackedType>(I.getType()) &&
3366 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
Chris Lattner5b2edb12006-02-12 08:02:11 +00003367 KnownZero, KnownOne))
3368 return &I;
3369
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003370 // or X, -1 == -1
Chris Lattner8f0d1562003-07-23 18:29:44 +00003371 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner330628a2006-01-06 17:59:59 +00003372 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00003373 // (X & C1) | C2 --> (X | C2) & (C1|C2)
3374 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Chris Lattnerb62f5082005-05-09 04:58:36 +00003375 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0->getName());
3376 Op0->setName("");
Chris Lattnerd4252a72004-07-30 07:50:03 +00003377 InsertNewInstBefore(Or, I);
3378 return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, C1));
3379 }
Chris Lattner8f0d1562003-07-23 18:29:44 +00003380
Chris Lattnerd4252a72004-07-30 07:50:03 +00003381 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
3382 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
3383 std::string Op0Name = Op0->getName(); Op0->setName("");
3384 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
3385 InsertNewInstBefore(Or, I);
3386 return BinaryOperator::createXor(Or,
3387 ConstantExpr::getAnd(C1, ConstantExpr::getNot(RHS)));
Chris Lattner8f0d1562003-07-23 18:29:44 +00003388 }
Chris Lattner183b3362004-04-09 19:05:30 +00003389
3390 // Try to fold constant and into select arguments.
3391 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00003392 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00003393 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00003394 if (isa<PHINode>(Op0))
3395 if (Instruction *NV = FoldOpIntoPhi(I))
3396 return NV;
Chris Lattner8f0d1562003-07-23 18:29:44 +00003397 }
3398
Chris Lattner330628a2006-01-06 17:59:59 +00003399 Value *A = 0, *B = 0;
3400 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattner4294cec2005-05-07 23:49:08 +00003401
3402 if (match(Op0, m_And(m_Value(A), m_Value(B))))
3403 if (A == Op1 || B == Op1) // (A & ?) | A --> A
3404 return ReplaceInstUsesWith(I, Op1);
3405 if (match(Op1, m_And(m_Value(A), m_Value(B))))
3406 if (A == Op0 || B == Op0) // A | (A & ?) --> A
3407 return ReplaceInstUsesWith(I, Op0);
3408
Chris Lattnerb7845d62006-07-10 20:25:24 +00003409 // (A | B) | C and A | (B | C) -> bswap if possible.
3410 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003411 if (match(Op0, m_Or(m_Value(), m_Value())) ||
Chris Lattnerb7845d62006-07-10 20:25:24 +00003412 match(Op1, m_Or(m_Value(), m_Value())) ||
3413 (match(Op0, m_Shift(m_Value(), m_Value())) &&
3414 match(Op1, m_Shift(m_Value(), m_Value())))) {
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003415 if (Instruction *BSwap = MatchBSwap(I))
3416 return BSwap;
3417 }
3418
Chris Lattnerb62f5082005-05-09 04:58:36 +00003419 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
3420 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003421 MaskedValueIsZero(Op1, C1->getZExtValue())) {
Chris Lattnerb62f5082005-05-09 04:58:36 +00003422 Instruction *NOr = BinaryOperator::createOr(A, Op1, Op0->getName());
3423 Op0->setName("");
3424 return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
3425 }
3426
3427 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
3428 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003429 MaskedValueIsZero(Op0, C1->getZExtValue())) {
Chris Lattnerb62f5082005-05-09 04:58:36 +00003430 Instruction *NOr = BinaryOperator::createOr(A, Op0, Op1->getName());
3431 Op0->setName("");
3432 return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
3433 }
3434
Chris Lattner15212982005-09-18 03:42:07 +00003435 // (A & C1)|(B & C2)
Chris Lattnerd4252a72004-07-30 07:50:03 +00003436 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattner15212982005-09-18 03:42:07 +00003437 match(Op1, m_And(m_Value(B), m_ConstantInt(C2)))) {
3438
3439 if (A == B) // (A & C1)|(A & C2) == A & (C1|C2)
3440 return BinaryOperator::createAnd(A, ConstantExpr::getOr(C1, C2));
3441
3442
Chris Lattner01f56c62005-09-18 06:02:59 +00003443 // If we have: ((V + N) & C1) | (V & C2)
3444 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
3445 // replace with V+N.
3446 if (C1 == ConstantExpr::getNot(C2)) {
Chris Lattner330628a2006-01-06 17:59:59 +00003447 Value *V1 = 0, *V2 = 0;
Reid Spencere0fc4df2006-10-20 07:07:24 +00003448 if ((C2->getZExtValue() & (C2->getZExtValue()+1)) == 0 && // C2 == 0+1+
Chris Lattner01f56c62005-09-18 06:02:59 +00003449 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
3450 // Add commutes, try both ways.
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003451 if (V1 == B && MaskedValueIsZero(V2, C2->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003452 return ReplaceInstUsesWith(I, A);
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003453 if (V2 == B && MaskedValueIsZero(V1, C2->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003454 return ReplaceInstUsesWith(I, A);
3455 }
3456 // Or commutes, try both ways.
Reid Spencere0fc4df2006-10-20 07:07:24 +00003457 if ((C1->getZExtValue() & (C1->getZExtValue()+1)) == 0 &&
Chris Lattner01f56c62005-09-18 06:02:59 +00003458 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
3459 // Add commutes, try both ways.
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003460 if (V1 == A && MaskedValueIsZero(V2, C1->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003461 return ReplaceInstUsesWith(I, B);
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003462 if (V2 == A && MaskedValueIsZero(V1, C1->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003463 return ReplaceInstUsesWith(I, B);
Chris Lattner15212982005-09-18 03:42:07 +00003464 }
3465 }
3466 }
Chris Lattner812aab72003-08-12 19:11:07 +00003467
Chris Lattnerd4252a72004-07-30 07:50:03 +00003468 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
3469 if (A == Op1) // ~A | A == -1
Misha Brukmanb1c93172005-04-21 23:48:37 +00003470 return ReplaceInstUsesWith(I,
Chris Lattnerd4252a72004-07-30 07:50:03 +00003471 ConstantIntegral::getAllOnesValue(I.getType()));
3472 } else {
3473 A = 0;
3474 }
Chris Lattner4294cec2005-05-07 23:49:08 +00003475 // Note, A is still live here!
Chris Lattnerd4252a72004-07-30 07:50:03 +00003476 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
3477 if (Op0 == B)
Misha Brukmanb1c93172005-04-21 23:48:37 +00003478 return ReplaceInstUsesWith(I,
Chris Lattnerd4252a72004-07-30 07:50:03 +00003479 ConstantIntegral::getAllOnesValue(I.getType()));
Chris Lattner3e327a42003-03-10 23:13:59 +00003480
Misha Brukman9c003d82004-07-30 12:50:08 +00003481 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattnerd4252a72004-07-30 07:50:03 +00003482 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3483 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
3484 I.getName()+".demorgan"), I);
3485 return BinaryOperator::createNot(And);
3486 }
Chris Lattner3e327a42003-03-10 23:13:59 +00003487 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00003488
Chris Lattner3ac7c262003-08-13 20:16:26 +00003489 // (setcc1 A, B) | (setcc2 A, B) --> (setcc3 A, B)
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003490 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1))) {
Chris Lattner3ac7c262003-08-13 20:16:26 +00003491 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
3492 return R;
3493
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003494 Value *LHSVal, *RHSVal;
3495 ConstantInt *LHSCst, *RHSCst;
3496 Instruction::BinaryOps LHSCC, RHSCC;
3497 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3498 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3499 if (LHSVal == RHSVal && // Found (X setcc C1) | (X setcc C2)
3500 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
Misha Brukmanb1c93172005-04-21 23:48:37 +00003501 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003502 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
3503 // Ensure that the larger constant is on the RHS.
3504 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
3505 SetCondInst *LHS = cast<SetCondInst>(Op0);
3506 if (cast<ConstantBool>(Cmp)->getValue()) {
3507 std::swap(LHS, RHS);
3508 std::swap(LHSCst, RHSCst);
3509 std::swap(LHSCC, RHSCC);
3510 }
3511
3512 // At this point, we know we have have two setcc instructions
3513 // comparing a value against two constants and or'ing the result
3514 // together. Because of the above check, we know that we only have
3515 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
3516 // FoldSetCCLogical check above), that the two constants are not
3517 // equal.
3518 assert(LHSCst != RHSCst && "Compares not folded above?");
3519
3520 switch (LHSCC) {
3521 default: assert(0 && "Unknown integer condition code!");
3522 case Instruction::SetEQ:
3523 switch (RHSCC) {
3524 default: assert(0 && "Unknown integer condition code!");
3525 case Instruction::SetEQ:
3526 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
3527 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3528 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3529 LHSVal->getName()+".off");
3530 InsertNewInstBefore(Add, I);
3531 const Type *UnsType = Add->getType()->getUnsignedVersion();
3532 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
3533 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
3534 AddCST = ConstantExpr::getCast(AddCST, UnsType);
3535 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
3536 }
3537 break; // (X == 13 | X == 15) -> no change
3538
Chris Lattner5c219462005-04-19 06:04:18 +00003539 case Instruction::SetGT: // (X == 13 | X > 14) -> no change
3540 break;
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003541 case Instruction::SetNE: // (X == 13 | X != 15) -> X != 15
3542 case Instruction::SetLT: // (X == 13 | X < 15) -> X < 15
3543 return ReplaceInstUsesWith(I, RHS);
3544 }
3545 break;
3546 case Instruction::SetNE:
3547 switch (RHSCC) {
3548 default: assert(0 && "Unknown integer condition code!");
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003549 case Instruction::SetEQ: // (X != 13 | X == 15) -> X != 13
3550 case Instruction::SetGT: // (X != 13 | X > 15) -> X != 13
3551 return ReplaceInstUsesWith(I, LHS);
3552 case Instruction::SetNE: // (X != 13 | X != 15) -> true
Chris Lattner2ceb6ee2005-06-17 03:59:17 +00003553 case Instruction::SetLT: // (X != 13 | X < 15) -> true
Chris Lattner6ab03f62006-09-28 23:35:22 +00003554 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003555 }
3556 break;
3557 case Instruction::SetLT:
3558 switch (RHSCC) {
3559 default: assert(0 && "Unknown integer condition code!");
3560 case Instruction::SetEQ: // (X < 13 | X == 14) -> no change
3561 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00003562 case Instruction::SetGT: // (X < 13 | X > 15) -> (X-13) > 2
3563 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false, I);
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003564 case Instruction::SetNE: // (X < 13 | X != 15) -> X != 15
3565 case Instruction::SetLT: // (X < 13 | X < 15) -> X < 15
3566 return ReplaceInstUsesWith(I, RHS);
3567 }
3568 break;
3569 case Instruction::SetGT:
3570 switch (RHSCC) {
3571 default: assert(0 && "Unknown integer condition code!");
3572 case Instruction::SetEQ: // (X > 13 | X == 15) -> X > 13
3573 case Instruction::SetGT: // (X > 13 | X > 15) -> X > 13
3574 return ReplaceInstUsesWith(I, LHS);
3575 case Instruction::SetNE: // (X > 13 | X != 15) -> true
3576 case Instruction::SetLT: // (X > 13 | X < 15) -> true
Chris Lattner6ab03f62006-09-28 23:35:22 +00003577 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003578 }
3579 }
3580 }
3581 }
Chris Lattner3af10532006-05-05 06:39:07 +00003582
3583 // fold (or (cast A), (cast B)) -> (cast (or A, B))
3584 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattnere745c7d2006-05-05 20:51:30 +00003585 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner3af10532006-05-05 06:39:07 +00003586 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Chris Lattnere745c7d2006-05-05 20:51:30 +00003587 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegral() &&
Chris Lattner1d441ad2006-05-06 09:00:16 +00003588 // Only do this if the casts both really cause code to be generated.
3589 ValueRequiresCast(Op0C->getOperand(0), I.getType(), TD) &&
3590 ValueRequiresCast(Op1C->getOperand(0), I.getType(), TD)) {
Chris Lattner3af10532006-05-05 06:39:07 +00003591 Instruction *NewOp = BinaryOperator::createOr(Op0C->getOperand(0),
3592 Op1C->getOperand(0),
3593 I.getName());
3594 InsertNewInstBefore(NewOp, I);
3595 return new CastInst(NewOp, I.getType());
3596 }
3597 }
3598
Chris Lattner15212982005-09-18 03:42:07 +00003599
Chris Lattner113f4f42002-06-25 16:13:24 +00003600 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003601}
3602
Chris Lattnerc2076352004-02-16 01:20:27 +00003603// XorSelf - Implements: X ^ X --> 0
3604struct XorSelf {
3605 Value *RHS;
3606 XorSelf(Value *rhs) : RHS(rhs) {}
3607 bool shouldApply(Value *LHS) const { return LHS == RHS; }
3608 Instruction *apply(BinaryOperator &Xor) const {
3609 return &Xor;
3610 }
3611};
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003612
3613
Chris Lattner113f4f42002-06-25 16:13:24 +00003614Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003615 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00003616 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003617
Chris Lattner81a7a232004-10-16 18:11:37 +00003618 if (isa<UndefValue>(Op1))
3619 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
3620
Chris Lattnerc2076352004-02-16 01:20:27 +00003621 // xor X, X = 0, even if X is nested in a sequence of Xor's.
3622 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
3623 assert(Result == &I && "AssociativeOpt didn't work?");
Chris Lattnere6794492002-08-12 21:17:25 +00003624 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc2076352004-02-16 01:20:27 +00003625 }
Chris Lattner5b2edb12006-02-12 08:02:11 +00003626
3627 // See if we can simplify any instructions used by the instruction whose sole
3628 // purpose is to compute bits we don't care about.
3629 uint64_t KnownZero, KnownOne;
Chris Lattnerd70d9f52006-03-25 21:58:26 +00003630 if (!isa<PackedType>(I.getType()) &&
3631 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
Chris Lattner5b2edb12006-02-12 08:02:11 +00003632 KnownZero, KnownOne))
3633 return &I;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003634
Chris Lattner97638592003-07-23 21:37:07 +00003635 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner97638592003-07-23 21:37:07 +00003636 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerb8d6e402002-08-20 18:24:26 +00003637 // xor (setcc A, B), true = not (setcc A, B) = setncc A, B
Chris Lattner97638592003-07-23 21:37:07 +00003638 if (SetCondInst *SCI = dyn_cast<SetCondInst>(Op0I))
Chris Lattner6ab03f62006-09-28 23:35:22 +00003639 if (RHS == ConstantBool::getTrue() && SCI->hasOneUse())
Chris Lattnerb8d6e402002-08-20 18:24:26 +00003640 return new SetCondInst(SCI->getInverseCondition(),
3641 SCI->getOperand(0), SCI->getOperand(1));
Chris Lattnere5806662003-11-04 23:50:51 +00003642
Chris Lattner8f2f5982003-11-05 01:06:05 +00003643 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003644 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
3645 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003646 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
3647 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003648 ConstantInt::get(I.getType(), 1));
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003649 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003650 }
Chris Lattner023a4832004-06-18 06:07:51 +00003651
3652 // ~(~X & Y) --> (X | ~Y)
3653 if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
3654 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
3655 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
3656 Instruction *NotY =
Misha Brukmanb1c93172005-04-21 23:48:37 +00003657 BinaryOperator::createNot(Op0I->getOperand(1),
Chris Lattner023a4832004-06-18 06:07:51 +00003658 Op0I->getOperand(1)->getName()+".not");
3659 InsertNewInstBefore(NotY, I);
3660 return BinaryOperator::createOr(Op0NotVal, NotY);
3661 }
3662 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003663
Chris Lattner97638592003-07-23 21:37:07 +00003664 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner5b2edb12006-02-12 08:02:11 +00003665 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner0f68fa62003-11-04 23:37:10 +00003666 // ~(X-c) --> (-c-1)-X
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003667 if (RHS->isAllOnesValue()) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003668 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
3669 return BinaryOperator::createSub(
3670 ConstantExpr::getSub(NegOp0CI,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003671 ConstantInt::get(I.getType(), 1)),
Chris Lattner0f68fa62003-11-04 23:37:10 +00003672 Op0I->getOperand(0));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003673 }
Chris Lattnerf78df7c2006-02-26 19:57:54 +00003674 } else if (Op0I->getOpcode() == Instruction::Or) {
3675 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
3676 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getZExtValue())) {
3677 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
3678 // Anything in both C1 and C2 is known to be zero, remove it from
3679 // NewRHS.
3680 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
3681 NewRHS = ConstantExpr::getAnd(NewRHS,
3682 ConstantExpr::getNot(CommonBits));
3683 WorkList.push_back(Op0I);
3684 I.setOperand(0, Op0I->getOperand(0));
3685 I.setOperand(1, NewRHS);
3686 return &I;
3687 }
Chris Lattner97638592003-07-23 21:37:07 +00003688 }
Chris Lattnerb8d6e402002-08-20 18:24:26 +00003689 }
Chris Lattner183b3362004-04-09 19:05:30 +00003690
3691 // Try to fold constant and into select arguments.
3692 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00003693 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00003694 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00003695 if (isa<PHINode>(Op0))
3696 if (Instruction *NV = FoldOpIntoPhi(I))
3697 return NV;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003698 }
3699
Chris Lattnerbb74e222003-03-10 23:06:50 +00003700 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00003701 if (X == Op1)
3702 return ReplaceInstUsesWith(I,
3703 ConstantIntegral::getAllOnesValue(I.getType()));
3704
Chris Lattnerbb74e222003-03-10 23:06:50 +00003705 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00003706 if (X == Op0)
3707 return ReplaceInstUsesWith(I,
3708 ConstantIntegral::getAllOnesValue(I.getType()));
3709
Chris Lattnerdcd07922006-04-01 08:03:55 +00003710 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1))
Chris Lattnerb36d9082004-02-16 03:54:20 +00003711 if (Op1I->getOpcode() == Instruction::Or) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003712 if (Op1I->getOperand(0) == Op0) { // B^(B|A) == (A|B)^B
Chris Lattnerdcd07922006-04-01 08:03:55 +00003713 Op1I->swapOperands();
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003714 I.swapOperands();
3715 std::swap(Op0, Op1);
3716 } else if (Op1I->getOperand(1) == Op0) { // B^(A|B) == (A|B)^B
Chris Lattnerdcd07922006-04-01 08:03:55 +00003717 I.swapOperands(); // Simplified below.
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003718 std::swap(Op0, Op1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003719 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00003720 } else if (Op1I->getOpcode() == Instruction::Xor) {
3721 if (Op0 == Op1I->getOperand(0)) // A^(A^B) == B
3722 return ReplaceInstUsesWith(I, Op1I->getOperand(1));
3723 else if (Op0 == Op1I->getOperand(1)) // A^(B^A) == B
3724 return ReplaceInstUsesWith(I, Op1I->getOperand(0));
Chris Lattnerdcd07922006-04-01 08:03:55 +00003725 } else if (Op1I->getOpcode() == Instruction::And && Op1I->hasOneUse()) {
3726 if (Op1I->getOperand(0) == Op0) // A^(A&B) -> A^(B&A)
3727 Op1I->swapOperands();
3728 if (Op0 == Op1I->getOperand(1)) { // A^(B&A) -> (B&A)^A
3729 I.swapOperands(); // Simplified below.
3730 std::swap(Op0, Op1);
3731 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00003732 }
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003733
Chris Lattnerdcd07922006-04-01 08:03:55 +00003734 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00003735 if (Op0I->getOpcode() == Instruction::Or && Op0I->hasOneUse()) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003736 if (Op0I->getOperand(0) == Op1) // (B|A)^B == (A|B)^B
Chris Lattnerdcd07922006-04-01 08:03:55 +00003737 Op0I->swapOperands();
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003738 if (Op0I->getOperand(1) == Op1) { // (A|B)^B == A & ~B
Chris Lattnerdcd07922006-04-01 08:03:55 +00003739 Instruction *NotB = BinaryOperator::createNot(Op1, "tmp");
3740 InsertNewInstBefore(NotB, I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003741 return BinaryOperator::createAnd(Op0I->getOperand(0), NotB);
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003742 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00003743 } else if (Op0I->getOpcode() == Instruction::Xor) {
3744 if (Op1 == Op0I->getOperand(0)) // (A^B)^A == B
3745 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
3746 else if (Op1 == Op0I->getOperand(1)) // (B^A)^A == B
3747 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattnerdcd07922006-04-01 08:03:55 +00003748 } else if (Op0I->getOpcode() == Instruction::And && Op0I->hasOneUse()) {
3749 if (Op0I->getOperand(0) == Op1) // (A&B)^A -> (B&A)^A
3750 Op0I->swapOperands();
Chris Lattner6cf49142006-04-01 22:05:01 +00003751 if (Op0I->getOperand(1) == Op1 && // (B&A)^A == ~B & A
3752 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattnerdcd07922006-04-01 08:03:55 +00003753 Instruction *N = BinaryOperator::createNot(Op0I->getOperand(0), "tmp");
3754 InsertNewInstBefore(N, I);
3755 return BinaryOperator::createAnd(N, Op1);
3756 }
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003757 }
3758
Chris Lattner3ac7c262003-08-13 20:16:26 +00003759 // (setcc1 A, B) ^ (setcc2 A, B) --> (setcc3 A, B)
3760 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
3761 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
3762 return R;
3763
Chris Lattner3af10532006-05-05 06:39:07 +00003764 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
3765 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattnere745c7d2006-05-05 20:51:30 +00003766 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner3af10532006-05-05 06:39:07 +00003767 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Chris Lattnere745c7d2006-05-05 20:51:30 +00003768 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegral() &&
Chris Lattner1d441ad2006-05-06 09:00:16 +00003769 // Only do this if the casts both really cause code to be generated.
3770 ValueRequiresCast(Op0C->getOperand(0), I.getType(), TD) &&
3771 ValueRequiresCast(Op1C->getOperand(0), I.getType(), TD)) {
Chris Lattner3af10532006-05-05 06:39:07 +00003772 Instruction *NewOp = BinaryOperator::createXor(Op0C->getOperand(0),
3773 Op1C->getOperand(0),
3774 I.getName());
3775 InsertNewInstBefore(NewOp, I);
3776 return new CastInst(NewOp, I.getType());
3777 }
3778 }
3779
Chris Lattner113f4f42002-06-25 16:13:24 +00003780 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003781}
3782
Chris Lattner6862fbd2004-09-29 17:40:11 +00003783static bool isPositive(ConstantInt *C) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00003784 return C->getSExtValue() >= 0;
Chris Lattner6862fbd2004-09-29 17:40:11 +00003785}
3786
3787/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
3788/// overflowed for this type.
3789static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
3790 ConstantInt *In2) {
3791 Result = cast<ConstantInt>(ConstantExpr::getAdd(In1, In2));
3792
3793 if (In1->getType()->isUnsigned())
Reid Spencere0fc4df2006-10-20 07:07:24 +00003794 return cast<ConstantInt>(Result)->getZExtValue() <
3795 cast<ConstantInt>(In1)->getZExtValue();
Chris Lattner6862fbd2004-09-29 17:40:11 +00003796 if (isPositive(In1) != isPositive(In2))
3797 return false;
3798 if (isPositive(In1))
Reid Spencere0fc4df2006-10-20 07:07:24 +00003799 return cast<ConstantInt>(Result)->getSExtValue() <
3800 cast<ConstantInt>(In1)->getSExtValue();
3801 return cast<ConstantInt>(Result)->getSExtValue() >
3802 cast<ConstantInt>(In1)->getSExtValue();
Chris Lattner6862fbd2004-09-29 17:40:11 +00003803}
3804
Chris Lattner0798af32005-01-13 20:14:25 +00003805/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
3806/// code necessary to compute the offset from the base pointer (without adding
3807/// in the base pointer). Return the result as a signed integer of intptr size.
3808static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
3809 TargetData &TD = IC.getTargetData();
3810 gep_type_iterator GTI = gep_type_begin(GEP);
3811 const Type *UIntPtrTy = TD.getIntPtrType();
3812 const Type *SIntPtrTy = UIntPtrTy->getSignedVersion();
3813 Value *Result = Constant::getNullValue(SIntPtrTy);
3814
3815 // Build a mask for high order bits.
Chris Lattner77defba2006-02-07 07:00:41 +00003816 uint64_t PtrSizeMask = ~0ULL >> (64-TD.getPointerSize()*8);
Chris Lattner0798af32005-01-13 20:14:25 +00003817
Chris Lattner0798af32005-01-13 20:14:25 +00003818 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
3819 Value *Op = GEP->getOperand(i);
Chris Lattnerd35d2102005-01-13 23:26:48 +00003820 uint64_t Size = TD.getTypeSize(GTI.getIndexedType()) & PtrSizeMask;
Reid Spencere0fc4df2006-10-20 07:07:24 +00003821 Constant *Scale = ConstantExpr::getCast(ConstantInt::get(UIntPtrTy, Size),
Chris Lattner0798af32005-01-13 20:14:25 +00003822 SIntPtrTy);
3823 if (Constant *OpC = dyn_cast<Constant>(Op)) {
3824 if (!OpC->isNullValue()) {
Chris Lattner4cb9fa32005-01-13 20:40:58 +00003825 OpC = ConstantExpr::getCast(OpC, SIntPtrTy);
Chris Lattner0798af32005-01-13 20:14:25 +00003826 Scale = ConstantExpr::getMul(OpC, Scale);
3827 if (Constant *RC = dyn_cast<Constant>(Result))
3828 Result = ConstantExpr::getAdd(RC, Scale);
3829 else {
3830 // Emit an add instruction.
3831 Result = IC.InsertNewInstBefore(
3832 BinaryOperator::createAdd(Result, Scale,
3833 GEP->getName()+".offs"), I);
3834 }
3835 }
3836 } else {
Chris Lattner7aa41cf2005-01-14 17:17:59 +00003837 // Convert to correct type.
3838 Op = IC.InsertNewInstBefore(new CastInst(Op, SIntPtrTy,
3839 Op->getName()+".c"), I);
3840 if (Size != 1)
Chris Lattner4cb9fa32005-01-13 20:40:58 +00003841 // We'll let instcombine(mul) convert this to a shl if possible.
3842 Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
3843 GEP->getName()+".idx"), I);
Chris Lattner0798af32005-01-13 20:14:25 +00003844
3845 // Emit an add instruction.
Chris Lattner4cb9fa32005-01-13 20:40:58 +00003846 Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
Chris Lattner0798af32005-01-13 20:14:25 +00003847 GEP->getName()+".offs"), I);
3848 }
3849 }
3850 return Result;
3851}
3852
3853/// FoldGEPSetCC - Fold comparisons between a GEP instruction and something
3854/// else. At this point we know that the GEP is on the LHS of the comparison.
3855Instruction *InstCombiner::FoldGEPSetCC(User *GEPLHS, Value *RHS,
3856 Instruction::BinaryOps Cond,
3857 Instruction &I) {
3858 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattner81e84172005-01-13 22:25:21 +00003859
3860 if (CastInst *CI = dyn_cast<CastInst>(RHS))
3861 if (isa<PointerType>(CI->getOperand(0)->getType()))
3862 RHS = CI->getOperand(0);
3863
Chris Lattner0798af32005-01-13 20:14:25 +00003864 Value *PtrBase = GEPLHS->getOperand(0);
3865 if (PtrBase == RHS) {
3866 // As an optimization, we don't actually have to compute the actual value of
3867 // OFFSET if this is a seteq or setne comparison, just return whether each
3868 // index is zero or not.
Chris Lattner81e84172005-01-13 22:25:21 +00003869 if (Cond == Instruction::SetEQ || Cond == Instruction::SetNE) {
3870 Instruction *InVal = 0;
Chris Lattnercd517ff2005-01-28 19:32:01 +00003871 gep_type_iterator GTI = gep_type_begin(GEPLHS);
3872 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i, ++GTI) {
Chris Lattner81e84172005-01-13 22:25:21 +00003873 bool EmitIt = true;
3874 if (Constant *C = dyn_cast<Constant>(GEPLHS->getOperand(i))) {
3875 if (isa<UndefValue>(C)) // undef index -> undef.
3876 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
3877 if (C->isNullValue())
3878 EmitIt = false;
Chris Lattnercd517ff2005-01-28 19:32:01 +00003879 else if (TD->getTypeSize(GTI.getIndexedType()) == 0) {
3880 EmitIt = false; // This is indexing into a zero sized array?
Misha Brukmanb1c93172005-04-21 23:48:37 +00003881 } else if (isa<ConstantInt>(C))
Chris Lattner81e84172005-01-13 22:25:21 +00003882 return ReplaceInstUsesWith(I, // No comparison is needed here.
3883 ConstantBool::get(Cond == Instruction::SetNE));
3884 }
3885
3886 if (EmitIt) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00003887 Instruction *Comp =
Chris Lattner81e84172005-01-13 22:25:21 +00003888 new SetCondInst(Cond, GEPLHS->getOperand(i),
3889 Constant::getNullValue(GEPLHS->getOperand(i)->getType()));
3890 if (InVal == 0)
3891 InVal = Comp;
3892 else {
3893 InVal = InsertNewInstBefore(InVal, I);
3894 InsertNewInstBefore(Comp, I);
3895 if (Cond == Instruction::SetNE) // True if any are unequal
3896 InVal = BinaryOperator::createOr(InVal, Comp);
3897 else // True if all are equal
3898 InVal = BinaryOperator::createAnd(InVal, Comp);
3899 }
3900 }
3901 }
3902
3903 if (InVal)
3904 return InVal;
3905 else
3906 ReplaceInstUsesWith(I, // No comparison is needed here, all indexes = 0
3907 ConstantBool::get(Cond == Instruction::SetEQ));
3908 }
Chris Lattner0798af32005-01-13 20:14:25 +00003909
3910 // Only lower this if the setcc is the only user of the GEP or if we expect
3911 // the result to fold to a constant!
3912 if (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) {
3913 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
3914 Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
3915 return new SetCondInst(Cond, Offset,
3916 Constant::getNullValue(Offset->getType()));
3917 }
3918 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
Chris Lattnera21bf8d2005-04-25 20:17:30 +00003919 // If the base pointers are different, but the indices are the same, just
3920 // compare the base pointer.
3921 if (PtrBase != GEPRHS->getOperand(0)) {
3922 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00003923 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattnerbd43b9d2005-04-26 14:40:41 +00003924 GEPRHS->getOperand(0)->getType();
Chris Lattnera21bf8d2005-04-25 20:17:30 +00003925 if (IndicesTheSame)
3926 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
3927 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
3928 IndicesTheSame = false;
3929 break;
3930 }
3931
3932 // If all indices are the same, just compare the base pointers.
3933 if (IndicesTheSame)
3934 return new SetCondInst(Cond, GEPLHS->getOperand(0),
3935 GEPRHS->getOperand(0));
3936
3937 // Otherwise, the base pointers are different and the indices are
3938 // different, bail out.
Chris Lattner0798af32005-01-13 20:14:25 +00003939 return 0;
Chris Lattnera21bf8d2005-04-25 20:17:30 +00003940 }
Chris Lattner0798af32005-01-13 20:14:25 +00003941
Chris Lattner81e84172005-01-13 22:25:21 +00003942 // If one of the GEPs has all zero indices, recurse.
3943 bool AllZeros = true;
3944 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
3945 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
3946 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
3947 AllZeros = false;
3948 break;
3949 }
3950 if (AllZeros)
3951 return FoldGEPSetCC(GEPRHS, GEPLHS->getOperand(0),
3952 SetCondInst::getSwappedCondition(Cond), I);
Chris Lattner4fa89822005-01-14 00:20:05 +00003953
3954 // If the other GEP has all zero indices, recurse.
Chris Lattner81e84172005-01-13 22:25:21 +00003955 AllZeros = true;
3956 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
3957 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
3958 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
3959 AllZeros = false;
3960 break;
3961 }
3962 if (AllZeros)
3963 return FoldGEPSetCC(GEPLHS, GEPRHS->getOperand(0), Cond, I);
3964
Chris Lattner4fa89822005-01-14 00:20:05 +00003965 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
3966 // If the GEPs only differ by one index, compare it.
3967 unsigned NumDifferences = 0; // Keep track of # differences.
3968 unsigned DiffOperand = 0; // The operand that differs.
3969 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
3970 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003971 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
3972 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattnerfc4429e2005-01-21 23:06:49 +00003973 // Irreconcilable differences.
Chris Lattner4fa89822005-01-14 00:20:05 +00003974 NumDifferences = 2;
3975 break;
3976 } else {
3977 if (NumDifferences++) break;
3978 DiffOperand = i;
3979 }
3980 }
3981
3982 if (NumDifferences == 0) // SAME GEP?
3983 return ReplaceInstUsesWith(I, // No comparison is needed here.
3984 ConstantBool::get(Cond == Instruction::SetEQ));
3985 else if (NumDifferences == 1) {
Chris Lattnerfc4429e2005-01-21 23:06:49 +00003986 Value *LHSV = GEPLHS->getOperand(DiffOperand);
3987 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Chris Lattner247aef82005-07-18 23:07:33 +00003988
3989 // Convert the operands to signed values to make sure to perform a
3990 // signed comparison.
3991 const Type *NewTy = LHSV->getType()->getSignedVersion();
3992 if (LHSV->getType() != NewTy)
Reid Spencer00c482b2006-10-26 19:19:06 +00003993 LHSV = InsertCastBefore(LHSV, NewTy, I);
Chris Lattner247aef82005-07-18 23:07:33 +00003994 if (RHSV->getType() != NewTy)
Reid Spencer00c482b2006-10-26 19:19:06 +00003995 RHSV = InsertCastBefore(RHSV, NewTy, I);
Chris Lattner247aef82005-07-18 23:07:33 +00003996 return new SetCondInst(Cond, LHSV, RHSV);
Chris Lattner4fa89822005-01-14 00:20:05 +00003997 }
3998 }
3999
Chris Lattner0798af32005-01-13 20:14:25 +00004000 // Only lower this if the setcc is the only user of the GEP or if we expect
4001 // the result to fold to a constant!
4002 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
4003 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
4004 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
4005 Value *L = EmitGEPOffset(GEPLHS, I, *this);
4006 Value *R = EmitGEPOffset(GEPRHS, I, *this);
4007 return new SetCondInst(Cond, L, R);
4008 }
4009 }
4010 return 0;
4011}
4012
4013
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004014Instruction *InstCombiner::visitSetCondInst(SetCondInst &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00004015 bool Changed = SimplifyCommutative(I);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004016 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4017 const Type *Ty = Op0->getType();
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004018
4019 // setcc X, X
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004020 if (Op0 == Op1)
4021 return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
Chris Lattner1fc23f32002-05-09 20:11:54 +00004022
Chris Lattner81a7a232004-10-16 18:11:37 +00004023 if (isa<UndefValue>(Op1)) // X setcc undef -> undef
4024 return ReplaceInstUsesWith(I, UndefValue::get(Type::BoolTy));
4025
Chris Lattner15ff1e12004-11-14 07:33:16 +00004026 // setcc <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
4027 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanb1c93172005-04-21 23:48:37 +00004028 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
4029 isa<ConstantPointerNull>(Op0)) &&
4030 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner15ff1e12004-11-14 07:33:16 +00004031 isa<ConstantPointerNull>(Op1)))
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004032 return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
4033
4034 // setcc's with boolean values can always be turned into bitwise operations
4035 if (Ty == Type::BoolTy) {
Chris Lattner4456da62004-08-11 00:50:51 +00004036 switch (I.getOpcode()) {
4037 default: assert(0 && "Invalid setcc instruction!");
4038 case Instruction::SetEQ: { // seteq bool %A, %B -> ~(A^B)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004039 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004040 InsertNewInstBefore(Xor, I);
Chris Lattner16930792003-11-03 04:25:02 +00004041 return BinaryOperator::createNot(Xor);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004042 }
Chris Lattner4456da62004-08-11 00:50:51 +00004043 case Instruction::SetNE:
4044 return BinaryOperator::createXor(Op0, Op1);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004045
Chris Lattner4456da62004-08-11 00:50:51 +00004046 case Instruction::SetGT:
4047 std::swap(Op0, Op1); // Change setgt -> setlt
4048 // FALL THROUGH
4049 case Instruction::SetLT: { // setlt bool A, B -> ~X & Y
4050 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4051 InsertNewInstBefore(Not, I);
4052 return BinaryOperator::createAnd(Not, Op1);
4053 }
4054 case Instruction::SetGE:
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004055 std::swap(Op0, Op1); // Change setge -> setle
Chris Lattner4456da62004-08-11 00:50:51 +00004056 // FALL THROUGH
4057 case Instruction::SetLE: { // setle bool %A, %B -> ~A | B
4058 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4059 InsertNewInstBefore(Not, I);
4060 return BinaryOperator::createOr(Not, Op1);
4061 }
4062 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004063 }
4064
Chris Lattner2dd01742004-06-09 04:24:29 +00004065 // See if we are doing a comparison between a constant and an instruction that
4066 // can be folded into the comparison.
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004067 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner6862fbd2004-09-29 17:40:11 +00004068 // Check to see if we are comparing against the minimum or maximum value...
4069 if (CI->isMinValue()) {
4070 if (I.getOpcode() == Instruction::SetLT) // A < MIN -> FALSE
Chris Lattner6ab03f62006-09-28 23:35:22 +00004071 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattner6862fbd2004-09-29 17:40:11 +00004072 if (I.getOpcode() == Instruction::SetGE) // A >= MIN -> TRUE
Chris Lattner6ab03f62006-09-28 23:35:22 +00004073 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
Chris Lattner6862fbd2004-09-29 17:40:11 +00004074 if (I.getOpcode() == Instruction::SetLE) // A <= MIN -> A == MIN
4075 return BinaryOperator::createSetEQ(Op0, Op1);
4076 if (I.getOpcode() == Instruction::SetGT) // A > MIN -> A != MIN
4077 return BinaryOperator::createSetNE(Op0, Op1);
4078
4079 } else if (CI->isMaxValue()) {
4080 if (I.getOpcode() == Instruction::SetGT) // A > MAX -> FALSE
Chris Lattner6ab03f62006-09-28 23:35:22 +00004081 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattner6862fbd2004-09-29 17:40:11 +00004082 if (I.getOpcode() == Instruction::SetLE) // A <= MAX -> TRUE
Chris Lattner6ab03f62006-09-28 23:35:22 +00004083 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
Chris Lattner6862fbd2004-09-29 17:40:11 +00004084 if (I.getOpcode() == Instruction::SetGE) // A >= MAX -> A == MAX
4085 return BinaryOperator::createSetEQ(Op0, Op1);
4086 if (I.getOpcode() == Instruction::SetLT) // A < MAX -> A != MAX
4087 return BinaryOperator::createSetNE(Op0, Op1);
4088
4089 // Comparing against a value really close to min or max?
4090 } else if (isMinValuePlusOne(CI)) {
4091 if (I.getOpcode() == Instruction::SetLT) // A < MIN+1 -> A == MIN
4092 return BinaryOperator::createSetEQ(Op0, SubOne(CI));
4093 if (I.getOpcode() == Instruction::SetGE) // A >= MIN-1 -> A != MIN
4094 return BinaryOperator::createSetNE(Op0, SubOne(CI));
4095
4096 } else if (isMaxValueMinusOne(CI)) {
4097 if (I.getOpcode() == Instruction::SetGT) // A > MAX-1 -> A == MAX
4098 return BinaryOperator::createSetEQ(Op0, AddOne(CI));
4099 if (I.getOpcode() == Instruction::SetLE) // A <= MAX-1 -> A != MAX
4100 return BinaryOperator::createSetNE(Op0, AddOne(CI));
4101 }
4102
4103 // If we still have a setle or setge instruction, turn it into the
4104 // appropriate setlt or setgt instruction. Since the border cases have
4105 // already been handled above, this requires little checking.
4106 //
4107 if (I.getOpcode() == Instruction::SetLE)
4108 return BinaryOperator::createSetLT(Op0, AddOne(CI));
4109 if (I.getOpcode() == Instruction::SetGE)
4110 return BinaryOperator::createSetGT(Op0, SubOne(CI));
4111
Chris Lattneree0f2802006-02-12 02:07:56 +00004112
4113 // See if we can fold the comparison based on bits known to be zero or one
4114 // in the input.
4115 uint64_t KnownZero, KnownOne;
4116 if (SimplifyDemandedBits(Op0, Ty->getIntegralTypeMask(),
4117 KnownZero, KnownOne, 0))
4118 return &I;
4119
4120 // Given the known and unknown bits, compute a range that the LHS could be
4121 // in.
4122 if (KnownOne | KnownZero) {
4123 if (Ty->isUnsigned()) { // Unsigned comparison.
4124 uint64_t Min, Max;
4125 uint64_t RHSVal = CI->getZExtValue();
4126 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne,
4127 Min, Max);
4128 switch (I.getOpcode()) { // LE/GE have been folded already.
4129 default: assert(0 && "Unknown setcc opcode!");
4130 case Instruction::SetEQ:
4131 if (Max < RHSVal || Min > RHSVal)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004132 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattneree0f2802006-02-12 02:07:56 +00004133 break;
4134 case Instruction::SetNE:
4135 if (Max < RHSVal || Min > RHSVal)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004136 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
Chris Lattneree0f2802006-02-12 02:07:56 +00004137 break;
4138 case Instruction::SetLT:
Chris Lattner6ab03f62006-09-28 23:35:22 +00004139 if (Max < RHSVal)
4140 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4141 if (Min > RHSVal)
4142 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattneree0f2802006-02-12 02:07:56 +00004143 break;
4144 case Instruction::SetGT:
Chris Lattner6ab03f62006-09-28 23:35:22 +00004145 if (Min > RHSVal)
4146 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4147 if (Max < RHSVal)
4148 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattneree0f2802006-02-12 02:07:56 +00004149 break;
4150 }
4151 } else { // Signed comparison.
4152 int64_t Min, Max;
4153 int64_t RHSVal = CI->getSExtValue();
4154 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne,
4155 Min, Max);
4156 switch (I.getOpcode()) { // LE/GE have been folded already.
4157 default: assert(0 && "Unknown setcc opcode!");
4158 case Instruction::SetEQ:
4159 if (Max < RHSVal || Min > RHSVal)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004160 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattneree0f2802006-02-12 02:07:56 +00004161 break;
4162 case Instruction::SetNE:
4163 if (Max < RHSVal || Min > RHSVal)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004164 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
Chris Lattneree0f2802006-02-12 02:07:56 +00004165 break;
4166 case Instruction::SetLT:
Chris Lattner6ab03f62006-09-28 23:35:22 +00004167 if (Max < RHSVal)
4168 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4169 if (Min > RHSVal)
4170 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattneree0f2802006-02-12 02:07:56 +00004171 break;
4172 case Instruction::SetGT:
Chris Lattner6ab03f62006-09-28 23:35:22 +00004173 if (Min > RHSVal)
4174 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4175 if (Max < RHSVal)
4176 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattneree0f2802006-02-12 02:07:56 +00004177 break;
4178 }
4179 }
4180 }
4181
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004182 // Since the RHS is a constantInt (CI), if the left hand side is an
4183 // instruction, see if that instruction also has constants so that the
4184 // instruction can be folded into the setcc
Chris Lattnere1e10e12004-05-25 06:32:08 +00004185 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004186 switch (LHSI->getOpcode()) {
4187 case Instruction::And:
4188 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
4189 LHSI->getOperand(0)->hasOneUse()) {
Chris Lattner4922a0e2006-09-18 05:27:43 +00004190 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
4191
4192 // If an operand is an AND of a truncating cast, we can widen the
4193 // and/compare to be the input width without changing the value
4194 // produced, eliminating a cast.
4195 if (CastInst *Cast = dyn_cast<CastInst>(LHSI->getOperand(0))) {
4196 // We can do this transformation if either the AND constant does not
4197 // have its sign bit set or if it is an equality comparison.
4198 // Extending a relational comparison when we're checking the sign
4199 // bit would not work.
4200 if (Cast->hasOneUse() && Cast->isTruncIntCast() &&
4201 (I.isEquality() ||
4202 (AndCST->getZExtValue() == (uint64_t)AndCST->getSExtValue()) &&
4203 (CI->getZExtValue() == (uint64_t)CI->getSExtValue()))) {
4204 ConstantInt *NewCST;
4205 ConstantInt *NewCI;
4206 if (Cast->getOperand(0)->getType()->isSigned()) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00004207 NewCST = ConstantInt::get(Cast->getOperand(0)->getType(),
Chris Lattner4922a0e2006-09-18 05:27:43 +00004208 AndCST->getZExtValue());
Reid Spencere0fc4df2006-10-20 07:07:24 +00004209 NewCI = ConstantInt::get(Cast->getOperand(0)->getType(),
Chris Lattner4922a0e2006-09-18 05:27:43 +00004210 CI->getZExtValue());
4211 } else {
Reid Spencere0fc4df2006-10-20 07:07:24 +00004212 NewCST = ConstantInt::get(Cast->getOperand(0)->getType(),
Chris Lattner4922a0e2006-09-18 05:27:43 +00004213 AndCST->getZExtValue());
Reid Spencere0fc4df2006-10-20 07:07:24 +00004214 NewCI = ConstantInt::get(Cast->getOperand(0)->getType(),
Chris Lattner4922a0e2006-09-18 05:27:43 +00004215 CI->getZExtValue());
4216 }
4217 Instruction *NewAnd =
4218 BinaryOperator::createAnd(Cast->getOperand(0), NewCST,
4219 LHSI->getName());
4220 InsertNewInstBefore(NewAnd, I);
4221 return new SetCondInst(I.getOpcode(), NewAnd, NewCI);
4222 }
4223 }
4224
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004225 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
4226 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
4227 // happens a LOT in code produced by the C front-end, for bitfield
4228 // access.
4229 ShiftInst *Shift = dyn_cast<ShiftInst>(LHSI->getOperand(0));
Chris Lattneree0f2802006-02-12 02:07:56 +00004230
4231 // Check to see if there is a noop-cast between the shift and the and.
4232 if (!Shift) {
4233 if (CastInst *CI = dyn_cast<CastInst>(LHSI->getOperand(0)))
4234 if (CI->getOperand(0)->getType()->isIntegral() &&
4235 CI->getOperand(0)->getType()->getPrimitiveSizeInBits() ==
4236 CI->getType()->getPrimitiveSizeInBits())
4237 Shift = dyn_cast<ShiftInst>(CI->getOperand(0));
4238 }
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004239
Reid Spencere0fc4df2006-10-20 07:07:24 +00004240 ConstantInt *ShAmt;
4241 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
Chris Lattneree0f2802006-02-12 02:07:56 +00004242 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
4243 const Type *AndTy = AndCST->getType(); // Type of the and.
Misha Brukmanb1c93172005-04-21 23:48:37 +00004244
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004245 // We can fold this as long as we can't shift unknown bits
4246 // into the mask. This can only happen with signed shift
4247 // rights, as they sign-extend.
4248 if (ShAmt) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004249 bool CanFold = Shift->isLogicalShift();
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004250 if (!CanFold) {
4251 // To test for the bad case of the signed shr, see if any
4252 // of the bits shifted in could be tested after the mask.
Reid Spencere0fc4df2006-10-20 07:07:24 +00004253 int ShAmtVal = Ty->getPrimitiveSizeInBits()-ShAmt->getZExtValue();
Chris Lattnerc53cb9d2005-06-17 01:29:28 +00004254 if (ShAmtVal < 0) ShAmtVal = 0; // Out of range shift.
4255
Reid Spencere0fc4df2006-10-20 07:07:24 +00004256 Constant *OShAmt = ConstantInt::get(Type::UByteTy, ShAmtVal);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004257 Constant *ShVal =
Chris Lattneree0f2802006-02-12 02:07:56 +00004258 ConstantExpr::getShl(ConstantInt::getAllOnesValue(AndTy),
4259 OShAmt);
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004260 if (ConstantExpr::getAnd(ShVal, AndCST)->isNullValue())
4261 CanFold = true;
4262 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004263
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004264 if (CanFold) {
Chris Lattner6afc02f2004-09-28 17:54:07 +00004265 Constant *NewCst;
4266 if (Shift->getOpcode() == Instruction::Shl)
4267 NewCst = ConstantExpr::getUShr(CI, ShAmt);
4268 else
4269 NewCst = ConstantExpr::getShl(CI, ShAmt);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004270
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004271 // Check to see if we are shifting out any of the bits being
4272 // compared.
4273 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != CI){
4274 // If we shifted bits out, the fold is not going to work out.
4275 // As a special case, check to see if this means that the
4276 // result is always true or false now.
4277 if (I.getOpcode() == Instruction::SetEQ)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004278 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004279 if (I.getOpcode() == Instruction::SetNE)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004280 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004281 } else {
4282 I.setOperand(1, NewCst);
Chris Lattner6afc02f2004-09-28 17:54:07 +00004283 Constant *NewAndCST;
4284 if (Shift->getOpcode() == Instruction::Shl)
4285 NewAndCST = ConstantExpr::getUShr(AndCST, ShAmt);
4286 else
4287 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
4288 LHSI->setOperand(1, NewAndCST);
Chris Lattneree0f2802006-02-12 02:07:56 +00004289 if (AndTy == Ty)
4290 LHSI->setOperand(0, Shift->getOperand(0));
4291 else {
4292 Value *NewCast = InsertCastBefore(Shift->getOperand(0), AndTy,
4293 *Shift);
4294 LHSI->setOperand(0, NewCast);
4295 }
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004296 WorkList.push_back(Shift); // Shift is dead.
4297 AddUsesToWorkList(I);
4298 return &I;
Chris Lattner1638de42004-07-21 19:50:44 +00004299 }
4300 }
Chris Lattner35167c32004-06-09 07:59:58 +00004301 }
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004302
4303 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
4304 // preferable because it allows the C<<Y expression to be hoisted out
4305 // of a loop if Y is invariant and X is not.
4306 if (Shift && Shift->hasOneUse() && CI->isNullValue() &&
Chris Lattnerde077922006-09-18 18:27:05 +00004307 I.isEquality() && !Shift->isArithmeticShift() &&
4308 isa<Instruction>(Shift->getOperand(0))) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004309 // Compute C << Y.
4310 Value *NS;
4311 if (Shift->getOpcode() == Instruction::Shr) {
4312 NS = new ShiftInst(Instruction::Shl, AndCST, Shift->getOperand(1),
4313 "tmp");
4314 } else {
4315 // Make sure we insert a logical shift.
Chris Lattner4922a0e2006-09-18 05:27:43 +00004316 Constant *NewAndCST = AndCST;
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004317 if (AndCST->getType()->isSigned())
Chris Lattner4922a0e2006-09-18 05:27:43 +00004318 NewAndCST = ConstantExpr::getCast(AndCST,
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004319 AndCST->getType()->getUnsignedVersion());
Chris Lattner4922a0e2006-09-18 05:27:43 +00004320 NS = new ShiftInst(Instruction::Shr, NewAndCST,
4321 Shift->getOperand(1), "tmp");
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004322 }
4323 InsertNewInstBefore(cast<Instruction>(NS), I);
4324
4325 // If C's sign doesn't agree with the and, insert a cast now.
4326 if (NS->getType() != LHSI->getType())
4327 NS = InsertCastBefore(NS, LHSI->getType(), I);
4328
4329 Value *ShiftOp = Shift->getOperand(0);
4330 if (ShiftOp->getType() != LHSI->getType())
4331 ShiftOp = InsertCastBefore(ShiftOp, LHSI->getType(), I);
4332
4333 // Compute X & (C << Y).
4334 Instruction *NewAnd =
4335 BinaryOperator::createAnd(ShiftOp, NS, LHSI->getName());
4336 InsertNewInstBefore(NewAnd, I);
4337
4338 I.setOperand(0, NewAnd);
4339 return &I;
4340 }
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004341 }
4342 break;
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004343
Chris Lattner272d5ca2004-09-28 18:22:15 +00004344 case Instruction::Shl: // (setcc (shl X, ShAmt), CI)
Reid Spencere0fc4df2006-10-20 07:07:24 +00004345 if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004346 if (I.isEquality()) {
Chris Lattner19b57f52005-06-15 20:53:31 +00004347 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
4348
4349 // Check that the shift amount is in range. If not, don't perform
4350 // undefined shifts. When the shift is visited it will be
4351 // simplified.
Reid Spencere0fc4df2006-10-20 07:07:24 +00004352 if (ShAmt->getZExtValue() >= TypeBits)
Chris Lattner19b57f52005-06-15 20:53:31 +00004353 break;
4354
Chris Lattner272d5ca2004-09-28 18:22:15 +00004355 // If we are comparing against bits always shifted out, the
4356 // comparison cannot succeed.
Misha Brukmanb1c93172005-04-21 23:48:37 +00004357 Constant *Comp =
Chris Lattner272d5ca2004-09-28 18:22:15 +00004358 ConstantExpr::getShl(ConstantExpr::getShr(CI, ShAmt), ShAmt);
4359 if (Comp != CI) {// Comparing against a bit that we know is zero.
4360 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
4361 Constant *Cst = ConstantBool::get(IsSetNE);
4362 return ReplaceInstUsesWith(I, Cst);
4363 }
4364
4365 if (LHSI->hasOneUse()) {
4366 // Otherwise strength reduce the shift into an and.
Reid Spencere0fc4df2006-10-20 07:07:24 +00004367 unsigned ShAmtVal = (unsigned)ShAmt->getZExtValue();
Chris Lattner272d5ca2004-09-28 18:22:15 +00004368 uint64_t Val = (1ULL << (TypeBits-ShAmtVal))-1;
4369
4370 Constant *Mask;
4371 if (CI->getType()->isUnsigned()) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00004372 Mask = ConstantInt::get(CI->getType(), Val);
Chris Lattner272d5ca2004-09-28 18:22:15 +00004373 } else if (ShAmtVal != 0) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00004374 Mask = ConstantInt::get(CI->getType(), Val);
Chris Lattner272d5ca2004-09-28 18:22:15 +00004375 } else {
4376 Mask = ConstantInt::getAllOnesValue(CI->getType());
4377 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004378
Chris Lattner272d5ca2004-09-28 18:22:15 +00004379 Instruction *AndI =
4380 BinaryOperator::createAnd(LHSI->getOperand(0),
4381 Mask, LHSI->getName()+".mask");
4382 Value *And = InsertNewInstBefore(AndI, I);
4383 return new SetCondInst(I.getOpcode(), And,
4384 ConstantExpr::getUShr(CI, ShAmt));
4385 }
4386 }
Chris Lattner272d5ca2004-09-28 18:22:15 +00004387 }
4388 break;
4389
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004390 case Instruction::Shr: // (setcc (shr X, ShAmt), CI)
Reid Spencere0fc4df2006-10-20 07:07:24 +00004391 if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004392 if (I.isEquality()) {
Chris Lattner19b57f52005-06-15 20:53:31 +00004393 // Check that the shift amount is in range. If not, don't perform
4394 // undefined shifts. When the shift is visited it will be
4395 // simplified.
Chris Lattner104002b2005-06-16 01:52:07 +00004396 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
Reid Spencere0fc4df2006-10-20 07:07:24 +00004397 if (ShAmt->getZExtValue() >= TypeBits)
Chris Lattner19b57f52005-06-15 20:53:31 +00004398 break;
4399
Chris Lattner1023b872004-09-27 16:18:50 +00004400 // If we are comparing against bits always shifted out, the
4401 // comparison cannot succeed.
Misha Brukmanb1c93172005-04-21 23:48:37 +00004402 Constant *Comp =
Chris Lattner1023b872004-09-27 16:18:50 +00004403 ConstantExpr::getShr(ConstantExpr::getShl(CI, ShAmt), ShAmt);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004404
Chris Lattner1023b872004-09-27 16:18:50 +00004405 if (Comp != CI) {// Comparing against a bit that we know is zero.
4406 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
4407 Constant *Cst = ConstantBool::get(IsSetNE);
4408 return ReplaceInstUsesWith(I, Cst);
4409 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004410
Chris Lattner1023b872004-09-27 16:18:50 +00004411 if (LHSI->hasOneUse() || CI->isNullValue()) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00004412 unsigned ShAmtVal = (unsigned)ShAmt->getZExtValue();
Chris Lattner272d5ca2004-09-28 18:22:15 +00004413
Chris Lattner1023b872004-09-27 16:18:50 +00004414 // Otherwise strength reduce the shift into an and.
4415 uint64_t Val = ~0ULL; // All ones.
4416 Val <<= ShAmtVal; // Shift over to the right spot.
4417
4418 Constant *Mask;
4419 if (CI->getType()->isUnsigned()) {
Chris Lattner2f1457f2005-04-24 17:46:05 +00004420 Val &= ~0ULL >> (64-TypeBits);
Reid Spencere0fc4df2006-10-20 07:07:24 +00004421 Mask = ConstantInt::get(CI->getType(), Val);
Chris Lattner1023b872004-09-27 16:18:50 +00004422 } else {
Reid Spencere0fc4df2006-10-20 07:07:24 +00004423 Mask = ConstantInt::get(CI->getType(), Val);
Chris Lattner1023b872004-09-27 16:18:50 +00004424 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004425
Chris Lattner1023b872004-09-27 16:18:50 +00004426 Instruction *AndI =
4427 BinaryOperator::createAnd(LHSI->getOperand(0),
4428 Mask, LHSI->getName()+".mask");
4429 Value *And = InsertNewInstBefore(AndI, I);
4430 return new SetCondInst(I.getOpcode(), And,
4431 ConstantExpr::getShl(CI, ShAmt));
4432 }
Chris Lattner1023b872004-09-27 16:18:50 +00004433 }
4434 }
4435 break;
Chris Lattner7e794272004-09-24 15:21:34 +00004436
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004437 case Instruction::SDiv:
4438 case Instruction::UDiv:
4439 // Fold: setcc ([us]div X, C1), C2 -> range test
4440 // Fold this div into the comparison, producing a range check.
4441 // Determine, based on the divide type, what the range is being
4442 // checked. If there is an overflow on the low or high side, remember
4443 // it, otherwise compute the range [low, hi) bounding the new value.
4444 // See: InsertRangeTest above for the kinds of replacements possible.
Chris Lattner6862fbd2004-09-29 17:40:11 +00004445 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004446 // FIXME: If the operand types don't match the type of the divide
4447 // then don't attempt this transform. The code below doesn't have the
4448 // logic to deal with a signed divide and an unsigned compare (and
4449 // vice versa). This is because (x /s C1) <s C2 produces different
4450 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
4451 // (x /u C1) <u C2. Simply casting the operands and result won't
4452 // work. :( The if statement below tests that condition and bails
4453 // if it finds it.
4454 const Type* DivRHSTy = DivRHS->getType();
4455 unsigned DivOpCode = LHSI->getOpcode();
4456 if (I.isEquality() &&
4457 ((DivOpCode == Instruction::SDiv && DivRHSTy->isUnsigned()) ||
4458 (DivOpCode == Instruction::UDiv && DivRHSTy->isSigned())))
4459 break;
4460
4461 // Initialize the variables that will indicate the nature of the
4462 // range check.
4463 bool LoOverflow = false, HiOverflow = false;
Chris Lattner6862fbd2004-09-29 17:40:11 +00004464 ConstantInt *LoBound = 0, *HiBound = 0;
4465
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004466 // Compute Prod = CI * DivRHS. We are essentially solving an equation
4467 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
4468 // C2 (CI). By solving for X we can turn this into a range check
4469 // instead of computing a divide.
4470 ConstantInt *Prod =
4471 cast<ConstantInt>(ConstantExpr::getMul(CI, DivRHS));
Chris Lattner6862fbd2004-09-29 17:40:11 +00004472
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004473 // Determine if the product overflows by seeing if the product is
4474 // not equal to the divide. Make sure we do the same kind of divide
4475 // as in the LHS instruction that we're folding.
4476 bool ProdOV = !DivRHS->isNullValue() &&
4477 (DivOpCode == Instruction::SDiv ?
4478 ConstantExpr::getSDiv(Prod, DivRHS) :
4479 ConstantExpr::getUDiv(Prod, DivRHS)) != CI;
4480
4481 // Get the SetCC opcode
Chris Lattnera92af962004-10-11 19:40:04 +00004482 Instruction::BinaryOps Opcode = I.getOpcode();
4483
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004484 if (DivRHS->isNullValue()) {
4485 // Don't hack on divide by zeros!
4486 } else if (DivOpCode == Instruction::UDiv) { // udiv
Chris Lattner6862fbd2004-09-29 17:40:11 +00004487 LoBound = Prod;
4488 LoOverflow = ProdOV;
4489 HiOverflow = ProdOV || AddWithOverflow(HiBound, LoBound, DivRHS);
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004490 } else if (isPositive(DivRHS)) { // Divisor is > 0.
Chris Lattner6862fbd2004-09-29 17:40:11 +00004491 if (CI->isNullValue()) { // (X / pos) op 0
4492 // Can't overflow.
4493 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
4494 HiBound = DivRHS;
4495 } else if (isPositive(CI)) { // (X / pos) op pos
4496 LoBound = Prod;
4497 LoOverflow = ProdOV;
4498 HiOverflow = ProdOV || AddWithOverflow(HiBound, Prod, DivRHS);
4499 } else { // (X / pos) op neg
4500 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
4501 LoOverflow = AddWithOverflow(LoBound, Prod,
4502 cast<ConstantInt>(DivRHSH));
4503 HiBound = Prod;
4504 HiOverflow = ProdOV;
4505 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004506 } else { // Divisor is < 0.
Chris Lattner6862fbd2004-09-29 17:40:11 +00004507 if (CI->isNullValue()) { // (X / neg) op 0
4508 LoBound = AddOne(DivRHS);
4509 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner73bcba52005-06-17 02:05:55 +00004510 if (HiBound == DivRHS)
Reid Spencer7e80b0b2006-10-26 06:15:43 +00004511 LoBound = 0; // - INTMIN = INTMIN
Chris Lattner6862fbd2004-09-29 17:40:11 +00004512 } else if (isPositive(CI)) { // (X / neg) op pos
4513 HiOverflow = LoOverflow = ProdOV;
4514 if (!LoOverflow)
4515 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS));
4516 HiBound = AddOne(Prod);
4517 } else { // (X / neg) op neg
4518 LoBound = Prod;
4519 LoOverflow = HiOverflow = ProdOV;
4520 HiBound = cast<ConstantInt>(ConstantExpr::getSub(Prod, DivRHS));
4521 }
Chris Lattner0b41e862004-10-08 19:15:44 +00004522
Chris Lattnera92af962004-10-11 19:40:04 +00004523 // Dividing by a negate swaps the condition.
4524 Opcode = SetCondInst::getSwappedCondition(Opcode);
Chris Lattner6862fbd2004-09-29 17:40:11 +00004525 }
4526
4527 if (LoBound) {
4528 Value *X = LHSI->getOperand(0);
Chris Lattnera92af962004-10-11 19:40:04 +00004529 switch (Opcode) {
Chris Lattner6862fbd2004-09-29 17:40:11 +00004530 default: assert(0 && "Unhandled setcc opcode!");
4531 case Instruction::SetEQ:
4532 if (LoOverflow && HiOverflow)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004533 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattner6862fbd2004-09-29 17:40:11 +00004534 else if (HiOverflow)
4535 return new SetCondInst(Instruction::SetGE, X, LoBound);
4536 else if (LoOverflow)
4537 return new SetCondInst(Instruction::SetLT, X, HiBound);
4538 else
4539 return InsertRangeTest(X, LoBound, HiBound, true, I);
4540 case Instruction::SetNE:
4541 if (LoOverflow && HiOverflow)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004542 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
Chris Lattner6862fbd2004-09-29 17:40:11 +00004543 else if (HiOverflow)
4544 return new SetCondInst(Instruction::SetLT, X, LoBound);
4545 else if (LoOverflow)
4546 return new SetCondInst(Instruction::SetGE, X, HiBound);
4547 else
4548 return InsertRangeTest(X, LoBound, HiBound, false, I);
4549 case Instruction::SetLT:
4550 if (LoOverflow)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004551 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattner6862fbd2004-09-29 17:40:11 +00004552 return new SetCondInst(Instruction::SetLT, X, LoBound);
4553 case Instruction::SetGT:
4554 if (HiOverflow)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004555 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattner6862fbd2004-09-29 17:40:11 +00004556 return new SetCondInst(Instruction::SetGE, X, HiBound);
4557 }
4558 }
4559 }
4560 break;
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004561 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004562
Chris Lattnerd492a0b2003-07-23 17:02:11 +00004563 // Simplify seteq and setne instructions...
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004564 if (I.isEquality()) {
Chris Lattnerd492a0b2003-07-23 17:02:11 +00004565 bool isSetNE = I.getOpcode() == Instruction::SetNE;
4566
Reid Spencere0fc4df2006-10-20 07:07:24 +00004567 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
4568 // the second operand is a constant, simplify a bit.
Chris Lattnerc992add2003-08-13 05:33:12 +00004569 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
4570 switch (BO->getOpcode()) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00004571#if 0
4572 case Instruction::SRem:
4573 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
4574 if (CI->isNullValue() && isa<ConstantInt>(BO->getOperand(1)) &&
4575 BO->hasOneUse()) {
4576 int64_t V = cast<ConstantInt>(BO->getOperand(1))->getSExtValue();
4577 if (V > 1 && isPowerOf2_64(V)) {
4578 Value *NewRem = InsertNewInstBefore(
4579 BinaryOperator::createURem(BO->getOperand(0),
4580 BO->getOperand(1),
4581 BO->getName()), I);
4582 return BinaryOperator::create(
4583 I.getOpcode(), NewRem,
4584 Constant::getNullValue(NewRem->getType()));
4585 }
4586 }
4587 break;
4588#endif
4589
Chris Lattner23b47b62004-07-06 07:38:18 +00004590 case Instruction::Rem:
4591 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
Reid Spencere0fc4df2006-10-20 07:07:24 +00004592 if (CI->isNullValue() && isa<ConstantInt>(BO->getOperand(1)) &&
4593 BO->hasOneUse() && BO->getOperand(1)->getType()->isSigned()) {
4594 int64_t V = cast<ConstantInt>(BO->getOperand(1))->getSExtValue();
4595 if (V > 1 && isPowerOf2_64(V)) {
Chris Lattner22d00a82005-08-02 19:16:58 +00004596 unsigned L2 = Log2_64(V);
Chris Lattner23b47b62004-07-06 07:38:18 +00004597 const Type *UTy = BO->getType()->getUnsignedVersion();
4598 Value *NewX = InsertNewInstBefore(new CastInst(BO->getOperand(0),
4599 UTy, "tmp"), I);
Reid Spencere0fc4df2006-10-20 07:07:24 +00004600 Constant *RHSCst = ConstantInt::get(UTy, 1ULL << L2);
Chris Lattner23b47b62004-07-06 07:38:18 +00004601 Value *NewRem =InsertNewInstBefore(BinaryOperator::createRem(NewX,
4602 RHSCst, BO->getName()), I);
4603 return BinaryOperator::create(I.getOpcode(), NewRem,
4604 Constant::getNullValue(UTy));
4605 }
Chris Lattner22d00a82005-08-02 19:16:58 +00004606 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004607 break;
Chris Lattnerc992add2003-08-13 05:33:12 +00004608 case Instruction::Add:
Chris Lattner6e079362004-06-27 22:51:36 +00004609 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
4610 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerb121ae12004-09-21 21:35:23 +00004611 if (BO->hasOneUse())
4612 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
4613 ConstantExpr::getSub(CI, BOp1C));
Chris Lattner6e079362004-06-27 22:51:36 +00004614 } else if (CI->isNullValue()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00004615 // Replace ((add A, B) != 0) with (A != -B) if A or B is
4616 // efficiently invertible, or if the add has just this one use.
4617 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004618
Chris Lattnerc992add2003-08-13 05:33:12 +00004619 if (Value *NegVal = dyn_castNegVal(BOp1))
4620 return new SetCondInst(I.getOpcode(), BOp0, NegVal);
4621 else if (Value *NegVal = dyn_castNegVal(BOp0))
4622 return new SetCondInst(I.getOpcode(), NegVal, BOp1);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00004623 else if (BO->hasOneUse()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00004624 Instruction *Neg = BinaryOperator::createNeg(BOp1, BO->getName());
4625 BO->setName("");
4626 InsertNewInstBefore(Neg, I);
4627 return new SetCondInst(I.getOpcode(), BOp0, Neg);
4628 }
4629 }
4630 break;
4631 case Instruction::Xor:
4632 // For the xor case, we can xor two constants together, eliminating
4633 // the explicit xor.
4634 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
4635 return BinaryOperator::create(I.getOpcode(), BO->getOperand(0),
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004636 ConstantExpr::getXor(CI, BOC));
Chris Lattnerc992add2003-08-13 05:33:12 +00004637
4638 // FALLTHROUGH
4639 case Instruction::Sub:
4640 // Replace (([sub|xor] A, B) != 0) with (A != B)
4641 if (CI->isNullValue())
4642 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
4643 BO->getOperand(1));
4644 break;
4645
4646 case Instruction::Or:
4647 // If bits are being or'd in that are not present in the constant we
4648 // are comparing against, then the comparison could never succeed!
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00004649 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Chris Lattnerc8e7e292004-06-10 02:12:35 +00004650 Constant *NotCI = ConstantExpr::getNot(CI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004651 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Chris Lattnerd492a0b2003-07-23 17:02:11 +00004652 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00004653 }
Chris Lattnerc992add2003-08-13 05:33:12 +00004654 break;
4655
4656 case Instruction::And:
4657 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerd492a0b2003-07-23 17:02:11 +00004658 // If bits are being compared against that are and'd out, then the
4659 // comparison can never succeed!
Chris Lattnerc8e7e292004-06-10 02:12:35 +00004660 if (!ConstantExpr::getAnd(CI,
4661 ConstantExpr::getNot(BOC))->isNullValue())
Chris Lattnerd492a0b2003-07-23 17:02:11 +00004662 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattnerc992add2003-08-13 05:33:12 +00004663
Chris Lattner35167c32004-06-09 07:59:58 +00004664 // If we have ((X & C) == C), turn it into ((X & C) != 0).
Chris Lattneree59d4b2004-06-10 02:33:20 +00004665 if (CI == BOC && isOneBitSet(CI))
Chris Lattner35167c32004-06-09 07:59:58 +00004666 return new SetCondInst(isSetNE ? Instruction::SetEQ :
4667 Instruction::SetNE, Op0,
4668 Constant::getNullValue(CI->getType()));
Chris Lattner35167c32004-06-09 07:59:58 +00004669
Chris Lattnerc992add2003-08-13 05:33:12 +00004670 // Replace (and X, (1 << size(X)-1) != 0) with x < 0, converting X
4671 // to be a signed value as appropriate.
4672 if (isSignBit(BOC)) {
4673 Value *X = BO->getOperand(0);
4674 // If 'X' is not signed, insert a cast now...
4675 if (!BOC->getType()->isSigned()) {
Chris Lattner97bfcea2004-06-17 18:16:02 +00004676 const Type *DestTy = BOC->getType()->getSignedVersion();
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004677 X = InsertCastBefore(X, DestTy, I);
Chris Lattnerc992add2003-08-13 05:33:12 +00004678 }
4679 return new SetCondInst(isSetNE ? Instruction::SetLT :
4680 Instruction::SetGE, X,
4681 Constant::getNullValue(X->getType()));
4682 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004683
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004684 // ((X & ~7) == 0) --> X < 8
Chris Lattner8fc5af42004-09-23 21:46:38 +00004685 if (CI->isNullValue() && isHighOnes(BOC)) {
4686 Value *X = BO->getOperand(0);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004687 Constant *NegX = ConstantExpr::getNeg(BOC);
Chris Lattner8fc5af42004-09-23 21:46:38 +00004688
4689 // If 'X' is signed, insert a cast now.
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004690 if (NegX->getType()->isSigned()) {
4691 const Type *DestTy = NegX->getType()->getUnsignedVersion();
4692 X = InsertCastBefore(X, DestTy, I);
4693 NegX = ConstantExpr::getCast(NegX, DestTy);
Chris Lattner8fc5af42004-09-23 21:46:38 +00004694 }
4695
4696 return new SetCondInst(isSetNE ? Instruction::SetGE :
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004697 Instruction::SetLT, X, NegX);
Chris Lattner8fc5af42004-09-23 21:46:38 +00004698 }
4699
Chris Lattnerd492a0b2003-07-23 17:02:11 +00004700 }
Chris Lattnerc992add2003-08-13 05:33:12 +00004701 default: break;
4702 }
4703 }
Chris Lattner2b55ea32004-02-23 07:16:20 +00004704 } else { // Not a SetEQ/SetNE
Misha Brukmanb1c93172005-04-21 23:48:37 +00004705 // If the LHS is a cast from an integral value of the same size,
Chris Lattner2b55ea32004-02-23 07:16:20 +00004706 if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
4707 Value *CastOp = Cast->getOperand(0);
4708 const Type *SrcTy = CastOp->getType();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004709 unsigned SrcTySize = SrcTy->getPrimitiveSizeInBits();
Chris Lattner2b55ea32004-02-23 07:16:20 +00004710 if (SrcTy != Cast->getType() && SrcTy->isInteger() &&
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004711 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00004712 assert((SrcTy->isSigned() ^ Cast->getType()->isSigned()) &&
Chris Lattner2b55ea32004-02-23 07:16:20 +00004713 "Source and destination signednesses should differ!");
4714 if (Cast->getType()->isSigned()) {
4715 // If this is a signed comparison, check for comparisons in the
4716 // vicinity of zero.
4717 if (I.getOpcode() == Instruction::SetLT && CI->isNullValue())
4718 // X < 0 => x > 127
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004719 return BinaryOperator::createSetGT(CastOp,
Reid Spencere0fc4df2006-10-20 07:07:24 +00004720 ConstantInt::get(SrcTy, (1ULL << (SrcTySize-1))-1));
Chris Lattner2b55ea32004-02-23 07:16:20 +00004721 else if (I.getOpcode() == Instruction::SetGT &&
Reid Spencere0fc4df2006-10-20 07:07:24 +00004722 cast<ConstantInt>(CI)->getSExtValue() == -1)
Chris Lattner2b55ea32004-02-23 07:16:20 +00004723 // X > -1 => x < 128
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004724 return BinaryOperator::createSetLT(CastOp,
Reid Spencere0fc4df2006-10-20 07:07:24 +00004725 ConstantInt::get(SrcTy, 1ULL << (SrcTySize-1)));
Chris Lattner2b55ea32004-02-23 07:16:20 +00004726 } else {
Reid Spencere0fc4df2006-10-20 07:07:24 +00004727 ConstantInt *CUI = cast<ConstantInt>(CI);
Chris Lattner2b55ea32004-02-23 07:16:20 +00004728 if (I.getOpcode() == Instruction::SetLT &&
Reid Spencere0fc4df2006-10-20 07:07:24 +00004729 CUI->getZExtValue() == 1ULL << (SrcTySize-1))
Chris Lattner2b55ea32004-02-23 07:16:20 +00004730 // X < 128 => X > -1
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004731 return BinaryOperator::createSetGT(CastOp,
Reid Spencere0fc4df2006-10-20 07:07:24 +00004732 ConstantInt::get(SrcTy, -1));
Chris Lattner2b55ea32004-02-23 07:16:20 +00004733 else if (I.getOpcode() == Instruction::SetGT &&
Reid Spencere0fc4df2006-10-20 07:07:24 +00004734 CUI->getZExtValue() == (1ULL << (SrcTySize-1))-1)
Chris Lattner2b55ea32004-02-23 07:16:20 +00004735 // X > 127 => X < 0
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004736 return BinaryOperator::createSetLT(CastOp,
4737 Constant::getNullValue(SrcTy));
Chris Lattner2b55ea32004-02-23 07:16:20 +00004738 }
4739 }
4740 }
Chris Lattnere967b342003-06-04 05:10:11 +00004741 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004742 }
4743
Chris Lattner77c32c32005-04-23 15:31:55 +00004744 // Handle setcc with constant RHS's that can be integer, FP or pointer.
4745 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
4746 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4747 switch (LHSI->getOpcode()) {
Chris Lattnera816eee2005-05-01 04:42:15 +00004748 case Instruction::GetElementPtr:
4749 if (RHSC->isNullValue()) {
4750 // Transform setcc GEP P, int 0, int 0, int 0, null -> setcc P, null
4751 bool isAllZeros = true;
4752 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
4753 if (!isa<Constant>(LHSI->getOperand(i)) ||
4754 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
4755 isAllZeros = false;
4756 break;
4757 }
4758 if (isAllZeros)
4759 return new SetCondInst(I.getOpcode(), LHSI->getOperand(0),
4760 Constant::getNullValue(LHSI->getOperand(0)->getType()));
4761 }
4762 break;
4763
Chris Lattner77c32c32005-04-23 15:31:55 +00004764 case Instruction::PHI:
4765 if (Instruction *NV = FoldOpIntoPhi(I))
4766 return NV;
4767 break;
4768 case Instruction::Select:
4769 // If either operand of the select is a constant, we can fold the
4770 // comparison into the select arms, which will cause one to be
4771 // constant folded and the select turned into a bitwise or.
4772 Value *Op1 = 0, *Op2 = 0;
4773 if (LHSI->hasOneUse()) {
4774 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
4775 // Fold the known value into the constant operand.
4776 Op1 = ConstantExpr::get(I.getOpcode(), C, RHSC);
4777 // Insert a new SetCC of the other select operand.
4778 Op2 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
4779 LHSI->getOperand(2), RHSC,
4780 I.getName()), I);
4781 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
4782 // Fold the known value into the constant operand.
4783 Op2 = ConstantExpr::get(I.getOpcode(), C, RHSC);
4784 // Insert a new SetCC of the other select operand.
4785 Op1 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
4786 LHSI->getOperand(1), RHSC,
4787 I.getName()), I);
4788 }
4789 }
Jeff Cohen82639852005-04-23 21:38:35 +00004790
Chris Lattner77c32c32005-04-23 15:31:55 +00004791 if (Op1)
4792 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
4793 break;
4794 }
4795 }
4796
Chris Lattner0798af32005-01-13 20:14:25 +00004797 // If we can optimize a 'setcc GEP, P' or 'setcc P, GEP', do so now.
4798 if (User *GEP = dyn_castGetElementPtr(Op0))
4799 if (Instruction *NI = FoldGEPSetCC(GEP, Op1, I.getOpcode(), I))
4800 return NI;
4801 if (User *GEP = dyn_castGetElementPtr(Op1))
4802 if (Instruction *NI = FoldGEPSetCC(GEP, Op0,
4803 SetCondInst::getSwappedCondition(I.getOpcode()), I))
4804 return NI;
4805
Chris Lattner16930792003-11-03 04:25:02 +00004806 // Test to see if the operands of the setcc are casted versions of other
4807 // values. If the cast can be stripped off both arguments, we do so now.
Chris Lattner6444c372003-11-03 05:17:03 +00004808 if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
4809 Value *CastOp0 = CI->getOperand(0);
4810 if (CastOp0->getType()->isLosslesslyConvertibleTo(CI->getType()) &&
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004811 (isa<Constant>(Op1) || isa<CastInst>(Op1)) && I.isEquality()) {
Chris Lattner16930792003-11-03 04:25:02 +00004812 // We keep moving the cast from the left operand over to the right
4813 // operand, where it can often be eliminated completely.
Chris Lattner6444c372003-11-03 05:17:03 +00004814 Op0 = CastOp0;
Misha Brukmanb1c93172005-04-21 23:48:37 +00004815
Chris Lattner16930792003-11-03 04:25:02 +00004816 // If operand #1 is a cast instruction, see if we can eliminate it as
4817 // well.
Chris Lattner6444c372003-11-03 05:17:03 +00004818 if (CastInst *CI2 = dyn_cast<CastInst>(Op1))
4819 if (CI2->getOperand(0)->getType()->isLosslesslyConvertibleTo(
Chris Lattner16930792003-11-03 04:25:02 +00004820 Op0->getType()))
Chris Lattner6444c372003-11-03 05:17:03 +00004821 Op1 = CI2->getOperand(0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004822
Chris Lattner16930792003-11-03 04:25:02 +00004823 // If Op1 is a constant, we can fold the cast into the constant.
4824 if (Op1->getType() != Op0->getType())
4825 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
4826 Op1 = ConstantExpr::getCast(Op1C, Op0->getType());
4827 } else {
4828 // Otherwise, cast the RHS right before the setcc
Reid Spencer00c482b2006-10-26 19:19:06 +00004829 Op1 = InsertCastBefore(Op1, Op0->getType(), I);
Chris Lattner16930792003-11-03 04:25:02 +00004830 }
4831 return BinaryOperator::create(I.getOpcode(), Op0, Op1);
4832 }
4833
Chris Lattner6444c372003-11-03 05:17:03 +00004834 // Handle the special case of: setcc (cast bool to X), <cst>
4835 // This comes up when you have code like
4836 // int X = A < B;
4837 // if (X) ...
4838 // For generality, we handle any zero-extension of any operand comparison
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004839 // with a constant or another cast from the same type.
4840 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
4841 if (Instruction *R = visitSetCondInstWithCastAndCast(I))
4842 return R;
Chris Lattner6444c372003-11-03 05:17:03 +00004843 }
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00004844
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004845 if (I.isEquality()) {
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00004846 Value *A, *B;
4847 if (match(Op0, m_Xor(m_Value(A), m_Value(B))) &&
4848 (A == Op1 || B == Op1)) {
4849 // (A^B) == A -> B == 0
4850 Value *OtherVal = A == Op1 ? B : A;
4851 return BinaryOperator::create(I.getOpcode(), OtherVal,
4852 Constant::getNullValue(A->getType()));
4853 } else if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
4854 (A == Op0 || B == Op0)) {
4855 // A == (A^B) -> B == 0
4856 Value *OtherVal = A == Op0 ? B : A;
4857 return BinaryOperator::create(I.getOpcode(), OtherVal,
4858 Constant::getNullValue(A->getType()));
4859 } else if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
4860 // (A-B) == A -> B == 0
4861 return BinaryOperator::create(I.getOpcode(), B,
4862 Constant::getNullValue(B->getType()));
4863 } else if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
4864 // A == (A-B) -> B == 0
4865 return BinaryOperator::create(I.getOpcode(), B,
4866 Constant::getNullValue(B->getType()));
4867 }
4868 }
Chris Lattner113f4f42002-06-25 16:13:24 +00004869 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004870}
4871
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004872// visitSetCondInstWithCastAndCast - Handle setcond (cast x to y), (cast/cst).
4873// We only handle extending casts so far.
4874//
4875Instruction *InstCombiner::visitSetCondInstWithCastAndCast(SetCondInst &SCI) {
4876 Value *LHSCIOp = cast<CastInst>(SCI.getOperand(0))->getOperand(0);
4877 const Type *SrcTy = LHSCIOp->getType();
4878 const Type *DestTy = SCI.getOperand(0)->getType();
4879 Value *RHSCIOp;
4880
4881 if (!DestTy->isIntegral() || !SrcTy->isIntegral())
Chris Lattner03f06f12005-01-17 03:20:02 +00004882 return 0;
4883
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004884 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
4885 unsigned DestBits = DestTy->getPrimitiveSizeInBits();
4886 if (SrcBits >= DestBits) return 0; // Only handle extending cast.
4887
4888 // Is this a sign or zero extension?
4889 bool isSignSrc = SrcTy->isSigned();
4890 bool isSignDest = DestTy->isSigned();
4891
4892 if (CastInst *CI = dyn_cast<CastInst>(SCI.getOperand(1))) {
4893 // Not an extension from the same type?
4894 RHSCIOp = CI->getOperand(0);
4895 if (RHSCIOp->getType() != LHSCIOp->getType()) return 0;
4896 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(SCI.getOperand(1))) {
4897 // Compute the constant that would happen if we truncated to SrcTy then
4898 // reextended to DestTy.
4899 Constant *Res = ConstantExpr::getCast(CI, SrcTy);
4900
4901 if (ConstantExpr::getCast(Res, DestTy) == CI) {
Devang Patelb42aef42006-10-19 18:54:08 +00004902 // Make sure that src sign and dest sign match. For example,
4903 //
4904 // %A = cast short %X to uint
4905 // %B = setgt uint %A, 1330
4906 //
Devang Patel88afd002006-10-19 19:21:36 +00004907 // It is incorrect to transform this into
Devang Patelb42aef42006-10-19 18:54:08 +00004908 //
4909 // %B = setgt short %X, 1330
4910 //
4911 // because %A may have negative value.
Devang Patel5d6df952006-10-19 20:59:13 +00004912 // However, it is OK if SrcTy is bool (See cast-set.ll testcase)
4913 // OR operation is EQ/NE.
4914 if (isSignSrc == isSignDest || SrcTy == Type::BoolTy || SCI.isEquality())
Devang Patelb42aef42006-10-19 18:54:08 +00004915 RHSCIOp = Res;
4916 else
4917 return 0;
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004918 } else {
4919 // If the value cannot be represented in the shorter type, we cannot emit
4920 // a simple comparison.
4921 if (SCI.getOpcode() == Instruction::SetEQ)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004922 return ReplaceInstUsesWith(SCI, ConstantBool::getFalse());
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004923 if (SCI.getOpcode() == Instruction::SetNE)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004924 return ReplaceInstUsesWith(SCI, ConstantBool::getTrue());
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004925
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004926 // Evaluate the comparison for LT.
4927 Value *Result;
4928 if (DestTy->isSigned()) {
4929 // We're performing a signed comparison.
4930 if (isSignSrc) {
4931 // Signed extend and signed comparison.
Reid Spencere0fc4df2006-10-20 07:07:24 +00004932 if (cast<ConstantInt>(CI)->getSExtValue() < 0)// X < (small) --> false
Chris Lattner6ab03f62006-09-28 23:35:22 +00004933 Result = ConstantBool::getFalse();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004934 else
Reid Spencere0fc4df2006-10-20 07:07:24 +00004935 Result = ConstantBool::getTrue(); // X < (large) --> true
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004936 } else {
4937 // Unsigned extend and signed comparison.
Reid Spencere0fc4df2006-10-20 07:07:24 +00004938 if (cast<ConstantInt>(CI)->getSExtValue() < 0)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004939 Result = ConstantBool::getFalse();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004940 else
Chris Lattner6ab03f62006-09-28 23:35:22 +00004941 Result = ConstantBool::getTrue();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004942 }
4943 } else {
4944 // We're performing an unsigned comparison.
4945 if (!isSignSrc) {
4946 // Unsigned extend & compare -> always true.
Chris Lattner6ab03f62006-09-28 23:35:22 +00004947 Result = ConstantBool::getTrue();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004948 } else {
4949 // We're performing an unsigned comp with a sign extended value.
4950 // This is true if the input is >= 0. [aka >s -1]
4951 Constant *NegOne = ConstantIntegral::getAllOnesValue(SrcTy);
4952 Result = InsertNewInstBefore(BinaryOperator::createSetGT(LHSCIOp,
4953 NegOne, SCI.getName()), SCI);
4954 }
Reid Spencer279fa252004-11-28 21:31:15 +00004955 }
Chris Lattner03f06f12005-01-17 03:20:02 +00004956
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00004957 // Finally, return the value computed.
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004958 if (SCI.getOpcode() == Instruction::SetLT) {
4959 return ReplaceInstUsesWith(SCI, Result);
4960 } else {
4961 assert(SCI.getOpcode()==Instruction::SetGT &&"SetCC should be folded!");
4962 if (Constant *CI = dyn_cast<Constant>(Result))
4963 return ReplaceInstUsesWith(SCI, ConstantExpr::getNot(CI));
4964 else
4965 return BinaryOperator::createNot(Result);
4966 }
Chris Lattner03f06f12005-01-17 03:20:02 +00004967 }
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004968 } else {
4969 return 0;
Reid Spencer279fa252004-11-28 21:31:15 +00004970 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004971
Chris Lattner252a8452005-06-16 03:00:08 +00004972 // Okay, just insert a compare of the reduced operands now!
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004973 return BinaryOperator::create(SCI.getOpcode(), LHSCIOp, RHSCIOp);
4974}
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004975
Chris Lattnere8d6c602003-03-10 19:16:08 +00004976Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +00004977 assert(I.getOperand(1)->getType() == Type::UByteTy);
4978 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00004979 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004980
4981 // shl X, 0 == X and shr X, 0 == X
4982 // shl 0, X == 0 and shr 0, X == 0
4983 if (Op1 == Constant::getNullValue(Type::UByteTy) ||
Chris Lattnere6794492002-08-12 21:17:25 +00004984 Op0 == Constant::getNullValue(Op0->getType()))
4985 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf5b4ef72006-02-12 08:07:37 +00004986
Chris Lattner81a7a232004-10-16 18:11:37 +00004987 if (isa<UndefValue>(Op0)) { // undef >>s X -> undef
4988 if (!isLeftShift && I.getType()->isSigned())
Chris Lattner67f05452004-10-16 23:28:04 +00004989 return ReplaceInstUsesWith(I, Op0);
Chris Lattner81a7a232004-10-16 18:11:37 +00004990 else // undef << X -> 0 AND undef >>u X -> 0
4991 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4992 }
4993 if (isa<UndefValue>(Op1)) {
Chris Lattner18aa4d82005-07-20 18:49:28 +00004994 if (isLeftShift || I.getType()->isUnsigned())// X << undef, X >>u undef -> 0
Chris Lattner81a7a232004-10-16 18:11:37 +00004995 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4996 else
4997 return ReplaceInstUsesWith(I, Op0); // X >>s undef -> X
4998 }
4999
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00005000 // shr int -1, X = -1 (for any arithmetic shift rights of ~0)
5001 if (!isLeftShift)
Reid Spencere0fc4df2006-10-20 07:07:24 +00005002 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Chris Lattner5dee3b22006-10-20 18:20:21 +00005003 if (CSI->isAllOnesValue() && Op0->getType()->isSigned())
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00005004 return ReplaceInstUsesWith(I, CSI);
5005
Chris Lattner183b3362004-04-09 19:05:30 +00005006 // Try to fold constant and into select arguments.
5007 if (isa<Constant>(Op0))
5008 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner86102b82005-01-01 16:22:27 +00005009 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00005010 return R;
5011
Chris Lattnerb18dbbf2005-05-08 17:34:56 +00005012 // See if we can turn a signed shr into an unsigned shr.
Chris Lattnerb3f24c92006-09-18 04:22:48 +00005013 if (I.isArithmeticShift()) {
Chris Lattnerc3ebf402006-02-07 07:27:52 +00005014 if (MaskedValueIsZero(Op0,
5015 1ULL << (I.getType()->getPrimitiveSizeInBits()-1))) {
Chris Lattnerb18dbbf2005-05-08 17:34:56 +00005016 Value *V = InsertCastBefore(Op0, I.getType()->getUnsignedVersion(), I);
5017 V = InsertNewInstBefore(new ShiftInst(Instruction::Shr, V, Op1,
5018 I.getName()), I);
5019 return new CastInst(V, I.getType());
5020 }
5021 }
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00005022
Reid Spencere0fc4df2006-10-20 07:07:24 +00005023 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
5024 if (CUI->getType()->isUnsigned())
5025 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
5026 return Res;
Chris Lattner14553932006-01-06 07:12:35 +00005027 return 0;
5028}
5029
Reid Spencere0fc4df2006-10-20 07:07:24 +00005030Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Chris Lattner14553932006-01-06 07:12:35 +00005031 ShiftInst &I) {
5032 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattnerb3309392006-01-06 07:22:22 +00005033 bool isSignedShift = Op0->getType()->isSigned();
5034 bool isUnsignedShift = !isSignedShift;
Chris Lattner14553932006-01-06 07:12:35 +00005035
Chris Lattnerf5b4ef72006-02-12 08:07:37 +00005036 // See if we can simplify any instructions used by the instruction whose sole
5037 // purpose is to compute bits we don't care about.
5038 uint64_t KnownZero, KnownOne;
5039 if (SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
5040 KnownZero, KnownOne))
5041 return &I;
5042
Chris Lattner14553932006-01-06 07:12:35 +00005043 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
5044 // of a signed value.
5045 //
5046 unsigned TypeBits = Op0->getType()->getPrimitiveSizeInBits();
Reid Spencere0fc4df2006-10-20 07:07:24 +00005047 if (Op1->getZExtValue() >= TypeBits) {
Chris Lattnerb3309392006-01-06 07:22:22 +00005048 if (isUnsignedShift || isLeftShift)
Chris Lattner14553932006-01-06 07:12:35 +00005049 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
5050 else {
Reid Spencere0fc4df2006-10-20 07:07:24 +00005051 I.setOperand(1, ConstantInt::get(Type::UByteTy, TypeBits-1));
Chris Lattner14553932006-01-06 07:12:35 +00005052 return &I;
Chris Lattnerf5ce2542004-02-23 20:30:06 +00005053 }
Chris Lattner14553932006-01-06 07:12:35 +00005054 }
5055
5056 // ((X*C1) << C2) == (X * (C1 << C2))
5057 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
5058 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
5059 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
5060 return BinaryOperator::createMul(BO->getOperand(0),
5061 ConstantExpr::getShl(BOOp, Op1));
5062
5063 // Try to fold constant and into select arguments.
5064 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5065 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5066 return R;
5067 if (isa<PHINode>(Op0))
5068 if (Instruction *NV = FoldOpIntoPhi(I))
5069 return NV;
5070
5071 if (Op0->hasOneUse()) {
Chris Lattner14553932006-01-06 07:12:35 +00005072 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
5073 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
5074 Value *V1, *V2;
5075 ConstantInt *CC;
5076 switch (Op0BO->getOpcode()) {
Chris Lattner27cb9db2005-09-18 05:12:10 +00005077 default: break;
5078 case Instruction::Add:
5079 case Instruction::And:
5080 case Instruction::Or:
5081 case Instruction::Xor:
5082 // These operators commute.
5083 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner797dee72005-09-18 06:30:59 +00005084 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
5085 match(Op0BO->getOperand(1),
Chris Lattner14553932006-01-06 07:12:35 +00005086 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Chris Lattner797dee72005-09-18 06:30:59 +00005087 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00005088 Op0BO->getOperand(0), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00005089 Op0BO->getName());
5090 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005091 Instruction *X =
5092 BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
5093 Op0BO->getOperand(1)->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00005094 InsertNewInstBefore(X, I); // (X + (Y << C))
5095 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
Chris Lattner14553932006-01-06 07:12:35 +00005096 C2 = ConstantExpr::getShl(C2, Op1);
Chris Lattner797dee72005-09-18 06:30:59 +00005097 return BinaryOperator::createAnd(X, C2);
5098 }
Chris Lattner14553932006-01-06 07:12:35 +00005099
Chris Lattner797dee72005-09-18 06:30:59 +00005100 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
5101 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
5102 match(Op0BO->getOperand(1),
5103 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner14553932006-01-06 07:12:35 +00005104 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005105 cast<BinaryOperator>(Op0BO->getOperand(1))->getOperand(0)->hasOneUse()) {
Chris Lattner797dee72005-09-18 06:30:59 +00005106 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00005107 Op0BO->getOperand(0), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00005108 Op0BO->getName());
5109 InsertNewInstBefore(YS, I); // (Y << C)
5110 Instruction *XM =
Chris Lattner14553932006-01-06 07:12:35 +00005111 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner797dee72005-09-18 06:30:59 +00005112 V1->getName()+".mask");
5113 InsertNewInstBefore(XM, I); // X & (CC << C)
5114
5115 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
5116 }
Chris Lattner14553932006-01-06 07:12:35 +00005117
Chris Lattner797dee72005-09-18 06:30:59 +00005118 // FALL THROUGH.
Chris Lattner27cb9db2005-09-18 05:12:10 +00005119 case Instruction::Sub:
5120 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner797dee72005-09-18 06:30:59 +00005121 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
5122 match(Op0BO->getOperand(0),
Chris Lattner14553932006-01-06 07:12:35 +00005123 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Chris Lattner797dee72005-09-18 06:30:59 +00005124 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00005125 Op0BO->getOperand(1), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00005126 Op0BO->getName());
5127 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005128 Instruction *X =
Chris Lattner1df0e982006-05-31 21:14:00 +00005129 BinaryOperator::create(Op0BO->getOpcode(), V1, YS,
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005130 Op0BO->getOperand(0)->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00005131 InsertNewInstBefore(X, I); // (X + (Y << C))
5132 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
Chris Lattner14553932006-01-06 07:12:35 +00005133 C2 = ConstantExpr::getShl(C2, Op1);
Chris Lattner797dee72005-09-18 06:30:59 +00005134 return BinaryOperator::createAnd(X, C2);
5135 }
Chris Lattner14553932006-01-06 07:12:35 +00005136
Chris Lattner1df0e982006-05-31 21:14:00 +00005137 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner797dee72005-09-18 06:30:59 +00005138 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
5139 match(Op0BO->getOperand(0),
5140 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner14553932006-01-06 07:12:35 +00005141 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005142 cast<BinaryOperator>(Op0BO->getOperand(0))
5143 ->getOperand(0)->hasOneUse()) {
Chris Lattner797dee72005-09-18 06:30:59 +00005144 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00005145 Op0BO->getOperand(1), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00005146 Op0BO->getName());
5147 InsertNewInstBefore(YS, I); // (Y << C)
5148 Instruction *XM =
Chris Lattner14553932006-01-06 07:12:35 +00005149 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner797dee72005-09-18 06:30:59 +00005150 V1->getName()+".mask");
5151 InsertNewInstBefore(XM, I); // X & (CC << C)
5152
Chris Lattner1df0e982006-05-31 21:14:00 +00005153 return BinaryOperator::create(Op0BO->getOpcode(), XM, YS);
Chris Lattner797dee72005-09-18 06:30:59 +00005154 }
Chris Lattner14553932006-01-06 07:12:35 +00005155
Chris Lattner27cb9db2005-09-18 05:12:10 +00005156 break;
Chris Lattner14553932006-01-06 07:12:35 +00005157 }
5158
5159
5160 // If the operand is an bitwise operator with a constant RHS, and the
5161 // shift is the only use, we can pull it out of the shift.
5162 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
5163 bool isValid = true; // Valid only for And, Or, Xor
5164 bool highBitSet = false; // Transform if high bit of constant set?
5165
5166 switch (Op0BO->getOpcode()) {
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00005167 default: isValid = false; break; // Do not perform transform!
Chris Lattner44bd3922004-10-08 03:46:20 +00005168 case Instruction::Add:
5169 isValid = isLeftShift;
5170 break;
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00005171 case Instruction::Or:
5172 case Instruction::Xor:
5173 highBitSet = false;
5174 break;
5175 case Instruction::And:
5176 highBitSet = true;
5177 break;
Chris Lattner14553932006-01-06 07:12:35 +00005178 }
5179
5180 // If this is a signed shift right, and the high bit is modified
5181 // by the logical operation, do not perform the transformation.
5182 // The highBitSet boolean indicates the value of the high bit of
5183 // the constant which would cause it to be modified for this
5184 // operation.
5185 //
Chris Lattnerb3309392006-01-06 07:22:22 +00005186 if (isValid && !isLeftShift && isSignedShift) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00005187 uint64_t Val = Op0C->getZExtValue();
Chris Lattner14553932006-01-06 07:12:35 +00005188 isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
5189 }
5190
5191 if (isValid) {
5192 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
5193
5194 Instruction *NewShift =
5195 new ShiftInst(I.getOpcode(), Op0BO->getOperand(0), Op1,
5196 Op0BO->getName());
5197 Op0BO->setName("");
5198 InsertNewInstBefore(NewShift, I);
5199
5200 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
5201 NewRHS);
5202 }
5203 }
5204 }
5205 }
5206
Chris Lattnereb372a02006-01-06 07:52:12 +00005207 // Find out if this is a shift of a shift by a constant.
5208 ShiftInst *ShiftOp = 0;
Chris Lattner14553932006-01-06 07:12:35 +00005209 if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0))
Chris Lattnereb372a02006-01-06 07:52:12 +00005210 ShiftOp = Op0SI;
5211 else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
5212 // If this is a noop-integer case of a shift instruction, use the shift.
5213 if (CI->getOperand(0)->getType()->isInteger() &&
5214 CI->getOperand(0)->getType()->getPrimitiveSizeInBits() ==
5215 CI->getType()->getPrimitiveSizeInBits() &&
5216 isa<ShiftInst>(CI->getOperand(0))) {
5217 ShiftOp = cast<ShiftInst>(CI->getOperand(0));
5218 }
5219 }
5220
Reid Spencere0fc4df2006-10-20 07:07:24 +00005221 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Chris Lattnereb372a02006-01-06 07:52:12 +00005222 // Find the operands and properties of the input shift. Note that the
5223 // signedness of the input shift may differ from the current shift if there
5224 // is a noop cast between the two.
5225 bool isShiftOfLeftShift = ShiftOp->getOpcode() == Instruction::Shl;
5226 bool isShiftOfSignedShift = ShiftOp->getType()->isSigned();
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005227 bool isShiftOfUnsignedShift = !isShiftOfSignedShift;
Chris Lattnereb372a02006-01-06 07:52:12 +00005228
Reid Spencere0fc4df2006-10-20 07:07:24 +00005229 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Chris Lattnereb372a02006-01-06 07:52:12 +00005230
Reid Spencere0fc4df2006-10-20 07:07:24 +00005231 unsigned ShiftAmt1 = (unsigned)ShiftAmt1C->getZExtValue();
5232 unsigned ShiftAmt2 = (unsigned)Op1->getZExtValue();
Chris Lattnereb372a02006-01-06 07:52:12 +00005233
5234 // Check for (A << c1) << c2 and (A >> c1) >> c2.
5235 if (isLeftShift == isShiftOfLeftShift) {
5236 // Do not fold these shifts if the first one is signed and the second one
5237 // is unsigned and this is a right shift. Further, don't do any folding
5238 // on them.
5239 if (isShiftOfSignedShift && isUnsignedShift && !isLeftShift)
5240 return 0;
Chris Lattner14553932006-01-06 07:12:35 +00005241
Chris Lattnereb372a02006-01-06 07:52:12 +00005242 unsigned Amt = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
5243 if (Amt > Op0->getType()->getPrimitiveSizeInBits())
5244 Amt = Op0->getType()->getPrimitiveSizeInBits();
Chris Lattner14553932006-01-06 07:12:35 +00005245
Chris Lattnereb372a02006-01-06 07:52:12 +00005246 Value *Op = ShiftOp->getOperand(0);
5247 if (isShiftOfSignedShift != isSignedShift)
5248 Op = InsertNewInstBefore(new CastInst(Op, I.getType(), "tmp"), I);
5249 return new ShiftInst(I.getOpcode(), Op,
Reid Spencere0fc4df2006-10-20 07:07:24 +00005250 ConstantInt::get(Type::UByteTy, Amt));
Chris Lattnereb372a02006-01-06 07:52:12 +00005251 }
5252
5253 // Check for (A << c1) >> c2 or (A >> c1) << c2. If we are dealing with
5254 // signed types, we can only support the (A >> c1) << c2 configuration,
5255 // because it can not turn an arbitrary bit of A into a sign bit.
5256 if (isUnsignedShift || isLeftShift) {
5257 // Calculate bitmask for what gets shifted off the edge.
5258 Constant *C = ConstantIntegral::getAllOnesValue(I.getType());
5259 if (isLeftShift)
5260 C = ConstantExpr::getShl(C, ShiftAmt1C);
5261 else
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005262 C = ConstantExpr::getUShr(C, ShiftAmt1C);
Chris Lattnereb372a02006-01-06 07:52:12 +00005263
5264 Value *Op = ShiftOp->getOperand(0);
5265 if (isShiftOfSignedShift != isSignedShift)
Reid Spencer00c482b2006-10-26 19:19:06 +00005266 Op = InsertCastBefore(Op, I.getType(), I);
Chris Lattnereb372a02006-01-06 07:52:12 +00005267
5268 Instruction *Mask =
5269 BinaryOperator::createAnd(Op, C, Op->getName()+".mask");
5270 InsertNewInstBefore(Mask, I);
5271
5272 // Figure out what flavor of shift we should use...
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005273 if (ShiftAmt1 == ShiftAmt2) {
Chris Lattnereb372a02006-01-06 07:52:12 +00005274 return ReplaceInstUsesWith(I, Mask); // (A << c) >> c === A & c2
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005275 } else if (ShiftAmt1 < ShiftAmt2) {
Chris Lattnereb372a02006-01-06 07:52:12 +00005276 return new ShiftInst(I.getOpcode(), Mask,
Reid Spencere0fc4df2006-10-20 07:07:24 +00005277 ConstantInt::get(Type::UByteTy, ShiftAmt2-ShiftAmt1));
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005278 } else if (isShiftOfUnsignedShift || isShiftOfLeftShift) {
5279 if (isShiftOfUnsignedShift && !isShiftOfLeftShift && isSignedShift) {
5280 // Make sure to emit an unsigned shift right, not a signed one.
5281 Mask = InsertNewInstBefore(new CastInst(Mask,
5282 Mask->getType()->getUnsignedVersion(),
5283 Op->getName()), I);
5284 Mask = new ShiftInst(Instruction::Shr, Mask,
Reid Spencere0fc4df2006-10-20 07:07:24 +00005285 ConstantInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005286 InsertNewInstBefore(Mask, I);
5287 return new CastInst(Mask, I.getType());
5288 } else {
5289 return new ShiftInst(ShiftOp->getOpcode(), Mask,
Reid Spencere0fc4df2006-10-20 07:07:24 +00005290 ConstantInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005291 }
5292 } else {
5293 // (X >>s C1) << C2 where C1 > C2 === (X >>s (C1-C2)) & mask
Reid Spencer00c482b2006-10-26 19:19:06 +00005294 Op = InsertCastBefore(Mask, I.getType()->getSignedVersion(), I);
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005295 Instruction *Shift =
5296 new ShiftInst(ShiftOp->getOpcode(), Op,
Reid Spencere0fc4df2006-10-20 07:07:24 +00005297 ConstantInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005298 InsertNewInstBefore(Shift, I);
5299
5300 C = ConstantIntegral::getAllOnesValue(Shift->getType());
5301 C = ConstantExpr::getShl(C, Op1);
5302 Mask = BinaryOperator::createAnd(Shift, C, Op->getName()+".mask");
5303 InsertNewInstBefore(Mask, I);
5304 return new CastInst(Mask, I.getType());
Chris Lattnereb372a02006-01-06 07:52:12 +00005305 }
5306 } else {
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005307 // We can handle signed (X << C1) >>s C2 if it's a sign extend. In
Chris Lattnereb372a02006-01-06 07:52:12 +00005308 // this case, C1 == C2 and C1 is 8, 16, or 32.
5309 if (ShiftAmt1 == ShiftAmt2) {
5310 const Type *SExtType = 0;
Chris Lattner655d08f2006-04-28 22:21:41 +00005311 switch (Op0->getType()->getPrimitiveSizeInBits() - ShiftAmt1) {
Chris Lattnereb372a02006-01-06 07:52:12 +00005312 case 8 : SExtType = Type::SByteTy; break;
5313 case 16: SExtType = Type::ShortTy; break;
5314 case 32: SExtType = Type::IntTy; break;
5315 }
5316
5317 if (SExtType) {
5318 Instruction *NewTrunc = new CastInst(ShiftOp->getOperand(0),
5319 SExtType, "sext");
5320 InsertNewInstBefore(NewTrunc, I);
5321 return new CastInst(NewTrunc, I.getType());
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00005322 }
Chris Lattner27cb9db2005-09-18 05:12:10 +00005323 }
Chris Lattner86102b82005-01-01 16:22:27 +00005324 }
Chris Lattnereb372a02006-01-06 07:52:12 +00005325 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005326 return 0;
5327}
5328
Chris Lattner48a44f72002-05-02 17:06:02 +00005329
Chris Lattner8f663e82005-10-29 04:36:15 +00005330/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
5331/// expression. If so, decompose it, returning some value X, such that Val is
5332/// X*Scale+Offset.
5333///
5334static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
5335 unsigned &Offset) {
5336 assert(Val->getType() == Type::UIntTy && "Unexpected allocation size type!");
Reid Spencere0fc4df2006-10-20 07:07:24 +00005337 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
5338 if (CI->getType()->isUnsigned()) {
5339 Offset = CI->getZExtValue();
5340 Scale = 1;
5341 return ConstantInt::get(Type::UIntTy, 0);
5342 }
Chris Lattner8f663e82005-10-29 04:36:15 +00005343 } else if (Instruction *I = dyn_cast<Instruction>(Val)) {
5344 if (I->getNumOperands() == 2) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00005345 if (ConstantInt *CUI = dyn_cast<ConstantInt>(I->getOperand(1))) {
5346 if (CUI->getType()->isUnsigned()) {
5347 if (I->getOpcode() == Instruction::Shl) {
5348 // This is a value scaled by '1 << the shift amt'.
5349 Scale = 1U << CUI->getZExtValue();
5350 Offset = 0;
5351 return I->getOperand(0);
5352 } else if (I->getOpcode() == Instruction::Mul) {
5353 // This value is scaled by 'CUI'.
5354 Scale = CUI->getZExtValue();
5355 Offset = 0;
5356 return I->getOperand(0);
5357 } else if (I->getOpcode() == Instruction::Add) {
5358 // We have X+C. Check to see if we really have (X*C2)+C1,
5359 // where C1 is divisible by C2.
5360 unsigned SubScale;
5361 Value *SubVal =
5362 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
5363 Offset += CUI->getZExtValue();
5364 if (SubScale > 1 && (Offset % SubScale == 0)) {
5365 Scale = SubScale;
5366 return SubVal;
5367 }
Chris Lattner8f663e82005-10-29 04:36:15 +00005368 }
5369 }
5370 }
5371 }
5372 }
5373
5374 // Otherwise, we can't look past this.
5375 Scale = 1;
5376 Offset = 0;
5377 return Val;
5378}
5379
5380
Chris Lattner216be912005-10-24 06:03:58 +00005381/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
5382/// try to eliminate the cast by moving the type information into the alloc.
5383Instruction *InstCombiner::PromoteCastOfAllocation(CastInst &CI,
5384 AllocationInst &AI) {
5385 const PointerType *PTy = dyn_cast<PointerType>(CI.getType());
Chris Lattnerbb171802005-10-27 05:53:56 +00005386 if (!PTy) return 0; // Not casting the allocation to a pointer type.
Chris Lattner216be912005-10-24 06:03:58 +00005387
Chris Lattnerac87beb2005-10-24 06:22:12 +00005388 // Remove any uses of AI that are dead.
5389 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
5390 std::vector<Instruction*> DeadUsers;
5391 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
5392 Instruction *User = cast<Instruction>(*UI++);
5393 if (isInstructionTriviallyDead(User)) {
5394 while (UI != E && *UI == User)
5395 ++UI; // If this instruction uses AI more than once, don't break UI.
5396
5397 // Add operands to the worklist.
5398 AddUsesToWorkList(*User);
5399 ++NumDeadInst;
5400 DEBUG(std::cerr << "IC: DCE: " << *User);
5401
5402 User->eraseFromParent();
5403 removeFromWorkList(User);
5404 }
5405 }
5406
Chris Lattner216be912005-10-24 06:03:58 +00005407 // Get the type really allocated and the type casted to.
5408 const Type *AllocElTy = AI.getAllocatedType();
5409 const Type *CastElTy = PTy->getElementType();
5410 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner355ecc02005-10-24 06:26:18 +00005411
Chris Lattner7d190672006-10-01 19:40:58 +00005412 unsigned AllocElTyAlign = TD->getTypeAlignment(AllocElTy);
5413 unsigned CastElTyAlign = TD->getTypeAlignment(CastElTy);
Chris Lattner355ecc02005-10-24 06:26:18 +00005414 if (CastElTyAlign < AllocElTyAlign) return 0;
5415
Chris Lattner46705b22005-10-24 06:35:18 +00005416 // If the allocation has multiple uses, only promote it if we are strictly
5417 // increasing the alignment of the resultant allocation. If we keep it the
5418 // same, we open the door to infinite loops of various kinds.
5419 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
5420
Chris Lattner216be912005-10-24 06:03:58 +00005421 uint64_t AllocElTySize = TD->getTypeSize(AllocElTy);
5422 uint64_t CastElTySize = TD->getTypeSize(CastElTy);
Chris Lattnerbb171802005-10-27 05:53:56 +00005423 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner355ecc02005-10-24 06:26:18 +00005424
Chris Lattner8270c332005-10-29 03:19:53 +00005425 // See if we can satisfy the modulus by pulling a scale out of the array
5426 // size argument.
Chris Lattner8f663e82005-10-29 04:36:15 +00005427 unsigned ArraySizeScale, ArrayOffset;
5428 Value *NumElements = // See if the array size is a decomposable linear expr.
5429 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
5430
Chris Lattner8270c332005-10-29 03:19:53 +00005431 // If we can now satisfy the modulus, by using a non-1 scale, we really can
5432 // do the xform.
Chris Lattner8f663e82005-10-29 04:36:15 +00005433 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
5434 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattnerb3ecf962005-10-27 06:12:00 +00005435
Chris Lattner8270c332005-10-29 03:19:53 +00005436 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
5437 Value *Amt = 0;
5438 if (Scale == 1) {
5439 Amt = NumElements;
5440 } else {
Reid Spencere0fc4df2006-10-20 07:07:24 +00005441 // If the allocation size is constant, form a constant mul expression
5442 Amt = ConstantInt::get(Type::UIntTy, Scale);
5443 if (isa<ConstantInt>(NumElements) && NumElements->getType()->isUnsigned())
5444 Amt = ConstantExpr::getMul(
5445 cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
5446 // otherwise multiply the amount and the number of elements
Chris Lattner8270c332005-10-29 03:19:53 +00005447 else if (Scale != 1) {
5448 Instruction *Tmp = BinaryOperator::createMul(Amt, NumElements, "tmp");
5449 Amt = InsertNewInstBefore(Tmp, AI);
Chris Lattnerb3ecf962005-10-27 06:12:00 +00005450 }
Chris Lattnerbb171802005-10-27 05:53:56 +00005451 }
5452
Chris Lattner8f663e82005-10-29 04:36:15 +00005453 if (unsigned Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00005454 Value *Off = ConstantInt::get(Type::UIntTy, Offset);
Chris Lattner8f663e82005-10-29 04:36:15 +00005455 Instruction *Tmp = BinaryOperator::createAdd(Amt, Off, "tmp");
5456 Amt = InsertNewInstBefore(Tmp, AI);
5457 }
5458
Chris Lattner216be912005-10-24 06:03:58 +00005459 std::string Name = AI.getName(); AI.setName("");
5460 AllocationInst *New;
5461 if (isa<MallocInst>(AI))
Nate Begeman848622f2005-11-05 09:21:28 +00005462 New = new MallocInst(CastElTy, Amt, AI.getAlignment(), Name);
Chris Lattner216be912005-10-24 06:03:58 +00005463 else
Nate Begeman848622f2005-11-05 09:21:28 +00005464 New = new AllocaInst(CastElTy, Amt, AI.getAlignment(), Name);
Chris Lattner216be912005-10-24 06:03:58 +00005465 InsertNewInstBefore(New, AI);
Chris Lattner46705b22005-10-24 06:35:18 +00005466
5467 // If the allocation has multiple uses, insert a cast and change all things
5468 // that used it to use the new cast. This will also hack on CI, but it will
5469 // die soon.
5470 if (!AI.hasOneUse()) {
5471 AddUsesToWorkList(AI);
5472 CastInst *NewCast = new CastInst(New, AI.getType(), "tmpcast");
5473 InsertNewInstBefore(NewCast, AI);
5474 AI.replaceAllUsesWith(NewCast);
5475 }
Chris Lattner216be912005-10-24 06:03:58 +00005476 return ReplaceInstUsesWith(CI, New);
5477}
5478
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005479/// CanEvaluateInDifferentType - Return true if we can take the specified value
5480/// and return it without inserting any new casts. This is used by code that
5481/// tries to decide whether promoting or shrinking integer operations to wider
5482/// or smaller types will allow us to eliminate a truncate or extend.
5483static bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
5484 int &NumCastsRemoved) {
5485 if (isa<Constant>(V)) return true;
5486
5487 Instruction *I = dyn_cast<Instruction>(V);
5488 if (!I || !I->hasOneUse()) return false;
5489
5490 switch (I->getOpcode()) {
5491 case Instruction::And:
5492 case Instruction::Or:
5493 case Instruction::Xor:
5494 // These operators can all arbitrarily be extended or truncated.
5495 return CanEvaluateInDifferentType(I->getOperand(0), Ty, NumCastsRemoved) &&
5496 CanEvaluateInDifferentType(I->getOperand(1), Ty, NumCastsRemoved);
5497 case Instruction::Cast:
5498 // If this is a cast from the destination type, we can trivially eliminate
5499 // it, and this will remove a cast overall.
5500 if (I->getOperand(0)->getType() == Ty) {
Chris Lattner3fda3862006-06-28 17:34:50 +00005501 // If the first operand is itself a cast, and is eliminable, do not count
5502 // this as an eliminable cast. We would prefer to eliminate those two
5503 // casts first.
5504 if (CastInst *OpCast = dyn_cast<CastInst>(I->getOperand(0)))
5505 return true;
5506
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005507 ++NumCastsRemoved;
5508 return true;
5509 }
5510 // TODO: Can handle more cases here.
5511 break;
5512 }
5513
5514 return false;
5515}
5516
5517/// EvaluateInDifferentType - Given an expression that
5518/// CanEvaluateInDifferentType returns true for, actually insert the code to
5519/// evaluate the expression.
5520Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty) {
5521 if (Constant *C = dyn_cast<Constant>(V))
5522 return ConstantExpr::getCast(C, Ty);
5523
5524 // Otherwise, it must be an instruction.
5525 Instruction *I = cast<Instruction>(V);
Chris Lattnerd0622b62006-05-20 23:14:03 +00005526 Instruction *Res = 0;
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005527 switch (I->getOpcode()) {
5528 case Instruction::And:
5529 case Instruction::Or:
5530 case Instruction::Xor: {
5531 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty);
5532 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty);
5533 Res = BinaryOperator::create((Instruction::BinaryOps)I->getOpcode(),
5534 LHS, RHS, I->getName());
5535 break;
5536 }
5537 case Instruction::Cast:
5538 // If this is a cast from the destination type, return the input.
5539 if (I->getOperand(0)->getType() == Ty)
5540 return I->getOperand(0);
5541
5542 // TODO: Can handle more cases here.
5543 assert(0 && "Unreachable!");
5544 break;
5545 }
5546
5547 return InsertNewInstBefore(Res, *I);
5548}
5549
Chris Lattner216be912005-10-24 06:03:58 +00005550
Chris Lattner48a44f72002-05-02 17:06:02 +00005551// CastInst simplification
Chris Lattner260ab202002-04-18 17:39:14 +00005552//
Chris Lattner113f4f42002-06-25 16:13:24 +00005553Instruction *InstCombiner::visitCastInst(CastInst &CI) {
Chris Lattner55d4bda2003-06-23 21:59:52 +00005554 Value *Src = CI.getOperand(0);
5555
Chris Lattner48a44f72002-05-02 17:06:02 +00005556 // If the user is casting a value to the same type, eliminate this cast
5557 // instruction...
Chris Lattner55d4bda2003-06-23 21:59:52 +00005558 if (CI.getType() == Src->getType())
5559 return ReplaceInstUsesWith(CI, Src);
Chris Lattner48a44f72002-05-02 17:06:02 +00005560
Chris Lattner81a7a232004-10-16 18:11:37 +00005561 if (isa<UndefValue>(Src)) // cast undef -> undef
5562 return ReplaceInstUsesWith(CI, UndefValue::get(CI.getType()));
5563
Chris Lattner48a44f72002-05-02 17:06:02 +00005564 // If casting the result of another cast instruction, try to eliminate this
5565 // one!
5566 //
Chris Lattner86102b82005-01-01 16:22:27 +00005567 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
5568 Value *A = CSrc->getOperand(0);
5569 if (isEliminableCastOfCast(A->getType(), CSrc->getType(),
5570 CI.getType(), TD)) {
Chris Lattner48a44f72002-05-02 17:06:02 +00005571 // This instruction now refers directly to the cast's src operand. This
5572 // has a good chance of making CSrc dead.
Chris Lattner113f4f42002-06-25 16:13:24 +00005573 CI.setOperand(0, CSrc->getOperand(0));
5574 return &CI;
Chris Lattner48a44f72002-05-02 17:06:02 +00005575 }
5576
Chris Lattner650b6da2002-08-02 20:00:25 +00005577 // If this is an A->B->A cast, and we are dealing with integral types, try
5578 // to convert this into a logical 'and' instruction.
5579 //
Misha Brukmanb1c93172005-04-21 23:48:37 +00005580 if (A->getType()->isInteger() &&
Chris Lattnerb0b412e2002-09-03 01:08:28 +00005581 CI.getType()->isInteger() && CSrc->getType()->isInteger() &&
Chris Lattner86102b82005-01-01 16:22:27 +00005582 CSrc->getType()->isUnsigned() && // B->A cast must zero extend
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005583 CSrc->getType()->getPrimitiveSizeInBits() <
5584 CI.getType()->getPrimitiveSizeInBits()&&
5585 A->getType()->getPrimitiveSizeInBits() ==
5586 CI.getType()->getPrimitiveSizeInBits()) {
Chris Lattner650b6da2002-08-02 20:00:25 +00005587 assert(CSrc->getType() != Type::ULongTy &&
5588 "Cannot have type bigger than ulong!");
Chris Lattner77defba2006-02-07 07:00:41 +00005589 uint64_t AndValue = CSrc->getType()->getIntegralTypeMask();
Reid Spencere0fc4df2006-10-20 07:07:24 +00005590 Constant *AndOp = ConstantInt::get(A->getType()->getUnsignedVersion(),
Chris Lattner86102b82005-01-01 16:22:27 +00005591 AndValue);
5592 AndOp = ConstantExpr::getCast(AndOp, A->getType());
5593 Instruction *And = BinaryOperator::createAnd(CSrc->getOperand(0), AndOp);
5594 if (And->getType() != CI.getType()) {
5595 And->setName(CSrc->getName()+".mask");
5596 InsertNewInstBefore(And, CI);
5597 And = new CastInst(And, CI.getType());
5598 }
5599 return And;
Chris Lattner650b6da2002-08-02 20:00:25 +00005600 }
5601 }
Chris Lattner2590e512006-02-07 06:56:34 +00005602
Chris Lattner03841652004-05-25 04:29:21 +00005603 // If this is a cast to bool, turn it into the appropriate setne instruction.
5604 if (CI.getType() == Type::BoolTy)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00005605 return BinaryOperator::createSetNE(CI.getOperand(0),
Chris Lattner03841652004-05-25 04:29:21 +00005606 Constant::getNullValue(CI.getOperand(0)->getType()));
5607
Chris Lattner2590e512006-02-07 06:56:34 +00005608 // See if we can simplify any instructions used by the LHS whose sole
5609 // purpose is to compute bits we don't care about.
Chris Lattner0157e7f2006-02-11 09:31:47 +00005610 if (CI.getType()->isInteger() && CI.getOperand(0)->getType()->isIntegral()) {
5611 uint64_t KnownZero, KnownOne;
5612 if (SimplifyDemandedBits(&CI, CI.getType()->getIntegralTypeMask(),
5613 KnownZero, KnownOne))
5614 return &CI;
5615 }
Chris Lattner2590e512006-02-07 06:56:34 +00005616
Chris Lattnerd0d51602003-06-21 23:12:02 +00005617 // If casting the result of a getelementptr instruction with no offset, turn
5618 // this into a cast of the original pointer!
5619 //
Chris Lattner55d4bda2003-06-23 21:59:52 +00005620 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattnerd0d51602003-06-21 23:12:02 +00005621 bool AllZeroOperands = true;
5622 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
5623 if (!isa<Constant>(GEP->getOperand(i)) ||
5624 !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
5625 AllZeroOperands = false;
5626 break;
5627 }
5628 if (AllZeroOperands) {
5629 CI.setOperand(0, GEP->getOperand(0));
5630 return &CI;
5631 }
5632 }
5633
Chris Lattnerf4ad1652003-11-02 05:57:39 +00005634 // If we are casting a malloc or alloca to a pointer to a type of the same
5635 // size, rewrite the allocation instruction to allocate the "right" type.
5636 //
5637 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
Chris Lattner216be912005-10-24 06:03:58 +00005638 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
5639 return V;
Chris Lattnerf4ad1652003-11-02 05:57:39 +00005640
Chris Lattner86102b82005-01-01 16:22:27 +00005641 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
5642 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
5643 return NV;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00005644 if (isa<PHINode>(Src))
5645 if (Instruction *NV = FoldOpIntoPhi(CI))
5646 return NV;
Chris Lattnerb19a5c62006-04-12 18:09:35 +00005647
5648 // If the source and destination are pointers, and this cast is equivalent to
5649 // a getelementptr X, 0, 0, 0... turn it into the appropriate getelementptr.
5650 // This can enhance SROA and other transforms that want type-safe pointers.
5651 if (const PointerType *DstPTy = dyn_cast<PointerType>(CI.getType()))
5652 if (const PointerType *SrcPTy = dyn_cast<PointerType>(Src->getType())) {
5653 const Type *DstTy = DstPTy->getElementType();
5654 const Type *SrcTy = SrcPTy->getElementType();
5655
5656 Constant *ZeroUInt = Constant::getNullValue(Type::UIntTy);
5657 unsigned NumZeros = 0;
5658 while (SrcTy != DstTy &&
Chris Lattnerd2862702006-09-11 21:43:16 +00005659 isa<CompositeType>(SrcTy) && !isa<PointerType>(SrcTy) &&
5660 SrcTy->getNumContainedTypes() /* not "{}" */) {
Chris Lattnerb19a5c62006-04-12 18:09:35 +00005661 SrcTy = cast<CompositeType>(SrcTy)->getTypeAtIndex(ZeroUInt);
5662 ++NumZeros;
5663 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00005664
Chris Lattnerb19a5c62006-04-12 18:09:35 +00005665 // If we found a path from the src to dest, create the getelementptr now.
5666 if (SrcTy == DstTy) {
5667 std::vector<Value*> Idxs(NumZeros+1, ZeroUInt);
5668 return new GetElementPtrInst(Src, Idxs);
5669 }
5670 }
5671
Chris Lattnerdfae8be2003-07-24 17:35:25 +00005672 // If the source value is an instruction with only this use, we can attempt to
5673 // propagate the cast into the instruction. Also, only handle integral types
5674 // for now.
Chris Lattner99155be2006-05-25 23:24:33 +00005675 if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
Chris Lattnerf95d9b92003-10-15 16:48:29 +00005676 if (SrcI->hasOneUse() && Src->getType()->isIntegral() &&
Chris Lattnerdfae8be2003-07-24 17:35:25 +00005677 CI.getType()->isInteger()) { // Don't mess with casts to bool here
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005678
5679 int NumCastsRemoved = 0;
5680 if (CanEvaluateInDifferentType(SrcI, CI.getType(), NumCastsRemoved)) {
5681 // If this cast is a truncate, evaluting in a different type always
5682 // eliminates the cast, so it is always a win. If this is a noop-cast
5683 // this just removes a noop cast which isn't pointful, but simplifies
5684 // the code. If this is a zero-extension, we need to do an AND to
5685 // maintain the clear top-part of the computation, so we require that
5686 // the input have eliminated at least one cast. If this is a sign
5687 // extension, we insert two new casts (to do the extension) so we
5688 // require that two casts have been eliminated.
5689 bool DoXForm;
5690 switch (getCastType(Src->getType(), CI.getType())) {
5691 default: assert(0 && "Unknown cast type!");
5692 case Noop:
5693 case Truncate:
5694 DoXForm = true;
5695 break;
5696 case Zeroext:
5697 DoXForm = NumCastsRemoved >= 1;
5698 break;
5699 case Signext:
5700 DoXForm = NumCastsRemoved >= 2;
5701 break;
5702 }
5703
5704 if (DoXForm) {
5705 Value *Res = EvaluateInDifferentType(SrcI, CI.getType());
5706 assert(Res->getType() == CI.getType());
5707 switch (getCastType(Src->getType(), CI.getType())) {
5708 default: assert(0 && "Unknown cast type!");
5709 case Noop:
5710 case Truncate:
5711 // Just replace this cast with the result.
5712 return ReplaceInstUsesWith(CI, Res);
5713 case Zeroext: {
5714 // We need to emit an AND to clear the high bits.
5715 unsigned SrcBitSize = Src->getType()->getPrimitiveSizeInBits();
5716 unsigned DestBitSize = CI.getType()->getPrimitiveSizeInBits();
5717 assert(SrcBitSize < DestBitSize && "Not a zext?");
Reid Spencere0fc4df2006-10-20 07:07:24 +00005718 Constant *C =
5719 ConstantInt::get(Type::ULongTy, (1ULL << SrcBitSize)-1);
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005720 C = ConstantExpr::getCast(C, CI.getType());
5721 return BinaryOperator::createAnd(Res, C);
5722 }
5723 case Signext:
5724 // We need to emit a cast to truncate, then a cast to sext.
5725 return new CastInst(InsertCastBefore(Res, Src->getType(), CI),
5726 CI.getType());
5727 }
5728 }
5729 }
5730
Chris Lattnerdfae8be2003-07-24 17:35:25 +00005731 const Type *DestTy = CI.getType();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005732 unsigned SrcBitSize = Src->getType()->getPrimitiveSizeInBits();
5733 unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
Chris Lattnerdfae8be2003-07-24 17:35:25 +00005734
5735 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
5736 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
5737
5738 switch (SrcI->getOpcode()) {
5739 case Instruction::Add:
5740 case Instruction::Mul:
5741 case Instruction::And:
5742 case Instruction::Or:
5743 case Instruction::Xor:
5744 // If we are discarding information, or just changing the sign, rewrite.
5745 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
5746 // Don't insert two casts if they cannot be eliminated. We allow two
5747 // casts to be inserted if the sizes are the same. This could only be
5748 // converting signedness, which is a noop.
Chris Lattner11ffd592004-07-20 05:21:00 +00005749 if (DestBitSize == SrcBitSize || !ValueRequiresCast(Op1, DestTy,TD) ||
5750 !ValueRequiresCast(Op0, DestTy, TD)) {
Chris Lattnerdfae8be2003-07-24 17:35:25 +00005751 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
5752 Value *Op1c = InsertOperandCastBefore(Op1, DestTy, SrcI);
5753 return BinaryOperator::create(cast<BinaryOperator>(SrcI)
5754 ->getOpcode(), Op0c, Op1c);
5755 }
5756 }
Chris Lattner72086162005-05-06 02:07:39 +00005757
5758 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
5759 if (SrcBitSize == 1 && SrcI->getOpcode() == Instruction::Xor &&
Chris Lattner6ab03f62006-09-28 23:35:22 +00005760 Op1 == ConstantBool::getTrue() &&
Chris Lattner72086162005-05-06 02:07:39 +00005761 (!Op0->hasOneUse() || !isa<SetCondInst>(Op0))) {
5762 Value *New = InsertOperandCastBefore(Op0, DestTy, &CI);
5763 return BinaryOperator::createXor(New,
5764 ConstantInt::get(CI.getType(), 1));
5765 }
Chris Lattnerdfae8be2003-07-24 17:35:25 +00005766 break;
Reid Spencer7e80b0b2006-10-26 06:15:43 +00005767 case Instruction::SDiv:
5768 case Instruction::UDiv:
5769 // If we are just changing the sign, rewrite.
5770 if (DestBitSize == SrcBitSize) {
5771 // Don't insert two casts if they cannot be eliminated. We allow two
5772 // casts to be inserted if the sizes are the same. This could only be
5773 // converting signedness, which is a noop.
5774 if (!ValueRequiresCast(Op1, DestTy,TD) ||
5775 !ValueRequiresCast(Op0, DestTy, TD)) {
5776 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
5777 Value *Op1c = InsertOperandCastBefore(Op1, DestTy, SrcI);
5778 return BinaryOperator::create(
5779 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
5780 }
5781 }
5782 break;
5783
Chris Lattnerdfae8be2003-07-24 17:35:25 +00005784 case Instruction::Shl:
5785 // Allow changing the sign of the source operand. Do not allow changing
5786 // the size of the shift, UNLESS the shift amount is a constant. We
5787 // mush not change variable sized shifts to a smaller size, because it
5788 // is undefined to shift more bits out than exist in the value.
5789 if (DestBitSize == SrcBitSize ||
5790 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
5791 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
5792 return new ShiftInst(Instruction::Shl, Op0c, Op1);
5793 }
5794 break;
Chris Lattner87380412005-05-06 04:18:52 +00005795 case Instruction::Shr:
5796 // If this is a signed shr, and if all bits shifted in are about to be
5797 // truncated off, turn it into an unsigned shr to allow greater
5798 // simplifications.
5799 if (DestBitSize < SrcBitSize && Src->getType()->isSigned() &&
5800 isa<ConstantInt>(Op1)) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00005801 unsigned ShiftAmt = cast<ConstantInt>(Op1)->getZExtValue();
Chris Lattner87380412005-05-06 04:18:52 +00005802 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
5803 // Convert to unsigned.
5804 Value *N1 = InsertOperandCastBefore(Op0,
5805 Op0->getType()->getUnsignedVersion(), &CI);
5806 // Insert the new shift, which is now unsigned.
5807 N1 = InsertNewInstBefore(new ShiftInst(Instruction::Shr, N1,
5808 Op1, Src->getName()), CI);
5809 return new CastInst(N1, CI.getType());
5810 }
5811 }
5812 break;
5813
Chris Lattnerc7bfed02006-02-27 02:38:23 +00005814 case Instruction::SetEQ:
Chris Lattner809dfac2005-05-04 19:10:26 +00005815 case Instruction::SetNE:
Chris Lattnerc7bfed02006-02-27 02:38:23 +00005816 // We if we are just checking for a seteq of a single bit and casting it
5817 // to an integer. If so, shift the bit to the appropriate place then
5818 // cast to integer to avoid the comparison.
Chris Lattner809dfac2005-05-04 19:10:26 +00005819 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerc7bfed02006-02-27 02:38:23 +00005820 uint64_t Op1CV = Op1C->getZExtValue();
5821 // cast (X == 0) to int --> X^1 iff X has only the low bit set.
5822 // cast (X == 0) to int --> (X>>1)^1 iff X has only the 2nd bit set.
5823 // cast (X == 1) to int --> X iff X has only the low bit set.
5824 // cast (X == 2) to int --> X>>1 iff X has only the 2nd bit set.
5825 // cast (X != 0) to int --> X iff X has only the low bit set.
5826 // cast (X != 0) to int --> X>>1 iff X has only the 2nd bit set.
5827 // cast (X != 1) to int --> X^1 iff X has only the low bit set.
5828 // cast (X != 2) to int --> (X>>1)^1 iff X has only the 2nd bit set.
5829 if (Op1CV == 0 || isPowerOf2_64(Op1CV)) {
5830 // If Op1C some other power of two, convert:
5831 uint64_t KnownZero, KnownOne;
5832 uint64_t TypeMask = Op1->getType()->getIntegralTypeMask();
5833 ComputeMaskedBits(Op0, TypeMask, KnownZero, KnownOne);
5834
5835 if (isPowerOf2_64(KnownZero^TypeMask)) { // Exactly one possible 1?
5836 bool isSetNE = SrcI->getOpcode() == Instruction::SetNE;
5837 if (Op1CV && (Op1CV != (KnownZero^TypeMask))) {
5838 // (X&4) == 2 --> false
5839 // (X&4) != 2 --> true
Chris Lattnerc5b6c9a2006-02-28 19:47:20 +00005840 Constant *Res = ConstantBool::get(isSetNE);
5841 Res = ConstantExpr::getCast(Res, CI.getType());
5842 return ReplaceInstUsesWith(CI, Res);
Chris Lattnerc7bfed02006-02-27 02:38:23 +00005843 }
5844
5845 unsigned ShiftAmt = Log2_64(KnownZero^TypeMask);
5846 Value *In = Op0;
5847 if (ShiftAmt) {
Chris Lattner4c2d3782005-05-06 01:53:19 +00005848 // Perform an unsigned shr by shiftamt. Convert input to
5849 // unsigned if it is signed.
Chris Lattner4c2d3782005-05-06 01:53:19 +00005850 if (In->getType()->isSigned())
Reid Spencer00c482b2006-10-26 19:19:06 +00005851 In = InsertCastBefore(
5852 In, In->getType()->getUnsignedVersion(), CI);
Chris Lattner4c2d3782005-05-06 01:53:19 +00005853 // Insert the shift to put the result in the low bit.
5854 In = InsertNewInstBefore(new ShiftInst(Instruction::Shr, In,
Chris Lattnerc7bfed02006-02-27 02:38:23 +00005855 ConstantInt::get(Type::UByteTy, ShiftAmt),
5856 In->getName()+".lobit"), CI);
Chris Lattner4c2d3782005-05-06 01:53:19 +00005857 }
Chris Lattnerc7bfed02006-02-27 02:38:23 +00005858
5859 if ((Op1CV != 0) == isSetNE) { // Toggle the low bit.
5860 Constant *One = ConstantInt::get(In->getType(), 1);
5861 In = BinaryOperator::createXor(In, One, "tmp");
5862 InsertNewInstBefore(cast<Instruction>(In), CI);
Chris Lattner4c2d3782005-05-06 01:53:19 +00005863 }
Chris Lattnerc7bfed02006-02-27 02:38:23 +00005864
5865 if (CI.getType() == In->getType())
5866 return ReplaceInstUsesWith(CI, In);
5867 else
5868 return new CastInst(In, CI.getType());
Chris Lattner4c2d3782005-05-06 01:53:19 +00005869 }
Chris Lattner809dfac2005-05-04 19:10:26 +00005870 }
5871 }
5872 break;
Chris Lattnerdfae8be2003-07-24 17:35:25 +00005873 }
5874 }
Chris Lattner99155be2006-05-25 23:24:33 +00005875
5876 if (SrcI->hasOneUse()) {
5877 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(SrcI)) {
5878 // Okay, we have (cast (shuffle ..)). We know this cast is a bitconvert
5879 // because the inputs are known to be a vector. Check to see if this is
5880 // a cast to a vector with the same # elts.
5881 if (isa<PackedType>(CI.getType()) &&
5882 cast<PackedType>(CI.getType())->getNumElements() ==
5883 SVI->getType()->getNumElements()) {
5884 CastInst *Tmp;
5885 // If either of the operands is a cast from CI.getType(), then
5886 // evaluating the shuffle in the casted destination's type will allow
5887 // us to eliminate at least one cast.
5888 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
5889 Tmp->getOperand(0)->getType() == CI.getType()) ||
5890 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
Chris Lattner95cebb02006-06-06 22:26:02 +00005891 Tmp->getOperand(0)->getType() == CI.getType())) {
Chris Lattner99155be2006-05-25 23:24:33 +00005892 Value *LHS = InsertOperandCastBefore(SVI->getOperand(0),
5893 CI.getType(), &CI);
5894 Value *RHS = InsertOperandCastBefore(SVI->getOperand(1),
5895 CI.getType(), &CI);
5896 // Return a new shuffle vector. Use the same element ID's, as we
5897 // know the vector types match #elts.
5898 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
5899 }
5900 }
5901 }
5902 }
5903 }
Chris Lattnerbb171802005-10-27 05:53:56 +00005904
Chris Lattner260ab202002-04-18 17:39:14 +00005905 return 0;
Chris Lattnerca081252001-12-14 16:52:21 +00005906}
5907
Chris Lattner56e4d3d2004-04-09 23:46:01 +00005908/// GetSelectFoldableOperands - We want to turn code that looks like this:
5909/// %C = or %A, %B
5910/// %D = select %cond, %C, %A
5911/// into:
5912/// %C = select %cond, %B, 0
5913/// %D = or %A, %C
5914///
5915/// Assuming that the specified instruction is an operand to the select, return
5916/// a bitmask indicating which operands of this instruction are foldable if they
5917/// equal the other incoming value of the select.
5918///
5919static unsigned GetSelectFoldableOperands(Instruction *I) {
5920 switch (I->getOpcode()) {
5921 case Instruction::Add:
5922 case Instruction::Mul:
5923 case Instruction::And:
5924 case Instruction::Or:
5925 case Instruction::Xor:
5926 return 3; // Can fold through either operand.
5927 case Instruction::Sub: // Can only fold on the amount subtracted.
5928 case Instruction::Shl: // Can only fold on the shift amount.
5929 case Instruction::Shr:
Misha Brukmanb1c93172005-04-21 23:48:37 +00005930 return 1;
Chris Lattner56e4d3d2004-04-09 23:46:01 +00005931 default:
5932 return 0; // Cannot fold
5933 }
5934}
5935
5936/// GetSelectFoldableConstant - For the same transformation as the previous
5937/// function, return the identity constant that goes into the select.
5938static Constant *GetSelectFoldableConstant(Instruction *I) {
5939 switch (I->getOpcode()) {
5940 default: assert(0 && "This cannot happen!"); abort();
5941 case Instruction::Add:
5942 case Instruction::Sub:
5943 case Instruction::Or:
5944 case Instruction::Xor:
5945 return Constant::getNullValue(I->getType());
5946 case Instruction::Shl:
5947 case Instruction::Shr:
5948 return Constant::getNullValue(Type::UByteTy);
5949 case Instruction::And:
5950 return ConstantInt::getAllOnesValue(I->getType());
5951 case Instruction::Mul:
5952 return ConstantInt::get(I->getType(), 1);
5953 }
5954}
5955
Chris Lattner411336f2005-01-19 21:50:18 +00005956/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
5957/// have the same opcode and only one use each. Try to simplify this.
5958Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
5959 Instruction *FI) {
5960 if (TI->getNumOperands() == 1) {
5961 // If this is a non-volatile load or a cast from the same type,
5962 // merge.
5963 if (TI->getOpcode() == Instruction::Cast) {
5964 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
5965 return 0;
5966 } else {
5967 return 0; // unknown unary op.
5968 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00005969
Chris Lattner411336f2005-01-19 21:50:18 +00005970 // Fold this by inserting a select from the input values.
5971 SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
5972 FI->getOperand(0), SI.getName()+".v");
5973 InsertNewInstBefore(NewSI, SI);
5974 return new CastInst(NewSI, TI->getType());
5975 }
5976
5977 // Only handle binary operators here.
5978 if (!isa<ShiftInst>(TI) && !isa<BinaryOperator>(TI))
5979 return 0;
5980
5981 // Figure out if the operations have any operands in common.
5982 Value *MatchOp, *OtherOpT, *OtherOpF;
5983 bool MatchIsOpZero;
5984 if (TI->getOperand(0) == FI->getOperand(0)) {
5985 MatchOp = TI->getOperand(0);
5986 OtherOpT = TI->getOperand(1);
5987 OtherOpF = FI->getOperand(1);
5988 MatchIsOpZero = true;
5989 } else if (TI->getOperand(1) == FI->getOperand(1)) {
5990 MatchOp = TI->getOperand(1);
5991 OtherOpT = TI->getOperand(0);
5992 OtherOpF = FI->getOperand(0);
5993 MatchIsOpZero = false;
5994 } else if (!TI->isCommutative()) {
5995 return 0;
5996 } else if (TI->getOperand(0) == FI->getOperand(1)) {
5997 MatchOp = TI->getOperand(0);
5998 OtherOpT = TI->getOperand(1);
5999 OtherOpF = FI->getOperand(0);
6000 MatchIsOpZero = true;
6001 } else if (TI->getOperand(1) == FI->getOperand(0)) {
6002 MatchOp = TI->getOperand(1);
6003 OtherOpT = TI->getOperand(0);
6004 OtherOpF = FI->getOperand(1);
6005 MatchIsOpZero = true;
6006 } else {
6007 return 0;
6008 }
6009
6010 // If we reach here, they do have operations in common.
6011 SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
6012 OtherOpF, SI.getName()+".v");
6013 InsertNewInstBefore(NewSI, SI);
6014
6015 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
6016 if (MatchIsOpZero)
6017 return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
6018 else
6019 return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
6020 } else {
6021 if (MatchIsOpZero)
6022 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), MatchOp, NewSI);
6023 else
6024 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), NewSI, MatchOp);
6025 }
6026}
6027
Chris Lattnerb909e8b2004-03-12 05:52:32 +00006028Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattner533bc492004-03-30 19:37:13 +00006029 Value *CondVal = SI.getCondition();
6030 Value *TrueVal = SI.getTrueValue();
6031 Value *FalseVal = SI.getFalseValue();
6032
6033 // select true, X, Y -> X
6034 // select false, X, Y -> Y
6035 if (ConstantBool *C = dyn_cast<ConstantBool>(CondVal))
Chris Lattner6ab03f62006-09-28 23:35:22 +00006036 return ReplaceInstUsesWith(SI, C->getValue() ? TrueVal : FalseVal);
Chris Lattner533bc492004-03-30 19:37:13 +00006037
6038 // select C, X, X -> X
6039 if (TrueVal == FalseVal)
6040 return ReplaceInstUsesWith(SI, TrueVal);
6041
Chris Lattner81a7a232004-10-16 18:11:37 +00006042 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
6043 return ReplaceInstUsesWith(SI, FalseVal);
6044 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
6045 return ReplaceInstUsesWith(SI, TrueVal);
6046 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
6047 if (isa<Constant>(TrueVal))
6048 return ReplaceInstUsesWith(SI, TrueVal);
6049 else
6050 return ReplaceInstUsesWith(SI, FalseVal);
6051 }
6052
Chris Lattner1c631e82004-04-08 04:43:23 +00006053 if (SI.getType() == Type::BoolTy)
6054 if (ConstantBool *C = dyn_cast<ConstantBool>(TrueVal)) {
Chris Lattner6ab03f62006-09-28 23:35:22 +00006055 if (C->getValue()) {
Chris Lattner1c631e82004-04-08 04:43:23 +00006056 // Change: A = select B, true, C --> A = or B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00006057 return BinaryOperator::createOr(CondVal, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00006058 } else {
6059 // Change: A = select B, false, C --> A = and !B, C
6060 Value *NotCond =
6061 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
6062 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00006063 return BinaryOperator::createAnd(NotCond, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00006064 }
6065 } else if (ConstantBool *C = dyn_cast<ConstantBool>(FalseVal)) {
Chris Lattner6ab03f62006-09-28 23:35:22 +00006066 if (C->getValue() == false) {
Chris Lattner1c631e82004-04-08 04:43:23 +00006067 // Change: A = select B, C, false --> A = and B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00006068 return BinaryOperator::createAnd(CondVal, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00006069 } else {
6070 // Change: A = select B, C, true --> A = or !B, C
6071 Value *NotCond =
6072 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
6073 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00006074 return BinaryOperator::createOr(NotCond, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00006075 }
6076 }
6077
Chris Lattner183b3362004-04-09 19:05:30 +00006078 // Selecting between two integer constants?
6079 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
6080 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
6081 // select C, 1, 0 -> cast C to int
Reid Spencere0fc4df2006-10-20 07:07:24 +00006082 if (FalseValC->isNullValue() && TrueValC->getZExtValue() == 1) {
Chris Lattner183b3362004-04-09 19:05:30 +00006083 return new CastInst(CondVal, SI.getType());
Reid Spencere0fc4df2006-10-20 07:07:24 +00006084 } else if (TrueValC->isNullValue() && FalseValC->getZExtValue() == 1) {
Chris Lattner183b3362004-04-09 19:05:30 +00006085 // select C, 0, 1 -> cast !C to int
6086 Value *NotCond =
6087 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
Chris Lattnercf7baf32004-04-09 18:19:44 +00006088 "not."+CondVal->getName()), SI);
Chris Lattner183b3362004-04-09 19:05:30 +00006089 return new CastInst(NotCond, SI.getType());
Chris Lattnercf7baf32004-04-09 18:19:44 +00006090 }
Chris Lattner35167c32004-06-09 07:59:58 +00006091
Chris Lattner380c7e92006-09-20 04:44:59 +00006092 if (SetCondInst *IC = dyn_cast<SetCondInst>(SI.getCondition())) {
6093
6094 // (x <s 0) ? -1 : 0 -> sra x, 31
6095 // (x >u 2147483647) ? -1 : 0 -> sra x, 31
6096 if (TrueValC->isAllOnesValue() && FalseValC->isNullValue())
6097 if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
6098 bool CanXForm = false;
6099 if (CmpCst->getType()->isSigned())
6100 CanXForm = CmpCst->isNullValue() &&
6101 IC->getOpcode() == Instruction::SetLT;
6102 else {
6103 unsigned Bits = CmpCst->getType()->getPrimitiveSizeInBits();
Reid Spencere0fc4df2006-10-20 07:07:24 +00006104 CanXForm = (CmpCst->getZExtValue() == ~0ULL >> (64-Bits+1)) &&
Chris Lattner380c7e92006-09-20 04:44:59 +00006105 IC->getOpcode() == Instruction::SetGT;
6106 }
6107
6108 if (CanXForm) {
6109 // The comparison constant and the result are not neccessarily the
6110 // same width. In any case, the first step to do is make sure
6111 // that X is signed.
6112 Value *X = IC->getOperand(0);
6113 if (!X->getType()->isSigned())
6114 X = InsertCastBefore(X, X->getType()->getSignedVersion(), SI);
6115
6116 // Now that X is signed, we have to make the all ones value. Do
6117 // this by inserting a new SRA.
6118 unsigned Bits = X->getType()->getPrimitiveSizeInBits();
Reid Spencere0fc4df2006-10-20 07:07:24 +00006119 Constant *ShAmt = ConstantInt::get(Type::UByteTy, Bits-1);
Chris Lattner380c7e92006-09-20 04:44:59 +00006120 Instruction *SRA = new ShiftInst(Instruction::Shr, X,
6121 ShAmt, "ones");
6122 InsertNewInstBefore(SRA, SI);
6123
6124 // Finally, convert to the type of the select RHS. If this is
6125 // smaller than the compare value, it will truncate the ones to
6126 // fit. If it is larger, it will sext the ones to fit.
6127 return new CastInst(SRA, SI.getType());
6128 }
6129 }
6130
6131
6132 // If one of the constants is zero (we know they can't both be) and we
6133 // have a setcc instruction with zero, and we have an 'and' with the
6134 // non-constant value, eliminate this whole mess. This corresponds to
6135 // cases like this: ((X & 27) ? 27 : 0)
6136 if (TrueValC->isNullValue() || FalseValC->isNullValue())
Chris Lattnerb3f24c92006-09-18 04:22:48 +00006137 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner35167c32004-06-09 07:59:58 +00006138 cast<Constant>(IC->getOperand(1))->isNullValue())
6139 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
6140 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00006141 isa<ConstantInt>(ICA->getOperand(1)) &&
6142 (ICA->getOperand(1) == TrueValC ||
6143 ICA->getOperand(1) == FalseValC) &&
Chris Lattner35167c32004-06-09 07:59:58 +00006144 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
6145 // Okay, now we know that everything is set up, we just don't
6146 // know whether we have a setne or seteq and whether the true or
6147 // false val is the zero.
6148 bool ShouldNotVal = !TrueValC->isNullValue();
6149 ShouldNotVal ^= IC->getOpcode() == Instruction::SetNE;
6150 Value *V = ICA;
6151 if (ShouldNotVal)
6152 V = InsertNewInstBefore(BinaryOperator::create(
6153 Instruction::Xor, V, ICA->getOperand(1)), SI);
6154 return ReplaceInstUsesWith(SI, V);
6155 }
Chris Lattner380c7e92006-09-20 04:44:59 +00006156 }
Chris Lattner533bc492004-03-30 19:37:13 +00006157 }
Chris Lattner623fba12004-04-10 22:21:27 +00006158
6159 // See if we are selecting two values based on a comparison of the two values.
6160 if (SetCondInst *SCI = dyn_cast<SetCondInst>(CondVal)) {
6161 if (SCI->getOperand(0) == TrueVal && SCI->getOperand(1) == FalseVal) {
6162 // Transform (X == Y) ? X : Y -> Y
6163 if (SCI->getOpcode() == Instruction::SetEQ)
6164 return ReplaceInstUsesWith(SI, FalseVal);
6165 // Transform (X != Y) ? X : Y -> X
6166 if (SCI->getOpcode() == Instruction::SetNE)
6167 return ReplaceInstUsesWith(SI, TrueVal);
6168 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6169
6170 } else if (SCI->getOperand(0) == FalseVal && SCI->getOperand(1) == TrueVal){
6171 // Transform (X == Y) ? Y : X -> X
6172 if (SCI->getOpcode() == Instruction::SetEQ)
Chris Lattner24cf0202004-04-11 01:39:19 +00006173 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattner623fba12004-04-10 22:21:27 +00006174 // Transform (X != Y) ? Y : X -> Y
6175 if (SCI->getOpcode() == Instruction::SetNE)
Chris Lattner24cf0202004-04-11 01:39:19 +00006176 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattner623fba12004-04-10 22:21:27 +00006177 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6178 }
6179 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00006180
Chris Lattnera04c9042005-01-13 22:52:24 +00006181 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
6182 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
6183 if (TI->hasOneUse() && FI->hasOneUse()) {
6184 bool isInverse = false;
6185 Instruction *AddOp = 0, *SubOp = 0;
6186
Chris Lattner411336f2005-01-19 21:50:18 +00006187 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
6188 if (TI->getOpcode() == FI->getOpcode())
6189 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
6190 return IV;
6191
6192 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
6193 // even legal for FP.
Chris Lattnera04c9042005-01-13 22:52:24 +00006194 if (TI->getOpcode() == Instruction::Sub &&
6195 FI->getOpcode() == Instruction::Add) {
6196 AddOp = FI; SubOp = TI;
6197 } else if (FI->getOpcode() == Instruction::Sub &&
6198 TI->getOpcode() == Instruction::Add) {
6199 AddOp = TI; SubOp = FI;
6200 }
6201
6202 if (AddOp) {
6203 Value *OtherAddOp = 0;
6204 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
6205 OtherAddOp = AddOp->getOperand(1);
6206 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
6207 OtherAddOp = AddOp->getOperand(0);
6208 }
6209
6210 if (OtherAddOp) {
Chris Lattnerb580d262006-02-24 18:05:58 +00006211 // So at this point we know we have (Y -> OtherAddOp):
6212 // select C, (add X, Y), (sub X, Z)
6213 Value *NegVal; // Compute -Z
6214 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
6215 NegVal = ConstantExpr::getNeg(C);
6216 } else {
6217 NegVal = InsertNewInstBefore(
6218 BinaryOperator::createNeg(SubOp->getOperand(1), "tmp"), SI);
Chris Lattnera04c9042005-01-13 22:52:24 +00006219 }
Chris Lattnerb580d262006-02-24 18:05:58 +00006220
6221 Value *NewTrueOp = OtherAddOp;
6222 Value *NewFalseOp = NegVal;
6223 if (AddOp != TI)
6224 std::swap(NewTrueOp, NewFalseOp);
6225 Instruction *NewSel =
6226 new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
6227
6228 NewSel = InsertNewInstBefore(NewSel, SI);
6229 return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
Chris Lattnera04c9042005-01-13 22:52:24 +00006230 }
6231 }
6232 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00006233
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006234 // See if we can fold the select into one of our operands.
6235 if (SI.getType()->isInteger()) {
6236 // See the comment above GetSelectFoldableOperands for a description of the
6237 // transformation we are doing here.
6238 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
6239 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
6240 !isa<Constant>(FalseVal))
6241 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
6242 unsigned OpToFold = 0;
6243 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
6244 OpToFold = 1;
6245 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
6246 OpToFold = 2;
6247 }
6248
6249 if (OpToFold) {
6250 Constant *C = GetSelectFoldableConstant(TVI);
6251 std::string Name = TVI->getName(); TVI->setName("");
6252 Instruction *NewSel =
6253 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C,
6254 Name);
6255 InsertNewInstBefore(NewSel, SI);
6256 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
6257 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
6258 else if (ShiftInst *SI = dyn_cast<ShiftInst>(TVI))
6259 return new ShiftInst(SI->getOpcode(), FalseVal, NewSel);
6260 else {
6261 assert(0 && "Unknown instruction!!");
6262 }
6263 }
6264 }
Chris Lattner6862fbd2004-09-29 17:40:11 +00006265
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006266 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
6267 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
6268 !isa<Constant>(TrueVal))
6269 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
6270 unsigned OpToFold = 0;
6271 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
6272 OpToFold = 1;
6273 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
6274 OpToFold = 2;
6275 }
6276
6277 if (OpToFold) {
6278 Constant *C = GetSelectFoldableConstant(FVI);
6279 std::string Name = FVI->getName(); FVI->setName("");
6280 Instruction *NewSel =
6281 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold),
6282 Name);
6283 InsertNewInstBefore(NewSel, SI);
6284 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
6285 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
6286 else if (ShiftInst *SI = dyn_cast<ShiftInst>(FVI))
6287 return new ShiftInst(SI->getOpcode(), TrueVal, NewSel);
6288 else {
6289 assert(0 && "Unknown instruction!!");
6290 }
6291 }
6292 }
6293 }
Chris Lattnerd6f636a2005-04-24 07:30:14 +00006294
6295 if (BinaryOperator::isNot(CondVal)) {
6296 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
6297 SI.setOperand(1, FalseVal);
6298 SI.setOperand(2, TrueVal);
6299 return &SI;
6300 }
6301
Chris Lattnerb909e8b2004-03-12 05:52:32 +00006302 return 0;
6303}
6304
Chris Lattner82f2ef22006-03-06 20:18:44 +00006305/// GetKnownAlignment - If the specified pointer has an alignment that we can
6306/// determine, return it, otherwise return 0.
6307static unsigned GetKnownAlignment(Value *V, TargetData *TD) {
6308 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
6309 unsigned Align = GV->getAlignment();
6310 if (Align == 0 && TD)
6311 Align = TD->getTypeAlignment(GV->getType()->getElementType());
6312 return Align;
6313 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
6314 unsigned Align = AI->getAlignment();
6315 if (Align == 0 && TD) {
6316 if (isa<AllocaInst>(AI))
6317 Align = TD->getTypeAlignment(AI->getType()->getElementType());
6318 else if (isa<MallocInst>(AI)) {
6319 // Malloc returns maximally aligned memory.
6320 Align = TD->getTypeAlignment(AI->getType()->getElementType());
6321 Align = std::max(Align, (unsigned)TD->getTypeAlignment(Type::DoubleTy));
6322 Align = std::max(Align, (unsigned)TD->getTypeAlignment(Type::LongTy));
6323 }
6324 }
6325 return Align;
Chris Lattner53ef5a02006-03-07 01:28:57 +00006326 } else if (isa<CastInst>(V) ||
6327 (isa<ConstantExpr>(V) &&
6328 cast<ConstantExpr>(V)->getOpcode() == Instruction::Cast)) {
6329 User *CI = cast<User>(V);
Chris Lattner82f2ef22006-03-06 20:18:44 +00006330 if (isa<PointerType>(CI->getOperand(0)->getType()))
6331 return GetKnownAlignment(CI->getOperand(0), TD);
6332 return 0;
Chris Lattner53ef5a02006-03-07 01:28:57 +00006333 } else if (isa<GetElementPtrInst>(V) ||
6334 (isa<ConstantExpr>(V) &&
6335 cast<ConstantExpr>(V)->getOpcode()==Instruction::GetElementPtr)) {
6336 User *GEPI = cast<User>(V);
Chris Lattner82f2ef22006-03-06 20:18:44 +00006337 unsigned BaseAlignment = GetKnownAlignment(GEPI->getOperand(0), TD);
6338 if (BaseAlignment == 0) return 0;
6339
6340 // If all indexes are zero, it is just the alignment of the base pointer.
6341 bool AllZeroOperands = true;
6342 for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
6343 if (!isa<Constant>(GEPI->getOperand(i)) ||
6344 !cast<Constant>(GEPI->getOperand(i))->isNullValue()) {
6345 AllZeroOperands = false;
6346 break;
6347 }
6348 if (AllZeroOperands)
6349 return BaseAlignment;
6350
6351 // Otherwise, if the base alignment is >= the alignment we expect for the
6352 // base pointer type, then we know that the resultant pointer is aligned at
6353 // least as much as its type requires.
6354 if (!TD) return 0;
6355
6356 const Type *BasePtrTy = GEPI->getOperand(0)->getType();
6357 if (TD->getTypeAlignment(cast<PointerType>(BasePtrTy)->getElementType())
Chris Lattner53ef5a02006-03-07 01:28:57 +00006358 <= BaseAlignment) {
6359 const Type *GEPTy = GEPI->getType();
6360 return TD->getTypeAlignment(cast<PointerType>(GEPTy)->getElementType());
6361 }
Chris Lattner82f2ef22006-03-06 20:18:44 +00006362 return 0;
6363 }
6364 return 0;
6365}
6366
Chris Lattnerb909e8b2004-03-12 05:52:32 +00006367
Chris Lattnerc66b2232006-01-13 20:11:04 +00006368/// visitCallInst - CallInst simplification. This mostly only handles folding
6369/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
6370/// the heavy lifting.
6371///
Chris Lattner970c33a2003-06-19 17:00:31 +00006372Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattnerc66b2232006-01-13 20:11:04 +00006373 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
6374 if (!II) return visitCallSite(&CI);
6375
Chris Lattner51ea1272004-02-28 05:22:00 +00006376 // Intrinsics cannot occur in an invoke, so handle them here instead of in
6377 // visitCallSite.
Chris Lattnerc66b2232006-01-13 20:11:04 +00006378 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner00648e12004-10-12 04:52:52 +00006379 bool Changed = false;
6380
6381 // memmove/cpy/set of zero bytes is a noop.
6382 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
6383 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
6384
Chris Lattner00648e12004-10-12 04:52:52 +00006385 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencere0fc4df2006-10-20 07:07:24 +00006386 if (CI->getZExtValue() == 1) {
Chris Lattner00648e12004-10-12 04:52:52 +00006387 // Replace the instruction with just byte operations. We would
6388 // transform other cases to loads/stores, but we don't know if
6389 // alignment is sufficient.
6390 }
Chris Lattner51ea1272004-02-28 05:22:00 +00006391 }
6392
Chris Lattner00648e12004-10-12 04:52:52 +00006393 // If we have a memmove and the source operation is a constant global,
6394 // then the source and dest pointers can't alias, so we can change this
6395 // into a call to memcpy.
Chris Lattner82f2ef22006-03-06 20:18:44 +00006396 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(II)) {
Chris Lattner00648e12004-10-12 04:52:52 +00006397 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
6398 if (GVSrc->isConstant()) {
6399 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner681ef2f2006-03-03 01:34:17 +00006400 const char *Name;
6401 if (CI.getCalledFunction()->getFunctionType()->getParamType(3) ==
6402 Type::UIntTy)
6403 Name = "llvm.memcpy.i32";
6404 else
6405 Name = "llvm.memcpy.i64";
6406 Function *MemCpy = M->getOrInsertFunction(Name,
Chris Lattner00648e12004-10-12 04:52:52 +00006407 CI.getCalledFunction()->getFunctionType());
6408 CI.setOperand(0, MemCpy);
6409 Changed = true;
6410 }
Chris Lattner82f2ef22006-03-06 20:18:44 +00006411 }
Chris Lattner00648e12004-10-12 04:52:52 +00006412
Chris Lattner82f2ef22006-03-06 20:18:44 +00006413 // If we can determine a pointer alignment that is bigger than currently
6414 // set, update the alignment.
6415 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
6416 unsigned Alignment1 = GetKnownAlignment(MI->getOperand(1), TD);
6417 unsigned Alignment2 = GetKnownAlignment(MI->getOperand(2), TD);
6418 unsigned Align = std::min(Alignment1, Alignment2);
Reid Spencere0fc4df2006-10-20 07:07:24 +00006419 if (MI->getAlignment()->getZExtValue() < Align) {
6420 MI->setAlignment(ConstantInt::get(Type::UIntTy, Align));
Chris Lattner82f2ef22006-03-06 20:18:44 +00006421 Changed = true;
6422 }
6423 } else if (isa<MemSetInst>(MI)) {
6424 unsigned Alignment = GetKnownAlignment(MI->getDest(), TD);
Reid Spencere0fc4df2006-10-20 07:07:24 +00006425 if (MI->getAlignment()->getZExtValue() < Alignment) {
6426 MI->setAlignment(ConstantInt::get(Type::UIntTy, Alignment));
Chris Lattner82f2ef22006-03-06 20:18:44 +00006427 Changed = true;
6428 }
6429 }
6430
Chris Lattnerc66b2232006-01-13 20:11:04 +00006431 if (Changed) return II;
Chris Lattner503221f2006-01-13 21:28:09 +00006432 } else {
6433 switch (II->getIntrinsicID()) {
6434 default: break;
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00006435 case Intrinsic::ppc_altivec_lvx:
6436 case Intrinsic::ppc_altivec_lvxl:
Chris Lattner36dd7c92006-04-17 22:26:56 +00006437 case Intrinsic::x86_sse_loadu_ps:
6438 case Intrinsic::x86_sse2_loadu_pd:
6439 case Intrinsic::x86_sse2_loadu_dq:
6440 // Turn PPC lvx -> load if the pointer is known aligned.
6441 // Turn X86 loadups -> load if the pointer is known aligned.
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00006442 if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
Chris Lattnere79d2492006-04-06 19:19:17 +00006443 Value *Ptr = InsertCastBefore(II->getOperand(1),
6444 PointerType::get(II->getType()), CI);
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00006445 return new LoadInst(Ptr);
6446 }
6447 break;
6448 case Intrinsic::ppc_altivec_stvx:
6449 case Intrinsic::ppc_altivec_stvxl:
6450 // Turn stvx -> store if the pointer is known aligned.
6451 if (GetKnownAlignment(II->getOperand(2), TD) >= 16) {
Chris Lattnere79d2492006-04-06 19:19:17 +00006452 const Type *OpPtrTy = PointerType::get(II->getOperand(1)->getType());
6453 Value *Ptr = InsertCastBefore(II->getOperand(2), OpPtrTy, CI);
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00006454 return new StoreInst(II->getOperand(1), Ptr);
6455 }
6456 break;
Chris Lattner36dd7c92006-04-17 22:26:56 +00006457 case Intrinsic::x86_sse_storeu_ps:
6458 case Intrinsic::x86_sse2_storeu_pd:
6459 case Intrinsic::x86_sse2_storeu_dq:
6460 case Intrinsic::x86_sse2_storel_dq:
6461 // Turn X86 storeu -> store if the pointer is known aligned.
6462 if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
6463 const Type *OpPtrTy = PointerType::get(II->getOperand(2)->getType());
6464 Value *Ptr = InsertCastBefore(II->getOperand(1), OpPtrTy, CI);
6465 return new StoreInst(II->getOperand(2), Ptr);
6466 }
6467 break;
Chris Lattner2deeaea2006-10-05 06:55:50 +00006468
6469 case Intrinsic::x86_sse_cvttss2si: {
6470 // These intrinsics only demands the 0th element of its input vector. If
6471 // we can simplify the input based on that, do so now.
6472 uint64_t UndefElts;
6473 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1,
6474 UndefElts)) {
6475 II->setOperand(1, V);
6476 return II;
6477 }
6478 break;
6479 }
6480
Chris Lattnere79d2492006-04-06 19:19:17 +00006481 case Intrinsic::ppc_altivec_vperm:
6482 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
6483 if (ConstantPacked *Mask = dyn_cast<ConstantPacked>(II->getOperand(3))) {
6484 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
6485
6486 // Check that all of the elements are integer constants or undefs.
6487 bool AllEltsOk = true;
6488 for (unsigned i = 0; i != 16; ++i) {
6489 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
6490 !isa<UndefValue>(Mask->getOperand(i))) {
6491 AllEltsOk = false;
6492 break;
6493 }
6494 }
6495
6496 if (AllEltsOk) {
6497 // Cast the input vectors to byte vectors.
6498 Value *Op0 = InsertCastBefore(II->getOperand(1), Mask->getType(), CI);
6499 Value *Op1 = InsertCastBefore(II->getOperand(2), Mask->getType(), CI);
6500 Value *Result = UndefValue::get(Op0->getType());
6501
6502 // Only extract each element once.
6503 Value *ExtractedElts[32];
6504 memset(ExtractedElts, 0, sizeof(ExtractedElts));
6505
6506 for (unsigned i = 0; i != 16; ++i) {
6507 if (isa<UndefValue>(Mask->getOperand(i)))
6508 continue;
Reid Spencere0fc4df2006-10-20 07:07:24 +00006509 unsigned Idx =cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
Chris Lattnere79d2492006-04-06 19:19:17 +00006510 Idx &= 31; // Match the hardware behavior.
6511
6512 if (ExtractedElts[Idx] == 0) {
6513 Instruction *Elt =
Chris Lattner2deeaea2006-10-05 06:55:50 +00006514 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
Chris Lattnere79d2492006-04-06 19:19:17 +00006515 InsertNewInstBefore(Elt, CI);
6516 ExtractedElts[Idx] = Elt;
6517 }
6518
6519 // Insert this value into the result vector.
Chris Lattner2deeaea2006-10-05 06:55:50 +00006520 Result = new InsertElementInst(Result, ExtractedElts[Idx], i,"tmp");
Chris Lattnere79d2492006-04-06 19:19:17 +00006521 InsertNewInstBefore(cast<Instruction>(Result), CI);
6522 }
6523 return new CastInst(Result, CI.getType());
6524 }
6525 }
6526 break;
6527
Chris Lattner503221f2006-01-13 21:28:09 +00006528 case Intrinsic::stackrestore: {
6529 // If the save is right next to the restore, remove the restore. This can
6530 // happen when variable allocas are DCE'd.
6531 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
6532 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
6533 BasicBlock::iterator BI = SS;
6534 if (&*++BI == II)
6535 return EraseInstFromFunction(CI);
6536 }
6537 }
6538
6539 // If the stack restore is in a return/unwind block and if there are no
6540 // allocas or calls between the restore and the return, nuke the restore.
6541 TerminatorInst *TI = II->getParent()->getTerminator();
6542 if (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)) {
6543 BasicBlock::iterator BI = II;
6544 bool CannotRemove = false;
6545 for (++BI; &*BI != TI; ++BI) {
6546 if (isa<AllocaInst>(BI) ||
6547 (isa<CallInst>(BI) && !isa<IntrinsicInst>(BI))) {
6548 CannotRemove = true;
6549 break;
6550 }
6551 }
6552 if (!CannotRemove)
6553 return EraseInstFromFunction(CI);
6554 }
6555 break;
6556 }
6557 }
Chris Lattner00648e12004-10-12 04:52:52 +00006558 }
6559
Chris Lattnerc66b2232006-01-13 20:11:04 +00006560 return visitCallSite(II);
Chris Lattner970c33a2003-06-19 17:00:31 +00006561}
6562
6563// InvokeInst simplification
6564//
6565Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattneraec3d942003-10-07 22:32:43 +00006566 return visitCallSite(&II);
Chris Lattner970c33a2003-06-19 17:00:31 +00006567}
6568
Chris Lattneraec3d942003-10-07 22:32:43 +00006569// visitCallSite - Improvements for call and invoke instructions.
6570//
6571Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner75b4d1d2003-10-07 22:54:13 +00006572 bool Changed = false;
6573
6574 // If the callee is a constexpr cast of a function, attempt to move the cast
6575 // to the arguments of the call/invoke.
Chris Lattneraec3d942003-10-07 22:32:43 +00006576 if (transformConstExprCastCall(CS)) return 0;
6577
Chris Lattner75b4d1d2003-10-07 22:54:13 +00006578 Value *Callee = CS.getCalledValue();
Chris Lattner81a7a232004-10-16 18:11:37 +00006579
Chris Lattner61d9d812005-05-13 07:09:09 +00006580 if (Function *CalleeF = dyn_cast<Function>(Callee))
6581 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
6582 Instruction *OldCall = CS.getInstruction();
6583 // If the call and callee calling conventions don't match, this call must
6584 // be unreachable, as the call is undefined.
Chris Lattner6ab03f62006-09-28 23:35:22 +00006585 new StoreInst(ConstantBool::getTrue(),
Chris Lattner61d9d812005-05-13 07:09:09 +00006586 UndefValue::get(PointerType::get(Type::BoolTy)), OldCall);
6587 if (!OldCall->use_empty())
6588 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
6589 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
6590 return EraseInstFromFunction(*OldCall);
6591 return 0;
6592 }
6593
Chris Lattner8ba9ec92004-10-18 02:59:09 +00006594 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
6595 // This instruction is not reachable, just remove it. We insert a store to
6596 // undef so that we know that this code is not reachable, despite the fact
6597 // that we can't modify the CFG here.
Chris Lattner6ab03f62006-09-28 23:35:22 +00006598 new StoreInst(ConstantBool::getTrue(),
Chris Lattner8ba9ec92004-10-18 02:59:09 +00006599 UndefValue::get(PointerType::get(Type::BoolTy)),
6600 CS.getInstruction());
6601
6602 if (!CS.getInstruction()->use_empty())
6603 CS.getInstruction()->
6604 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
6605
6606 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
6607 // Don't break the CFG, insert a dummy cond branch.
6608 new BranchInst(II->getNormalDest(), II->getUnwindDest(),
Chris Lattner6ab03f62006-09-28 23:35:22 +00006609 ConstantBool::getTrue(), II);
Chris Lattner81a7a232004-10-16 18:11:37 +00006610 }
Chris Lattner8ba9ec92004-10-18 02:59:09 +00006611 return EraseInstFromFunction(*CS.getInstruction());
6612 }
Chris Lattner81a7a232004-10-16 18:11:37 +00006613
Chris Lattner75b4d1d2003-10-07 22:54:13 +00006614 const PointerType *PTy = cast<PointerType>(Callee->getType());
6615 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
6616 if (FTy->isVarArg()) {
6617 // See if we can optimize any arguments passed through the varargs area of
6618 // the call.
6619 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
6620 E = CS.arg_end(); I != E; ++I)
6621 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
6622 // If this cast does not effect the value passed through the varargs
6623 // area, we can eliminate the use of the cast.
6624 Value *Op = CI->getOperand(0);
6625 if (CI->getType()->isLosslesslyConvertibleTo(Op->getType())) {
6626 *I = Op;
6627 Changed = true;
6628 }
6629 }
6630 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00006631
Chris Lattner75b4d1d2003-10-07 22:54:13 +00006632 return Changed ? CS.getInstruction() : 0;
Chris Lattneraec3d942003-10-07 22:32:43 +00006633}
6634
Chris Lattner970c33a2003-06-19 17:00:31 +00006635// transformConstExprCastCall - If the callee is a constexpr cast of a function,
6636// attempt to move the cast to the arguments of the call/invoke.
6637//
6638bool InstCombiner::transformConstExprCastCall(CallSite CS) {
6639 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
6640 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Chris Lattnerf3edc492004-07-18 18:59:44 +00006641 if (CE->getOpcode() != Instruction::Cast || !isa<Function>(CE->getOperand(0)))
Chris Lattner970c33a2003-06-19 17:00:31 +00006642 return false;
Reid Spencer87436872004-07-18 00:38:32 +00006643 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner970c33a2003-06-19 17:00:31 +00006644 Instruction *Caller = CS.getInstruction();
6645
6646 // Okay, this is a cast from a function to a different type. Unless doing so
6647 // would cause a type conversion of one of our arguments, change this call to
6648 // be a direct call with arguments casted to the appropriate types.
6649 //
6650 const FunctionType *FT = Callee->getFunctionType();
6651 const Type *OldRetTy = Caller->getType();
6652
Chris Lattner1f7942f2004-01-14 06:06:08 +00006653 // Check to see if we are changing the return type...
6654 if (OldRetTy != FT->getReturnType()) {
6655 if (Callee->isExternal() &&
Andrew Lenharth61eae292006-04-20 14:56:47 +00006656 !(OldRetTy->isLosslesslyConvertibleTo(FT->getReturnType()) ||
6657 (isa<PointerType>(FT->getReturnType()) &&
Andrew Lenharthf89e6302006-04-20 15:41:37 +00006658 TD->getIntPtrType()->isLosslesslyConvertibleTo(OldRetTy)))
Andrew Lenharth61eae292006-04-20 14:56:47 +00006659 && !Caller->use_empty())
Chris Lattner1f7942f2004-01-14 06:06:08 +00006660 return false; // Cannot transform this return value...
6661
6662 // If the callsite is an invoke instruction, and the return value is used by
6663 // a PHI node in a successor, we cannot change the return type of the call
6664 // because there is no place to put the cast instruction (without breaking
6665 // the critical edge). Bail out in this case.
6666 if (!Caller->use_empty())
6667 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
6668 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
6669 UI != E; ++UI)
6670 if (PHINode *PN = dyn_cast<PHINode>(*UI))
6671 if (PN->getParent() == II->getNormalDest() ||
Chris Lattnerfae8ab32004-02-08 21:44:31 +00006672 PN->getParent() == II->getUnwindDest())
Chris Lattner1f7942f2004-01-14 06:06:08 +00006673 return false;
6674 }
Chris Lattner970c33a2003-06-19 17:00:31 +00006675
6676 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
6677 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanb1c93172005-04-21 23:48:37 +00006678
Chris Lattner970c33a2003-06-19 17:00:31 +00006679 CallSite::arg_iterator AI = CS.arg_begin();
6680 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
6681 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthebfa24e2006-06-28 01:01:52 +00006682 const Type *ActTy = (*AI)->getType();
Reid Spencere0fc4df2006-10-20 07:07:24 +00006683 ConstantInt* c = dyn_cast<ConstantInt>(*AI);
Andrew Lenharthebfa24e2006-06-28 01:01:52 +00006684 //Either we can cast directly, or we can upconvert the argument
6685 bool isConvertible = ActTy->isLosslesslyConvertibleTo(ParamTy) ||
6686 (ParamTy->isIntegral() && ActTy->isIntegral() &&
6687 ParamTy->isSigned() == ActTy->isSigned() &&
6688 ParamTy->getPrimitiveSize() >= ActTy->getPrimitiveSize()) ||
6689 (c && ParamTy->getPrimitiveSize() >= ActTy->getPrimitiveSize() &&
Reid Spencere0fc4df2006-10-20 07:07:24 +00006690 c->getSExtValue() > 0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00006691 if (Callee->isExternal() && !isConvertible) return false;
Chris Lattner970c33a2003-06-19 17:00:31 +00006692 }
6693
6694 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
6695 Callee->isExternal())
6696 return false; // Do not delete arguments unless we have a function body...
6697
6698 // Okay, we decided that this is a safe thing to do: go ahead and start
6699 // inserting cast instructions as necessary...
6700 std::vector<Value*> Args;
6701 Args.reserve(NumActualArgs);
6702
6703 AI = CS.arg_begin();
6704 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
6705 const Type *ParamTy = FT->getParamType(i);
6706 if ((*AI)->getType() == ParamTy) {
6707 Args.push_back(*AI);
6708 } else {
Chris Lattner1c631e82004-04-08 04:43:23 +00006709 Args.push_back(InsertNewInstBefore(new CastInst(*AI, ParamTy, "tmp"),
6710 *Caller));
Chris Lattner970c33a2003-06-19 17:00:31 +00006711 }
6712 }
6713
6714 // If the function takes more arguments than the call was taking, add them
6715 // now...
6716 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
6717 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
6718
6719 // If we are removing arguments to the function, emit an obnoxious warning...
6720 if (FT->getNumParams() < NumActualArgs)
6721 if (!FT->isVarArg()) {
6722 std::cerr << "WARNING: While resolving call to function '"
6723 << Callee->getName() << "' arguments were dropped!\n";
6724 } else {
6725 // Add all of the arguments in their promoted form to the arg list...
6726 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
6727 const Type *PTy = getPromotedType((*AI)->getType());
6728 if (PTy != (*AI)->getType()) {
6729 // Must promote to pass through va_arg area!
6730 Instruction *Cast = new CastInst(*AI, PTy, "tmp");
6731 InsertNewInstBefore(Cast, *Caller);
6732 Args.push_back(Cast);
6733 } else {
6734 Args.push_back(*AI);
6735 }
6736 }
6737 }
6738
6739 if (FT->getReturnType() == Type::VoidTy)
6740 Caller->setName(""); // Void type should not have a name...
6741
6742 Instruction *NC;
6743 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Chris Lattnerfae8ab32004-02-08 21:44:31 +00006744 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
Chris Lattner970c33a2003-06-19 17:00:31 +00006745 Args, Caller->getName(), Caller);
Chris Lattner05c703e2005-05-14 12:25:32 +00006746 cast<InvokeInst>(II)->setCallingConv(II->getCallingConv());
Chris Lattner970c33a2003-06-19 17:00:31 +00006747 } else {
6748 NC = new CallInst(Callee, Args, Caller->getName(), Caller);
Chris Lattner6aacb0f2005-05-06 06:48:21 +00006749 if (cast<CallInst>(Caller)->isTailCall())
6750 cast<CallInst>(NC)->setTailCall();
Chris Lattner05c703e2005-05-14 12:25:32 +00006751 cast<CallInst>(NC)->setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Chris Lattner970c33a2003-06-19 17:00:31 +00006752 }
6753
6754 // Insert a cast of the return type as necessary...
6755 Value *NV = NC;
6756 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
6757 if (NV->getType() != Type::VoidTy) {
6758 NV = NC = new CastInst(NC, Caller->getType(), "tmp");
Chris Lattner686767f2003-10-30 00:46:41 +00006759
6760 // If this is an invoke instruction, we should insert it after the first
6761 // non-phi, instruction in the normal successor block.
6762 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
6763 BasicBlock::iterator I = II->getNormalDest()->begin();
6764 while (isa<PHINode>(I)) ++I;
6765 InsertNewInstBefore(NC, *I);
6766 } else {
6767 // Otherwise, it's a call, just insert cast right after the call instr
6768 InsertNewInstBefore(NC, *Caller);
6769 }
Chris Lattner51ea1272004-02-28 05:22:00 +00006770 AddUsersToWorkList(*Caller);
Chris Lattner970c33a2003-06-19 17:00:31 +00006771 } else {
Chris Lattnere29d6342004-10-17 21:22:38 +00006772 NV = UndefValue::get(Caller->getType());
Chris Lattner970c33a2003-06-19 17:00:31 +00006773 }
6774 }
6775
6776 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
6777 Caller->replaceAllUsesWith(NV);
6778 Caller->getParent()->getInstList().erase(Caller);
6779 removeFromWorkList(Caller);
6780 return true;
6781}
6782
Chris Lattnercadac0c2006-11-01 04:51:18 +00006783/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
6784/// and if a/b/c/d and the add's all have a single use, turn this into two phi's
6785/// and a single binop.
6786Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
6787 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
6788 assert(isa<BinaryOperator>(FirstInst) || isa<ShiftInst>(FirstInst));
6789 unsigned Opc = FirstInst->getOpcode();
Chris Lattnerdc826fc2006-11-01 04:55:47 +00006790 const Type *LHSType = FirstInst->getOperand(0)->getType();
Chris Lattnercadac0c2006-11-01 04:51:18 +00006791
6792 // Scan to see if all operands are the same opcode, all have one use, and all
6793 // kill their operands (i.e. the operands have one use).
Chris Lattnerdc826fc2006-11-01 04:55:47 +00006794 for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
Chris Lattnercadac0c2006-11-01 04:51:18 +00006795 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Chris Lattnerdc826fc2006-11-01 04:55:47 +00006796 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
6797 // Verify type of the LHS matches so we don't fold setcc's of different
6798 // types.
6799 I->getOperand(0)->getType() != LHSType)
Chris Lattnercadac0c2006-11-01 04:51:18 +00006800 return 0;
6801 }
6802
6803 // Otherwise, this is safe and profitable to transform. Create two phi nodes.
6804 PHINode *NewLHS = new PHINode(FirstInst->getOperand(0)->getType(),
6805 FirstInst->getOperand(0)->getName()+".pn");
6806 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
6807 PHINode *NewRHS = new PHINode(FirstInst->getOperand(1)->getType(),
6808 FirstInst->getOperand(1)->getName()+".pn");
6809 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
6810
6811 Value *InLHS = FirstInst->getOperand(0);
6812 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
6813 Value *InRHS = FirstInst->getOperand(1);
6814 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
6815
6816 // Add all operands to the new PHsI.
6817 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
6818 Value *NewInLHS = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
6819 Value *NewInRHS = cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
6820 if (NewInLHS != InLHS) InLHS = 0;
6821 if (NewInRHS != InRHS) InRHS = 0;
6822 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
6823 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
6824 }
6825
6826 InsertNewInstBefore(NewLHS, PN);
6827 InsertNewInstBefore(NewRHS, PN);
6828
6829 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
6830 return BinaryOperator::create(BinOp->getOpcode(), NewLHS, NewRHS);
6831 else
6832 return new ShiftInst(cast<ShiftInst>(FirstInst)->getOpcode(),
6833 NewLHS, NewRHS);
6834}
6835
Chris Lattner14f82c72006-11-01 07:13:54 +00006836/// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
6837/// of the block that defines it. This means that it must be obvious the value
6838/// of the load is not changed from the point of the load to the end of the
6839/// block it is in.
6840static bool isSafeToSinkLoad(LoadInst *L) {
6841 BasicBlock::iterator BBI = L, E = L->getParent()->end();
6842
6843 for (++BBI; BBI != E; ++BBI)
6844 if (BBI->mayWriteToMemory())
6845 return false;
6846 return true;
6847}
6848
Chris Lattner970c33a2003-06-19 17:00:31 +00006849
Chris Lattner7515cab2004-11-14 19:13:23 +00006850// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
6851// operator and they all are only used by the PHI, PHI together their
6852// inputs, and do the operation once, to the result of the PHI.
6853Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
6854 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
6855
6856 // Scan the instruction, looking for input operations that can be folded away.
6857 // If all input operands to the phi are the same instruction (e.g. a cast from
6858 // the same type or "+42") we can pull the operation through the PHI, reducing
6859 // code size and simplifying code.
6860 Constant *ConstantOp = 0;
6861 const Type *CastSrcTy = 0;
Chris Lattner14f82c72006-11-01 07:13:54 +00006862 bool isVolatile = false;
Chris Lattner7515cab2004-11-14 19:13:23 +00006863 if (isa<CastInst>(FirstInst)) {
6864 CastSrcTy = FirstInst->getOperand(0)->getType();
6865 } else if (isa<BinaryOperator>(FirstInst) || isa<ShiftInst>(FirstInst)) {
Chris Lattnercadac0c2006-11-01 04:51:18 +00006866 // Can fold binop or shift here if the RHS is a constant, otherwise call
6867 // FoldPHIArgBinOpIntoPHI.
Chris Lattner7515cab2004-11-14 19:13:23 +00006868 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Chris Lattnercadac0c2006-11-01 04:51:18 +00006869 if (ConstantOp == 0)
6870 return FoldPHIArgBinOpIntoPHI(PN);
Chris Lattner14f82c72006-11-01 07:13:54 +00006871 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
6872 isVolatile = LI->isVolatile();
6873 // We can't sink the load if the loaded value could be modified between the
6874 // load and the PHI.
6875 if (LI->getParent() != PN.getIncomingBlock(0) ||
6876 !isSafeToSinkLoad(LI))
6877 return 0;
Chris Lattner7515cab2004-11-14 19:13:23 +00006878 } else {
6879 return 0; // Cannot fold this operation.
6880 }
6881
6882 // Check to see if all arguments are the same operation.
6883 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
6884 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
6885 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
6886 if (!I->hasOneUse() || I->getOpcode() != FirstInst->getOpcode())
6887 return 0;
6888 if (CastSrcTy) {
6889 if (I->getOperand(0)->getType() != CastSrcTy)
6890 return 0; // Cast operation must match.
Chris Lattner14f82c72006-11-01 07:13:54 +00006891 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
6892 // We can't sink the load if the loaded value could be modified between the
6893 // load and the PHI.
6894 if (LI->isVolatile() != isVolatile ||
6895 LI->getParent() != PN.getIncomingBlock(i) ||
6896 !isSafeToSinkLoad(LI))
6897 return 0;
Chris Lattner7515cab2004-11-14 19:13:23 +00006898 } else if (I->getOperand(1) != ConstantOp) {
6899 return 0;
6900 }
6901 }
6902
6903 // Okay, they are all the same operation. Create a new PHI node of the
6904 // correct type, and PHI together all of the LHS's of the instructions.
6905 PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
6906 PN.getName()+".in");
Chris Lattnerd8e20182005-01-29 00:39:08 +00006907 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattner46dd5a62004-11-14 19:29:34 +00006908
6909 Value *InVal = FirstInst->getOperand(0);
6910 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattner7515cab2004-11-14 19:13:23 +00006911
6912 // Add all operands to the new PHI.
Chris Lattner46dd5a62004-11-14 19:29:34 +00006913 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
6914 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
6915 if (NewInVal != InVal)
6916 InVal = 0;
6917 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
6918 }
6919
6920 Value *PhiVal;
6921 if (InVal) {
6922 // The new PHI unions all of the same values together. This is really
6923 // common, so we handle it intelligently here for compile-time speed.
6924 PhiVal = InVal;
6925 delete NewPN;
6926 } else {
6927 InsertNewInstBefore(NewPN, PN);
6928 PhiVal = NewPN;
6929 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00006930
Chris Lattner7515cab2004-11-14 19:13:23 +00006931 // Insert and return the new operation.
6932 if (isa<CastInst>(FirstInst))
Chris Lattner46dd5a62004-11-14 19:29:34 +00006933 return new CastInst(PhiVal, PN.getType());
Chris Lattner14f82c72006-11-01 07:13:54 +00006934 else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst))
6935 return new LoadInst(PhiVal, "", isVolatile);
Chris Lattner7515cab2004-11-14 19:13:23 +00006936 else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattner46dd5a62004-11-14 19:29:34 +00006937 return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattner7515cab2004-11-14 19:13:23 +00006938 else
6939 return new ShiftInst(cast<ShiftInst>(FirstInst)->getOpcode(),
Chris Lattner46dd5a62004-11-14 19:29:34 +00006940 PhiVal, ConstantOp);
Chris Lattner7515cab2004-11-14 19:13:23 +00006941}
Chris Lattner48a44f72002-05-02 17:06:02 +00006942
Chris Lattner71536432005-01-17 05:10:15 +00006943/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
6944/// that is dead.
6945static bool DeadPHICycle(PHINode *PN, std::set<PHINode*> &PotentiallyDeadPHIs) {
6946 if (PN->use_empty()) return true;
6947 if (!PN->hasOneUse()) return false;
6948
6949 // Remember this node, and if we find the cycle, return.
6950 if (!PotentiallyDeadPHIs.insert(PN).second)
6951 return true;
6952
6953 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
6954 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanb1c93172005-04-21 23:48:37 +00006955
Chris Lattner71536432005-01-17 05:10:15 +00006956 return false;
6957}
6958
Chris Lattnerbbbdd852002-05-06 18:06:38 +00006959// PHINode simplification
6960//
Chris Lattner113f4f42002-06-25 16:13:24 +00006961Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonbbf89902006-07-10 22:15:25 +00006962 // If LCSSA is around, don't mess with Phi nodes
6963 if (mustPreserveAnalysisID(LCSSAID)) return 0;
Owen Andersona6968f82006-07-10 19:03:49 +00006964
Owen Andersonae8aa642006-07-10 22:03:18 +00006965 if (Value *V = PN.hasConstantValue())
6966 return ReplaceInstUsesWith(PN, V);
6967
6968 // If the only user of this instruction is a cast instruction, and all of the
6969 // incoming values are constants, change this PHI to merge together the casted
6970 // constants.
6971 if (PN.hasOneUse())
6972 if (CastInst *CI = dyn_cast<CastInst>(PN.use_back()))
6973 if (CI->getType() != PN.getType()) { // noop casts will be folded
6974 bool AllConstant = true;
6975 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
6976 if (!isa<Constant>(PN.getIncomingValue(i))) {
6977 AllConstant = false;
6978 break;
6979 }
6980 if (AllConstant) {
6981 // Make a new PHI with all casted values.
6982 PHINode *New = new PHINode(CI->getType(), PN.getName(), &PN);
6983 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
6984 Constant *OldArg = cast<Constant>(PN.getIncomingValue(i));
6985 New->addIncoming(ConstantExpr::getCast(OldArg, New->getType()),
6986 PN.getIncomingBlock(i));
6987 }
6988
6989 // Update the cast instruction.
6990 CI->setOperand(0, New);
6991 WorkList.push_back(CI); // revisit the cast instruction to fold.
6992 WorkList.push_back(New); // Make sure to revisit the new Phi
6993 return &PN; // PN is now dead!
6994 }
6995 }
6996
6997 // If all PHI operands are the same operation, pull them through the PHI,
6998 // reducing code size.
6999 if (isa<Instruction>(PN.getIncomingValue(0)) &&
7000 PN.getIncomingValue(0)->hasOneUse())
7001 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
7002 return Result;
7003
7004 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
7005 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
7006 // PHI)... break the cycle.
7007 if (PN.hasOneUse())
7008 if (PHINode *PU = dyn_cast<PHINode>(PN.use_back())) {
7009 std::set<PHINode*> PotentiallyDeadPHIs;
7010 PotentiallyDeadPHIs.insert(&PN);
7011 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
7012 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
7013 }
7014
Chris Lattner91daeb52003-12-19 05:58:40 +00007015 return 0;
Chris Lattnerbbbdd852002-05-06 18:06:38 +00007016}
7017
Chris Lattner69193f92004-04-05 01:30:19 +00007018static Value *InsertSignExtendToPtrTy(Value *V, const Type *DTy,
7019 Instruction *InsertPoint,
7020 InstCombiner *IC) {
7021 unsigned PS = IC->getTargetData().getPointerSize();
7022 const Type *VTy = V->getType();
Chris Lattner69193f92004-04-05 01:30:19 +00007023 if (!VTy->isSigned() && VTy->getPrimitiveSize() < PS)
7024 // We must insert a cast to ensure we sign-extend.
Reid Spencer00c482b2006-10-26 19:19:06 +00007025 V = IC->InsertCastBefore(V, VTy->getSignedVersion(), *InsertPoint);
7026 return IC->InsertCastBefore(V, DTy, *InsertPoint);
Chris Lattner69193f92004-04-05 01:30:19 +00007027}
7028
Chris Lattner48a44f72002-05-02 17:06:02 +00007029
Chris Lattner113f4f42002-06-25 16:13:24 +00007030Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner5f667a62004-05-07 22:09:22 +00007031 Value *PtrOp = GEP.getOperand(0);
Chris Lattner471bd762003-05-22 19:07:21 +00007032 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
Chris Lattner113f4f42002-06-25 16:13:24 +00007033 // If so, eliminate the noop.
Chris Lattner8d0bacb2004-02-22 05:25:17 +00007034 if (GEP.getNumOperands() == 1)
Chris Lattner5f667a62004-05-07 22:09:22 +00007035 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner8d0bacb2004-02-22 05:25:17 +00007036
Chris Lattner81a7a232004-10-16 18:11:37 +00007037 if (isa<UndefValue>(GEP.getOperand(0)))
7038 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
7039
Chris Lattner8d0bacb2004-02-22 05:25:17 +00007040 bool HasZeroPointerIndex = false;
7041 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
7042 HasZeroPointerIndex = C->isNullValue();
7043
7044 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner5f667a62004-05-07 22:09:22 +00007045 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner48a44f72002-05-02 17:06:02 +00007046
Chris Lattner69193f92004-04-05 01:30:19 +00007047 // Eliminate unneeded casts for indices.
7048 bool MadeChange = false;
Chris Lattner2b2412d2004-04-07 18:38:20 +00007049 gep_type_iterator GTI = gep_type_begin(GEP);
7050 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI)
7051 if (isa<SequentialType>(*GTI)) {
7052 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
7053 Value *Src = CI->getOperand(0);
7054 const Type *SrcTy = Src->getType();
7055 const Type *DestTy = CI->getType();
7056 if (Src->getType()->isInteger()) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00007057 if (SrcTy->getPrimitiveSizeInBits() ==
7058 DestTy->getPrimitiveSizeInBits()) {
Chris Lattner2b2412d2004-04-07 18:38:20 +00007059 // We can always eliminate a cast from ulong or long to the other.
7060 // We can always eliminate a cast from uint to int or the other on
7061 // 32-bit pointer platforms.
Chris Lattnerd1f46d32005-04-24 06:59:08 +00007062 if (DestTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()){
Chris Lattner2b2412d2004-04-07 18:38:20 +00007063 MadeChange = true;
7064 GEP.setOperand(i, Src);
7065 }
7066 } else if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
7067 SrcTy->getPrimitiveSize() == 4) {
7068 // We can always eliminate a cast from int to [u]long. We can
7069 // eliminate a cast from uint to [u]long iff the target is a 32-bit
7070 // pointer target.
Misha Brukmanb1c93172005-04-21 23:48:37 +00007071 if (SrcTy->isSigned() ||
Chris Lattnerd1f46d32005-04-24 06:59:08 +00007072 SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
Chris Lattner2b2412d2004-04-07 18:38:20 +00007073 MadeChange = true;
7074 GEP.setOperand(i, Src);
7075 }
Chris Lattner69193f92004-04-05 01:30:19 +00007076 }
7077 }
7078 }
Chris Lattner2b2412d2004-04-07 18:38:20 +00007079 // If we are using a wider index than needed for this platform, shrink it
7080 // to what we need. If the incoming value needs a cast instruction,
7081 // insert it. This explicit cast can make subsequent optimizations more
7082 // obvious.
7083 Value *Op = GEP.getOperand(i);
7084 if (Op->getType()->getPrimitiveSize() > TD->getPointerSize())
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00007085 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner44d0b952004-07-20 01:48:15 +00007086 GEP.setOperand(i, ConstantExpr::getCast(C,
7087 TD->getIntPtrType()->getSignedVersion()));
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00007088 MadeChange = true;
7089 } else {
Reid Spencer00c482b2006-10-26 19:19:06 +00007090 Op = InsertCastBefore(Op, TD->getIntPtrType(), GEP);
Chris Lattner2b2412d2004-04-07 18:38:20 +00007091 GEP.setOperand(i, Op);
7092 MadeChange = true;
7093 }
Chris Lattner44d0b952004-07-20 01:48:15 +00007094
7095 // If this is a constant idx, make sure to canonicalize it to be a signed
7096 // operand, otherwise CSE and other optimizations are pessimized.
Reid Spencere0fc4df2006-10-20 07:07:24 +00007097 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op))
7098 if (CUI->getType()->isUnsigned()) {
7099 GEP.setOperand(i,
7100 ConstantExpr::getCast(CUI, CUI->getType()->getSignedVersion()));
7101 MadeChange = true;
7102 }
Chris Lattner69193f92004-04-05 01:30:19 +00007103 }
7104 if (MadeChange) return &GEP;
7105
Chris Lattnerae7a0d32002-08-02 19:29:35 +00007106 // Combine Indices - If the source pointer to this getelementptr instruction
7107 // is a getelementptr instruction, combine the indices of the two
7108 // getelementptr instructions into a single instruction.
7109 //
Chris Lattner57c67b02004-03-25 22:59:29 +00007110 std::vector<Value*> SrcGEPOperands;
Chris Lattner0798af32005-01-13 20:14:25 +00007111 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattner57c67b02004-03-25 22:59:29 +00007112 SrcGEPOperands.assign(Src->op_begin(), Src->op_end());
Chris Lattner57c67b02004-03-25 22:59:29 +00007113
7114 if (!SrcGEPOperands.empty()) {
Chris Lattner5f667a62004-05-07 22:09:22 +00007115 // Note that if our source is a gep chain itself that we wait for that
7116 // chain to be resolved before we perform this transformation. This
7117 // avoids us creating a TON of code in some cases.
7118 //
7119 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
7120 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
7121 return 0; // Wait until our source is folded to completion.
7122
Chris Lattnerae7a0d32002-08-02 19:29:35 +00007123 std::vector<Value *> Indices;
Chris Lattner5f667a62004-05-07 22:09:22 +00007124
7125 // Find out whether the last index in the source GEP is a sequential idx.
7126 bool EndsWithSequential = false;
7127 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
7128 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattner8ec5f882004-05-08 22:41:42 +00007129 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00007130
Chris Lattnerae7a0d32002-08-02 19:29:35 +00007131 // Can we combine the two pointer arithmetics offsets?
Chris Lattner5f667a62004-05-07 22:09:22 +00007132 if (EndsWithSequential) {
Chris Lattner235af562003-03-05 22:33:14 +00007133 // Replace: gep (gep %P, long B), long A, ...
7134 // With: T = long A+B; gep %P, T, ...
7135 //
Chris Lattner5f667a62004-05-07 22:09:22 +00007136 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner69193f92004-04-05 01:30:19 +00007137 if (SO1 == Constant::getNullValue(SO1->getType())) {
7138 Sum = GO1;
7139 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
7140 Sum = SO1;
7141 } else {
7142 // If they aren't the same type, convert both to an integer of the
7143 // target's pointer size.
7144 if (SO1->getType() != GO1->getType()) {
7145 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
7146 SO1 = ConstantExpr::getCast(SO1C, GO1->getType());
7147 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
7148 GO1 = ConstantExpr::getCast(GO1C, SO1->getType());
7149 } else {
7150 unsigned PS = TD->getPointerSize();
Chris Lattner69193f92004-04-05 01:30:19 +00007151 if (SO1->getType()->getPrimitiveSize() == PS) {
7152 // Convert GO1 to SO1's type.
7153 GO1 = InsertSignExtendToPtrTy(GO1, SO1->getType(), &GEP, this);
7154
7155 } else if (GO1->getType()->getPrimitiveSize() == PS) {
7156 // Convert SO1 to GO1's type.
7157 SO1 = InsertSignExtendToPtrTy(SO1, GO1->getType(), &GEP, this);
7158 } else {
7159 const Type *PT = TD->getIntPtrType();
7160 SO1 = InsertSignExtendToPtrTy(SO1, PT, &GEP, this);
7161 GO1 = InsertSignExtendToPtrTy(GO1, PT, &GEP, this);
7162 }
7163 }
7164 }
Chris Lattner5f667a62004-05-07 22:09:22 +00007165 if (isa<Constant>(SO1) && isa<Constant>(GO1))
7166 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
7167 else {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00007168 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
7169 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner5f667a62004-05-07 22:09:22 +00007170 }
Chris Lattner69193f92004-04-05 01:30:19 +00007171 }
Chris Lattner5f667a62004-05-07 22:09:22 +00007172
7173 // Recycle the GEP we already have if possible.
7174 if (SrcGEPOperands.size() == 2) {
7175 GEP.setOperand(0, SrcGEPOperands[0]);
7176 GEP.setOperand(1, Sum);
7177 return &GEP;
7178 } else {
7179 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
7180 SrcGEPOperands.end()-1);
7181 Indices.push_back(Sum);
7182 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
7183 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00007184 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner69193f92004-04-05 01:30:19 +00007185 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00007186 SrcGEPOperands.size() != 1) {
Chris Lattnerae7a0d32002-08-02 19:29:35 +00007187 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattner57c67b02004-03-25 22:59:29 +00007188 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
7189 SrcGEPOperands.end());
Chris Lattnerae7a0d32002-08-02 19:29:35 +00007190 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
7191 }
7192
7193 if (!Indices.empty())
Chris Lattner57c67b02004-03-25 22:59:29 +00007194 return new GetElementPtrInst(SrcGEPOperands[0], Indices, GEP.getName());
Chris Lattnerc59af1d2002-08-17 22:21:59 +00007195
Chris Lattner5f667a62004-05-07 22:09:22 +00007196 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattnerc59af1d2002-08-17 22:21:59 +00007197 // GEP of global variable. If all of the indices for this GEP are
7198 // constants, we can promote this to a constexpr instead of an instruction.
7199
7200 // Scan for nonconstants...
7201 std::vector<Constant*> Indices;
7202 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
7203 for (; I != E && isa<Constant>(*I); ++I)
7204 Indices.push_back(cast<Constant>(*I));
7205
7206 if (I == E) { // If they are all constants...
Chris Lattnerf3edc492004-07-18 18:59:44 +00007207 Constant *CE = ConstantExpr::getGetElementPtr(GV, Indices);
Chris Lattnerc59af1d2002-08-17 22:21:59 +00007208
7209 // Replace all uses of the GEP with the new constexpr...
7210 return ReplaceInstUsesWith(GEP, CE);
7211 }
Chris Lattner567b81f2005-09-13 00:40:14 +00007212 } else if (Value *X = isCast(PtrOp)) { // Is the operand a cast?
7213 if (!isa<PointerType>(X->getType())) {
7214 // Not interesting. Source pointer must be a cast from pointer.
7215 } else if (HasZeroPointerIndex) {
7216 // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
7217 // into : GEP [10 x ubyte]* X, long 0, ...
7218 //
7219 // This occurs when the program declares an array extern like "int X[];"
7220 //
7221 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
7222 const PointerType *XTy = cast<PointerType>(X->getType());
7223 if (const ArrayType *XATy =
7224 dyn_cast<ArrayType>(XTy->getElementType()))
7225 if (const ArrayType *CATy =
7226 dyn_cast<ArrayType>(CPTy->getElementType()))
7227 if (CATy->getElementType() == XATy->getElementType()) {
7228 // At this point, we know that the cast source type is a pointer
7229 // to an array of the same type as the destination pointer
7230 // array. Because the array type is never stepped over (there
7231 // is a leading zero) we can fold the cast into this GEP.
7232 GEP.setOperand(0, X);
7233 return &GEP;
7234 }
7235 } else if (GEP.getNumOperands() == 2) {
7236 // Transform things like:
Chris Lattner2a893292005-09-13 18:36:04 +00007237 // %t = getelementptr ubyte* cast ([2 x int]* %str to uint*), uint %V
7238 // into: %t1 = getelementptr [2 x int*]* %str, int 0, uint %V; cast
Chris Lattner567b81f2005-09-13 00:40:14 +00007239 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
7240 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
7241 if (isa<ArrayType>(SrcElTy) &&
7242 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
7243 TD->getTypeSize(ResElTy)) {
7244 Value *V = InsertNewInstBefore(
7245 new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
7246 GEP.getOperand(1), GEP.getName()), GEP);
7247 return new CastInst(V, GEP.getType());
Chris Lattner8d0bacb2004-02-22 05:25:17 +00007248 }
Chris Lattner2a893292005-09-13 18:36:04 +00007249
7250 // Transform things like:
7251 // getelementptr sbyte* cast ([100 x double]* X to sbyte*), int %tmp
7252 // (where tmp = 8*tmp2) into:
7253 // getelementptr [100 x double]* %arr, int 0, int %tmp.2
7254
7255 if (isa<ArrayType>(SrcElTy) &&
7256 (ResElTy == Type::SByteTy || ResElTy == Type::UByteTy)) {
7257 uint64_t ArrayEltSize =
7258 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType());
7259
7260 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
7261 // allow either a mul, shift, or constant here.
7262 Value *NewIdx = 0;
7263 ConstantInt *Scale = 0;
7264 if (ArrayEltSize == 1) {
7265 NewIdx = GEP.getOperand(1);
7266 Scale = ConstantInt::get(NewIdx->getType(), 1);
7267 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Chris Lattnera393e4d2005-09-14 17:32:56 +00007268 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner2a893292005-09-13 18:36:04 +00007269 Scale = CI;
7270 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
7271 if (Inst->getOpcode() == Instruction::Shl &&
7272 isa<ConstantInt>(Inst->getOperand(1))) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00007273 unsigned ShAmt =
7274 cast<ConstantInt>(Inst->getOperand(1))->getZExtValue();
Chris Lattner2a893292005-09-13 18:36:04 +00007275 if (Inst->getType()->isSigned())
Reid Spencere0fc4df2006-10-20 07:07:24 +00007276 Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmt);
Chris Lattner2a893292005-09-13 18:36:04 +00007277 else
Reid Spencere0fc4df2006-10-20 07:07:24 +00007278 Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmt);
Chris Lattner2a893292005-09-13 18:36:04 +00007279 NewIdx = Inst->getOperand(0);
7280 } else if (Inst->getOpcode() == Instruction::Mul &&
7281 isa<ConstantInt>(Inst->getOperand(1))) {
7282 Scale = cast<ConstantInt>(Inst->getOperand(1));
7283 NewIdx = Inst->getOperand(0);
7284 }
7285 }
7286
7287 // If the index will be to exactly the right offset with the scale taken
7288 // out, perform the transformation.
Reid Spencere0fc4df2006-10-20 07:07:24 +00007289 if (Scale && Scale->getZExtValue() % ArrayEltSize == 0) {
7290 if (ConstantInt *C = dyn_cast<ConstantInt>(Scale))
7291 Scale = ConstantInt::get(Scale->getType(),
7292 Scale->getZExtValue() / ArrayEltSize);
7293 if (Scale->getZExtValue() != 1) {
Chris Lattner2a893292005-09-13 18:36:04 +00007294 Constant *C = ConstantExpr::getCast(Scale, NewIdx->getType());
7295 Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
7296 NewIdx = InsertNewInstBefore(Sc, GEP);
7297 }
7298
7299 // Insert the new GEP instruction.
7300 Instruction *Idx =
7301 new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
7302 NewIdx, GEP.getName());
7303 Idx = InsertNewInstBefore(Idx, GEP);
7304 return new CastInst(Idx, GEP.getType());
7305 }
7306 }
Chris Lattner8d0bacb2004-02-22 05:25:17 +00007307 }
Chris Lattnerca081252001-12-14 16:52:21 +00007308 }
7309
Chris Lattnerca081252001-12-14 16:52:21 +00007310 return 0;
7311}
7312
Chris Lattner1085bdf2002-11-04 16:18:53 +00007313Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
7314 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
7315 if (AI.isArrayAllocation()) // Check C != 1
Reid Spencere0fc4df2006-10-20 07:07:24 +00007316 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
7317 const Type *NewTy =
7318 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Chris Lattnera2620ac2002-11-09 00:49:43 +00007319 AllocationInst *New = 0;
Chris Lattner1085bdf2002-11-04 16:18:53 +00007320
7321 // Create and insert the replacement instruction...
7322 if (isa<MallocInst>(AI))
Nate Begeman848622f2005-11-05 09:21:28 +00007323 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00007324 else {
7325 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Nate Begeman848622f2005-11-05 09:21:28 +00007326 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00007327 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00007328
7329 InsertNewInstBefore(New, AI);
Misha Brukmanb1c93172005-04-21 23:48:37 +00007330
Chris Lattner1085bdf2002-11-04 16:18:53 +00007331 // Scan to the end of the allocation instructions, to skip over a block of
7332 // allocas if possible...
7333 //
7334 BasicBlock::iterator It = New;
7335 while (isa<AllocationInst>(*It)) ++It;
7336
7337 // Now that I is pointing to the first non-allocation-inst in the block,
7338 // insert our getelementptr instruction...
7339 //
Chris Lattner809dfac2005-05-04 19:10:26 +00007340 Value *NullIdx = Constant::getNullValue(Type::IntTy);
7341 Value *V = new GetElementPtrInst(New, NullIdx, NullIdx,
7342 New->getName()+".sub", It);
Chris Lattner1085bdf2002-11-04 16:18:53 +00007343
7344 // Now make everything use the getelementptr instead of the original
7345 // allocation.
Chris Lattnerabb77c92004-03-19 06:08:10 +00007346 return ReplaceInstUsesWith(AI, V);
Chris Lattner81a7a232004-10-16 18:11:37 +00007347 } else if (isa<UndefValue>(AI.getArraySize())) {
7348 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner1085bdf2002-11-04 16:18:53 +00007349 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00007350
7351 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
7352 // Note that we only do this for alloca's, because malloc should allocate and
7353 // return a unique pointer, even for a zero byte allocation.
Misha Brukmanb1c93172005-04-21 23:48:37 +00007354 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
Chris Lattner49df6ce2004-07-02 22:55:47 +00007355 TD->getTypeSize(AI.getAllocatedType()) == 0)
Chris Lattnerabb77c92004-03-19 06:08:10 +00007356 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
7357
Chris Lattner1085bdf2002-11-04 16:18:53 +00007358 return 0;
7359}
7360
Chris Lattner8427bff2003-12-07 01:24:23 +00007361Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
7362 Value *Op = FI.getOperand(0);
7363
7364 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
7365 if (CastInst *CI = dyn_cast<CastInst>(Op))
7366 if (isa<PointerType>(CI->getOperand(0)->getType())) {
7367 FI.setOperand(0, CI->getOperand(0));
7368 return &FI;
7369 }
7370
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007371 // free undef -> unreachable.
7372 if (isa<UndefValue>(Op)) {
7373 // Insert a new store to null because we cannot modify the CFG here.
Chris Lattner6ab03f62006-09-28 23:35:22 +00007374 new StoreInst(ConstantBool::getTrue(),
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007375 UndefValue::get(PointerType::get(Type::BoolTy)), &FI);
7376 return EraseInstFromFunction(FI);
7377 }
7378
Chris Lattnerf3a36602004-02-28 04:57:37 +00007379 // If we have 'free null' delete the instruction. This can happen in stl code
7380 // when lots of inlining happens.
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007381 if (isa<ConstantPointerNull>(Op))
Chris Lattner51ea1272004-02-28 05:22:00 +00007382 return EraseInstFromFunction(FI);
Chris Lattnerf3a36602004-02-28 04:57:37 +00007383
Chris Lattner8427bff2003-12-07 01:24:23 +00007384 return 0;
7385}
7386
7387
Chris Lattner72684fe2005-01-31 05:51:45 +00007388/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Chris Lattner35e24772004-07-13 01:49:43 +00007389static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
7390 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00007391 Value *CastOp = CI->getOperand(0);
Chris Lattner35e24772004-07-13 01:49:43 +00007392
7393 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00007394 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Chris Lattner35e24772004-07-13 01:49:43 +00007395 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00007396
Chris Lattnerebca4762006-04-02 05:37:12 +00007397 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
7398 isa<PackedType>(DestPTy)) {
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00007399 // If the source is an array, the code below will not succeed. Check to
7400 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
7401 // constants.
7402 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
7403 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
7404 if (ASrcTy->getNumElements() != 0) {
7405 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
7406 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
7407 SrcTy = cast<PointerType>(CastOp->getType());
7408 SrcPTy = SrcTy->getElementType();
7409 }
7410
Chris Lattnerebca4762006-04-02 05:37:12 +00007411 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
7412 isa<PackedType>(SrcPTy)) &&
Chris Lattnerecfa9b52005-03-29 06:37:47 +00007413 // Do not allow turning this into a load of an integer, which is then
7414 // casted to a pointer, this pessimizes pointer analysis a lot.
7415 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00007416 IC.getTargetData().getTypeSize(SrcPTy) ==
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00007417 IC.getTargetData().getTypeSize(DestPTy)) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00007418
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00007419 // Okay, we are casting from one integer or pointer type to another of
7420 // the same size. Instead of casting the pointer before the load, cast
7421 // the result of the loaded value.
7422 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
7423 CI->getName(),
7424 LI.isVolatile()),LI);
7425 // Now cast the result of the load.
7426 return new CastInst(NewLoad, LI.getType());
7427 }
Chris Lattner35e24772004-07-13 01:49:43 +00007428 }
7429 }
7430 return 0;
7431}
7432
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00007433/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattnere6f13092004-09-19 19:18:10 +00007434/// from this value cannot trap. If it is not obviously safe to load from the
7435/// specified pointer, we do a quick local scan of the basic block containing
7436/// ScanFrom, to determine if the address is already accessed.
7437static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
7438 // If it is an alloca or global variable, it is always safe to load from.
7439 if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
7440
7441 // Otherwise, be a little bit agressive by scanning the local block where we
7442 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00007443 // from/to. If so, the previous load or store would have already trapped,
7444 // so there is no harm doing an extra load (also, CSE will later eliminate
7445 // the load entirely).
Chris Lattnere6f13092004-09-19 19:18:10 +00007446 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
7447
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00007448 while (BBI != E) {
Chris Lattnere6f13092004-09-19 19:18:10 +00007449 --BBI;
7450
7451 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
7452 if (LI->getOperand(0) == V) return true;
7453 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
7454 if (SI->getOperand(1) == V) return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +00007455
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00007456 }
Chris Lattnere6f13092004-09-19 19:18:10 +00007457 return false;
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00007458}
7459
Chris Lattner0f1d8a32003-06-26 05:06:25 +00007460Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
7461 Value *Op = LI.getOperand(0);
Chris Lattner7e8af382004-01-12 04:13:56 +00007462
Chris Lattnera9d84e32005-05-01 04:24:53 +00007463 // load (cast X) --> cast (load X) iff safe
7464 if (CastInst *CI = dyn_cast<CastInst>(Op))
7465 if (Instruction *Res = InstCombineLoadCast(*this, LI))
7466 return Res;
7467
7468 // None of the following transforms are legal for volatile loads.
7469 if (LI.isVolatile()) return 0;
Chris Lattnerb990f7d2005-09-12 22:00:15 +00007470
Chris Lattnerb990f7d2005-09-12 22:00:15 +00007471 if (&LI.getParent()->front() != &LI) {
7472 BasicBlock::iterator BBI = &LI; --BBI;
Chris Lattnere0bfdf12005-09-12 22:21:03 +00007473 // If the instruction immediately before this is a store to the same
7474 // address, do a simple form of store->load forwarding.
Chris Lattnerb990f7d2005-09-12 22:00:15 +00007475 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
7476 if (SI->getOperand(1) == LI.getOperand(0))
7477 return ReplaceInstUsesWith(LI, SI->getOperand(0));
Chris Lattnere0bfdf12005-09-12 22:21:03 +00007478 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
7479 if (LIB->getOperand(0) == LI.getOperand(0))
7480 return ReplaceInstUsesWith(LI, LIB);
Chris Lattnerb990f7d2005-09-12 22:00:15 +00007481 }
Chris Lattnera9d84e32005-05-01 04:24:53 +00007482
7483 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op))
7484 if (isa<ConstantPointerNull>(GEPI->getOperand(0)) ||
7485 isa<UndefValue>(GEPI->getOperand(0))) {
7486 // Insert a new store to null instruction before the load to indicate
7487 // that this code is not reachable. We do this instead of inserting
7488 // an unreachable instruction directly because we cannot modify the
7489 // CFG.
7490 new StoreInst(UndefValue::get(LI.getType()),
7491 Constant::getNullValue(Op->getType()), &LI);
7492 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
7493 }
7494
Chris Lattner81a7a232004-10-16 18:11:37 +00007495 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattnera9d84e32005-05-01 04:24:53 +00007496 // load null/undef -> undef
7497 if ((C->isNullValue() || isa<UndefValue>(C))) {
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007498 // Insert a new store to null instruction before the load to indicate that
7499 // this code is not reachable. We do this instead of inserting an
7500 // unreachable instruction directly because we cannot modify the CFG.
Chris Lattnera9d84e32005-05-01 04:24:53 +00007501 new StoreInst(UndefValue::get(LI.getType()),
7502 Constant::getNullValue(Op->getType()), &LI);
Chris Lattner81a7a232004-10-16 18:11:37 +00007503 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007504 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00007505
Chris Lattner81a7a232004-10-16 18:11:37 +00007506 // Instcombine load (constant global) into the value loaded.
7507 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
7508 if (GV->isConstant() && !GV->isExternal())
7509 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanb1c93172005-04-21 23:48:37 +00007510
Chris Lattner81a7a232004-10-16 18:11:37 +00007511 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
7512 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
7513 if (CE->getOpcode() == Instruction::GetElementPtr) {
7514 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
7515 if (GV->isConstant() && !GV->isExternal())
Chris Lattner0b011ec2005-09-26 05:28:06 +00007516 if (Constant *V =
7517 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
Chris Lattner81a7a232004-10-16 18:11:37 +00007518 return ReplaceInstUsesWith(LI, V);
Chris Lattnera9d84e32005-05-01 04:24:53 +00007519 if (CE->getOperand(0)->isNullValue()) {
7520 // Insert a new store to null instruction before the load to indicate
7521 // that this code is not reachable. We do this instead of inserting
7522 // an unreachable instruction directly because we cannot modify the
7523 // CFG.
7524 new StoreInst(UndefValue::get(LI.getType()),
7525 Constant::getNullValue(Op->getType()), &LI);
7526 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
7527 }
7528
Chris Lattner81a7a232004-10-16 18:11:37 +00007529 } else if (CE->getOpcode() == Instruction::Cast) {
7530 if (Instruction *Res = InstCombineLoadCast(*this, LI))
7531 return Res;
7532 }
7533 }
Chris Lattnere228ee52004-04-08 20:39:49 +00007534
Chris Lattnera9d84e32005-05-01 04:24:53 +00007535 if (Op->hasOneUse()) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00007536 // Change select and PHI nodes to select values instead of addresses: this
7537 // helps alias analysis out a lot, allows many others simplifications, and
7538 // exposes redundancy in the code.
7539 //
7540 // Note that we cannot do the transformation unless we know that the
7541 // introduced loads cannot trap! Something like this is valid as long as
7542 // the condition is always false: load (select bool %C, int* null, int* %G),
7543 // but it would not be valid if we transformed it to load from null
7544 // unconditionally.
7545 //
7546 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
7547 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattnere6f13092004-09-19 19:18:10 +00007548 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
7549 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00007550 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner42618552004-09-20 10:15:10 +00007551 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00007552 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner42618552004-09-20 10:15:10 +00007553 SI->getOperand(2)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00007554 return new SelectInst(SI->getCondition(), V1, V2);
7555 }
7556
Chris Lattnerbdcf41a2004-09-23 15:46:00 +00007557 // load (select (cond, null, P)) -> load P
7558 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
7559 if (C->isNullValue()) {
7560 LI.setOperand(0, SI->getOperand(2));
7561 return &LI;
7562 }
7563
7564 // load (select (cond, P, null)) -> load P
7565 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
7566 if (C->isNullValue()) {
7567 LI.setOperand(0, SI->getOperand(1));
7568 return &LI;
7569 }
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00007570 }
7571 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00007572 return 0;
7573}
7574
Chris Lattner72684fe2005-01-31 05:51:45 +00007575/// InstCombineStoreToCast - Fold 'store V, (cast P)' -> store (cast V), P'
7576/// when possible.
7577static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
7578 User *CI = cast<User>(SI.getOperand(1));
7579 Value *CastOp = CI->getOperand(0);
7580
7581 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
7582 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
7583 const Type *SrcPTy = SrcTy->getElementType();
7584
7585 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
7586 // If the source is an array, the code below will not succeed. Check to
7587 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
7588 // constants.
7589 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
7590 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
7591 if (ASrcTy->getNumElements() != 0) {
7592 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
7593 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
7594 SrcTy = cast<PointerType>(CastOp->getType());
7595 SrcPTy = SrcTy->getElementType();
7596 }
7597
7598 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00007599 IC.getTargetData().getTypeSize(SrcPTy) ==
Chris Lattner72684fe2005-01-31 05:51:45 +00007600 IC.getTargetData().getTypeSize(DestPTy)) {
7601
7602 // Okay, we are casting from one integer or pointer type to another of
7603 // the same size. Instead of casting the pointer before the store, cast
7604 // the value to be stored.
7605 Value *NewCast;
7606 if (Constant *C = dyn_cast<Constant>(SI.getOperand(0)))
7607 NewCast = ConstantExpr::getCast(C, SrcPTy);
7608 else
7609 NewCast = IC.InsertNewInstBefore(new CastInst(SI.getOperand(0),
7610 SrcPTy,
7611 SI.getOperand(0)->getName()+".c"), SI);
7612
7613 return new StoreInst(NewCast, CastOp);
7614 }
7615 }
7616 }
7617 return 0;
7618}
7619
Chris Lattner31f486c2005-01-31 05:36:43 +00007620Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
7621 Value *Val = SI.getOperand(0);
7622 Value *Ptr = SI.getOperand(1);
7623
7624 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner5997cf92006-02-08 03:25:32 +00007625 EraseInstFromFunction(SI);
Chris Lattner31f486c2005-01-31 05:36:43 +00007626 ++NumCombined;
7627 return 0;
7628 }
7629
Chris Lattner5997cf92006-02-08 03:25:32 +00007630 // Do really simple DSE, to catch cases where there are several consequtive
7631 // stores to the same location, separated by a few arithmetic operations. This
7632 // situation often occurs with bitfield accesses.
7633 BasicBlock::iterator BBI = &SI;
7634 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
7635 --ScanInsts) {
7636 --BBI;
7637
7638 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
7639 // Prev store isn't volatile, and stores to the same location?
7640 if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
7641 ++NumDeadStore;
7642 ++BBI;
7643 EraseInstFromFunction(*PrevSI);
7644 continue;
7645 }
7646 break;
7647 }
7648
Chris Lattnerdab43b22006-05-26 19:19:20 +00007649 // If this is a load, we have to stop. However, if the loaded value is from
7650 // the pointer we're loading and is producing the pointer we're storing,
7651 // then *this* store is dead (X = load P; store X -> P).
7652 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
7653 if (LI == Val && LI->getOperand(0) == Ptr) {
7654 EraseInstFromFunction(SI);
7655 ++NumCombined;
7656 return 0;
7657 }
7658 // Otherwise, this is a load from some other location. Stores before it
7659 // may not be dead.
7660 break;
7661 }
7662
Chris Lattner5997cf92006-02-08 03:25:32 +00007663 // Don't skip over loads or things that can modify memory.
Chris Lattnerdab43b22006-05-26 19:19:20 +00007664 if (BBI->mayWriteToMemory())
Chris Lattner5997cf92006-02-08 03:25:32 +00007665 break;
7666 }
7667
7668
7669 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner31f486c2005-01-31 05:36:43 +00007670
7671 // store X, null -> turns into 'unreachable' in SimplifyCFG
7672 if (isa<ConstantPointerNull>(Ptr)) {
7673 if (!isa<UndefValue>(Val)) {
7674 SI.setOperand(0, UndefValue::get(Val->getType()));
7675 if (Instruction *U = dyn_cast<Instruction>(Val))
7676 WorkList.push_back(U); // Dropped a use.
7677 ++NumCombined;
7678 }
7679 return 0; // Do not modify these!
7680 }
7681
7682 // store undef, Ptr -> noop
7683 if (isa<UndefValue>(Val)) {
Chris Lattner5997cf92006-02-08 03:25:32 +00007684 EraseInstFromFunction(SI);
Chris Lattner31f486c2005-01-31 05:36:43 +00007685 ++NumCombined;
7686 return 0;
7687 }
7688
Chris Lattner72684fe2005-01-31 05:51:45 +00007689 // If the pointer destination is a cast, see if we can fold the cast into the
7690 // source instead.
7691 if (CastInst *CI = dyn_cast<CastInst>(Ptr))
7692 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
7693 return Res;
7694 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
7695 if (CE->getOpcode() == Instruction::Cast)
7696 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
7697 return Res;
7698
Chris Lattner219175c2005-09-12 23:23:25 +00007699
7700 // If this store is the last instruction in the basic block, and if the block
7701 // ends with an unconditional branch, try to move it to the successor block.
Chris Lattner5997cf92006-02-08 03:25:32 +00007702 BBI = &SI; ++BBI;
Chris Lattner219175c2005-09-12 23:23:25 +00007703 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
7704 if (BI->isUnconditional()) {
7705 // Check to see if the successor block has exactly two incoming edges. If
7706 // so, see if the other predecessor contains a store to the same location.
7707 // if so, insert a PHI node (if needed) and move the stores down.
7708 BasicBlock *Dest = BI->getSuccessor(0);
7709
7710 pred_iterator PI = pred_begin(Dest);
7711 BasicBlock *Other = 0;
7712 if (*PI != BI->getParent())
7713 Other = *PI;
7714 ++PI;
7715 if (PI != pred_end(Dest)) {
7716 if (*PI != BI->getParent())
7717 if (Other)
7718 Other = 0;
7719 else
7720 Other = *PI;
7721 if (++PI != pred_end(Dest))
7722 Other = 0;
7723 }
7724 if (Other) { // If only one other pred...
7725 BBI = Other->getTerminator();
7726 // Make sure this other block ends in an unconditional branch and that
7727 // there is an instruction before the branch.
7728 if (isa<BranchInst>(BBI) && cast<BranchInst>(BBI)->isUnconditional() &&
7729 BBI != Other->begin()) {
7730 --BBI;
7731 StoreInst *OtherStore = dyn_cast<StoreInst>(BBI);
7732
7733 // If this instruction is a store to the same location.
7734 if (OtherStore && OtherStore->getOperand(1) == SI.getOperand(1)) {
7735 // Okay, we know we can perform this transformation. Insert a PHI
7736 // node now if we need it.
7737 Value *MergedVal = OtherStore->getOperand(0);
7738 if (MergedVal != SI.getOperand(0)) {
7739 PHINode *PN = new PHINode(MergedVal->getType(), "storemerge");
7740 PN->reserveOperandSpace(2);
7741 PN->addIncoming(SI.getOperand(0), SI.getParent());
7742 PN->addIncoming(OtherStore->getOperand(0), Other);
7743 MergedVal = InsertNewInstBefore(PN, Dest->front());
7744 }
7745
7746 // Advance to a place where it is safe to insert the new store and
7747 // insert it.
7748 BBI = Dest->begin();
7749 while (isa<PHINode>(BBI)) ++BBI;
7750 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
7751 OtherStore->isVolatile()), *BBI);
7752
7753 // Nuke the old stores.
Chris Lattner5997cf92006-02-08 03:25:32 +00007754 EraseInstFromFunction(SI);
7755 EraseInstFromFunction(*OtherStore);
Chris Lattner219175c2005-09-12 23:23:25 +00007756 ++NumCombined;
7757 return 0;
7758 }
7759 }
7760 }
7761 }
7762
Chris Lattner31f486c2005-01-31 05:36:43 +00007763 return 0;
7764}
7765
7766
Chris Lattner9eef8a72003-06-04 04:46:00 +00007767Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
7768 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4fdd96c2005-06-18 17:37:34 +00007769 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00007770 BasicBlock *TrueDest;
7771 BasicBlock *FalseDest;
7772 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
7773 !isa<Constant>(X)) {
7774 // Swap Destinations and condition...
7775 BI.setCondition(X);
7776 BI.setSuccessor(0, FalseDest);
7777 BI.setSuccessor(1, TrueDest);
7778 return &BI;
7779 }
7780
7781 // Cannonicalize setne -> seteq
7782 Instruction::BinaryOps Op; Value *Y;
7783 if (match(&BI, m_Br(m_SetCond(Op, m_Value(X), m_Value(Y)),
7784 TrueDest, FalseDest)))
7785 if ((Op == Instruction::SetNE || Op == Instruction::SetLE ||
7786 Op == Instruction::SetGE) && BI.getCondition()->hasOneUse()) {
7787 SetCondInst *I = cast<SetCondInst>(BI.getCondition());
7788 std::string Name = I->getName(); I->setName("");
7789 Instruction::BinaryOps NewOpcode = SetCondInst::getInverseCondition(Op);
7790 Value *NewSCC = BinaryOperator::create(NewOpcode, X, Y, Name, I);
Chris Lattnere967b342003-06-04 05:10:11 +00007791 // Swap Destinations and condition...
Chris Lattnerd4252a72004-07-30 07:50:03 +00007792 BI.setCondition(NewSCC);
Chris Lattnere967b342003-06-04 05:10:11 +00007793 BI.setSuccessor(0, FalseDest);
7794 BI.setSuccessor(1, TrueDest);
Chris Lattnerd4252a72004-07-30 07:50:03 +00007795 removeFromWorkList(I);
7796 I->getParent()->getInstList().erase(I);
7797 WorkList.push_back(cast<Instruction>(NewSCC));
Chris Lattnere967b342003-06-04 05:10:11 +00007798 return &BI;
7799 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00007800
Chris Lattner9eef8a72003-06-04 04:46:00 +00007801 return 0;
7802}
Chris Lattner1085bdf2002-11-04 16:18:53 +00007803
Chris Lattner4c9c20a2004-07-03 00:26:11 +00007804Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
7805 Value *Cond = SI.getCondition();
7806 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
7807 if (I->getOpcode() == Instruction::Add)
7808 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7809 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
7810 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattner81a7a232004-10-16 18:11:37 +00007811 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner4c9c20a2004-07-03 00:26:11 +00007812 AddRHS));
7813 SI.setOperand(0, I->getOperand(0));
7814 WorkList.push_back(I);
7815 return &SI;
7816 }
7817 }
7818 return 0;
7819}
7820
Chris Lattner6bc98652006-03-05 00:22:33 +00007821/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
7822/// is to leave as a vector operation.
7823static bool CheapToScalarize(Value *V, bool isConstant) {
7824 if (isa<ConstantAggregateZero>(V))
7825 return true;
7826 if (ConstantPacked *C = dyn_cast<ConstantPacked>(V)) {
7827 if (isConstant) return true;
7828 // If all elts are the same, we can extract.
7829 Constant *Op0 = C->getOperand(0);
7830 for (unsigned i = 1; i < C->getNumOperands(); ++i)
7831 if (C->getOperand(i) != Op0)
7832 return false;
7833 return true;
7834 }
7835 Instruction *I = dyn_cast<Instruction>(V);
7836 if (!I) return false;
7837
7838 // Insert element gets simplified to the inserted element or is deleted if
7839 // this is constant idx extract element and its a constant idx insertelt.
7840 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
7841 isa<ConstantInt>(I->getOperand(2)))
7842 return true;
7843 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
7844 return true;
7845 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
7846 if (BO->hasOneUse() &&
7847 (CheapToScalarize(BO->getOperand(0), isConstant) ||
7848 CheapToScalarize(BO->getOperand(1), isConstant)))
7849 return true;
7850
7851 return false;
7852}
7853
Chris Lattner12249be2006-05-25 23:48:38 +00007854/// getShuffleMask - Read and decode a shufflevector mask. It turns undef
7855/// elements into values that are larger than the #elts in the input.
7856static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
7857 unsigned NElts = SVI->getType()->getNumElements();
7858 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
7859 return std::vector<unsigned>(NElts, 0);
7860 if (isa<UndefValue>(SVI->getOperand(2)))
7861 return std::vector<unsigned>(NElts, 2*NElts);
7862
7863 std::vector<unsigned> Result;
7864 const ConstantPacked *CP = cast<ConstantPacked>(SVI->getOperand(2));
7865 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
7866 if (isa<UndefValue>(CP->getOperand(i)))
7867 Result.push_back(NElts*2); // undef -> 8
7868 else
Reid Spencere0fc4df2006-10-20 07:07:24 +00007869 Result.push_back(cast<ConstantInt>(CP->getOperand(i))->getZExtValue());
Chris Lattner12249be2006-05-25 23:48:38 +00007870 return Result;
7871}
7872
Chris Lattner8d1d8d32006-03-31 23:01:56 +00007873/// FindScalarElement - Given a vector and an element number, see if the scalar
7874/// value is already around as a register, for example if it were inserted then
7875/// extracted from the vector.
7876static Value *FindScalarElement(Value *V, unsigned EltNo) {
7877 assert(isa<PackedType>(V->getType()) && "Not looking at a vector?");
7878 const PackedType *PTy = cast<PackedType>(V->getType());
Chris Lattner2d37f922006-04-10 23:06:36 +00007879 unsigned Width = PTy->getNumElements();
7880 if (EltNo >= Width) // Out of range access.
Chris Lattner8d1d8d32006-03-31 23:01:56 +00007881 return UndefValue::get(PTy->getElementType());
7882
7883 if (isa<UndefValue>(V))
7884 return UndefValue::get(PTy->getElementType());
7885 else if (isa<ConstantAggregateZero>(V))
7886 return Constant::getNullValue(PTy->getElementType());
7887 else if (ConstantPacked *CP = dyn_cast<ConstantPacked>(V))
7888 return CP->getOperand(EltNo);
7889 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
7890 // If this is an insert to a variable element, we don't know what it is.
Reid Spencere0fc4df2006-10-20 07:07:24 +00007891 if (!isa<ConstantInt>(III->getOperand(2)))
7892 return 0;
7893 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Chris Lattner8d1d8d32006-03-31 23:01:56 +00007894
7895 // If this is an insert to the element we are looking for, return the
7896 // inserted value.
Reid Spencere0fc4df2006-10-20 07:07:24 +00007897 if (EltNo == IIElt)
7898 return III->getOperand(1);
Chris Lattner8d1d8d32006-03-31 23:01:56 +00007899
7900 // Otherwise, the insertelement doesn't modify the value, recurse on its
7901 // vector input.
7902 return FindScalarElement(III->getOperand(0), EltNo);
Chris Lattner2d37f922006-04-10 23:06:36 +00007903 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Chris Lattner12249be2006-05-25 23:48:38 +00007904 unsigned InEl = getShuffleMask(SVI)[EltNo];
7905 if (InEl < Width)
7906 return FindScalarElement(SVI->getOperand(0), InEl);
7907 else if (InEl < Width*2)
7908 return FindScalarElement(SVI->getOperand(1), InEl - Width);
7909 else
7910 return UndefValue::get(PTy->getElementType());
Chris Lattner8d1d8d32006-03-31 23:01:56 +00007911 }
7912
7913 // Otherwise, we don't know.
7914 return 0;
7915}
7916
Robert Bocchinoa8352962006-01-13 22:48:06 +00007917Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Chris Lattner8d1d8d32006-03-31 23:01:56 +00007918
Chris Lattner92346c32006-03-31 18:25:14 +00007919 // If packed val is undef, replace extract with scalar undef.
7920 if (isa<UndefValue>(EI.getOperand(0)))
7921 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
7922
7923 // If packed val is constant 0, replace extract with scalar 0.
7924 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
7925 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
7926
Robert Bocchinoa8352962006-01-13 22:48:06 +00007927 if (ConstantPacked *C = dyn_cast<ConstantPacked>(EI.getOperand(0))) {
7928 // If packed val is constant with uniform operands, replace EI
7929 // with that operand
Chris Lattner6bc98652006-03-05 00:22:33 +00007930 Constant *op0 = C->getOperand(0);
Robert Bocchinoa8352962006-01-13 22:48:06 +00007931 for (unsigned i = 1; i < C->getNumOperands(); ++i)
Chris Lattner6bc98652006-03-05 00:22:33 +00007932 if (C->getOperand(i) != op0) {
7933 op0 = 0;
7934 break;
7935 }
7936 if (op0)
7937 return ReplaceInstUsesWith(EI, op0);
Robert Bocchinoa8352962006-01-13 22:48:06 +00007938 }
Chris Lattner6bc98652006-03-05 00:22:33 +00007939
Chris Lattner8d1d8d32006-03-31 23:01:56 +00007940 // If extracting a specified index from the vector, see if we can recursively
7941 // find a previously computed scalar that was inserted into the vector.
Reid Spencere0fc4df2006-10-20 07:07:24 +00007942 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Chris Lattner2deeaea2006-10-05 06:55:50 +00007943 // This instruction only demands the single element from the input vector.
7944 // If the input vector has a single use, simplify it based on this use
7945 // property.
Reid Spencere0fc4df2006-10-20 07:07:24 +00007946 uint64_t IndexVal = IdxC->getZExtValue();
Chris Lattner2deeaea2006-10-05 06:55:50 +00007947 if (EI.getOperand(0)->hasOneUse()) {
7948 uint64_t UndefElts;
7949 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Reid Spencere0fc4df2006-10-20 07:07:24 +00007950 1 << IndexVal,
Chris Lattner2deeaea2006-10-05 06:55:50 +00007951 UndefElts)) {
7952 EI.setOperand(0, V);
7953 return &EI;
7954 }
7955 }
7956
Reid Spencere0fc4df2006-10-20 07:07:24 +00007957 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
Chris Lattner8d1d8d32006-03-31 23:01:56 +00007958 return ReplaceInstUsesWith(EI, Elt);
Chris Lattner2d37f922006-04-10 23:06:36 +00007959 }
Chris Lattner8d1d8d32006-03-31 23:01:56 +00007960
Chris Lattner83f65782006-05-25 22:53:38 +00007961 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Robert Bocchinoa8352962006-01-13 22:48:06 +00007962 if (I->hasOneUse()) {
7963 // Push extractelement into predecessor operation if legal and
7964 // profitable to do so
7965 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Chris Lattner6bc98652006-03-05 00:22:33 +00007966 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
7967 if (CheapToScalarize(BO, isConstantElt)) {
7968 ExtractElementInst *newEI0 =
7969 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
7970 EI.getName()+".lhs");
7971 ExtractElementInst *newEI1 =
7972 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
7973 EI.getName()+".rhs");
7974 InsertNewInstBefore(newEI0, EI);
7975 InsertNewInstBefore(newEI1, EI);
7976 return BinaryOperator::create(BO->getOpcode(), newEI0, newEI1);
7977 }
7978 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Robert Bocchinoa8352962006-01-13 22:48:06 +00007979 Value *Ptr = InsertCastBefore(I->getOperand(0),
7980 PointerType::get(EI.getType()), EI);
7981 GetElementPtrInst *GEP =
7982 new GetElementPtrInst(Ptr, EI.getOperand(1),
7983 I->getName() + ".gep");
7984 InsertNewInstBefore(GEP, EI);
7985 return new LoadInst(GEP);
Chris Lattner83f65782006-05-25 22:53:38 +00007986 }
7987 }
7988 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
7989 // Extracting the inserted element?
7990 if (IE->getOperand(2) == EI.getOperand(1))
7991 return ReplaceInstUsesWith(EI, IE->getOperand(1));
7992 // If the inserted and extracted elements are constants, they must not
7993 // be the same value, extract from the pre-inserted value instead.
7994 if (isa<Constant>(IE->getOperand(2)) &&
7995 isa<Constant>(EI.getOperand(1))) {
7996 AddUsesToWorkList(EI);
7997 EI.setOperand(0, IE->getOperand(0));
7998 return &EI;
7999 }
8000 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
8001 // If this is extracting an element from a shufflevector, figure out where
8002 // it came from and extract from the appropriate input element instead.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008003 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
8004 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
Chris Lattner12249be2006-05-25 23:48:38 +00008005 Value *Src;
8006 if (SrcIdx < SVI->getType()->getNumElements())
8007 Src = SVI->getOperand(0);
8008 else if (SrcIdx < SVI->getType()->getNumElements()*2) {
8009 SrcIdx -= SVI->getType()->getNumElements();
8010 Src = SVI->getOperand(1);
8011 } else {
8012 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattner612fa8e2006-03-30 22:02:40 +00008013 }
Chris Lattner2deeaea2006-10-05 06:55:50 +00008014 return new ExtractElementInst(Src, SrcIdx);
Robert Bocchinoa8352962006-01-13 22:48:06 +00008015 }
8016 }
Chris Lattner83f65782006-05-25 22:53:38 +00008017 }
Robert Bocchinoa8352962006-01-13 22:48:06 +00008018 return 0;
8019}
8020
Chris Lattner90951862006-04-16 00:51:47 +00008021/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
8022/// elements from either LHS or RHS, return the shuffle mask and true.
8023/// Otherwise, return false.
8024static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
8025 std::vector<Constant*> &Mask) {
8026 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
8027 "Invalid CollectSingleShuffleElements");
8028 unsigned NumElts = cast<PackedType>(V->getType())->getNumElements();
8029
8030 if (isa<UndefValue>(V)) {
8031 Mask.assign(NumElts, UndefValue::get(Type::UIntTy));
8032 return true;
8033 } else if (V == LHS) {
8034 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencere0fc4df2006-10-20 07:07:24 +00008035 Mask.push_back(ConstantInt::get(Type::UIntTy, i));
Chris Lattner90951862006-04-16 00:51:47 +00008036 return true;
8037 } else if (V == RHS) {
8038 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencere0fc4df2006-10-20 07:07:24 +00008039 Mask.push_back(ConstantInt::get(Type::UIntTy, i+NumElts));
Chris Lattner90951862006-04-16 00:51:47 +00008040 return true;
8041 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
8042 // If this is an insert of an extract from some other vector, include it.
8043 Value *VecOp = IEI->getOperand(0);
8044 Value *ScalarOp = IEI->getOperand(1);
8045 Value *IdxOp = IEI->getOperand(2);
8046
Chris Lattnerb6cb64b2006-04-27 21:14:21 +00008047 if (!isa<ConstantInt>(IdxOp))
8048 return false;
Reid Spencere0fc4df2006-10-20 07:07:24 +00008049 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerb6cb64b2006-04-27 21:14:21 +00008050
8051 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
8052 // Okay, we can handle this if the vector we are insertinting into is
8053 // transitively ok.
8054 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
8055 // If so, update the mask to reflect the inserted undef.
8056 Mask[InsertedIdx] = UndefValue::get(Type::UIntTy);
8057 return true;
8058 }
8059 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
8060 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner90951862006-04-16 00:51:47 +00008061 EI->getOperand(0)->getType() == V->getType()) {
8062 unsigned ExtractedIdx =
Reid Spencere0fc4df2006-10-20 07:07:24 +00008063 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattner90951862006-04-16 00:51:47 +00008064
8065 // This must be extracting from either LHS or RHS.
8066 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
8067 // Okay, we can handle this if the vector we are insertinting into is
8068 // transitively ok.
8069 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
8070 // If so, update the mask to reflect the inserted value.
8071 if (EI->getOperand(0) == LHS) {
8072 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencere0fc4df2006-10-20 07:07:24 +00008073 ConstantInt::get(Type::UIntTy, ExtractedIdx);
Chris Lattner90951862006-04-16 00:51:47 +00008074 } else {
8075 assert(EI->getOperand(0) == RHS);
8076 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencere0fc4df2006-10-20 07:07:24 +00008077 ConstantInt::get(Type::UIntTy, ExtractedIdx+NumElts);
Chris Lattner90951862006-04-16 00:51:47 +00008078
8079 }
8080 return true;
8081 }
8082 }
8083 }
8084 }
8085 }
8086 // TODO: Handle shufflevector here!
8087
8088 return false;
8089}
8090
8091/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
8092/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
8093/// that computes V and the LHS value of the shuffle.
Chris Lattner39fac442006-04-15 01:39:45 +00008094static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Chris Lattner90951862006-04-16 00:51:47 +00008095 Value *&RHS) {
8096 assert(isa<PackedType>(V->getType()) &&
8097 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattner39fac442006-04-15 01:39:45 +00008098 "Invalid shuffle!");
8099 unsigned NumElts = cast<PackedType>(V->getType())->getNumElements();
8100
8101 if (isa<UndefValue>(V)) {
8102 Mask.assign(NumElts, UndefValue::get(Type::UIntTy));
8103 return V;
8104 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00008105 Mask.assign(NumElts, ConstantInt::get(Type::UIntTy, 0));
Chris Lattner39fac442006-04-15 01:39:45 +00008106 return V;
8107 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
8108 // If this is an insert of an extract from some other vector, include it.
8109 Value *VecOp = IEI->getOperand(0);
8110 Value *ScalarOp = IEI->getOperand(1);
8111 Value *IdxOp = IEI->getOperand(2);
8112
8113 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
8114 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
8115 EI->getOperand(0)->getType() == V->getType()) {
8116 unsigned ExtractedIdx =
Reid Spencere0fc4df2006-10-20 07:07:24 +00008117 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
8118 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattner39fac442006-04-15 01:39:45 +00008119
8120 // Either the extracted from or inserted into vector must be RHSVec,
8121 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner90951862006-04-16 00:51:47 +00008122 if (EI->getOperand(0) == RHS || RHS == 0) {
8123 RHS = EI->getOperand(0);
8124 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
Chris Lattner39fac442006-04-15 01:39:45 +00008125 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencere0fc4df2006-10-20 07:07:24 +00008126 ConstantInt::get(Type::UIntTy, NumElts+ExtractedIdx);
Chris Lattner39fac442006-04-15 01:39:45 +00008127 return V;
8128 }
8129
Chris Lattner90951862006-04-16 00:51:47 +00008130 if (VecOp == RHS) {
8131 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
Chris Lattner39fac442006-04-15 01:39:45 +00008132 // Everything but the extracted element is replaced with the RHS.
8133 for (unsigned i = 0; i != NumElts; ++i) {
8134 if (i != InsertedIdx)
Reid Spencere0fc4df2006-10-20 07:07:24 +00008135 Mask[i] = ConstantInt::get(Type::UIntTy, NumElts+i);
Chris Lattner39fac442006-04-15 01:39:45 +00008136 }
8137 return V;
8138 }
Chris Lattner90951862006-04-16 00:51:47 +00008139
8140 // If this insertelement is a chain that comes from exactly these two
8141 // vectors, return the vector and the effective shuffle.
8142 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
8143 return EI->getOperand(0);
8144
Chris Lattner39fac442006-04-15 01:39:45 +00008145 }
8146 }
8147 }
Chris Lattner90951862006-04-16 00:51:47 +00008148 // TODO: Handle shufflevector here!
Chris Lattner39fac442006-04-15 01:39:45 +00008149
8150 // Otherwise, can't do anything fancy. Return an identity vector.
8151 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencere0fc4df2006-10-20 07:07:24 +00008152 Mask.push_back(ConstantInt::get(Type::UIntTy, i));
Chris Lattner39fac442006-04-15 01:39:45 +00008153 return V;
8154}
8155
8156Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
8157 Value *VecOp = IE.getOperand(0);
8158 Value *ScalarOp = IE.getOperand(1);
8159 Value *IdxOp = IE.getOperand(2);
8160
8161 // If the inserted element was extracted from some other vector, and if the
8162 // indexes are constant, try to turn this into a shufflevector operation.
8163 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
8164 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
8165 EI->getOperand(0)->getType() == IE.getType()) {
8166 unsigned NumVectorElts = IE.getType()->getNumElements();
Reid Spencere0fc4df2006-10-20 07:07:24 +00008167 unsigned ExtractedIdx=cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
8168 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattner39fac442006-04-15 01:39:45 +00008169
8170 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
8171 return ReplaceInstUsesWith(IE, VecOp);
8172
8173 if (InsertedIdx >= NumVectorElts) // Out of range insert.
8174 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
8175
8176 // If we are extracting a value from a vector, then inserting it right
8177 // back into the same place, just use the input vector.
8178 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
8179 return ReplaceInstUsesWith(IE, VecOp);
8180
8181 // We could theoretically do this for ANY input. However, doing so could
8182 // turn chains of insertelement instructions into a chain of shufflevector
8183 // instructions, and right now we do not merge shufflevectors. As such,
8184 // only do this in a situation where it is clear that there is benefit.
8185 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
8186 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
8187 // the values of VecOp, except then one read from EIOp0.
8188 // Build a new shuffle mask.
8189 std::vector<Constant*> Mask;
8190 if (isa<UndefValue>(VecOp))
8191 Mask.assign(NumVectorElts, UndefValue::get(Type::UIntTy));
8192 else {
8193 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
Reid Spencere0fc4df2006-10-20 07:07:24 +00008194 Mask.assign(NumVectorElts, ConstantInt::get(Type::UIntTy,
Chris Lattner39fac442006-04-15 01:39:45 +00008195 NumVectorElts));
8196 }
Reid Spencere0fc4df2006-10-20 07:07:24 +00008197 Mask[InsertedIdx] = ConstantInt::get(Type::UIntTy, ExtractedIdx);
Chris Lattner39fac442006-04-15 01:39:45 +00008198 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
8199 ConstantPacked::get(Mask));
8200 }
8201
8202 // If this insertelement isn't used by some other insertelement, turn it
8203 // (and any insertelements it points to), into one big shuffle.
8204 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
8205 std::vector<Constant*> Mask;
Chris Lattner90951862006-04-16 00:51:47 +00008206 Value *RHS = 0;
8207 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
8208 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
8209 // We now have a shuffle of LHS, RHS, Mask.
8210 return new ShuffleVectorInst(LHS, RHS, ConstantPacked::get(Mask));
Chris Lattner39fac442006-04-15 01:39:45 +00008211 }
8212 }
8213 }
8214
8215 return 0;
8216}
8217
8218
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008219Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
8220 Value *LHS = SVI.getOperand(0);
8221 Value *RHS = SVI.getOperand(1);
Chris Lattner12249be2006-05-25 23:48:38 +00008222 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008223
8224 bool MadeChange = false;
8225
Chris Lattner2deeaea2006-10-05 06:55:50 +00008226 // Undefined shuffle mask -> undefined value.
Chris Lattner12249be2006-05-25 23:48:38 +00008227 if (isa<UndefValue>(SVI.getOperand(2)))
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008228 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
8229
Chris Lattner39fac442006-04-15 01:39:45 +00008230 // TODO: If we have shuffle(x, undef, mask) and any elements of mask refer to
8231 // the undef, change them to undefs.
8232
Chris Lattner12249be2006-05-25 23:48:38 +00008233 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
8234 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
8235 if (LHS == RHS || isa<UndefValue>(LHS)) {
8236 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008237 // shuffle(undef,undef,mask) -> undef.
8238 return ReplaceInstUsesWith(SVI, LHS);
8239 }
8240
Chris Lattner12249be2006-05-25 23:48:38 +00008241 // Remap any references to RHS to use LHS.
8242 std::vector<Constant*> Elts;
8243 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner0e477162006-05-26 00:29:06 +00008244 if (Mask[i] >= 2*e)
Chris Lattner12249be2006-05-25 23:48:38 +00008245 Elts.push_back(UndefValue::get(Type::UIntTy));
Chris Lattner0e477162006-05-26 00:29:06 +00008246 else {
8247 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
8248 (Mask[i] < e && isa<UndefValue>(LHS)))
8249 Mask[i] = 2*e; // Turn into undef.
8250 else
8251 Mask[i] &= (e-1); // Force to LHS.
Reid Spencere0fc4df2006-10-20 07:07:24 +00008252 Elts.push_back(ConstantInt::get(Type::UIntTy, Mask[i]));
Chris Lattner0e477162006-05-26 00:29:06 +00008253 }
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008254 }
Chris Lattner12249be2006-05-25 23:48:38 +00008255 SVI.setOperand(0, SVI.getOperand(1));
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008256 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Chris Lattner12249be2006-05-25 23:48:38 +00008257 SVI.setOperand(2, ConstantPacked::get(Elts));
Chris Lattner0e477162006-05-26 00:29:06 +00008258 LHS = SVI.getOperand(0);
8259 RHS = SVI.getOperand(1);
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008260 MadeChange = true;
8261 }
8262
Chris Lattner0e477162006-05-26 00:29:06 +00008263 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner12249be2006-05-25 23:48:38 +00008264 bool isLHSID = true, isRHSID = true;
Chris Lattner34cebe72006-04-16 00:03:56 +00008265
Chris Lattner12249be2006-05-25 23:48:38 +00008266 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
8267 if (Mask[i] >= e*2) continue; // Ignore undef values.
8268 // Is this an identity shuffle of the LHS value?
8269 isLHSID &= (Mask[i] == i);
8270
8271 // Is this an identity shuffle of the RHS value?
8272 isRHSID &= (Mask[i]-e == i);
Chris Lattner34cebe72006-04-16 00:03:56 +00008273 }
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008274
Chris Lattner12249be2006-05-25 23:48:38 +00008275 // Eliminate identity shuffles.
8276 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
8277 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008278
Chris Lattner0e477162006-05-26 00:29:06 +00008279 // If the LHS is a shufflevector itself, see if we can combine it with this
8280 // one without producing an unusual shuffle. Here we are really conservative:
8281 // we are absolutely afraid of producing a shuffle mask not in the input
8282 // program, because the code gen may not be smart enough to turn a merged
8283 // shuffle into two specific shuffles: it may produce worse code. As such,
8284 // we only merge two shuffles if the result is one of the two input shuffle
8285 // masks. In this case, merging the shuffles just removes one instruction,
8286 // which we know is safe. This is good for things like turning:
8287 // (splat(splat)) -> splat.
8288 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
8289 if (isa<UndefValue>(RHS)) {
8290 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
8291
8292 std::vector<unsigned> NewMask;
8293 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
8294 if (Mask[i] >= 2*e)
8295 NewMask.push_back(2*e);
8296 else
8297 NewMask.push_back(LHSMask[Mask[i]]);
8298
8299 // If the result mask is equal to the src shuffle or this shuffle mask, do
8300 // the replacement.
8301 if (NewMask == LHSMask || NewMask == Mask) {
8302 std::vector<Constant*> Elts;
8303 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
8304 if (NewMask[i] >= e*2) {
8305 Elts.push_back(UndefValue::get(Type::UIntTy));
8306 } else {
Reid Spencere0fc4df2006-10-20 07:07:24 +00008307 Elts.push_back(ConstantInt::get(Type::UIntTy, NewMask[i]));
Chris Lattner0e477162006-05-26 00:29:06 +00008308 }
8309 }
8310 return new ShuffleVectorInst(LHSSVI->getOperand(0),
8311 LHSSVI->getOperand(1),
8312 ConstantPacked::get(Elts));
8313 }
8314 }
8315 }
8316
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008317 return MadeChange ? &SVI : 0;
8318}
8319
8320
Robert Bocchinoa8352962006-01-13 22:48:06 +00008321
Chris Lattner99f48c62002-09-02 04:59:56 +00008322void InstCombiner::removeFromWorkList(Instruction *I) {
8323 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
8324 WorkList.end());
8325}
8326
Chris Lattner39c98bb2004-12-08 23:43:58 +00008327
8328/// TryToSinkInstruction - Try to move the specified instruction from its
8329/// current block into the beginning of DestBlock, which can only happen if it's
8330/// safe to move the instruction past all of the instructions between it and the
8331/// end of its block.
8332static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
8333 assert(I->hasOneUse() && "Invariants didn't hold!");
8334
Chris Lattnerc4f67e62005-10-27 17:13:11 +00008335 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
8336 if (isa<PHINode>(I) || I->mayWriteToMemory()) return false;
Misha Brukmanb1c93172005-04-21 23:48:37 +00008337
Chris Lattner39c98bb2004-12-08 23:43:58 +00008338 // Do not sink alloca instructions out of the entry block.
8339 if (isa<AllocaInst>(I) && I->getParent() == &DestBlock->getParent()->front())
8340 return false;
8341
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00008342 // We can only sink load instructions if there is nothing between the load and
8343 // the end of block that could change the value.
8344 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00008345 for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
8346 Scan != E; ++Scan)
8347 if (Scan->mayWriteToMemory())
8348 return false;
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00008349 }
Chris Lattner39c98bb2004-12-08 23:43:58 +00008350
8351 BasicBlock::iterator InsertPos = DestBlock->begin();
8352 while (isa<PHINode>(InsertPos)) ++InsertPos;
8353
Chris Lattner9f269e42005-08-08 19:11:57 +00008354 I->moveBefore(InsertPos);
Chris Lattner39c98bb2004-12-08 23:43:58 +00008355 ++NumSunkInst;
8356 return true;
8357}
8358
Chris Lattner1443bc52006-05-11 17:11:52 +00008359/// OptimizeConstantExpr - Given a constant expression and target data layout
8360/// information, symbolically evaluation the constant expr to something simpler
8361/// if possible.
8362static Constant *OptimizeConstantExpr(ConstantExpr *CE, const TargetData *TD) {
8363 if (!TD) return CE;
8364
8365 Constant *Ptr = CE->getOperand(0);
8366 if (CE->getOpcode() == Instruction::GetElementPtr && Ptr->isNullValue() &&
8367 cast<PointerType>(Ptr->getType())->getElementType()->isSized()) {
8368 // If this is a constant expr gep that is effectively computing an
8369 // "offsetof", fold it into 'cast int Size to T*' instead of 'gep 0, 0, 12'
8370 bool isFoldableGEP = true;
8371 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
8372 if (!isa<ConstantInt>(CE->getOperand(i)))
8373 isFoldableGEP = false;
8374 if (isFoldableGEP) {
8375 std::vector<Value*> Ops(CE->op_begin()+1, CE->op_end());
8376 uint64_t Offset = TD->getIndexedOffset(Ptr->getType(), Ops);
Reid Spencere0fc4df2006-10-20 07:07:24 +00008377 Constant *C = ConstantInt::get(Type::ULongTy, Offset);
Chris Lattner1443bc52006-05-11 17:11:52 +00008378 C = ConstantExpr::getCast(C, TD->getIntPtrType());
8379 return ConstantExpr::getCast(C, CE->getType());
8380 }
8381 }
8382
8383 return CE;
8384}
8385
Chris Lattnera36ee4e2006-05-10 19:00:36 +00008386
8387/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
8388/// all reachable code to the worklist.
8389///
8390/// This has a couple of tricks to make the code faster and more powerful. In
8391/// particular, we constant fold and DCE instructions as we go, to avoid adding
8392/// them to the worklist (this significantly speeds up instcombine on code where
8393/// many instructions are dead or constant). Additionally, if we find a branch
8394/// whose condition is a known constant, we only visit the reachable successors.
8395///
8396static void AddReachableCodeToWorklist(BasicBlock *BB,
8397 std::set<BasicBlock*> &Visited,
Chris Lattner1443bc52006-05-11 17:11:52 +00008398 std::vector<Instruction*> &WorkList,
8399 const TargetData *TD) {
Chris Lattnera36ee4e2006-05-10 19:00:36 +00008400 // We have now visited this block! If we've already been here, bail out.
8401 if (!Visited.insert(BB).second) return;
8402
8403 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
8404 Instruction *Inst = BBI++;
8405
8406 // DCE instruction if trivially dead.
8407 if (isInstructionTriviallyDead(Inst)) {
8408 ++NumDeadInst;
8409 DEBUG(std::cerr << "IC: DCE: " << *Inst);
8410 Inst->eraseFromParent();
8411 continue;
8412 }
8413
8414 // ConstantProp instruction if trivially constant.
8415 if (Constant *C = ConstantFoldInstruction(Inst)) {
Chris Lattner1443bc52006-05-11 17:11:52 +00008416 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
8417 C = OptimizeConstantExpr(CE, TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00008418 DEBUG(std::cerr << "IC: ConstFold to: " << *C << " from: " << *Inst);
8419 Inst->replaceAllUsesWith(C);
8420 ++NumConstProp;
8421 Inst->eraseFromParent();
8422 continue;
8423 }
8424
8425 WorkList.push_back(Inst);
8426 }
8427
8428 // Recursively visit successors. If this is a branch or switch on a constant,
8429 // only visit the reachable successor.
8430 TerminatorInst *TI = BB->getTerminator();
8431 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
8432 if (BI->isConditional() && isa<ConstantBool>(BI->getCondition())) {
8433 bool CondVal = cast<ConstantBool>(BI->getCondition())->getValue();
Chris Lattner1443bc52006-05-11 17:11:52 +00008434 AddReachableCodeToWorklist(BI->getSuccessor(!CondVal), Visited, WorkList,
8435 TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00008436 return;
8437 }
8438 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
8439 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
8440 // See if this is an explicit destination.
8441 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
8442 if (SI->getCaseValue(i) == Cond) {
Chris Lattner1443bc52006-05-11 17:11:52 +00008443 AddReachableCodeToWorklist(SI->getSuccessor(i), Visited, WorkList,TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00008444 return;
8445 }
8446
8447 // Otherwise it is the default destination.
Chris Lattner1443bc52006-05-11 17:11:52 +00008448 AddReachableCodeToWorklist(SI->getSuccessor(0), Visited, WorkList, TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00008449 return;
8450 }
8451 }
8452
8453 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
Chris Lattner1443bc52006-05-11 17:11:52 +00008454 AddReachableCodeToWorklist(TI->getSuccessor(i), Visited, WorkList, TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00008455}
8456
Chris Lattner113f4f42002-06-25 16:13:24 +00008457bool InstCombiner::runOnFunction(Function &F) {
Chris Lattner260ab202002-04-18 17:39:14 +00008458 bool Changed = false;
Chris Lattnerf4ad1652003-11-02 05:57:39 +00008459 TD = &getAnalysis<TargetData>();
Chris Lattnerca081252001-12-14 16:52:21 +00008460
Chris Lattner4ed40f72005-07-07 20:40:38 +00008461 {
Chris Lattnera36ee4e2006-05-10 19:00:36 +00008462 // Do a depth-first traversal of the function, populate the worklist with
8463 // the reachable instructions. Ignore blocks that are not reachable. Keep
8464 // track of which blocks we visit.
Chris Lattner4ed40f72005-07-07 20:40:38 +00008465 std::set<BasicBlock*> Visited;
Chris Lattner1443bc52006-05-11 17:11:52 +00008466 AddReachableCodeToWorklist(F.begin(), Visited, WorkList, TD);
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00008467
Chris Lattner4ed40f72005-07-07 20:40:38 +00008468 // Do a quick scan over the function. If we find any blocks that are
8469 // unreachable, remove any instructions inside of them. This prevents
8470 // the instcombine code from having to deal with some bad special cases.
8471 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
8472 if (!Visited.count(BB)) {
8473 Instruction *Term = BB->getTerminator();
8474 while (Term != BB->begin()) { // Remove instrs bottom-up
8475 BasicBlock::iterator I = Term; --I;
Chris Lattner2d3a7a62004-04-27 15:13:33 +00008476
Chris Lattner4ed40f72005-07-07 20:40:38 +00008477 DEBUG(std::cerr << "IC: DCE: " << *I);
8478 ++NumDeadInst;
8479
8480 if (!I->use_empty())
8481 I->replaceAllUsesWith(UndefValue::get(I->getType()));
8482 I->eraseFromParent();
8483 }
8484 }
8485 }
Chris Lattnerca081252001-12-14 16:52:21 +00008486
8487 while (!WorkList.empty()) {
8488 Instruction *I = WorkList.back(); // Get an instruction from the worklist
8489 WorkList.pop_back();
8490
Chris Lattner1443bc52006-05-11 17:11:52 +00008491 // Check to see if we can DCE the instruction.
Chris Lattner99f48c62002-09-02 04:59:56 +00008492 if (isInstructionTriviallyDead(I)) {
Chris Lattner1443bc52006-05-11 17:11:52 +00008493 // Add operands to the worklist.
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00008494 if (I->getNumOperands() < 4)
Chris Lattner51ea1272004-02-28 05:22:00 +00008495 AddUsesToWorkList(*I);
Chris Lattner99f48c62002-09-02 04:59:56 +00008496 ++NumDeadInst;
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00008497
Chris Lattnercd517ff2005-01-28 19:32:01 +00008498 DEBUG(std::cerr << "IC: DCE: " << *I);
8499
8500 I->eraseFromParent();
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00008501 removeFromWorkList(I);
8502 continue;
8503 }
Chris Lattner99f48c62002-09-02 04:59:56 +00008504
Chris Lattner1443bc52006-05-11 17:11:52 +00008505 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattner99f48c62002-09-02 04:59:56 +00008506 if (Constant *C = ConstantFoldInstruction(I)) {
Chris Lattner1443bc52006-05-11 17:11:52 +00008507 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
8508 C = OptimizeConstantExpr(CE, TD);
Chris Lattnercd517ff2005-01-28 19:32:01 +00008509 DEBUG(std::cerr << "IC: ConstFold to: " << *C << " from: " << *I);
8510
Chris Lattner1443bc52006-05-11 17:11:52 +00008511 // Add operands to the worklist.
Chris Lattner51ea1272004-02-28 05:22:00 +00008512 AddUsesToWorkList(*I);
Chris Lattnerc6509f42002-12-05 22:41:53 +00008513 ReplaceInstUsesWith(*I, C);
8514
Chris Lattner99f48c62002-09-02 04:59:56 +00008515 ++NumConstProp;
Chris Lattnera36ee4e2006-05-10 19:00:36 +00008516 I->eraseFromParent();
Chris Lattner800aaaf2003-10-07 15:17:02 +00008517 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00008518 continue;
Chris Lattner99f48c62002-09-02 04:59:56 +00008519 }
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00008520
Chris Lattner39c98bb2004-12-08 23:43:58 +00008521 // See if we can trivially sink this instruction to a successor basic block.
8522 if (I->hasOneUse()) {
8523 BasicBlock *BB = I->getParent();
8524 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
8525 if (UserParent != BB) {
8526 bool UserIsSuccessor = false;
8527 // See if the user is one of our successors.
8528 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
8529 if (*SI == UserParent) {
8530 UserIsSuccessor = true;
8531 break;
8532 }
8533
8534 // If the user is one of our immediate successors, and if that successor
8535 // only has us as a predecessors (we'd have to split the critical edge
8536 // otherwise), we can keep going.
8537 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
8538 next(pred_begin(UserParent)) == pred_end(UserParent))
8539 // Okay, the CFG is simple enough, try to sink this instruction.
8540 Changed |= TryToSinkInstruction(I, UserParent);
8541 }
8542 }
8543
Chris Lattnerca081252001-12-14 16:52:21 +00008544 // Now that we have an instruction, try combining it to simplify it...
Chris Lattnerae7a0d32002-08-02 19:29:35 +00008545 if (Instruction *Result = visit(*I)) {
Chris Lattner0b18c1d2002-05-10 15:38:35 +00008546 ++NumCombined;
Chris Lattner260ab202002-04-18 17:39:14 +00008547 // Should we replace the old instruction with a new one?
Chris Lattner053c0932002-05-14 15:24:07 +00008548 if (Result != I) {
Chris Lattner7d2a5392004-03-13 23:54:27 +00008549 DEBUG(std::cerr << "IC: Old = " << *I
8550 << " New = " << *Result);
8551
Chris Lattner396dbfe2004-06-09 05:08:07 +00008552 // Everything uses the new instruction now.
8553 I->replaceAllUsesWith(Result);
8554
8555 // Push the new instruction and any users onto the worklist.
8556 WorkList.push_back(Result);
8557 AddUsersToWorkList(*Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00008558
8559 // Move the name to the new instruction first...
8560 std::string OldName = I->getName(); I->setName("");
Chris Lattner950fc782003-10-07 22:58:41 +00008561 Result->setName(OldName);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00008562
8563 // Insert the new instruction into the basic block...
8564 BasicBlock *InstParent = I->getParent();
Chris Lattner7515cab2004-11-14 19:13:23 +00008565 BasicBlock::iterator InsertPos = I;
8566
8567 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
8568 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
8569 ++InsertPos;
8570
8571 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00008572
Chris Lattner63d75af2004-05-01 23:27:23 +00008573 // Make sure that we reprocess all operands now that we reduced their
8574 // use counts.
Chris Lattnerb643a9e2004-05-01 23:19:52 +00008575 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
8576 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
8577 WorkList.push_back(OpI);
8578
Chris Lattner396dbfe2004-06-09 05:08:07 +00008579 // Instructions can end up on the worklist more than once. Make sure
8580 // we do not process an instruction that has been deleted.
8581 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00008582
8583 // Erase the old instruction.
8584 InstParent->getInstList().erase(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00008585 } else {
Chris Lattner7d2a5392004-03-13 23:54:27 +00008586 DEBUG(std::cerr << "IC: MOD = " << *I);
8587
Chris Lattnerae7a0d32002-08-02 19:29:35 +00008588 // If the instruction was modified, it's possible that it is now dead.
8589 // if so, remove it.
Chris Lattner63d75af2004-05-01 23:27:23 +00008590 if (isInstructionTriviallyDead(I)) {
8591 // Make sure we process all operands now that we are reducing their
8592 // use counts.
8593 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
8594 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
8595 WorkList.push_back(OpI);
Misha Brukmanb1c93172005-04-21 23:48:37 +00008596
Chris Lattner63d75af2004-05-01 23:27:23 +00008597 // Instructions may end up in the worklist more than once. Erase all
Robert Bocchinoa8352962006-01-13 22:48:06 +00008598 // occurrences of this instruction.
Chris Lattner99f48c62002-09-02 04:59:56 +00008599 removeFromWorkList(I);
Chris Lattner31f486c2005-01-31 05:36:43 +00008600 I->eraseFromParent();
Chris Lattner396dbfe2004-06-09 05:08:07 +00008601 } else {
8602 WorkList.push_back(Result);
8603 AddUsersToWorkList(*Result);
Chris Lattnerae7a0d32002-08-02 19:29:35 +00008604 }
Chris Lattner053c0932002-05-14 15:24:07 +00008605 }
Chris Lattner260ab202002-04-18 17:39:14 +00008606 Changed = true;
Chris Lattnerca081252001-12-14 16:52:21 +00008607 }
8608 }
8609
Chris Lattner260ab202002-04-18 17:39:14 +00008610 return Changed;
Chris Lattner04805fa2002-02-26 21:46:54 +00008611}
8612
Brian Gaeke38b79e82004-07-27 17:43:21 +00008613FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattner260ab202002-04-18 17:39:14 +00008614 return new InstCombiner();
Chris Lattner04805fa2002-02-26 21:46:54 +00008615}
Brian Gaeke960707c2003-11-11 22:41:34 +00008616