blob: f0961de52743d90547eb64b842764213670b71a4 [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);
134 Instruction *visitDiv(BinaryOperator &I);
135 Instruction *visitRem(BinaryOperator &I);
136 Instruction *visitAnd(BinaryOperator &I);
137 Instruction *visitOr (BinaryOperator &I);
138 Instruction *visitXor(BinaryOperator &I);
Chris Lattnerd1f46d32005-04-24 06:59:08 +0000139 Instruction *visitSetCondInst(SetCondInst &I);
140 Instruction *visitSetCondInstWithCastAndCast(SetCondInst &SCI);
141
Chris Lattner0798af32005-01-13 20:14:25 +0000142 Instruction *FoldGEPSetCC(User *GEPLHS, Value *RHS,
143 Instruction::BinaryOps Cond, Instruction &I);
Chris Lattnere8d6c602003-03-10 19:16:08 +0000144 Instruction *visitShiftInst(ShiftInst &I);
Chris Lattner14553932006-01-06 07:12:35 +0000145 Instruction *FoldShiftByConstant(Value *Op0, ConstantUInt *Op1,
146 ShiftInst &I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000147 Instruction *visitCastInst(CastInst &CI);
Chris Lattner411336f2005-01-19 21:50:18 +0000148 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
149 Instruction *FI);
Chris Lattnerb909e8b2004-03-12 05:52:32 +0000150 Instruction *visitSelectInst(SelectInst &CI);
Chris Lattner970c33a2003-06-19 17:00:31 +0000151 Instruction *visitCallInst(CallInst &CI);
152 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner113f4f42002-06-25 16:13:24 +0000153 Instruction *visitPHINode(PHINode &PN);
154 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Chris Lattner1085bdf2002-11-04 16:18:53 +0000155 Instruction *visitAllocationInst(AllocationInst &AI);
Chris Lattner8427bff2003-12-07 01:24:23 +0000156 Instruction *visitFreeInst(FreeInst &FI);
Chris Lattner0f1d8a32003-06-26 05:06:25 +0000157 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattner31f486c2005-01-31 05:36:43 +0000158 Instruction *visitStoreInst(StoreInst &SI);
Chris Lattner9eef8a72003-06-04 04:46:00 +0000159 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner4c9c20a2004-07-03 00:26:11 +0000160 Instruction *visitSwitchInst(SwitchInst &SI);
Chris Lattner39fac442006-04-15 01:39:45 +0000161 Instruction *visitInsertElementInst(InsertElementInst &IE);
Robert Bocchinoa8352962006-01-13 22:48:06 +0000162 Instruction *visitExtractElementInst(ExtractElementInst &EI);
Chris Lattnerfbb77a42006-04-10 22:45:52 +0000163 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
Chris Lattner260ab202002-04-18 17:39:14 +0000164
165 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner113f4f42002-06-25 16:13:24 +0000166 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000167
Chris Lattner970c33a2003-06-19 17:00:31 +0000168 private:
Chris Lattneraec3d942003-10-07 22:32:43 +0000169 Instruction *visitCallSite(CallSite CS);
Chris Lattner970c33a2003-06-19 17:00:31 +0000170 bool transformConstExprCastCall(CallSite CS);
171
Chris Lattner69193f92004-04-05 01:30:19 +0000172 public:
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000173 // InsertNewInstBefore - insert an instruction New before instruction Old
174 // in the program. Add the new instruction to the worklist.
175 //
Chris Lattner623826c2004-09-28 21:48:02 +0000176 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattner65217ff2002-08-23 18:32:43 +0000177 assert(New && New->getParent() == 0 &&
178 "New instruction already inserted into a basic block!");
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000179 BasicBlock *BB = Old.getParent();
180 BB->getInstList().insert(&Old, New); // Insert inst
181 WorkList.push_back(New); // Add to worklist
Chris Lattnere79e8542004-02-23 06:38:22 +0000182 return New;
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000183 }
184
Chris Lattner7e794272004-09-24 15:21:34 +0000185 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
186 /// This also adds the cast to the worklist. Finally, this returns the
187 /// cast.
188 Value *InsertCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
189 if (V->getType() == Ty) return V;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000190
Chris Lattnere79d2492006-04-06 19:19:17 +0000191 if (Constant *CV = dyn_cast<Constant>(V))
192 return ConstantExpr::getCast(CV, Ty);
193
Chris Lattner7e794272004-09-24 15:21:34 +0000194 Instruction *C = new CastInst(V, Ty, V->getName(), &Pos);
195 WorkList.push_back(C);
196 return C;
197 }
198
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000199 // ReplaceInstUsesWith - This method is to be used when an instruction is
200 // found to be dead, replacable with another preexisting expression. Here
201 // we add all uses of I to the worklist, replace all uses of I with the new
202 // value, then return I, so that the inst combiner will know that I was
203 // modified.
204 //
205 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattner51ea1272004-02-28 05:22:00 +0000206 AddUsersToWorkList(I); // Add all modified instrs to worklist
Chris Lattner8953b902004-04-05 02:10:19 +0000207 if (&I != V) {
208 I.replaceAllUsesWith(V);
209 return &I;
210 } else {
211 // If we are replacing the instruction with itself, this must be in a
212 // segment of unreachable code, so just clobber the instruction.
Chris Lattner8ba9ec92004-10-18 02:59:09 +0000213 I.replaceAllUsesWith(UndefValue::get(I.getType()));
Chris Lattner8953b902004-04-05 02:10:19 +0000214 return &I;
215 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000216 }
Chris Lattner51ea1272004-02-28 05:22:00 +0000217
Chris Lattner2590e512006-02-07 06:56:34 +0000218 // UpdateValueUsesWith - This method is to be used when an value is
219 // found to be replacable with another preexisting expression or was
220 // updated. Here we add all uses of I to the worklist, replace all uses of
221 // I with the new value (unless the instruction was just updated), then
222 // return true, so that the inst combiner will know that I was modified.
223 //
224 bool UpdateValueUsesWith(Value *Old, Value *New) {
225 AddUsersToWorkList(*Old); // Add all modified instrs to worklist
226 if (Old != New)
227 Old->replaceAllUsesWith(New);
228 if (Instruction *I = dyn_cast<Instruction>(Old))
229 WorkList.push_back(I);
Chris Lattner5b2edb12006-02-12 08:02:11 +0000230 if (Instruction *I = dyn_cast<Instruction>(New))
231 WorkList.push_back(I);
Chris Lattner2590e512006-02-07 06:56:34 +0000232 return true;
233 }
234
Chris Lattner51ea1272004-02-28 05:22:00 +0000235 // EraseInstFromFunction - When dealing with an instruction that has side
236 // effects or produces a void value, we can't rely on DCE to delete the
237 // instruction. Instead, visit methods should return the value returned by
238 // this function.
239 Instruction *EraseInstFromFunction(Instruction &I) {
240 assert(I.use_empty() && "Cannot erase instruction that is used!");
241 AddUsesToWorkList(I);
242 removeFromWorkList(&I);
Chris Lattner95307542004-11-18 21:41:39 +0000243 I.eraseFromParent();
Chris Lattner51ea1272004-02-28 05:22:00 +0000244 return 0; // Don't do anything with FI
245 }
246
Chris Lattner3ac7c262003-08-13 20:16:26 +0000247 private:
Chris Lattnerdfae8be2003-07-24 17:35:25 +0000248 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
249 /// InsertBefore instruction. This is specialized a bit to avoid inserting
250 /// casts that are known to not do anything...
251 ///
252 Value *InsertOperandCastBefore(Value *V, const Type *DestTy,
253 Instruction *InsertBefore);
254
Chris Lattner7fb29e12003-03-11 00:12:48 +0000255 // SimplifyCommutative - This performs a few simplifications for commutative
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000256 // operators.
Chris Lattner7fb29e12003-03-11 00:12:48 +0000257 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerba1cb382003-09-19 17:17:26 +0000258
Chris Lattner0157e7f2006-02-11 09:31:47 +0000259 bool SimplifyDemandedBits(Value *V, uint64_t Mask,
260 uint64_t &KnownZero, uint64_t &KnownOne,
261 unsigned Depth = 0);
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000262
Chris Lattner2deeaea2006-10-05 06:55:50 +0000263 Value *SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
264 uint64_t &UndefElts, unsigned Depth = 0);
265
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000266 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
267 // PHI node as operand #0, see if we can fold the instruction into the PHI
268 // (which is only possible if all operands to the PHI are constants).
269 Instruction *FoldOpIntoPhi(Instruction &I);
270
Chris Lattner7515cab2004-11-14 19:13:23 +0000271 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
272 // operator and they all are only used by the PHI, PHI together their
273 // inputs, and do the operation once, to the result of the PHI.
274 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
275
Chris Lattnerba1cb382003-09-19 17:17:26 +0000276 Instruction *OptAndOp(Instruction *Op, ConstantIntegral *OpRHS,
277 ConstantIntegral *AndRHS, BinaryOperator &TheAnd);
Chris Lattneraf517572005-09-18 04:24:45 +0000278
279 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantIntegral *Mask,
280 bool isSub, Instruction &I);
Chris Lattner6862fbd2004-09-29 17:40:11 +0000281 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
282 bool Inside, Instruction &IB);
Chris Lattner216be912005-10-24 06:03:58 +0000283 Instruction *PromoteCastOfAllocation(CastInst &CI, AllocationInst &AI);
Chris Lattnerc482a9e2006-06-15 19:07:26 +0000284 Instruction *MatchBSwap(BinaryOperator &I);
285
Chris Lattner1ebbe6a2006-05-13 02:06:03 +0000286 Value *EvaluateInDifferentType(Value *V, const Type *Ty);
Chris Lattner260ab202002-04-18 17:39:14 +0000287 };
Chris Lattnerb28b6802002-07-23 18:06:35 +0000288
Chris Lattnerc2d3d312006-08-27 22:42:52 +0000289 RegisterPass<InstCombiner> X("instcombine", "Combine redundant instructions");
Chris Lattner260ab202002-04-18 17:39:14 +0000290}
291
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000292// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattner81a7a232004-10-16 18:11:37 +0000293// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000294static unsigned getComplexity(Value *V) {
295 if (isa<Instruction>(V)) {
296 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
Chris Lattner81a7a232004-10-16 18:11:37 +0000297 return 3;
298 return 4;
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000299 }
Chris Lattner81a7a232004-10-16 18:11:37 +0000300 if (isa<Argument>(V)) return 3;
301 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000302}
Chris Lattner260ab202002-04-18 17:39:14 +0000303
Chris Lattner7fb29e12003-03-11 00:12:48 +0000304// isOnlyUse - Return true if this instruction will be deleted if we stop using
305// it.
306static bool isOnlyUse(Value *V) {
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000307 return V->hasOneUse() || isa<Constant>(V);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000308}
309
Chris Lattnere79e8542004-02-23 06:38:22 +0000310// getPromotedType - Return the specified type promoted as it would be to pass
311// though a va_arg area...
312static const Type *getPromotedType(const Type *Ty) {
Chris Lattner97bfcea2004-06-17 18:16:02 +0000313 switch (Ty->getTypeID()) {
Chris Lattnere79e8542004-02-23 06:38:22 +0000314 case Type::SByteTyID:
315 case Type::ShortTyID: return Type::IntTy;
316 case Type::UByteTyID:
317 case Type::UShortTyID: return Type::UIntTy;
318 case Type::FloatTyID: return Type::DoubleTy;
319 default: return Ty;
320 }
321}
322
Chris Lattner567b81f2005-09-13 00:40:14 +0000323/// isCast - If the specified operand is a CastInst or a constant expr cast,
324/// return the operand value, otherwise return null.
325static Value *isCast(Value *V) {
326 if (CastInst *I = dyn_cast<CastInst>(V))
327 return I->getOperand(0);
328 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
329 if (CE->getOpcode() == Instruction::Cast)
330 return CE->getOperand(0);
331 return 0;
332}
333
Chris Lattner1d441ad2006-05-06 09:00:16 +0000334enum CastType {
335 Noop = 0,
336 Truncate = 1,
337 Signext = 2,
338 Zeroext = 3
339};
340
341/// getCastType - In the future, we will split the cast instruction into these
342/// various types. Until then, we have to do the analysis here.
343static CastType getCastType(const Type *Src, const Type *Dest) {
344 assert(Src->isIntegral() && Dest->isIntegral() &&
345 "Only works on integral types!");
346 unsigned SrcSize = Src->getPrimitiveSizeInBits();
347 unsigned DestSize = Dest->getPrimitiveSizeInBits();
348
349 if (SrcSize == DestSize) return Noop;
350 if (SrcSize > DestSize) return Truncate;
351 if (Src->isSigned()) return Signext;
352 return Zeroext;
353}
354
355
356// isEliminableCastOfCast - Return true if it is valid to eliminate the CI
357// instruction.
358//
359static bool isEliminableCastOfCast(const Type *SrcTy, const Type *MidTy,
360 const Type *DstTy, TargetData *TD) {
361
362 // It is legal to eliminate the instruction if casting A->B->A if the sizes
363 // are identical and the bits don't get reinterpreted (for example
364 // int->float->int would not be allowed).
365 if (SrcTy == DstTy && SrcTy->isLosslesslyConvertibleTo(MidTy))
366 return true;
367
368 // If we are casting between pointer and integer types, treat pointers as
369 // integers of the appropriate size for the code below.
370 if (isa<PointerType>(SrcTy)) SrcTy = TD->getIntPtrType();
371 if (isa<PointerType>(MidTy)) MidTy = TD->getIntPtrType();
372 if (isa<PointerType>(DstTy)) DstTy = TD->getIntPtrType();
373
374 // Allow free casting and conversion of sizes as long as the sign doesn't
375 // change...
376 if (SrcTy->isIntegral() && MidTy->isIntegral() && DstTy->isIntegral()) {
377 CastType FirstCast = getCastType(SrcTy, MidTy);
378 CastType SecondCast = getCastType(MidTy, DstTy);
379
380 // Capture the effect of these two casts. If the result is a legal cast,
381 // the CastType is stored here, otherwise a special code is used.
382 static const unsigned CastResult[] = {
383 // First cast is noop
384 0, 1, 2, 3,
385 // First cast is a truncate
386 1, 1, 4, 4, // trunc->extend is not safe to eliminate
387 // First cast is a sign ext
388 2, 5, 2, 4, // signext->zeroext never ok
389 // First cast is a zero ext
390 3, 5, 3, 3,
391 };
392
393 unsigned Result = CastResult[FirstCast*4+SecondCast];
394 switch (Result) {
395 default: assert(0 && "Illegal table value!");
396 case 0:
397 case 1:
398 case 2:
399 case 3:
400 // FIXME: in the future, when LLVM has explicit sign/zeroextends and
401 // truncates, we could eliminate more casts.
402 return (unsigned)getCastType(SrcTy, DstTy) == Result;
403 case 4:
404 return false; // Not possible to eliminate this here.
405 case 5:
406 // Sign or zero extend followed by truncate is always ok if the result
407 // is a truncate or noop.
408 CastType ResultCast = getCastType(SrcTy, DstTy);
409 if (ResultCast == Noop || ResultCast == Truncate)
410 return true;
411 // Otherwise we are still growing the value, we are only safe if the
412 // result will match the sign/zeroextendness of the result.
413 return ResultCast == FirstCast;
414 }
415 }
416
417 // If this is a cast from 'float -> double -> integer', cast from
418 // 'float -> integer' directly, as the value isn't changed by the
419 // float->double conversion.
420 if (SrcTy->isFloatingPoint() && MidTy->isFloatingPoint() &&
421 DstTy->isIntegral() &&
422 SrcTy->getPrimitiveSize() < MidTy->getPrimitiveSize())
423 return true;
424
425 // Packed type conversions don't modify bits.
426 if (isa<PackedType>(SrcTy) && isa<PackedType>(MidTy) &&isa<PackedType>(DstTy))
427 return true;
428
429 return false;
430}
431
432/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
433/// in any code being generated. It does not require codegen if V is simple
434/// enough or if the cast can be folded into other casts.
435static bool ValueRequiresCast(const Value *V, const Type *Ty, TargetData *TD) {
436 if (V->getType() == Ty || isa<Constant>(V)) return false;
437
438 // If this is a noop cast, it isn't real codegen.
439 if (V->getType()->isLosslesslyConvertibleTo(Ty))
440 return false;
441
Chris Lattner99155be2006-05-25 23:24:33 +0000442 // If this is another cast that can be eliminated, it isn't codegen either.
Chris Lattner1d441ad2006-05-06 09:00:16 +0000443 if (const CastInst *CI = dyn_cast<CastInst>(V))
444 if (isEliminableCastOfCast(CI->getOperand(0)->getType(), CI->getType(), Ty,
445 TD))
446 return false;
447 return true;
448}
449
450/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
451/// InsertBefore instruction. This is specialized a bit to avoid inserting
452/// casts that are known to not do anything...
453///
454Value *InstCombiner::InsertOperandCastBefore(Value *V, const Type *DestTy,
455 Instruction *InsertBefore) {
456 if (V->getType() == DestTy) return V;
457 if (Constant *C = dyn_cast<Constant>(V))
458 return ConstantExpr::getCast(C, DestTy);
459
460 CastInst *CI = new CastInst(V, DestTy, V->getName());
461 InsertNewInstBefore(CI, *InsertBefore);
462 return CI;
463}
464
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000465// SimplifyCommutative - This performs a few simplifications for commutative
466// operators:
Chris Lattner260ab202002-04-18 17:39:14 +0000467//
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000468// 1. Order operands such that they are listed from right (least complex) to
469// left (most complex). This puts constants before unary operators before
470// binary operators.
471//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000472// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
473// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000474//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000475bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000476 bool Changed = false;
477 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
478 Changed = !I.swapOperands();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000479
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000480 if (!I.isAssociative()) return Changed;
481 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattner7fb29e12003-03-11 00:12:48 +0000482 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
483 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
484 if (isa<Constant>(I.getOperand(1))) {
Chris Lattner34428442003-05-27 16:40:51 +0000485 Constant *Folded = ConstantExpr::get(I.getOpcode(),
486 cast<Constant>(I.getOperand(1)),
487 cast<Constant>(Op->getOperand(1)));
Chris Lattner7fb29e12003-03-11 00:12:48 +0000488 I.setOperand(0, Op->getOperand(0));
489 I.setOperand(1, Folded);
490 return true;
491 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
492 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
493 isOnlyUse(Op) && isOnlyUse(Op1)) {
494 Constant *C1 = cast<Constant>(Op->getOperand(1));
495 Constant *C2 = cast<Constant>(Op1->getOperand(1));
496
497 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner34428442003-05-27 16:40:51 +0000498 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000499 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
500 Op1->getOperand(0),
501 Op1->getName(), &I);
502 WorkList.push_back(New);
503 I.setOperand(0, New);
504 I.setOperand(1, Folded);
505 return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000506 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000507 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000508 return Changed;
Chris Lattner260ab202002-04-18 17:39:14 +0000509}
Chris Lattnerca081252001-12-14 16:52:21 +0000510
Chris Lattnerbb74e222003-03-10 23:06:50 +0000511// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
512// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattner9fa53de2002-05-06 16:49:18 +0000513//
Chris Lattnerbb74e222003-03-10 23:06:50 +0000514static inline Value *dyn_castNegVal(Value *V) {
515 if (BinaryOperator::isNeg(V))
Chris Lattnerd6f636a2005-04-24 07:30:14 +0000516 return BinaryOperator::getNegArgument(V);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000517
Chris Lattner9ad0d552004-12-14 20:08:06 +0000518 // Constants can be considered to be negated values if they can be folded.
519 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
520 return ConstantExpr::getNeg(C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000521 return 0;
Chris Lattner9fa53de2002-05-06 16:49:18 +0000522}
523
Chris Lattnerbb74e222003-03-10 23:06:50 +0000524static inline Value *dyn_castNotVal(Value *V) {
525 if (BinaryOperator::isNot(V))
Chris Lattnerd6f636a2005-04-24 07:30:14 +0000526 return BinaryOperator::getNotArgument(V);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000527
528 // Constants can be considered to be not'ed values...
Chris Lattnerdd65d862003-04-30 22:34:06 +0000529 if (ConstantIntegral *C = dyn_cast<ConstantIntegral>(V))
Chris Lattnerc8e7e292004-06-10 02:12:35 +0000530 return ConstantExpr::getNot(C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000531 return 0;
532}
533
Chris Lattner7fb29e12003-03-11 00:12:48 +0000534// dyn_castFoldableMul - If this value is a multiply that can be folded into
535// other computations (because it has a constant operand), return the
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000536// non-constant operand of the multiply, and set CST to point to the multiplier.
537// Otherwise, return null.
Chris Lattner7fb29e12003-03-11 00:12:48 +0000538//
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000539static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000540 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000541 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattner7fb29e12003-03-11 00:12:48 +0000542 if (I->getOpcode() == Instruction::Mul)
Chris Lattner970136362004-11-15 05:54:07 +0000543 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattner7fb29e12003-03-11 00:12:48 +0000544 return I->getOperand(0);
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000545 if (I->getOpcode() == Instruction::Shl)
Chris Lattner970136362004-11-15 05:54:07 +0000546 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000547 // The multiplier is really 1 << CST.
548 Constant *One = ConstantInt::get(V->getType(), 1);
549 CST = cast<ConstantInt>(ConstantExpr::getShl(One, CST));
550 return I->getOperand(0);
551 }
552 }
Chris Lattner7fb29e12003-03-11 00:12:48 +0000553 return 0;
Chris Lattner3082c5a2003-02-18 19:28:33 +0000554}
Chris Lattner31ae8632002-08-14 17:51:49 +0000555
Chris Lattner0798af32005-01-13 20:14:25 +0000556/// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
557/// expression, return it.
558static User *dyn_castGetElementPtr(Value *V) {
559 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
560 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
561 if (CE->getOpcode() == Instruction::GetElementPtr)
562 return cast<User>(V);
563 return false;
564}
565
Chris Lattner623826c2004-09-28 21:48:02 +0000566// AddOne, SubOne - Add or subtract a constant one from an integer constant...
Chris Lattner6862fbd2004-09-29 17:40:11 +0000567static ConstantInt *AddOne(ConstantInt *C) {
568 return cast<ConstantInt>(ConstantExpr::getAdd(C,
569 ConstantInt::get(C->getType(), 1)));
Chris Lattner623826c2004-09-28 21:48:02 +0000570}
Chris Lattner6862fbd2004-09-29 17:40:11 +0000571static ConstantInt *SubOne(ConstantInt *C) {
572 return cast<ConstantInt>(ConstantExpr::getSub(C,
573 ConstantInt::get(C->getType(), 1)));
Chris Lattner623826c2004-09-28 21:48:02 +0000574}
575
Chris Lattner0157e7f2006-02-11 09:31:47 +0000576/// GetConstantInType - Return a ConstantInt with the specified type and value.
577///
Chris Lattneree0f2802006-02-12 02:07:56 +0000578static ConstantIntegral *GetConstantInType(const Type *Ty, uint64_t Val) {
Chris Lattner0157e7f2006-02-11 09:31:47 +0000579 if (Ty->isUnsigned())
580 return ConstantUInt::get(Ty, Val);
Chris Lattneree0f2802006-02-12 02:07:56 +0000581 else if (Ty->getTypeID() == Type::BoolTyID)
582 return ConstantBool::get(Val);
Chris Lattner0157e7f2006-02-11 09:31:47 +0000583 int64_t SVal = Val;
584 SVal <<= 64-Ty->getPrimitiveSizeInBits();
585 SVal >>= 64-Ty->getPrimitiveSizeInBits();
586 return ConstantSInt::get(Ty, SVal);
587}
588
589
Chris Lattner4534dd592006-02-09 07:38:58 +0000590/// ComputeMaskedBits - Determine which of the bits specified in Mask are
591/// known to be either zero or one and return them in the KnownZero/KnownOne
592/// bitsets. This code only analyzes bits in Mask, in order to short-circuit
593/// processing.
594static void ComputeMaskedBits(Value *V, uint64_t Mask, uint64_t &KnownZero,
595 uint64_t &KnownOne, unsigned Depth = 0) {
Chris Lattner0b3557f2005-09-24 23:43:33 +0000596 // Note, we cannot consider 'undef' to be "IsZero" here. The problem is that
597 // we cannot optimize based on the assumption that it is zero without changing
Chris Lattnerc3ebf402006-02-07 07:27:52 +0000598 // it to be an explicit zero. If we don't change it to zero, other code could
Chris Lattner0b3557f2005-09-24 23:43:33 +0000599 // optimized based on the contradictory assumption that it is non-zero.
600 // Because instcombine aggressively folds operations with undef args anyway,
601 // this won't lose us code quality.
Chris Lattner4534dd592006-02-09 07:38:58 +0000602 if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(V)) {
603 // We know all of the bits for a constant!
Chris Lattner0157e7f2006-02-11 09:31:47 +0000604 KnownOne = CI->getZExtValue() & Mask;
Chris Lattner4534dd592006-02-09 07:38:58 +0000605 KnownZero = ~KnownOne & Mask;
606 return;
607 }
608
609 KnownZero = KnownOne = 0; // Don't know anything.
Chris Lattner92a68652006-02-07 08:05:22 +0000610 if (Depth == 6 || Mask == 0)
Chris Lattner4534dd592006-02-09 07:38:58 +0000611 return; // Limit search depth.
612
613 uint64_t KnownZero2, KnownOne2;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000614 Instruction *I = dyn_cast<Instruction>(V);
615 if (!I) return;
616
Chris Lattnerfb296922006-05-04 17:33:35 +0000617 Mask &= V->getType()->getIntegralTypeMask();
618
Chris Lattner0157e7f2006-02-11 09:31:47 +0000619 switch (I->getOpcode()) {
620 case Instruction::And:
621 // If either the LHS or the RHS are Zero, the result is zero.
622 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
623 Mask &= ~KnownZero;
624 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
625 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
626 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
627
628 // Output known-1 bits are only known if set in both the LHS & RHS.
629 KnownOne &= KnownOne2;
630 // Output known-0 are known to be clear if zero in either the LHS | RHS.
631 KnownZero |= KnownZero2;
632 return;
633 case Instruction::Or:
634 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
635 Mask &= ~KnownOne;
636 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
637 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
638 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
639
640 // Output known-0 bits are only known if clear in both the LHS & RHS.
641 KnownZero &= KnownZero2;
642 // Output known-1 are known to be set if set in either the LHS | RHS.
643 KnownOne |= KnownOne2;
644 return;
645 case Instruction::Xor: {
646 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
647 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
648 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
649 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
650
651 // Output known-0 bits are known if clear or set in both the LHS & RHS.
652 uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
653 // Output known-1 are known to be set if set in only one of the LHS, RHS.
654 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
655 KnownZero = KnownZeroOut;
656 return;
657 }
658 case Instruction::Select:
659 ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
660 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
661 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
662 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
663
664 // Only known if known in both the LHS and RHS.
665 KnownOne &= KnownOne2;
666 KnownZero &= KnownZero2;
667 return;
668 case Instruction::Cast: {
669 const Type *SrcTy = I->getOperand(0)->getType();
670 if (!SrcTy->isIntegral()) return;
671
672 // If this is an integer truncate or noop, just look in the input.
673 if (SrcTy->getPrimitiveSizeInBits() >=
674 I->getType()->getPrimitiveSizeInBits()) {
675 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
Chris Lattner4534dd592006-02-09 07:38:58 +0000676 return;
677 }
Chris Lattner4534dd592006-02-09 07:38:58 +0000678
Chris Lattner0157e7f2006-02-11 09:31:47 +0000679 // Sign or Zero extension. Compute the bits in the result that are not
680 // present in the input.
681 uint64_t NotIn = ~SrcTy->getIntegralTypeMask();
682 uint64_t NewBits = I->getType()->getIntegralTypeMask() & NotIn;
Chris Lattner62010c42005-10-09 06:36:35 +0000683
Chris Lattner0157e7f2006-02-11 09:31:47 +0000684 // Handle zero extension.
685 if (!SrcTy->isSigned()) {
686 Mask &= SrcTy->getIntegralTypeMask();
687 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
688 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
689 // The top bits are known to be zero.
690 KnownZero |= NewBits;
691 } else {
692 // Sign extension.
693 Mask &= SrcTy->getIntegralTypeMask();
694 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
695 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattner92a68652006-02-07 08:05:22 +0000696
Chris Lattner0157e7f2006-02-11 09:31:47 +0000697 // If the sign bit of the input is known set or clear, then we know the
698 // top bits of the result.
699 uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
700 if (KnownZero & InSignBit) { // Input sign bit known zero
Chris Lattner4534dd592006-02-09 07:38:58 +0000701 KnownZero |= NewBits;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000702 KnownOne &= ~NewBits;
703 } else if (KnownOne & InSignBit) { // Input sign bit known set
704 KnownOne |= NewBits;
705 KnownZero &= ~NewBits;
706 } else { // Input sign bit unknown
707 KnownZero &= ~NewBits;
708 KnownOne &= ~NewBits;
709 }
710 }
711 return;
712 }
713 case Instruction::Shl:
714 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
715 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1))) {
716 Mask >>= SA->getValue();
717 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
718 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
719 KnownZero <<= SA->getValue();
720 KnownOne <<= SA->getValue();
721 KnownZero |= (1ULL << SA->getValue())-1; // low bits known zero.
722 return;
723 }
724 break;
725 case Instruction::Shr:
726 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
727 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1))) {
728 // Compute the new bits that are at the top now.
729 uint64_t HighBits = (1ULL << SA->getValue())-1;
730 HighBits <<= I->getType()->getPrimitiveSizeInBits()-SA->getValue();
731
732 if (I->getType()->isUnsigned()) { // Unsigned shift right.
733 Mask <<= SA->getValue();
734 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
735 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
736 KnownZero >>= SA->getValue();
737 KnownOne >>= SA->getValue();
738 KnownZero |= HighBits; // high bits known zero.
Chris Lattner4534dd592006-02-09 07:38:58 +0000739 } else {
Chris Lattner0157e7f2006-02-11 09:31:47 +0000740 Mask <<= SA->getValue();
741 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
742 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
743 KnownZero >>= SA->getValue();
744 KnownOne >>= SA->getValue();
745
746 // Handle the sign bits.
747 uint64_t SignBit = 1ULL << (I->getType()->getPrimitiveSizeInBits()-1);
748 SignBit >>= SA->getValue(); // Adjust to where it is now in the mask.
749
750 if (KnownZero & SignBit) { // New bits are known zero.
751 KnownZero |= HighBits;
752 } else if (KnownOne & SignBit) { // New bits are known one.
753 KnownOne |= HighBits;
Chris Lattner4534dd592006-02-09 07:38:58 +0000754 }
755 }
756 return;
Chris Lattner62010c42005-10-09 06:36:35 +0000757 }
Chris Lattner0157e7f2006-02-11 09:31:47 +0000758 break;
Chris Lattner0b3557f2005-09-24 23:43:33 +0000759 }
Chris Lattner92a68652006-02-07 08:05:22 +0000760}
761
762/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
763/// this predicate to simplify operations downstream. Mask is known to be zero
764/// for bits that V cannot have.
765static bool MaskedValueIsZero(Value *V, uint64_t Mask, unsigned Depth = 0) {
Chris Lattner4534dd592006-02-09 07:38:58 +0000766 uint64_t KnownZero, KnownOne;
767 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
768 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
769 return (KnownZero & Mask) == Mask;
Chris Lattner0b3557f2005-09-24 23:43:33 +0000770}
771
Chris Lattner0157e7f2006-02-11 09:31:47 +0000772/// ShrinkDemandedConstant - Check to see if the specified operand of the
773/// specified instruction is a constant integer. If so, check to see if there
774/// are any bits set in the constant that are not demanded. If so, shrink the
775/// constant and return true.
776static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
777 uint64_t Demanded) {
778 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
779 if (!OpC) return false;
780
781 // If there are no bits set that aren't demanded, nothing to do.
782 if ((~Demanded & OpC->getZExtValue()) == 0)
783 return false;
784
785 // This is producing any bits that are not needed, shrink the RHS.
786 uint64_t Val = Demanded & OpC->getZExtValue();
787 I->setOperand(OpNo, GetConstantInType(OpC->getType(), Val));
788 return true;
789}
790
Chris Lattneree0f2802006-02-12 02:07:56 +0000791// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
792// set of known zero and one bits, compute the maximum and minimum values that
793// could have the specified known zero and known one bits, returning them in
794// min/max.
795static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
796 uint64_t KnownZero,
797 uint64_t KnownOne,
798 int64_t &Min, int64_t &Max) {
799 uint64_t TypeBits = Ty->getIntegralTypeMask();
800 uint64_t UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
801
802 uint64_t SignBit = 1ULL << (Ty->getPrimitiveSizeInBits()-1);
803
804 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
805 // bit if it is unknown.
806 Min = KnownOne;
807 Max = KnownOne|UnknownBits;
808
809 if (SignBit & UnknownBits) { // Sign bit is unknown
810 Min |= SignBit;
811 Max &= ~SignBit;
812 }
813
814 // Sign extend the min/max values.
815 int ShAmt = 64-Ty->getPrimitiveSizeInBits();
816 Min = (Min << ShAmt) >> ShAmt;
817 Max = (Max << ShAmt) >> ShAmt;
818}
819
820// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
821// a set of known zero and one bits, compute the maximum and minimum values that
822// could have the specified known zero and known one bits, returning them in
823// min/max.
824static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
825 uint64_t KnownZero,
826 uint64_t KnownOne,
827 uint64_t &Min,
828 uint64_t &Max) {
829 uint64_t TypeBits = Ty->getIntegralTypeMask();
830 uint64_t UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
831
832 // The minimum value is when the unknown bits are all zeros.
833 Min = KnownOne;
834 // The maximum value is when the unknown bits are all ones.
835 Max = KnownOne|UnknownBits;
836}
Chris Lattner0157e7f2006-02-11 09:31:47 +0000837
838
839/// SimplifyDemandedBits - Look at V. At this point, we know that only the
840/// DemandedMask bits of the result of V are ever used downstream. If we can
841/// use this information to simplify V, do so and return true. Otherwise,
842/// analyze the expression and return a mask of KnownOne and KnownZero bits for
843/// the expression (used to simplify the caller). The KnownZero/One bits may
844/// only be accurate for those bits in the DemandedMask.
845bool InstCombiner::SimplifyDemandedBits(Value *V, uint64_t DemandedMask,
846 uint64_t &KnownZero, uint64_t &KnownOne,
Chris Lattner2590e512006-02-07 06:56:34 +0000847 unsigned Depth) {
Chris Lattner0157e7f2006-02-11 09:31:47 +0000848 if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(V)) {
849 // We know all of the bits for a constant!
850 KnownOne = CI->getZExtValue() & DemandedMask;
851 KnownZero = ~KnownOne & DemandedMask;
852 return false;
853 }
854
855 KnownZero = KnownOne = 0;
Chris Lattner2590e512006-02-07 06:56:34 +0000856 if (!V->hasOneUse()) { // Other users may use these bits.
Chris Lattner0157e7f2006-02-11 09:31:47 +0000857 if (Depth != 0) { // Not at the root.
858 // Just compute the KnownZero/KnownOne bits to simplify things downstream.
859 ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
Chris Lattner2590e512006-02-07 06:56:34 +0000860 return false;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000861 }
Chris Lattner2590e512006-02-07 06:56:34 +0000862 // If this is the root being simplified, allow it to have multiple uses,
Chris Lattner0157e7f2006-02-11 09:31:47 +0000863 // just set the DemandedMask to all bits.
864 DemandedMask = V->getType()->getIntegralTypeMask();
865 } else if (DemandedMask == 0) { // Not demanding any bits from V.
Chris Lattner92a68652006-02-07 08:05:22 +0000866 if (V != UndefValue::get(V->getType()))
867 return UpdateValueUsesWith(V, UndefValue::get(V->getType()));
868 return false;
Chris Lattner2590e512006-02-07 06:56:34 +0000869 } else if (Depth == 6) { // Limit search depth.
870 return false;
871 }
872
873 Instruction *I = dyn_cast<Instruction>(V);
874 if (!I) return false; // Only analyze instructions.
875
Chris Lattnerfb296922006-05-04 17:33:35 +0000876 DemandedMask &= V->getType()->getIntegralTypeMask();
877
Chris Lattner0157e7f2006-02-11 09:31:47 +0000878 uint64_t KnownZero2, KnownOne2;
Chris Lattner2590e512006-02-07 06:56:34 +0000879 switch (I->getOpcode()) {
880 default: break;
881 case Instruction::And:
Chris Lattner0157e7f2006-02-11 09:31:47 +0000882 // If either the LHS or the RHS are Zero, the result is zero.
883 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
884 KnownZero, KnownOne, Depth+1))
885 return true;
886 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
887
888 // If something is known zero on the RHS, the bits aren't demanded on the
889 // LHS.
890 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownZero,
891 KnownZero2, KnownOne2, Depth+1))
892 return true;
893 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
894
895 // If all of the demanded bits are known one on one side, return the other.
896 // These bits cannot contribute to the result of the 'and'.
897 if ((DemandedMask & ~KnownZero2 & KnownOne) == (DemandedMask & ~KnownZero2))
898 return UpdateValueUsesWith(I, I->getOperand(0));
899 if ((DemandedMask & ~KnownZero & KnownOne2) == (DemandedMask & ~KnownZero))
900 return UpdateValueUsesWith(I, I->getOperand(1));
Chris Lattner5b2edb12006-02-12 08:02:11 +0000901
902 // If all of the demanded bits in the inputs are known zeros, return zero.
903 if ((DemandedMask & (KnownZero|KnownZero2)) == DemandedMask)
904 return UpdateValueUsesWith(I, Constant::getNullValue(I->getType()));
905
Chris Lattner0157e7f2006-02-11 09:31:47 +0000906 // If the RHS is a constant, see if we can simplify it.
Chris Lattner5b2edb12006-02-12 08:02:11 +0000907 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~KnownZero2))
Chris Lattner0157e7f2006-02-11 09:31:47 +0000908 return UpdateValueUsesWith(I, I);
909
910 // Output known-1 bits are only known if set in both the LHS & RHS.
911 KnownOne &= KnownOne2;
912 // Output known-0 are known to be clear if zero in either the LHS | RHS.
913 KnownZero |= KnownZero2;
914 break;
915 case Instruction::Or:
916 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
917 KnownZero, KnownOne, Depth+1))
918 return true;
919 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
920 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownOne,
921 KnownZero2, KnownOne2, Depth+1))
922 return true;
923 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
924
925 // If all of the demanded bits are known zero on one side, return the other.
926 // These bits cannot contribute to the result of the 'or'.
Jeff Cohen0add83e2006-02-18 03:20:33 +0000927 if ((DemandedMask & ~KnownOne2 & KnownZero) == (DemandedMask & ~KnownOne2))
Chris Lattner0157e7f2006-02-11 09:31:47 +0000928 return UpdateValueUsesWith(I, I->getOperand(0));
Jeff Cohen0add83e2006-02-18 03:20:33 +0000929 if ((DemandedMask & ~KnownOne & KnownZero2) == (DemandedMask & ~KnownOne))
Chris Lattner0157e7f2006-02-11 09:31:47 +0000930 return UpdateValueUsesWith(I, I->getOperand(1));
Chris Lattner5b2edb12006-02-12 08:02:11 +0000931
932 // If all of the potentially set bits on one side are known to be set on
933 // the other side, just use the 'other' side.
934 if ((DemandedMask & (~KnownZero) & KnownOne2) ==
935 (DemandedMask & (~KnownZero)))
936 return UpdateValueUsesWith(I, I->getOperand(0));
Nate Begeman8a77efe2006-02-16 21:11:51 +0000937 if ((DemandedMask & (~KnownZero2) & KnownOne) ==
938 (DemandedMask & (~KnownZero2)))
939 return UpdateValueUsesWith(I, I->getOperand(1));
Chris Lattner0157e7f2006-02-11 09:31:47 +0000940
941 // If the RHS is a constant, see if we can simplify it.
942 if (ShrinkDemandedConstant(I, 1, DemandedMask))
943 return UpdateValueUsesWith(I, I);
944
945 // Output known-0 bits are only known if clear in both the LHS & RHS.
946 KnownZero &= KnownZero2;
947 // Output known-1 are known to be set if set in either the LHS | RHS.
948 KnownOne |= KnownOne2;
949 break;
950 case Instruction::Xor: {
951 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
952 KnownZero, KnownOne, Depth+1))
953 return true;
954 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
955 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
956 KnownZero2, KnownOne2, Depth+1))
957 return true;
958 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
959
960 // If all of the demanded bits are known zero on one side, return the other.
961 // These bits cannot contribute to the result of the 'xor'.
962 if ((DemandedMask & KnownZero) == DemandedMask)
963 return UpdateValueUsesWith(I, I->getOperand(0));
964 if ((DemandedMask & KnownZero2) == DemandedMask)
965 return UpdateValueUsesWith(I, I->getOperand(1));
966
967 // Output known-0 bits are known if clear or set in both the LHS & RHS.
968 uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
969 // Output known-1 are known to be set if set in only one of the LHS, RHS.
970 uint64_t KnownOneOut = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
971
972 // If all of the unknown bits are known to be zero on one side or the other
973 // (but not both) turn this into an *inclusive* or.
Chris Lattner5b2edb12006-02-12 08:02:11 +0000974 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattner0157e7f2006-02-11 09:31:47 +0000975 if (uint64_t UnknownBits = DemandedMask & ~(KnownZeroOut|KnownOneOut)) {
976 if ((UnknownBits & (KnownZero|KnownZero2)) == UnknownBits) {
977 Instruction *Or =
978 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
979 I->getName());
980 InsertNewInstBefore(Or, *I);
981 return UpdateValueUsesWith(I, Or);
Chris Lattner2590e512006-02-07 06:56:34 +0000982 }
983 }
Chris Lattner0157e7f2006-02-11 09:31:47 +0000984
Chris Lattner5b2edb12006-02-12 08:02:11 +0000985 // If all of the demanded bits on one side are known, and all of the set
986 // bits on that side are also known to be set on the other side, turn this
987 // into an AND, as we know the bits will be cleared.
988 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
989 if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask) { // all known
990 if ((KnownOne & KnownOne2) == KnownOne) {
991 Constant *AndC = GetConstantInType(I->getType(),
992 ~KnownOne & DemandedMask);
993 Instruction *And =
994 BinaryOperator::createAnd(I->getOperand(0), AndC, "tmp");
995 InsertNewInstBefore(And, *I);
996 return UpdateValueUsesWith(I, And);
997 }
998 }
999
Chris Lattner0157e7f2006-02-11 09:31:47 +00001000 // If the RHS is a constant, see if we can simplify it.
1001 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1002 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1003 return UpdateValueUsesWith(I, I);
1004
1005 KnownZero = KnownZeroOut;
1006 KnownOne = KnownOneOut;
1007 break;
1008 }
1009 case Instruction::Select:
1010 if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
1011 KnownZero, KnownOne, Depth+1))
1012 return true;
1013 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1014 KnownZero2, KnownOne2, Depth+1))
1015 return true;
1016 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1017 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1018
1019 // If the operands are constants, see if we can simplify them.
1020 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1021 return UpdateValueUsesWith(I, I);
1022 if (ShrinkDemandedConstant(I, 2, DemandedMask))
1023 return UpdateValueUsesWith(I, I);
1024
1025 // Only known if known in both the LHS and RHS.
1026 KnownOne &= KnownOne2;
1027 KnownZero &= KnownZero2;
1028 break;
Chris Lattner2590e512006-02-07 06:56:34 +00001029 case Instruction::Cast: {
1030 const Type *SrcTy = I->getOperand(0)->getType();
Chris Lattner0157e7f2006-02-11 09:31:47 +00001031 if (!SrcTy->isIntegral()) return false;
Chris Lattner2590e512006-02-07 06:56:34 +00001032
Chris Lattner0157e7f2006-02-11 09:31:47 +00001033 // If this is an integer truncate or noop, just look in the input.
1034 if (SrcTy->getPrimitiveSizeInBits() >=
1035 I->getType()->getPrimitiveSizeInBits()) {
Chris Lattner850465d2006-09-16 03:14:10 +00001036 // Cast to bool is a comparison against 0, which demands all bits. We
1037 // can't propagate anything useful up.
1038 if (I->getType() == Type::BoolTy)
1039 break;
1040
Chris Lattner0157e7f2006-02-11 09:31:47 +00001041 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1042 KnownZero, KnownOne, Depth+1))
1043 return true;
1044 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1045 break;
1046 }
1047
1048 // Sign or Zero extension. Compute the bits in the result that are not
1049 // present in the input.
1050 uint64_t NotIn = ~SrcTy->getIntegralTypeMask();
1051 uint64_t NewBits = I->getType()->getIntegralTypeMask() & NotIn;
1052
1053 // Handle zero extension.
1054 if (!SrcTy->isSigned()) {
1055 DemandedMask &= SrcTy->getIntegralTypeMask();
1056 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1057 KnownZero, KnownOne, Depth+1))
1058 return true;
1059 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1060 // The top bits are known to be zero.
1061 KnownZero |= NewBits;
1062 } else {
1063 // Sign extension.
Chris Lattner7d852282006-02-13 22:41:07 +00001064 uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
1065 int64_t InputDemandedBits = DemandedMask & SrcTy->getIntegralTypeMask();
1066
1067 // If any of the sign extended bits are demanded, we know that the sign
1068 // bit is demanded.
1069 if (NewBits & DemandedMask)
1070 InputDemandedBits |= InSignBit;
1071
1072 if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
Chris Lattner0157e7f2006-02-11 09:31:47 +00001073 KnownZero, KnownOne, Depth+1))
1074 return true;
1075 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1076
1077 // If the sign bit of the input is known set or clear, then we know the
1078 // top bits of the result.
Chris Lattner2590e512006-02-07 06:56:34 +00001079
Chris Lattner0157e7f2006-02-11 09:31:47 +00001080 // If the input sign bit is known zero, or if the NewBits are not demanded
1081 // convert this into a zero extension.
1082 if ((KnownZero & InSignBit) || (NewBits & ~DemandedMask) == NewBits) {
Chris Lattner2590e512006-02-07 06:56:34 +00001083 // Convert to unsigned first.
Chris Lattner44314822006-02-07 19:07:40 +00001084 Instruction *NewVal;
Chris Lattner2590e512006-02-07 06:56:34 +00001085 NewVal = new CastInst(I->getOperand(0), SrcTy->getUnsignedVersion(),
Chris Lattner44314822006-02-07 19:07:40 +00001086 I->getOperand(0)->getName());
1087 InsertNewInstBefore(NewVal, *I);
Chris Lattner0157e7f2006-02-11 09:31:47 +00001088 // Then cast that to the destination type.
Chris Lattner44314822006-02-07 19:07:40 +00001089 NewVal = new CastInst(NewVal, I->getType(), I->getName());
1090 InsertNewInstBefore(NewVal, *I);
Chris Lattner2590e512006-02-07 06:56:34 +00001091 return UpdateValueUsesWith(I, NewVal);
Chris Lattner0157e7f2006-02-11 09:31:47 +00001092 } else if (KnownOne & InSignBit) { // Input sign bit known set
1093 KnownOne |= NewBits;
1094 KnownZero &= ~NewBits;
1095 } else { // Input sign bit unknown
1096 KnownZero &= ~NewBits;
1097 KnownOne &= ~NewBits;
Chris Lattner2590e512006-02-07 06:56:34 +00001098 }
Chris Lattner2590e512006-02-07 06:56:34 +00001099 }
Chris Lattner0157e7f2006-02-11 09:31:47 +00001100 break;
Chris Lattner2590e512006-02-07 06:56:34 +00001101 }
Chris Lattner2590e512006-02-07 06:56:34 +00001102 case Instruction::Shl:
Chris Lattner0157e7f2006-02-11 09:31:47 +00001103 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1))) {
1104 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask >> SA->getValue(),
1105 KnownZero, KnownOne, Depth+1))
1106 return true;
1107 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1108 KnownZero <<= SA->getValue();
1109 KnownOne <<= SA->getValue();
1110 KnownZero |= (1ULL << SA->getValue())-1; // low bits known zero.
1111 }
Chris Lattner2590e512006-02-07 06:56:34 +00001112 break;
1113 case Instruction::Shr:
Chris Lattner420c4bc2006-09-18 04:31:40 +00001114 // If this is an arithmetic shift right and only the low-bit is set, we can
1115 // always convert this into a logical shr, even if the shift amount is
1116 // variable. The low bit of the shift cannot be an input sign bit unless
1117 // the shift amount is >= the size of the datatype, which is undefined.
1118 if (DemandedMask == 1 && I->getType()->isSigned()) {
1119 // Convert the input to unsigned.
1120 Instruction *NewVal = new CastInst(I->getOperand(0),
1121 I->getType()->getUnsignedVersion(),
1122 I->getOperand(0)->getName());
1123 InsertNewInstBefore(NewVal, *I);
1124 // Perform the unsigned shift right.
1125 NewVal = new ShiftInst(Instruction::Shr, NewVal, I->getOperand(1),
1126 I->getName());
1127 InsertNewInstBefore(NewVal, *I);
1128 // Then cast that to the destination type.
1129 NewVal = new CastInst(NewVal, I->getType(), I->getName());
1130 InsertNewInstBefore(NewVal, *I);
1131 return UpdateValueUsesWith(I, NewVal);
1132 }
1133
Chris Lattner0157e7f2006-02-11 09:31:47 +00001134 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1))) {
1135 unsigned ShAmt = SA->getValue();
1136
1137 // Compute the new bits that are at the top now.
1138 uint64_t HighBits = (1ULL << ShAmt)-1;
1139 HighBits <<= I->getType()->getPrimitiveSizeInBits() - ShAmt;
Chris Lattner68e74752006-02-13 06:09:08 +00001140 uint64_t TypeMask = I->getType()->getIntegralTypeMask();
Chris Lattner0157e7f2006-02-11 09:31:47 +00001141 if (I->getType()->isUnsigned()) { // Unsigned shift right.
Chris Lattner68e74752006-02-13 06:09:08 +00001142 if (SimplifyDemandedBits(I->getOperand(0),
1143 (DemandedMask << ShAmt) & TypeMask,
Chris Lattner0157e7f2006-02-11 09:31:47 +00001144 KnownZero, KnownOne, Depth+1))
1145 return true;
1146 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattner68e74752006-02-13 06:09:08 +00001147 KnownZero &= TypeMask;
1148 KnownOne &= TypeMask;
Chris Lattner0157e7f2006-02-11 09:31:47 +00001149 KnownZero >>= ShAmt;
1150 KnownOne >>= ShAmt;
1151 KnownZero |= HighBits; // high bits known zero.
1152 } else { // Signed shift right.
Chris Lattner68e74752006-02-13 06:09:08 +00001153 if (SimplifyDemandedBits(I->getOperand(0),
1154 (DemandedMask << ShAmt) & TypeMask,
Chris Lattner0157e7f2006-02-11 09:31:47 +00001155 KnownZero, KnownOne, Depth+1))
1156 return true;
1157 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattner68e74752006-02-13 06:09:08 +00001158 KnownZero &= TypeMask;
1159 KnownOne &= TypeMask;
Chris Lattner0157e7f2006-02-11 09:31:47 +00001160 KnownZero >>= SA->getValue();
1161 KnownOne >>= SA->getValue();
1162
1163 // Handle the sign bits.
1164 uint64_t SignBit = 1ULL << (I->getType()->getPrimitiveSizeInBits()-1);
1165 SignBit >>= SA->getValue(); // Adjust to where it is now in the mask.
1166
1167 // If the input sign bit is known to be zero, or if none of the top bits
1168 // are demanded, turn this into an unsigned shift right.
1169 if ((KnownZero & SignBit) || (HighBits & ~DemandedMask) == HighBits) {
1170 // Convert the input to unsigned.
1171 Instruction *NewVal;
1172 NewVal = new CastInst(I->getOperand(0),
1173 I->getType()->getUnsignedVersion(),
1174 I->getOperand(0)->getName());
1175 InsertNewInstBefore(NewVal, *I);
1176 // Perform the unsigned shift right.
1177 NewVal = new ShiftInst(Instruction::Shr, NewVal, SA, I->getName());
1178 InsertNewInstBefore(NewVal, *I);
1179 // Then cast that to the destination type.
1180 NewVal = new CastInst(NewVal, I->getType(), I->getName());
1181 InsertNewInstBefore(NewVal, *I);
1182 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.
1280 ConstantUInt *Idx = dyn_cast<ConstantUInt>(I->getOperand(2));
1281 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.
1292 unsigned IdxNo = Idx->getValue();
1293 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.
1798 uint64_t AddRHSV = CRHS->getRawValue();
1799
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.
1805 uint64_t AddRHSHighBitsAnd = AddRHSHighBits & C2->getRawValue();
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
Andrew Lenharth4f339be2006-09-19 18:24:51 +00001822 // add (cast *A to intptrtype) B -> cast (GEP (cast *A to sbyte*) B) -> intptrtype
1823 {
1824 CastInst* CI = dyn_cast<CastInst>(LHS);
1825 Value* Other = RHS;
1826 if (!CI) {
1827 CI = dyn_cast<CastInst>(RHS);
1828 Other = LHS;
1829 }
Andrew Lenharth44cb67a2006-09-20 15:37:57 +00001830 if (CI && CI->getType()->isSized() &&
1831 (CI->getType()->getPrimitiveSize() ==
1832 TD->getIntPtrType()->getPrimitiveSize())
1833 && isa<PointerType>(CI->getOperand(0)->getType())) {
1834 Value* I2 = InsertCastBefore(CI->getOperand(0),
1835 PointerType::get(Type::SByteTy), I);
1836 I2 = InsertNewInstBefore(new GetElementPtrInst(I2, Other, "ctg2"), I);
1837 return new CastInst(I2, CI->getType());
Andrew Lenharth4f339be2006-09-19 18:24:51 +00001838 }
1839 }
1840
Chris Lattner113f4f42002-06-25 16:13:24 +00001841 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +00001842}
1843
Chris Lattnerbdb0ce02003-07-22 21:46:59 +00001844// isSignBit - Return true if the value represented by the constant only has the
1845// highest order bit set.
1846static bool isSignBit(ConstantInt *CI) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001847 unsigned NumBits = CI->getType()->getPrimitiveSizeInBits();
Chris Lattner2f1457f2005-04-24 17:46:05 +00001848 return (CI->getRawValue() & (~0ULL >> (64-NumBits))) == (1ULL << (NumBits-1));
Chris Lattnerbdb0ce02003-07-22 21:46:59 +00001849}
1850
Chris Lattner022167f2004-03-13 00:11:49 +00001851/// RemoveNoopCast - Strip off nonconverting casts from the value.
1852///
1853static Value *RemoveNoopCast(Value *V) {
1854 if (CastInst *CI = dyn_cast<CastInst>(V)) {
1855 const Type *CTy = CI->getType();
1856 const Type *OpTy = CI->getOperand(0)->getType();
1857 if (CTy->isInteger() && OpTy->isInteger()) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001858 if (CTy->getPrimitiveSizeInBits() == OpTy->getPrimitiveSizeInBits())
Chris Lattner022167f2004-03-13 00:11:49 +00001859 return RemoveNoopCast(CI->getOperand(0));
1860 } else if (isa<PointerType>(CTy) && isa<PointerType>(OpTy))
1861 return RemoveNoopCast(CI->getOperand(0));
1862 }
1863 return V;
1864}
1865
Chris Lattner113f4f42002-06-25 16:13:24 +00001866Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +00001867 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001868
Chris Lattnere6794492002-08-12 21:17:25 +00001869 if (Op0 == Op1) // sub X, X -> 0
1870 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner260ab202002-04-18 17:39:14 +00001871
Chris Lattnere6794492002-08-12 21:17:25 +00001872 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattnerbb74e222003-03-10 23:06:50 +00001873 if (Value *V = dyn_castNegVal(Op1))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001874 return BinaryOperator::createAdd(Op0, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +00001875
Chris Lattner81a7a232004-10-16 18:11:37 +00001876 if (isa<UndefValue>(Op0))
1877 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
1878 if (isa<UndefValue>(Op1))
1879 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
1880
Chris Lattner8f2f5982003-11-05 01:06:05 +00001881 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
1882 // Replace (-1 - A) with (~A)...
Chris Lattner3082c5a2003-02-18 19:28:33 +00001883 if (C->isAllOnesValue())
1884 return BinaryOperator::createNot(Op1);
Chris Lattnerad3c4952002-05-09 01:29:19 +00001885
Chris Lattner8f2f5982003-11-05 01:06:05 +00001886 // C - ~X == X + (1+C)
Reid Spencer4fdd96c2005-06-18 17:37:34 +00001887 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00001888 if (match(Op1, m_Not(m_Value(X))))
1889 return BinaryOperator::createAdd(X,
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001890 ConstantExpr::getAdd(C, ConstantInt::get(I.getType(), 1)));
Chris Lattner92295c52004-03-12 23:53:13 +00001891 // -((uint)X >> 31) -> ((int)X >> 31)
1892 // -((int)X >> 31) -> ((uint)X >> 31)
Chris Lattner022167f2004-03-13 00:11:49 +00001893 if (C->isNullValue()) {
1894 Value *NoopCastedRHS = RemoveNoopCast(Op1);
1895 if (ShiftInst *SI = dyn_cast<ShiftInst>(NoopCastedRHS))
Chris Lattner92295c52004-03-12 23:53:13 +00001896 if (SI->getOpcode() == Instruction::Shr)
1897 if (ConstantUInt *CU = dyn_cast<ConstantUInt>(SI->getOperand(1))) {
1898 const Type *NewTy;
Chris Lattner022167f2004-03-13 00:11:49 +00001899 if (SI->getType()->isSigned())
Chris Lattner97bfcea2004-06-17 18:16:02 +00001900 NewTy = SI->getType()->getUnsignedVersion();
Chris Lattner92295c52004-03-12 23:53:13 +00001901 else
Chris Lattner97bfcea2004-06-17 18:16:02 +00001902 NewTy = SI->getType()->getSignedVersion();
Chris Lattner92295c52004-03-12 23:53:13 +00001903 // Check to see if we are shifting out everything but the sign bit.
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001904 if (CU->getValue() == SI->getType()->getPrimitiveSizeInBits()-1) {
Chris Lattner92295c52004-03-12 23:53:13 +00001905 // Ok, the transformation is safe. Insert a cast of the incoming
1906 // value, then the new shift, then the new cast.
1907 Instruction *FirstCast = new CastInst(SI->getOperand(0), NewTy,
1908 SI->getOperand(0)->getName());
1909 Value *InV = InsertNewInstBefore(FirstCast, I);
1910 Instruction *NewShift = new ShiftInst(Instruction::Shr, FirstCast,
1911 CU, SI->getName());
Chris Lattner022167f2004-03-13 00:11:49 +00001912 if (NewShift->getType() == I.getType())
1913 return NewShift;
1914 else {
1915 InV = InsertNewInstBefore(NewShift, I);
1916 return new CastInst(NewShift, I.getType());
1917 }
Chris Lattner92295c52004-03-12 23:53:13 +00001918 }
1919 }
Chris Lattner022167f2004-03-13 00:11:49 +00001920 }
Chris Lattner183b3362004-04-09 19:05:30 +00001921
1922 // Try to fold constant sub into select arguments.
1923 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner86102b82005-01-01 16:22:27 +00001924 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00001925 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001926
1927 if (isa<PHINode>(Op0))
1928 if (Instruction *NV = FoldOpIntoPhi(I))
1929 return NV;
Chris Lattner8f2f5982003-11-05 01:06:05 +00001930 }
1931
Chris Lattnera9be4492005-04-07 16:15:25 +00001932 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
1933 if (Op1I->getOpcode() == Instruction::Add &&
1934 !Op0->getType()->isFloatingPoint()) {
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00001935 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Chris Lattnera9be4492005-04-07 16:15:25 +00001936 return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00001937 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Chris Lattnera9be4492005-04-07 16:15:25 +00001938 return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00001939 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
1940 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
1941 // C1-(X+C2) --> (C1-C2)-X
1942 return BinaryOperator::createSub(ConstantExpr::getSub(CI1, CI2),
1943 Op1I->getOperand(0));
1944 }
Chris Lattnera9be4492005-04-07 16:15:25 +00001945 }
1946
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001947 if (Op1I->hasOneUse()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00001948 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
1949 // is not used by anyone else...
1950 //
Chris Lattnerc2f0aa52004-02-02 20:09:56 +00001951 if (Op1I->getOpcode() == Instruction::Sub &&
1952 !Op1I->getType()->isFloatingPoint()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00001953 // Swap the two operands of the subexpr...
1954 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
1955 Op1I->setOperand(0, IIOp1);
1956 Op1I->setOperand(1, IIOp0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001957
Chris Lattner3082c5a2003-02-18 19:28:33 +00001958 // Create the new top level add instruction...
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001959 return BinaryOperator::createAdd(Op0, Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001960 }
1961
1962 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
1963 //
1964 if (Op1I->getOpcode() == Instruction::And &&
1965 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
1966 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
1967
Chris Lattner396dbfe2004-06-09 05:08:07 +00001968 Value *NewNot =
1969 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001970 return BinaryOperator::createAnd(Op0, NewNot);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001971 }
Chris Lattner57c8d992003-02-18 19:57:07 +00001972
Reid Spencer3c514952006-10-16 23:08:08 +00001973 // 0 - (X sdiv C) -> (X sdiv -C)
Chris Lattner0aee4b72004-10-06 15:08:25 +00001974 if (Op1I->getOpcode() == Instruction::Div)
1975 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
Reid Spencer3c514952006-10-16 23:08:08 +00001976 if (CSI->isNullValue())
Chris Lattner0aee4b72004-10-06 15:08:25 +00001977 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Misha Brukmanb1c93172005-04-21 23:48:37 +00001978 return BinaryOperator::createDiv(Op1I->getOperand(0),
Chris Lattner0aee4b72004-10-06 15:08:25 +00001979 ConstantExpr::getNeg(DivRHS));
1980
Chris Lattner57c8d992003-02-18 19:57:07 +00001981 // X - X*C --> X * (1-C)
Reid Spencer4fdd96c2005-06-18 17:37:34 +00001982 ConstantInt *C2 = 0;
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001983 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00001984 Constant *CP1 =
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001985 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1), C2);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001986 return BinaryOperator::createMul(Op0, CP1);
Chris Lattner57c8d992003-02-18 19:57:07 +00001987 }
Chris Lattnerad3c4952002-05-09 01:29:19 +00001988 }
Chris Lattnera9be4492005-04-07 16:15:25 +00001989 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00001990
Chris Lattner47060462005-04-07 17:14:51 +00001991 if (!Op0->getType()->isFloatingPoint())
1992 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
1993 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner411336f2005-01-19 21:50:18 +00001994 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
1995 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
1996 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
1997 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner47060462005-04-07 17:14:51 +00001998 } else if (Op0I->getOpcode() == Instruction::Sub) {
1999 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
2000 return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
Chris Lattner411336f2005-01-19 21:50:18 +00002001 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002002
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002003 ConstantInt *C1;
2004 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2005 if (X == Op1) { // X*C - X --> X * (C-1)
2006 Constant *CP1 = ConstantExpr::getSub(C1, ConstantInt::get(I.getType(),1));
2007 return BinaryOperator::createMul(Op1, CP1);
2008 }
Chris Lattner57c8d992003-02-18 19:57:07 +00002009
Chris Lattner8c3e7b92004-11-13 19:50:12 +00002010 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
2011 if (X == dyn_castFoldableMul(Op1, C2))
2012 return BinaryOperator::createMul(Op1, ConstantExpr::getSub(C1, C2));
2013 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002014 return 0;
Chris Lattner260ab202002-04-18 17:39:14 +00002015}
2016
Chris Lattnere79e8542004-02-23 06:38:22 +00002017/// isSignBitCheck - Given an exploded setcc instruction, return true if it is
2018/// really just returns true if the most significant (sign) bit is set.
2019static bool isSignBitCheck(unsigned Opcode, Value *LHS, ConstantInt *RHS) {
2020 if (RHS->getType()->isSigned()) {
2021 // True if source is LHS < 0 or LHS <= -1
2022 return Opcode == Instruction::SetLT && RHS->isNullValue() ||
2023 Opcode == Instruction::SetLE && RHS->isAllOnesValue();
2024 } else {
2025 ConstantUInt *RHSC = cast<ConstantUInt>(RHS);
2026 // True if source is LHS > 127 or LHS >= 128, where the constants depend on
2027 // the size of the integer type.
2028 if (Opcode == Instruction::SetGE)
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002029 return RHSC->getValue() ==
2030 1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1);
Chris Lattnere79e8542004-02-23 06:38:22 +00002031 if (Opcode == Instruction::SetGT)
2032 return RHSC->getValue() ==
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002033 (1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1))-1;
Chris Lattnere79e8542004-02-23 06:38:22 +00002034 }
2035 return false;
2036}
2037
Chris Lattner113f4f42002-06-25 16:13:24 +00002038Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00002039 bool Changed = SimplifyCommutative(I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002040 Value *Op0 = I.getOperand(0);
Chris Lattner260ab202002-04-18 17:39:14 +00002041
Chris Lattner81a7a232004-10-16 18:11:37 +00002042 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
2043 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2044
Chris Lattnere6794492002-08-12 21:17:25 +00002045 // Simplify mul instructions with a constant RHS...
Chris Lattner3082c5a2003-02-18 19:28:33 +00002046 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2047 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerede3fe02003-08-13 04:18:28 +00002048
2049 // ((X << C1)*C2) == (X * (C2 << C1))
2050 if (ShiftInst *SI = dyn_cast<ShiftInst>(Op0))
2051 if (SI->getOpcode() == Instruction::Shl)
2052 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002053 return BinaryOperator::createMul(SI->getOperand(0),
2054 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanb1c93172005-04-21 23:48:37 +00002055
Chris Lattnercce81be2003-09-11 22:24:54 +00002056 if (CI->isNullValue())
2057 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2058 if (CI->equalsInt(1)) // X * 1 == X
2059 return ReplaceInstUsesWith(I, Op0);
2060 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Chris Lattner35236d82003-06-25 17:09:20 +00002061 return BinaryOperator::createNeg(Op0, I.getName());
Chris Lattner31ba1292002-04-29 22:24:47 +00002062
Chris Lattnercce81be2003-09-11 22:24:54 +00002063 int64_t Val = (int64_t)cast<ConstantInt>(CI)->getRawValue();
Chris Lattner22d00a82005-08-02 19:16:58 +00002064 if (isPowerOf2_64(Val)) { // Replace X*(2^C) with X << C
2065 uint64_t C = Log2_64(Val);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002066 return new ShiftInst(Instruction::Shl, Op0,
2067 ConstantUInt::get(Type::UByteTy, C));
Chris Lattner22d00a82005-08-02 19:16:58 +00002068 }
Robert Bocchino7b5b86c2004-07-27 21:02:21 +00002069 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00002070 if (Op1F->isNullValue())
2071 return ReplaceInstUsesWith(I, Op1);
Chris Lattner31ba1292002-04-29 22:24:47 +00002072
Chris Lattner3082c5a2003-02-18 19:28:33 +00002073 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2074 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2075 if (Op1F->getValue() == 1.0)
2076 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
2077 }
Chris Lattner32c01df2006-03-04 06:04:02 +00002078
2079 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2080 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2081 isa<ConstantInt>(Op0I->getOperand(1))) {
2082 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2083 Instruction *Add = BinaryOperator::createMul(Op0I->getOperand(0),
2084 Op1, "tmp");
2085 InsertNewInstBefore(Add, I);
2086 Value *C1C2 = ConstantExpr::getMul(Op1,
2087 cast<Constant>(Op0I->getOperand(1)));
2088 return BinaryOperator::createAdd(Add, C1C2);
2089
2090 }
Chris Lattner183b3362004-04-09 19:05:30 +00002091
2092 // Try to fold constant mul into select arguments.
2093 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00002094 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00002095 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002096
2097 if (isa<PHINode>(Op0))
2098 if (Instruction *NV = FoldOpIntoPhi(I))
2099 return NV;
Chris Lattner260ab202002-04-18 17:39:14 +00002100 }
2101
Chris Lattner934a64cf2003-03-10 23:23:04 +00002102 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
2103 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002104 return BinaryOperator::createMul(Op0v, Op1v);
Chris Lattner934a64cf2003-03-10 23:23:04 +00002105
Chris Lattner2635b522004-02-23 05:39:21 +00002106 // If one of the operands of the multiply is a cast from a boolean value, then
2107 // we know the bool is either zero or one, so this is a 'masking' multiply.
2108 // See if we can simplify things based on how the boolean was originally
2109 // formed.
2110 CastInst *BoolCast = 0;
2111 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(0)))
2112 if (CI->getOperand(0)->getType() == Type::BoolTy)
2113 BoolCast = CI;
2114 if (!BoolCast)
2115 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(1)))
2116 if (CI->getOperand(0)->getType() == Type::BoolTy)
2117 BoolCast = CI;
2118 if (BoolCast) {
2119 if (SetCondInst *SCI = dyn_cast<SetCondInst>(BoolCast->getOperand(0))) {
2120 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2121 const Type *SCOpTy = SCIOp0->getType();
2122
Chris Lattnere79e8542004-02-23 06:38:22 +00002123 // If the setcc is true iff the sign bit of X is set, then convert this
2124 // multiply into a shift/and combination.
2125 if (isa<ConstantInt>(SCIOp1) &&
2126 isSignBitCheck(SCI->getOpcode(), SCIOp0, cast<ConstantInt>(SCIOp1))) {
Chris Lattner2635b522004-02-23 05:39:21 +00002127 // Shift the X value right to turn it into "all signbits".
2128 Constant *Amt = ConstantUInt::get(Type::UByteTy,
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002129 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattnere79e8542004-02-23 06:38:22 +00002130 if (SCIOp0->getType()->isUnsigned()) {
Chris Lattner97bfcea2004-06-17 18:16:02 +00002131 const Type *NewTy = SCIOp0->getType()->getSignedVersion();
Chris Lattnere79e8542004-02-23 06:38:22 +00002132 SCIOp0 = InsertNewInstBefore(new CastInst(SCIOp0, NewTy,
2133 SCIOp0->getName()), I);
2134 }
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())
Chris Lattnere79e8542004-02-23 06:38:22 +00002144 V = InsertNewInstBefore(new CastInst(V, I.getType(), V->getName()),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
Chris Lattner113f4f42002-06-25 16:13:24 +00002155Instruction *InstCombiner::visitDiv(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002156 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner81a7a232004-10-16 18:11:37 +00002157
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002158 if (isa<UndefValue>(Op0)) // undef / X -> 0
2159 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2160 if (isa<UndefValue>(Op1))
2161 return ReplaceInstUsesWith(I, Op1); // X / undef -> undef
2162
2163 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnere20c3342004-04-26 14:01:59 +00002164 // div X, 1 == X
Chris Lattnere6794492002-08-12 21:17:25 +00002165 if (RHS->equalsInt(1))
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002166 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002167
Chris Lattnere20c3342004-04-26 14:01:59 +00002168 // div X, -1 == -X
2169 if (RHS->isAllOnesValue())
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002170 return BinaryOperator::createNeg(Op0);
Chris Lattnere20c3342004-04-26 14:01:59 +00002171
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002172 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
Chris Lattner272d5ca2004-09-28 18:22:15 +00002173 if (LHS->getOpcode() == Instruction::Div)
2174 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Chris Lattner272d5ca2004-09-28 18:22:15 +00002175 // (X / C1) / C2 -> X / (C1*C2)
2176 return BinaryOperator::createDiv(LHS->getOperand(0),
2177 ConstantExpr::getMul(RHS, LHSRHS));
2178 }
2179
Chris Lattner3082c5a2003-02-18 19:28:33 +00002180 // Check to see if this is an unsigned division with an exact power of 2,
2181 // if so, convert to a right shift.
2182 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
2183 if (uint64_t Val = C->getValue()) // Don't break X / 0
Chris Lattner22d00a82005-08-02 19:16:58 +00002184 if (isPowerOf2_64(Val)) {
2185 uint64_t C = Log2_64(Val);
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002186 return new ShiftInst(Instruction::Shr, Op0,
Chris Lattner3082c5a2003-02-18 19:28:33 +00002187 ConstantUInt::get(Type::UByteTy, C));
Chris Lattner22d00a82005-08-02 19:16:58 +00002188 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002189
Chris Lattner4ad08352004-10-09 02:50:40 +00002190 // -X/C -> X/-C
2191 if (RHS->getType()->isSigned())
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002192 if (Value *LHSNeg = dyn_castNegVal(Op0))
Chris Lattner4ad08352004-10-09 02:50:40 +00002193 return BinaryOperator::createDiv(LHSNeg, ConstantExpr::getNeg(RHS));
2194
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002195 if (!RHS->isNullValue()) {
2196 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00002197 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002198 return R;
2199 if (isa<PHINode>(Op0))
2200 if (Instruction *NV = FoldOpIntoPhi(I))
2201 return NV;
2202 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00002203 }
2204
Chris Lattnerd79dc792006-09-09 20:26:32 +00002205 // Handle div X, Cond?Y:Z
2206 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2207 // div X, (Cond ? 0 : Y) -> div X, Y. If the div and the select are in the
2208 // same basic block, then we replace the select with Y, and the condition of
2209 // the select with false (if the cond value is in the same BB). If the
2210 // select has uses other than the div, this allows them to be simplified
2211 // also.
2212 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2213 if (ST->isNullValue()) {
2214 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2215 if (CondI && CondI->getParent() == I.getParent())
Chris Lattner6ab03f62006-09-28 23:35:22 +00002216 UpdateValueUsesWith(CondI, ConstantBool::getFalse());
Chris Lattnerd79dc792006-09-09 20:26:32 +00002217 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2218 I.setOperand(1, SI->getOperand(2));
2219 else
2220 UpdateValueUsesWith(SI, SI->getOperand(2));
2221 return &I;
2222 }
2223 // Likewise for: div X, (Cond ? Y : 0) -> div X, Y
2224 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2225 if (ST->isNullValue()) {
2226 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2227 if (CondI && CondI->getParent() == I.getParent())
Chris Lattner6ab03f62006-09-28 23:35:22 +00002228 UpdateValueUsesWith(CondI, ConstantBool::getTrue());
Chris Lattnerd79dc792006-09-09 20:26:32 +00002229 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2230 I.setOperand(1, SI->getOperand(1));
2231 else
2232 UpdateValueUsesWith(SI, SI->getOperand(1));
2233 return &I;
2234 }
2235
2236 // If this is 'udiv X, (Cond ? C1, C2)' where C1&C2 are powers of two,
2237 // transform this into: '(Cond ? (udiv X, C1) : (udiv X, C2))'.
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002238 if (ConstantUInt *STO = dyn_cast<ConstantUInt>(SI->getOperand(1)))
2239 if (ConstantUInt *SFO = dyn_cast<ConstantUInt>(SI->getOperand(2))) {
Chris Lattnerd79dc792006-09-09 20:26:32 +00002240 // STO == 0 and SFO == 0 handled above.
Chris Lattner42362612005-04-08 04:03:26 +00002241 uint64_t TVA = STO->getValue(), FVA = SFO->getValue();
Chris Lattner22d00a82005-08-02 19:16:58 +00002242 if (isPowerOf2_64(TVA) && isPowerOf2_64(FVA)) {
2243 unsigned TSA = Log2_64(TVA), FSA = Log2_64(FVA);
Chris Lattner42362612005-04-08 04:03:26 +00002244 Constant *TC = ConstantUInt::get(Type::UByteTy, TSA);
2245 Instruction *TSI = new ShiftInst(Instruction::Shr, Op0,
2246 TC, SI->getName()+".t");
2247 TSI = InsertNewInstBefore(TSI, I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002248
Chris Lattner42362612005-04-08 04:03:26 +00002249 Constant *FC = ConstantUInt::get(Type::UByteTy, FSA);
2250 Instruction *FSI = new ShiftInst(Instruction::Shr, Op0,
2251 FC, SI->getName()+".f");
2252 FSI = InsertNewInstBefore(FSI, I);
2253 return new SelectInst(SI->getOperand(0), TSI, FSI);
2254 }
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002255 }
Chris Lattnerd79dc792006-09-09 20:26:32 +00002256 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002257
Chris Lattner3082c5a2003-02-18 19:28:33 +00002258 // 0 / X == 0, we don't need to preserve faults!
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002259 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattner3082c5a2003-02-18 19:28:33 +00002260 if (LHS->equalsInt(0))
2261 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2262
Chris Lattnerdd0c1742005-11-05 07:40:31 +00002263 if (I.getType()->isSigned()) {
Chris Lattnerc3ebf402006-02-07 07:27:52 +00002264 // If the sign bits of both operands are zero (i.e. we can prove they are
Chris Lattnerdd0c1742005-11-05 07:40:31 +00002265 // unsigned inputs), turn this into a udiv.
Chris Lattnerc3ebf402006-02-07 07:27:52 +00002266 uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
2267 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
Chris Lattnerdd0c1742005-11-05 07:40:31 +00002268 const Type *NTy = Op0->getType()->getUnsignedVersion();
2269 Instruction *LHS = new CastInst(Op0, NTy, Op0->getName());
2270 InsertNewInstBefore(LHS, I);
2271 Value *RHS;
2272 if (Constant *R = dyn_cast<Constant>(Op1))
2273 RHS = ConstantExpr::getCast(R, NTy);
2274 else
2275 RHS = InsertNewInstBefore(new CastInst(Op1, NTy, Op1->getName()), I);
2276 Instruction *Div = BinaryOperator::createDiv(LHS, RHS, I.getName());
2277 InsertNewInstBefore(Div, I);
2278 return new CastInst(Div, I.getType());
2279 }
Chris Lattner2e90b732006-02-05 07:54:04 +00002280 } else {
2281 // Known to be an unsigned division.
2282 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
2283 // Turn A / (C1 << N), where C1 is "1<<C2" into A >> (N+C2) [udiv only].
2284 if (RHSI->getOpcode() == Instruction::Shl &&
2285 isa<ConstantUInt>(RHSI->getOperand(0))) {
2286 unsigned C1 = cast<ConstantUInt>(RHSI->getOperand(0))->getRawValue();
2287 if (isPowerOf2_64(C1)) {
2288 unsigned C2 = Log2_64(C1);
2289 Value *Add = RHSI->getOperand(1);
2290 if (C2) {
2291 Constant *C2V = ConstantUInt::get(Add->getType(), C2);
2292 Add = InsertNewInstBefore(BinaryOperator::createAdd(Add, C2V,
2293 "tmp"), I);
2294 }
2295 return new ShiftInst(Instruction::Shr, Op0, Add);
2296 }
2297 }
2298 }
Chris Lattnerdd0c1742005-11-05 07:40:31 +00002299 }
2300
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002301 return 0;
2302}
2303
2304
Chris Lattner85dda9a2006-03-02 06:50:58 +00002305/// GetFactor - If we can prove that the specified value is at least a multiple
2306/// of some factor, return that factor.
2307static Constant *GetFactor(Value *V) {
2308 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
2309 return CI;
2310
2311 // Unless we can be tricky, we know this is a multiple of 1.
2312 Constant *Result = ConstantInt::get(V->getType(), 1);
2313
2314 Instruction *I = dyn_cast<Instruction>(V);
2315 if (!I) return Result;
2316
2317 if (I->getOpcode() == Instruction::Mul) {
2318 // Handle multiplies by a constant, etc.
2319 return ConstantExpr::getMul(GetFactor(I->getOperand(0)),
2320 GetFactor(I->getOperand(1)));
2321 } else if (I->getOpcode() == Instruction::Shl) {
2322 // (X<<C) -> X * (1 << C)
2323 if (Constant *ShRHS = dyn_cast<Constant>(I->getOperand(1))) {
2324 ShRHS = ConstantExpr::getShl(Result, ShRHS);
2325 return ConstantExpr::getMul(GetFactor(I->getOperand(0)), ShRHS);
2326 }
2327 } else if (I->getOpcode() == Instruction::And) {
2328 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
2329 // X & 0xFFF0 is known to be a multiple of 16.
2330 unsigned Zeros = CountTrailingZeros_64(RHS->getZExtValue());
2331 if (Zeros != V->getType()->getPrimitiveSizeInBits())
2332 return ConstantExpr::getShl(Result,
2333 ConstantUInt::get(Type::UByteTy, Zeros));
2334 }
2335 } else if (I->getOpcode() == Instruction::Cast) {
2336 Value *Op = I->getOperand(0);
2337 // Only handle int->int casts.
2338 if (!Op->getType()->isInteger()) return Result;
2339 return ConstantExpr::getCast(GetFactor(Op), V->getType());
2340 }
2341 return Result;
2342}
2343
Chris Lattner113f4f42002-06-25 16:13:24 +00002344Instruction *InstCombiner::visitRem(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002345 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner0de4a8d2006-02-28 05:30:45 +00002346
2347 // 0 % X == 0, we don't need to preserve faults!
2348 if (Constant *LHS = dyn_cast<Constant>(Op0))
2349 if (LHS->isNullValue())
2350 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2351
2352 if (isa<UndefValue>(Op0)) // undef % X -> 0
2353 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2354 if (isa<UndefValue>(Op1))
2355 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
2356
Chris Lattnere9ff0ea2005-11-05 07:28:37 +00002357 if (I.getType()->isSigned()) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002358 if (Value *RHSNeg = dyn_castNegVal(Op1))
Chris Lattner98c6bdf2004-07-06 07:11:42 +00002359 if (!isa<ConstantSInt>(RHSNeg) ||
Chris Lattner8e726062004-08-09 21:05:48 +00002360 cast<ConstantSInt>(RHSNeg)->getValue() > 0) {
Chris Lattner7fd5f072004-07-06 07:01:22 +00002361 // X % -Y -> X % Y
2362 AddUsesToWorkList(I);
2363 I.setOperand(1, RHSNeg);
2364 return &I;
2365 }
Chris Lattnere9ff0ea2005-11-05 07:28:37 +00002366
2367 // If the top bits of both operands are zero (i.e. we can prove they are
2368 // unsigned inputs), turn this into a urem.
Chris Lattnerc3ebf402006-02-07 07:27:52 +00002369 uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
2370 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
Chris Lattnere9ff0ea2005-11-05 07:28:37 +00002371 const Type *NTy = Op0->getType()->getUnsignedVersion();
2372 Instruction *LHS = new CastInst(Op0, NTy, Op0->getName());
2373 InsertNewInstBefore(LHS, I);
2374 Value *RHS;
2375 if (Constant *R = dyn_cast<Constant>(Op1))
2376 RHS = ConstantExpr::getCast(R, NTy);
2377 else
2378 RHS = InsertNewInstBefore(new CastInst(Op1, NTy, Op1->getName()), I);
2379 Instruction *Rem = BinaryOperator::createRem(LHS, RHS, I.getName());
2380 InsertNewInstBefore(Rem, I);
2381 return new CastInst(Rem, I.getType());
2382 }
2383 }
Chris Lattner7fd5f072004-07-06 07:01:22 +00002384
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002385 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner0de4a8d2006-02-28 05:30:45 +00002386 // X % 0 == undef, we don't need to preserve faults!
2387 if (RHS->equalsInt(0))
2388 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2389
Chris Lattner3082c5a2003-02-18 19:28:33 +00002390 if (RHS->equalsInt(1)) // X % 1 == 0
2391 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2392
2393 // Check to see if this is an unsigned remainder with an exact power of 2,
2394 // if so, convert to a bitwise and.
2395 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
Chris Lattner0de4a8d2006-02-28 05:30:45 +00002396 if (isPowerOf2_64(C->getValue()))
2397 return BinaryOperator::createAnd(Op0, SubOne(C));
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002398
Chris Lattnerb70f1412006-02-28 05:49:21 +00002399 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2400 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2401 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2402 return R;
2403 } else if (isa<PHINode>(Op0I)) {
2404 if (Instruction *NV = FoldOpIntoPhi(I))
2405 return NV;
Chris Lattnerb70f1412006-02-28 05:49:21 +00002406 }
Chris Lattner85dda9a2006-03-02 06:50:58 +00002407
2408 // X*C1%C2 --> 0 iff C1%C2 == 0
2409 if (ConstantExpr::getRem(GetFactor(Op0I), RHS)->isNullValue())
2410 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerb70f1412006-02-28 05:49:21 +00002411 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00002412 }
2413
Chris Lattner2e90b732006-02-05 07:54:04 +00002414 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
2415 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1) [urem only].
2416 if (I.getType()->isUnsigned() &&
2417 RHSI->getOpcode() == Instruction::Shl &&
2418 isa<ConstantUInt>(RHSI->getOperand(0))) {
2419 unsigned C1 = cast<ConstantUInt>(RHSI->getOperand(0))->getRawValue();
2420 if (isPowerOf2_64(C1)) {
2421 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
2422 Value *Add = InsertNewInstBefore(BinaryOperator::createAdd(RHSI, N1,
2423 "tmp"), I);
2424 return BinaryOperator::createAnd(Op0, Add);
2425 }
2426 }
Chris Lattner0de4a8d2006-02-28 05:30:45 +00002427
2428 // If this is 'urem X, (Cond ? C1, C2)' where C1&C2 are powers of two,
2429 // transform this into: '(Cond ? (urem X, C1) : (urem X, C2))'.
Chris Lattnerd79dc792006-09-09 20:26:32 +00002430 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2431 // rem X, (Cond ? 0 : Y) -> rem X, Y. If the rem and the select are in
2432 // the same basic block, then we replace the select with Y, and the
2433 // condition of the select with false (if the cond value is in the same
2434 // BB). If the select has uses other than the div, this allows them to be
2435 // simplified also.
2436 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2437 if (ST->isNullValue()) {
2438 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2439 if (CondI && CondI->getParent() == I.getParent())
Chris Lattner6ab03f62006-09-28 23:35:22 +00002440 UpdateValueUsesWith(CondI, ConstantBool::getFalse());
Chris Lattnerd79dc792006-09-09 20:26:32 +00002441 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2442 I.setOperand(1, SI->getOperand(2));
2443 else
2444 UpdateValueUsesWith(SI, SI->getOperand(2));
2445 return &I;
2446 }
2447 // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
2448 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2449 if (ST->isNullValue()) {
2450 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2451 if (CondI && CondI->getParent() == I.getParent())
Chris Lattner6ab03f62006-09-28 23:35:22 +00002452 UpdateValueUsesWith(CondI, ConstantBool::getTrue());
Chris Lattnerd79dc792006-09-09 20:26:32 +00002453 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2454 I.setOperand(1, SI->getOperand(1));
2455 else
2456 UpdateValueUsesWith(SI, SI->getOperand(1));
2457 return &I;
2458 }
2459
2460
Chris Lattner0de4a8d2006-02-28 05:30:45 +00002461 if (ConstantUInt *STO = dyn_cast<ConstantUInt>(SI->getOperand(1)))
2462 if (ConstantUInt *SFO = dyn_cast<ConstantUInt>(SI->getOperand(2))) {
Chris Lattnerd79dc792006-09-09 20:26:32 +00002463 // STO == 0 and SFO == 0 handled above.
Chris Lattner0de4a8d2006-02-28 05:30:45 +00002464
2465 if (isPowerOf2_64(STO->getValue()) && isPowerOf2_64(SFO->getValue())){
2466 Value *TrueAnd = InsertNewInstBefore(BinaryOperator::createAnd(Op0,
2467 SubOne(STO), SI->getName()+".t"), I);
2468 Value *FalseAnd = InsertNewInstBefore(BinaryOperator::createAnd(Op0,
2469 SubOne(SFO), SI->getName()+".f"), I);
2470 return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
2471 }
2472 }
Chris Lattnerd79dc792006-09-09 20:26:32 +00002473 }
Chris Lattner2e90b732006-02-05 07:54:04 +00002474 }
2475
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002476 return 0;
2477}
2478
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002479// isMaxValueMinusOne - return true if this is Max-1
Chris Lattnere6794492002-08-12 21:17:25 +00002480static bool isMaxValueMinusOne(const ConstantInt *C) {
Chris Lattner77defba2006-02-07 07:00:41 +00002481 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
2482 return CU->getValue() == C->getType()->getIntegralTypeMask()-1;
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002483
2484 const ConstantSInt *CS = cast<ConstantSInt>(C);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002485
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002486 // Calculate 0111111111..11111
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002487 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002488 int64_t Val = INT64_MAX; // All ones
2489 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
2490 return CS->getValue() == Val-1;
2491}
2492
2493// isMinValuePlusOne - return true if this is Min+1
Chris Lattnere6794492002-08-12 21:17:25 +00002494static bool isMinValuePlusOne(const ConstantInt *C) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002495 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
2496 return CU->getValue() == 1;
2497
2498 const ConstantSInt *CS = cast<ConstantSInt>(C);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002499
2500 // Calculate 1111111111000000000000
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002501 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002502 int64_t Val = -1; // All ones
2503 Val <<= TypeBits-1; // Shift over to the right spot
2504 return CS->getValue() == Val+1;
2505}
2506
Chris Lattner35167c32004-06-09 07:59:58 +00002507// isOneBitSet - Return true if there is exactly one bit set in the specified
2508// constant.
2509static bool isOneBitSet(const ConstantInt *CI) {
2510 uint64_t V = CI->getRawValue();
2511 return V && (V & (V-1)) == 0;
2512}
2513
Chris Lattner8fc5af42004-09-23 21:46:38 +00002514#if 0 // Currently unused
2515// isLowOnes - Return true if the constant is of the form 0+1+.
2516static bool isLowOnes(const ConstantInt *CI) {
2517 uint64_t V = CI->getRawValue();
2518
2519 // There won't be bits set in parts that the type doesn't contain.
2520 V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
2521
2522 uint64_t U = V+1; // If it is low ones, this should be a power of two.
2523 return U && V && (U & V) == 0;
2524}
2525#endif
2526
2527// isHighOnes - Return true if the constant is of the form 1+0+.
2528// This is the same as lowones(~X).
2529static bool isHighOnes(const ConstantInt *CI) {
2530 uint64_t V = ~CI->getRawValue();
Chris Lattner2c14cf72005-08-07 07:03:10 +00002531 if (~V == 0) return false; // 0's does not match "1+"
Chris Lattner8fc5af42004-09-23 21:46:38 +00002532
2533 // There won't be bits set in parts that the type doesn't contain.
2534 V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
2535
2536 uint64_t U = V+1; // If it is low ones, this should be a power of two.
2537 return U && V && (U & V) == 0;
2538}
2539
2540
Chris Lattner3ac7c262003-08-13 20:16:26 +00002541/// getSetCondCode - Encode a setcc opcode into a three bit mask. These bits
2542/// are carefully arranged to allow folding of expressions such as:
2543///
2544/// (A < B) | (A > B) --> (A != B)
2545///
2546/// Bit value '4' represents that the comparison is true if A > B, bit value '2'
2547/// represents that the comparison is true if A == B, and bit value '1' is true
2548/// if A < B.
2549///
2550static unsigned getSetCondCode(const SetCondInst *SCI) {
2551 switch (SCI->getOpcode()) {
2552 // False -> 0
2553 case Instruction::SetGT: return 1;
2554 case Instruction::SetEQ: return 2;
2555 case Instruction::SetGE: return 3;
2556 case Instruction::SetLT: return 4;
2557 case Instruction::SetNE: return 5;
2558 case Instruction::SetLE: return 6;
2559 // True -> 7
2560 default:
2561 assert(0 && "Invalid SetCC opcode!");
2562 return 0;
2563 }
2564}
2565
2566/// getSetCCValue - This is the complement of getSetCondCode, which turns an
2567/// opcode and two operands into either a constant true or false, or a brand new
2568/// SetCC instruction.
2569static Value *getSetCCValue(unsigned Opcode, Value *LHS, Value *RHS) {
2570 switch (Opcode) {
Chris Lattner6ab03f62006-09-28 23:35:22 +00002571 case 0: return ConstantBool::getFalse();
Chris Lattner3ac7c262003-08-13 20:16:26 +00002572 case 1: return new SetCondInst(Instruction::SetGT, LHS, RHS);
2573 case 2: return new SetCondInst(Instruction::SetEQ, LHS, RHS);
2574 case 3: return new SetCondInst(Instruction::SetGE, LHS, RHS);
2575 case 4: return new SetCondInst(Instruction::SetLT, LHS, RHS);
2576 case 5: return new SetCondInst(Instruction::SetNE, LHS, RHS);
2577 case 6: return new SetCondInst(Instruction::SetLE, LHS, RHS);
Chris Lattner6ab03f62006-09-28 23:35:22 +00002578 case 7: return ConstantBool::getTrue();
Chris Lattner3ac7c262003-08-13 20:16:26 +00002579 default: assert(0 && "Illegal SetCCCode!"); return 0;
2580 }
2581}
2582
2583// FoldSetCCLogical - Implements (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
2584struct FoldSetCCLogical {
2585 InstCombiner &IC;
2586 Value *LHS, *RHS;
2587 FoldSetCCLogical(InstCombiner &ic, SetCondInst *SCI)
2588 : IC(ic), LHS(SCI->getOperand(0)), RHS(SCI->getOperand(1)) {}
2589 bool shouldApply(Value *V) const {
2590 if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
2591 return (SCI->getOperand(0) == LHS && SCI->getOperand(1) == RHS ||
2592 SCI->getOperand(0) == RHS && SCI->getOperand(1) == LHS);
2593 return false;
2594 }
2595 Instruction *apply(BinaryOperator &Log) const {
2596 SetCondInst *SCI = cast<SetCondInst>(Log.getOperand(0));
2597 if (SCI->getOperand(0) != LHS) {
2598 assert(SCI->getOperand(1) == LHS);
2599 SCI->swapOperands(); // Swap the LHS and RHS of the SetCC
2600 }
2601
2602 unsigned LHSCode = getSetCondCode(SCI);
2603 unsigned RHSCode = getSetCondCode(cast<SetCondInst>(Log.getOperand(1)));
2604 unsigned Code;
2605 switch (Log.getOpcode()) {
2606 case Instruction::And: Code = LHSCode & RHSCode; break;
2607 case Instruction::Or: Code = LHSCode | RHSCode; break;
2608 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner2caaaba2003-09-22 20:33:34 +00002609 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattner3ac7c262003-08-13 20:16:26 +00002610 }
2611
2612 Value *RV = getSetCCValue(Code, LHS, RHS);
2613 if (Instruction *I = dyn_cast<Instruction>(RV))
2614 return I;
2615 // Otherwise, it's a constant boolean value...
2616 return IC.ReplaceInstUsesWith(Log, RV);
2617 }
2618};
2619
Chris Lattnerba1cb382003-09-19 17:17:26 +00002620// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
2621// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
2622// guaranteed to be either a shift instruction or a binary operator.
2623Instruction *InstCombiner::OptAndOp(Instruction *Op,
2624 ConstantIntegral *OpRHS,
2625 ConstantIntegral *AndRHS,
2626 BinaryOperator &TheAnd) {
2627 Value *X = Op->getOperand(0);
Chris Lattnerfcf21a72004-01-12 19:47:05 +00002628 Constant *Together = 0;
2629 if (!isa<ShiftInst>(Op))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002630 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002631
Chris Lattnerba1cb382003-09-19 17:17:26 +00002632 switch (Op->getOpcode()) {
2633 case Instruction::Xor:
Chris Lattner86102b82005-01-01 16:22:27 +00002634 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00002635 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
2636 std::string OpName = Op->getName(); Op->setName("");
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002637 Instruction *And = BinaryOperator::createAnd(X, AndRHS, OpName);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002638 InsertNewInstBefore(And, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002639 return BinaryOperator::createXor(And, Together);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002640 }
2641 break;
2642 case Instruction::Or:
Chris Lattner86102b82005-01-01 16:22:27 +00002643 if (Together == AndRHS) // (X | C) & C --> C
2644 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002645
Chris Lattner86102b82005-01-01 16:22:27 +00002646 if (Op->hasOneUse() && Together != OpRHS) {
2647 // (X | C1) & C2 --> (X | (C1&C2)) & C2
2648 std::string Op0Name = Op->getName(); Op->setName("");
2649 Instruction *Or = BinaryOperator::createOr(X, Together, Op0Name);
2650 InsertNewInstBefore(Or, TheAnd);
2651 return BinaryOperator::createAnd(Or, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002652 }
2653 break;
2654 case Instruction::Add:
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002655 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00002656 // Adding a one to a single bit bit-field should be turned into an XOR
2657 // of the bit. First thing to check is to see if this AND is with a
2658 // single bit constant.
Chris Lattner35167c32004-06-09 07:59:58 +00002659 uint64_t AndRHSV = cast<ConstantInt>(AndRHS)->getRawValue();
Chris Lattnerba1cb382003-09-19 17:17:26 +00002660
2661 // Clear bits that are not part of the constant.
Chris Lattner77defba2006-02-07 07:00:41 +00002662 AndRHSV &= AndRHS->getType()->getIntegralTypeMask();
Chris Lattnerba1cb382003-09-19 17:17:26 +00002663
2664 // If there is only one bit set...
Chris Lattner35167c32004-06-09 07:59:58 +00002665 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00002666 // Ok, at this point, we know that we are masking the result of the
2667 // ADD down to exactly one bit. If the constant we are adding has
2668 // no bits set below this bit, then we can eliminate the ADD.
Chris Lattner35167c32004-06-09 07:59:58 +00002669 uint64_t AddRHS = cast<ConstantInt>(OpRHS)->getRawValue();
Misha Brukmanb1c93172005-04-21 23:48:37 +00002670
Chris Lattnerba1cb382003-09-19 17:17:26 +00002671 // Check to see if any bits below the one bit set in AndRHSV are set.
2672 if ((AddRHS & (AndRHSV-1)) == 0) {
2673 // If not, the only thing that can effect the output of the AND is
2674 // the bit specified by AndRHSV. If that bit is set, the effect of
2675 // the XOR is to toggle the bit. If it is clear, then the ADD has
2676 // no effect.
2677 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
2678 TheAnd.setOperand(0, X);
2679 return &TheAnd;
2680 } else {
2681 std::string Name = Op->getName(); Op->setName("");
2682 // Pull the XOR out of the AND.
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002683 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS, Name);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002684 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002685 return BinaryOperator::createXor(NewAnd, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002686 }
2687 }
2688 }
2689 }
2690 break;
Chris Lattner2da29172003-09-19 19:05:02 +00002691
2692 case Instruction::Shl: {
2693 // We know that the AND will not produce any of the bits shifted in, so if
2694 // the anded constant includes them, clear them now!
2695 //
2696 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner7e794272004-09-24 15:21:34 +00002697 Constant *ShlMask = ConstantExpr::getShl(AllOne, OpRHS);
2698 Constant *CI = ConstantExpr::getAnd(AndRHS, ShlMask);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002699
Chris Lattner7e794272004-09-24 15:21:34 +00002700 if (CI == ShlMask) { // Masking out bits that the shift already masks
2701 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
2702 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner2da29172003-09-19 19:05:02 +00002703 TheAnd.setOperand(1, CI);
2704 return &TheAnd;
2705 }
2706 break;
Misha Brukmanb1c93172005-04-21 23:48:37 +00002707 }
Chris Lattner2da29172003-09-19 19:05:02 +00002708 case Instruction::Shr:
2709 // We know that the AND will not produce any of the bits shifted in, so if
2710 // the anded constant includes them, clear them now! This only applies to
2711 // unsigned shifts, because a signed shr may bring in set bits!
2712 //
2713 if (AndRHS->getType()->isUnsigned()) {
2714 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner7e794272004-09-24 15:21:34 +00002715 Constant *ShrMask = ConstantExpr::getShr(AllOne, OpRHS);
2716 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
2717
2718 if (CI == ShrMask) { // Masking out bits that the shift already masks.
2719 return ReplaceInstUsesWith(TheAnd, Op);
2720 } else if (CI != AndRHS) {
2721 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
Chris Lattner2da29172003-09-19 19:05:02 +00002722 return &TheAnd;
2723 }
Chris Lattner7e794272004-09-24 15:21:34 +00002724 } else { // Signed shr.
2725 // See if this is shifting in some sign extension, then masking it out
2726 // with an and.
2727 if (Op->hasOneUse()) {
2728 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
2729 Constant *ShrMask = ConstantExpr::getUShr(AllOne, OpRHS);
2730 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
Chris Lattner5c3c21e2004-10-22 04:53:16 +00002731 if (CI == AndRHS) { // Masking out bits shifted in.
Chris Lattner7e794272004-09-24 15:21:34 +00002732 // Make the argument unsigned.
2733 Value *ShVal = Op->getOperand(0);
2734 ShVal = InsertCastBefore(ShVal,
2735 ShVal->getType()->getUnsignedVersion(),
2736 TheAnd);
2737 ShVal = InsertNewInstBefore(new ShiftInst(Instruction::Shr, ShVal,
2738 OpRHS, Op->getName()),
2739 TheAnd);
Chris Lattner70c20392004-10-27 05:57:15 +00002740 Value *AndRHS2 = ConstantExpr::getCast(AndRHS, ShVal->getType());
2741 ShVal = InsertNewInstBefore(BinaryOperator::createAnd(ShVal, AndRHS2,
2742 TheAnd.getName()),
2743 TheAnd);
Chris Lattner7e794272004-09-24 15:21:34 +00002744 return new CastInst(ShVal, Op->getType());
2745 }
2746 }
Chris Lattner2da29172003-09-19 19:05:02 +00002747 }
2748 break;
Chris Lattnerba1cb382003-09-19 17:17:26 +00002749 }
2750 return 0;
2751}
2752
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002753
Chris Lattner6862fbd2004-09-29 17:40:11 +00002754/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
2755/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
2756/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. IB is the location to
2757/// insert new instructions.
2758Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
2759 bool Inside, Instruction &IB) {
2760 assert(cast<ConstantBool>(ConstantExpr::getSetLE(Lo, Hi))->getValue() &&
2761 "Lo is not <= Hi in range emission code!");
2762 if (Inside) {
2763 if (Lo == Hi) // Trivially false.
2764 return new SetCondInst(Instruction::SetNE, V, V);
2765 if (cast<ConstantIntegral>(Lo)->isMinValue())
2766 return new SetCondInst(Instruction::SetLT, V, Hi);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002767
Chris Lattner6862fbd2004-09-29 17:40:11 +00002768 Constant *AddCST = ConstantExpr::getNeg(Lo);
2769 Instruction *Add = BinaryOperator::createAdd(V, AddCST,V->getName()+".off");
2770 InsertNewInstBefore(Add, IB);
2771 // Convert to unsigned for the comparison.
2772 const Type *UnsType = Add->getType()->getUnsignedVersion();
2773 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
2774 AddCST = ConstantExpr::getAdd(AddCST, Hi);
2775 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2776 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
2777 }
2778
2779 if (Lo == Hi) // Trivially true.
2780 return new SetCondInst(Instruction::SetEQ, V, V);
2781
2782 Hi = SubOne(cast<ConstantInt>(Hi));
2783 if (cast<ConstantIntegral>(Lo)->isMinValue()) // V < 0 || V >= Hi ->'V > Hi-1'
2784 return new SetCondInst(Instruction::SetGT, V, Hi);
2785
2786 // Emit X-Lo > Hi-Lo-1
2787 Constant *AddCST = ConstantExpr::getNeg(Lo);
2788 Instruction *Add = BinaryOperator::createAdd(V, AddCST, V->getName()+".off");
2789 InsertNewInstBefore(Add, IB);
2790 // Convert to unsigned for the comparison.
2791 const Type *UnsType = Add->getType()->getUnsignedVersion();
2792 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
2793 AddCST = ConstantExpr::getAdd(AddCST, Hi);
2794 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2795 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
2796}
2797
Chris Lattnerb4b25302005-09-18 07:22:02 +00002798// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
2799// any number of 0s on either side. The 1s are allowed to wrap from LSB to
2800// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
2801// not, since all 1s are not contiguous.
2802static bool isRunOfOnes(ConstantIntegral *Val, unsigned &MB, unsigned &ME) {
2803 uint64_t V = Val->getRawValue();
2804 if (!isShiftedMask_64(V)) return false;
2805
2806 // look for the first zero bit after the run of ones
2807 MB = 64-CountLeadingZeros_64((V - 1) ^ V);
2808 // look for the first non-zero bit
2809 ME = 64-CountLeadingZeros_64(V);
2810 return true;
2811}
2812
2813
2814
2815/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
2816/// where isSub determines whether the operator is a sub. If we can fold one of
2817/// the following xforms:
Chris Lattneraf517572005-09-18 04:24:45 +00002818///
2819/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
2820/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
2821/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
2822///
2823/// return (A +/- B).
2824///
2825Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
2826 ConstantIntegral *Mask, bool isSub,
2827 Instruction &I) {
2828 Instruction *LHSI = dyn_cast<Instruction>(LHS);
2829 if (!LHSI || LHSI->getNumOperands() != 2 ||
2830 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
2831
2832 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
2833
2834 switch (LHSI->getOpcode()) {
2835 default: return 0;
2836 case Instruction::And:
Chris Lattnerb4b25302005-09-18 07:22:02 +00002837 if (ConstantExpr::getAnd(N, Mask) == Mask) {
2838 // If the AndRHS is a power of two minus one (0+1+), this is simple.
2839 if ((Mask->getRawValue() & Mask->getRawValue()+1) == 0)
2840 break;
2841
2842 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
2843 // part, we don't need any explicit masks to take them out of A. If that
2844 // is all N is, ignore it.
2845 unsigned MB, ME;
2846 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Chris Lattnerc3ebf402006-02-07 07:27:52 +00002847 uint64_t Mask = RHS->getType()->getIntegralTypeMask();
2848 Mask >>= 64-MB+1;
2849 if (MaskedValueIsZero(RHS, Mask))
Chris Lattnerb4b25302005-09-18 07:22:02 +00002850 break;
2851 }
2852 }
Chris Lattneraf517572005-09-18 04:24:45 +00002853 return 0;
2854 case Instruction::Or:
2855 case Instruction::Xor:
Chris Lattnerb4b25302005-09-18 07:22:02 +00002856 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
2857 if ((Mask->getRawValue() & Mask->getRawValue()+1) == 0 &&
2858 ConstantExpr::getAnd(N, Mask)->isNullValue())
Chris Lattneraf517572005-09-18 04:24:45 +00002859 break;
2860 return 0;
2861 }
2862
2863 Instruction *New;
2864 if (isSub)
2865 New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
2866 else
2867 New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
2868 return InsertNewInstBefore(New, I);
2869}
2870
Chris Lattner113f4f42002-06-25 16:13:24 +00002871Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00002872 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00002873 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002874
Chris Lattner81a7a232004-10-16 18:11:37 +00002875 if (isa<UndefValue>(Op1)) // X & undef -> 0
2876 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2877
Chris Lattner86102b82005-01-01 16:22:27 +00002878 // and X, X = X
2879 if (Op0 == Op1)
Chris Lattnere6794492002-08-12 21:17:25 +00002880 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002881
Chris Lattner5b2edb12006-02-12 08:02:11 +00002882 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner5997cf92006-02-08 03:25:32 +00002883 // purpose is to compute bits we don't care about.
Chris Lattner0157e7f2006-02-11 09:31:47 +00002884 uint64_t KnownZero, KnownOne;
Chris Lattnerd70d9f52006-03-25 21:58:26 +00002885 if (!isa<PackedType>(I.getType()) &&
2886 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
Chris Lattner0157e7f2006-02-11 09:31:47 +00002887 KnownZero, KnownOne))
Chris Lattner5997cf92006-02-08 03:25:32 +00002888 return &I;
2889
Chris Lattner86102b82005-01-01 16:22:27 +00002890 if (ConstantIntegral *AndRHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00002891 uint64_t AndRHSMask = AndRHS->getZExtValue();
2892 uint64_t TypeMask = Op0->getType()->getIntegralTypeMask();
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00002893 uint64_t NotAndRHS = AndRHSMask^TypeMask;
Chris Lattner86102b82005-01-01 16:22:27 +00002894
Chris Lattnerba1cb382003-09-19 17:17:26 +00002895 // Optimize a variety of ((val OP C1) & C2) combinations...
2896 if (isa<BinaryOperator>(Op0) || isa<ShiftInst>(Op0)) {
2897 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner86102b82005-01-01 16:22:27 +00002898 Value *Op0LHS = Op0I->getOperand(0);
2899 Value *Op0RHS = Op0I->getOperand(1);
2900 switch (Op0I->getOpcode()) {
2901 case Instruction::Xor:
2902 case Instruction::Or:
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00002903 // If the mask is only needed on one incoming arm, push it up.
2904 if (Op0I->hasOneUse()) {
2905 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
2906 // Not masking anything out for the LHS, move to RHS.
2907 Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
2908 Op0RHS->getName()+".masked");
2909 InsertNewInstBefore(NewRHS, I);
2910 return BinaryOperator::create(
2911 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002912 }
Chris Lattnerc3ebf402006-02-07 07:27:52 +00002913 if (!isa<Constant>(Op0RHS) &&
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00002914 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
2915 // Not masking anything out for the RHS, move to LHS.
2916 Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
2917 Op0LHS->getName()+".masked");
2918 InsertNewInstBefore(NewLHS, I);
2919 return BinaryOperator::create(
2920 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
2921 }
2922 }
2923
Chris Lattner86102b82005-01-01 16:22:27 +00002924 break;
Chris Lattneraf517572005-09-18 04:24:45 +00002925 case Instruction::Add:
Chris Lattnerb4b25302005-09-18 07:22:02 +00002926 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
2927 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
2928 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
2929 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
2930 return BinaryOperator::createAnd(V, AndRHS);
2931 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
2932 return BinaryOperator::createAnd(V, AndRHS); // Add commutes
Chris Lattneraf517572005-09-18 04:24:45 +00002933 break;
2934
2935 case Instruction::Sub:
Chris Lattnerb4b25302005-09-18 07:22:02 +00002936 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
2937 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
2938 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
2939 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
2940 return BinaryOperator::createAnd(V, AndRHS);
Chris Lattneraf517572005-09-18 04:24:45 +00002941 break;
Chris Lattner86102b82005-01-01 16:22:27 +00002942 }
2943
Chris Lattner16464b32003-07-23 19:25:52 +00002944 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner86102b82005-01-01 16:22:27 +00002945 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerba1cb382003-09-19 17:17:26 +00002946 return Res;
Chris Lattner86102b82005-01-01 16:22:27 +00002947 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
2948 const Type *SrcTy = CI->getOperand(0)->getType();
2949
Chris Lattner2c14cf72005-08-07 07:03:10 +00002950 // If this is an integer truncation or change from signed-to-unsigned, and
2951 // if the source is an and/or with immediate, transform it. This
2952 // frequently occurs for bitfield accesses.
2953 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
2954 if (SrcTy->getPrimitiveSizeInBits() >=
2955 I.getType()->getPrimitiveSizeInBits() &&
2956 CastOp->getNumOperands() == 2)
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00002957 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1)))
Chris Lattner2c14cf72005-08-07 07:03:10 +00002958 if (CastOp->getOpcode() == Instruction::And) {
2959 // Change: and (cast (and X, C1) to T), C2
2960 // into : and (cast X to T), trunc(C1)&C2
2961 // This will folds the two ands together, which may allow other
2962 // simplifications.
2963 Instruction *NewCast =
2964 new CastInst(CastOp->getOperand(0), I.getType(),
2965 CastOp->getName()+".shrunk");
2966 NewCast = InsertNewInstBefore(NewCast, I);
2967
2968 Constant *C3=ConstantExpr::getCast(AndCI, I.getType());//trunc(C1)
2969 C3 = ConstantExpr::getAnd(C3, AndRHS); // trunc(C1)&C2
2970 return BinaryOperator::createAnd(NewCast, C3);
2971 } else if (CastOp->getOpcode() == Instruction::Or) {
2972 // Change: and (cast (or X, C1) to T), C2
2973 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
2974 Constant *C3=ConstantExpr::getCast(AndCI, I.getType());//trunc(C1)
2975 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
2976 return ReplaceInstUsesWith(I, AndRHS);
2977 }
2978 }
Chris Lattner33217db2003-07-23 19:36:21 +00002979 }
Chris Lattner183b3362004-04-09 19:05:30 +00002980
2981 // Try to fold constant and into select arguments.
2982 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00002983 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00002984 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002985 if (isa<PHINode>(Op0))
2986 if (Instruction *NV = FoldOpIntoPhi(I))
2987 return NV;
Chris Lattner49b47ae2003-07-23 17:57:01 +00002988 }
2989
Chris Lattnerbb74e222003-03-10 23:06:50 +00002990 Value *Op0NotVal = dyn_castNotVal(Op0);
2991 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002992
Chris Lattner023a4832004-06-18 06:07:51 +00002993 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
2994 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2995
Misha Brukman9c003d82004-07-30 12:50:08 +00002996 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattnerbb74e222003-03-10 23:06:50 +00002997 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002998 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
2999 I.getName()+".demorgan");
Chris Lattner49b47ae2003-07-23 17:57:01 +00003000 InsertNewInstBefore(Or, I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00003001 return BinaryOperator::createNot(Or);
3002 }
Chris Lattner8b10ab32006-02-13 23:07:23 +00003003
3004 {
3005 Value *A = 0, *B = 0;
3006 ConstantInt *C1 = 0, *C2 = 0;
3007 if (match(Op0, m_Or(m_Value(A), m_Value(B))))
3008 if (A == Op1 || B == Op1) // (A | ?) & A --> A
3009 return ReplaceInstUsesWith(I, Op1);
3010 if (match(Op1, m_Or(m_Value(A), m_Value(B))))
3011 if (A == Op0 || B == Op0) // A & (A | ?) --> A
3012 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerdcd07922006-04-01 08:03:55 +00003013
3014 if (Op0->hasOneUse() &&
3015 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3016 if (A == Op1) { // (A^B)&A -> A&(A^B)
3017 I.swapOperands(); // Simplify below
3018 std::swap(Op0, Op1);
3019 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
3020 cast<BinaryOperator>(Op0)->swapOperands();
3021 I.swapOperands(); // Simplify below
3022 std::swap(Op0, Op1);
3023 }
3024 }
3025 if (Op1->hasOneUse() &&
3026 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3027 if (B == Op0) { // B&(A^B) -> B&(B^A)
3028 cast<BinaryOperator>(Op1)->swapOperands();
3029 std::swap(A, B);
3030 }
3031 if (A == Op0) { // A&(A^B) -> A & ~B
3032 Instruction *NotB = BinaryOperator::createNot(B, "tmp");
3033 InsertNewInstBefore(NotB, I);
3034 return BinaryOperator::createAnd(A, NotB);
3035 }
3036 }
Chris Lattner8b10ab32006-02-13 23:07:23 +00003037 }
3038
Chris Lattner3082c5a2003-02-18 19:28:33 +00003039
Chris Lattner623826c2004-09-28 21:48:02 +00003040 if (SetCondInst *RHS = dyn_cast<SetCondInst>(Op1)) {
3041 // (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
Chris Lattner3ac7c262003-08-13 20:16:26 +00003042 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
3043 return R;
3044
Chris Lattner623826c2004-09-28 21:48:02 +00003045 Value *LHSVal, *RHSVal;
3046 ConstantInt *LHSCst, *RHSCst;
3047 Instruction::BinaryOps LHSCC, RHSCC;
3048 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3049 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3050 if (LHSVal == RHSVal && // Found (X setcc C1) & (X setcc C2)
3051 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
Misha Brukmanb1c93172005-04-21 23:48:37 +00003052 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
Chris Lattner623826c2004-09-28 21:48:02 +00003053 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
3054 // Ensure that the larger constant is on the RHS.
3055 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
3056 SetCondInst *LHS = cast<SetCondInst>(Op0);
3057 if (cast<ConstantBool>(Cmp)->getValue()) {
3058 std::swap(LHS, RHS);
3059 std::swap(LHSCst, RHSCst);
3060 std::swap(LHSCC, RHSCC);
3061 }
3062
3063 // At this point, we know we have have two setcc instructions
3064 // comparing a value against two constants and and'ing the result
3065 // together. Because of the above check, we know that we only have
3066 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
3067 // FoldSetCCLogical check above), that the two constants are not
3068 // equal.
3069 assert(LHSCst != RHSCst && "Compares not folded above?");
3070
3071 switch (LHSCC) {
3072 default: assert(0 && "Unknown integer condition code!");
3073 case Instruction::SetEQ:
3074 switch (RHSCC) {
3075 default: assert(0 && "Unknown integer condition code!");
3076 case Instruction::SetEQ: // (X == 13 & X == 15) -> false
3077 case Instruction::SetGT: // (X == 13 & X > 15) -> false
Chris Lattner6ab03f62006-09-28 23:35:22 +00003078 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattner623826c2004-09-28 21:48:02 +00003079 case Instruction::SetNE: // (X == 13 & X != 15) -> X == 13
3080 case Instruction::SetLT: // (X == 13 & X < 15) -> X == 13
3081 return ReplaceInstUsesWith(I, LHS);
3082 }
3083 case Instruction::SetNE:
3084 switch (RHSCC) {
3085 default: assert(0 && "Unknown integer condition code!");
3086 case Instruction::SetLT:
3087 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X < 14) -> X < 13
3088 return new SetCondInst(Instruction::SetLT, LHSVal, LHSCst);
3089 break; // (X != 13 & X < 15) -> no change
3090 case Instruction::SetEQ: // (X != 13 & X == 15) -> X == 15
3091 case Instruction::SetGT: // (X != 13 & X > 15) -> X > 15
3092 return ReplaceInstUsesWith(I, RHS);
3093 case Instruction::SetNE:
3094 if (LHSCst == SubOne(RHSCst)) {// (X != 13 & X != 14) -> X-13 >u 1
3095 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3096 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3097 LHSVal->getName()+".off");
3098 InsertNewInstBefore(Add, I);
3099 const Type *UnsType = Add->getType()->getUnsignedVersion();
3100 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
3101 AddCST = ConstantExpr::getSub(RHSCst, LHSCst);
3102 AddCST = ConstantExpr::getCast(AddCST, UnsType);
3103 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
3104 }
3105 break; // (X != 13 & X != 15) -> no change
3106 }
3107 break;
3108 case Instruction::SetLT:
3109 switch (RHSCC) {
3110 default: assert(0 && "Unknown integer condition code!");
3111 case Instruction::SetEQ: // (X < 13 & X == 15) -> false
3112 case Instruction::SetGT: // (X < 13 & X > 15) -> false
Chris Lattner6ab03f62006-09-28 23:35:22 +00003113 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattner623826c2004-09-28 21:48:02 +00003114 case Instruction::SetNE: // (X < 13 & X != 15) -> X < 13
3115 case Instruction::SetLT: // (X < 13 & X < 15) -> X < 13
3116 return ReplaceInstUsesWith(I, LHS);
3117 }
3118 case Instruction::SetGT:
3119 switch (RHSCC) {
3120 default: assert(0 && "Unknown integer condition code!");
3121 case Instruction::SetEQ: // (X > 13 & X == 15) -> X > 13
3122 return ReplaceInstUsesWith(I, LHS);
3123 case Instruction::SetGT: // (X > 13 & X > 15) -> X > 15
3124 return ReplaceInstUsesWith(I, RHS);
3125 case Instruction::SetNE:
3126 if (RHSCst == AddOne(LHSCst)) // (X > 13 & X != 14) -> X > 14
3127 return new SetCondInst(Instruction::SetGT, LHSVal, RHSCst);
3128 break; // (X > 13 & X != 15) -> no change
Chris Lattner6862fbd2004-09-29 17:40:11 +00003129 case Instruction::SetLT: // (X > 13 & X < 15) -> (X-14) <u 1
3130 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true, I);
Chris Lattner623826c2004-09-28 21:48:02 +00003131 }
3132 }
3133 }
3134 }
3135
Chris Lattner3af10532006-05-05 06:39:07 +00003136 // fold (and (cast A), (cast B)) -> (cast (and A, B))
3137 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattnere745c7d2006-05-05 20:51:30 +00003138 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner3af10532006-05-05 06:39:07 +00003139 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Chris Lattnere745c7d2006-05-05 20:51:30 +00003140 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegral() &&
Chris Lattner1d441ad2006-05-06 09:00:16 +00003141 // Only do this if the casts both really cause code to be generated.
3142 ValueRequiresCast(Op0C->getOperand(0), I.getType(), TD) &&
3143 ValueRequiresCast(Op1C->getOperand(0), I.getType(), TD)) {
Chris Lattner3af10532006-05-05 06:39:07 +00003144 Instruction *NewOp = BinaryOperator::createAnd(Op0C->getOperand(0),
3145 Op1C->getOperand(0),
3146 I.getName());
3147 InsertNewInstBefore(NewOp, I);
3148 return new CastInst(NewOp, I.getType());
3149 }
3150 }
3151
Chris Lattner113f4f42002-06-25 16:13:24 +00003152 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003153}
3154
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003155/// CollectBSwapParts - Look to see if the specified value defines a single byte
3156/// in the result. If it does, and if the specified byte hasn't been filled in
3157/// yet, fill it in and return false.
3158static bool CollectBSwapParts(Value *V, std::vector<Value*> &ByteValues) {
3159 Instruction *I = dyn_cast<Instruction>(V);
3160 if (I == 0) return true;
3161
3162 // If this is an or instruction, it is an inner node of the bswap.
3163 if (I->getOpcode() == Instruction::Or)
3164 return CollectBSwapParts(I->getOperand(0), ByteValues) ||
3165 CollectBSwapParts(I->getOperand(1), ByteValues);
3166
3167 // If this is a shift by a constant int, and it is "24", then its operand
3168 // defines a byte. We only handle unsigned types here.
3169 if (isa<ShiftInst>(I) && isa<ConstantInt>(I->getOperand(1))) {
3170 // Not shifting the entire input by N-1 bytes?
3171 if (cast<ConstantInt>(I->getOperand(1))->getRawValue() !=
3172 8*(ByteValues.size()-1))
3173 return true;
3174
3175 unsigned DestNo;
3176 if (I->getOpcode() == Instruction::Shl) {
3177 // X << 24 defines the top byte with the lowest of the input bytes.
3178 DestNo = ByteValues.size()-1;
3179 } else {
3180 // X >>u 24 defines the low byte with the highest of the input bytes.
3181 DestNo = 0;
3182 }
3183
3184 // If the destination byte value is already defined, the values are or'd
3185 // together, which isn't a bswap (unless it's an or of the same bits).
3186 if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
3187 return true;
3188 ByteValues[DestNo] = I->getOperand(0);
3189 return false;
3190 }
3191
3192 // Otherwise, we can only handle and(shift X, imm), imm). Bail out of if we
3193 // don't have this.
3194 Value *Shift = 0, *ShiftLHS = 0;
3195 ConstantInt *AndAmt = 0, *ShiftAmt = 0;
3196 if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
3197 !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
3198 return true;
3199 Instruction *SI = cast<Instruction>(Shift);
3200
3201 // Make sure that the shift amount is by a multiple of 8 and isn't too big.
3202 if (ShiftAmt->getRawValue() & 7 ||
3203 ShiftAmt->getRawValue() > 8*ByteValues.size())
3204 return true;
3205
3206 // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
3207 unsigned DestByte;
3208 for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
3209 if (AndAmt->getRawValue() == uint64_t(0xFF) << 8*DestByte)
3210 break;
3211 // Unknown mask for bswap.
3212 if (DestByte == ByteValues.size()) return true;
3213
3214 unsigned ShiftBytes = ShiftAmt->getRawValue()/8;
3215 unsigned SrcByte;
3216 if (SI->getOpcode() == Instruction::Shl)
3217 SrcByte = DestByte - ShiftBytes;
3218 else
3219 SrcByte = DestByte + ShiftBytes;
3220
3221 // If the SrcByte isn't a bswapped value from the DestByte, reject it.
3222 if (SrcByte != ByteValues.size()-DestByte-1)
3223 return true;
3224
3225 // If the destination byte value is already defined, the values are or'd
3226 // together, which isn't a bswap (unless it's an or of the same bits).
3227 if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
3228 return true;
3229 ByteValues[DestByte] = SI->getOperand(0);
3230 return false;
3231}
3232
3233/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
3234/// If so, insert the new bswap intrinsic and return it.
3235Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
3236 // We can only handle bswap of unsigned integers, and cannot bswap one byte.
3237 if (!I.getType()->isUnsigned() || I.getType() == Type::UByteTy)
3238 return 0;
3239
3240 /// ByteValues - For each byte of the result, we keep track of which value
3241 /// defines each byte.
3242 std::vector<Value*> ByteValues;
3243 ByteValues.resize(I.getType()->getPrimitiveSize());
3244
3245 // Try to find all the pieces corresponding to the bswap.
3246 if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
3247 CollectBSwapParts(I.getOperand(1), ByteValues))
3248 return 0;
3249
3250 // Check to see if all of the bytes come from the same value.
3251 Value *V = ByteValues[0];
3252 if (V == 0) return 0; // Didn't find a byte? Must be zero.
3253
3254 // Check to make sure that all of the bytes come from the same value.
3255 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
3256 if (ByteValues[i] != V)
3257 return 0;
3258
3259 // If they do then *success* we can turn this into a bswap. Figure out what
3260 // bswap to make it into.
3261 Module *M = I.getParent()->getParent()->getParent();
Chris Lattner091b6ea2006-07-11 18:31:26 +00003262 const char *FnName = 0;
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003263 if (I.getType() == Type::UShortTy)
3264 FnName = "llvm.bswap.i16";
3265 else if (I.getType() == Type::UIntTy)
3266 FnName = "llvm.bswap.i32";
3267 else if (I.getType() == Type::ULongTy)
3268 FnName = "llvm.bswap.i64";
3269 else
3270 assert(0 && "Unknown integer type!");
3271 Function *F = M->getOrInsertFunction(FnName, I.getType(), I.getType(), NULL);
3272
3273 return new CallInst(F, V);
3274}
3275
3276
Chris Lattner113f4f42002-06-25 16:13:24 +00003277Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003278 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00003279 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003280
Chris Lattner81a7a232004-10-16 18:11:37 +00003281 if (isa<UndefValue>(Op1))
3282 return ReplaceInstUsesWith(I, // X | undef -> -1
3283 ConstantIntegral::getAllOnesValue(I.getType()));
3284
Chris Lattner5b2edb12006-02-12 08:02:11 +00003285 // or X, X = X
3286 if (Op0 == Op1)
Chris Lattnere6794492002-08-12 21:17:25 +00003287 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003288
Chris Lattner5b2edb12006-02-12 08:02:11 +00003289 // See if we can simplify any instructions used by the instruction whose sole
3290 // purpose is to compute bits we don't care about.
3291 uint64_t KnownZero, KnownOne;
Chris Lattnerd70d9f52006-03-25 21:58:26 +00003292 if (!isa<PackedType>(I.getType()) &&
3293 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
Chris Lattner5b2edb12006-02-12 08:02:11 +00003294 KnownZero, KnownOne))
3295 return &I;
3296
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003297 // or X, -1 == -1
Chris Lattner8f0d1562003-07-23 18:29:44 +00003298 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner330628a2006-01-06 17:59:59 +00003299 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00003300 // (X & C1) | C2 --> (X | C2) & (C1|C2)
3301 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Chris Lattnerb62f5082005-05-09 04:58:36 +00003302 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0->getName());
3303 Op0->setName("");
Chris Lattnerd4252a72004-07-30 07:50:03 +00003304 InsertNewInstBefore(Or, I);
3305 return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, C1));
3306 }
Chris Lattner8f0d1562003-07-23 18:29:44 +00003307
Chris Lattnerd4252a72004-07-30 07:50:03 +00003308 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
3309 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
3310 std::string Op0Name = Op0->getName(); Op0->setName("");
3311 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
3312 InsertNewInstBefore(Or, I);
3313 return BinaryOperator::createXor(Or,
3314 ConstantExpr::getAnd(C1, ConstantExpr::getNot(RHS)));
Chris Lattner8f0d1562003-07-23 18:29:44 +00003315 }
Chris Lattner183b3362004-04-09 19:05:30 +00003316
3317 // Try to fold constant and into select arguments.
3318 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00003319 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00003320 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00003321 if (isa<PHINode>(Op0))
3322 if (Instruction *NV = FoldOpIntoPhi(I))
3323 return NV;
Chris Lattner8f0d1562003-07-23 18:29:44 +00003324 }
3325
Chris Lattner330628a2006-01-06 17:59:59 +00003326 Value *A = 0, *B = 0;
3327 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattner4294cec2005-05-07 23:49:08 +00003328
3329 if (match(Op0, m_And(m_Value(A), m_Value(B))))
3330 if (A == Op1 || B == Op1) // (A & ?) | A --> A
3331 return ReplaceInstUsesWith(I, Op1);
3332 if (match(Op1, m_And(m_Value(A), m_Value(B))))
3333 if (A == Op0 || B == Op0) // A | (A & ?) --> A
3334 return ReplaceInstUsesWith(I, Op0);
3335
Chris Lattnerb7845d62006-07-10 20:25:24 +00003336 // (A | B) | C and A | (B | C) -> bswap if possible.
3337 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003338 if (match(Op0, m_Or(m_Value(), m_Value())) ||
Chris Lattnerb7845d62006-07-10 20:25:24 +00003339 match(Op1, m_Or(m_Value(), m_Value())) ||
3340 (match(Op0, m_Shift(m_Value(), m_Value())) &&
3341 match(Op1, m_Shift(m_Value(), m_Value())))) {
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003342 if (Instruction *BSwap = MatchBSwap(I))
3343 return BSwap;
3344 }
3345
Chris Lattnerb62f5082005-05-09 04:58:36 +00003346 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
3347 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003348 MaskedValueIsZero(Op1, C1->getZExtValue())) {
Chris Lattnerb62f5082005-05-09 04:58:36 +00003349 Instruction *NOr = BinaryOperator::createOr(A, Op1, Op0->getName());
3350 Op0->setName("");
3351 return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
3352 }
3353
3354 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
3355 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003356 MaskedValueIsZero(Op0, C1->getZExtValue())) {
Chris Lattnerb62f5082005-05-09 04:58:36 +00003357 Instruction *NOr = BinaryOperator::createOr(A, Op0, Op1->getName());
3358 Op0->setName("");
3359 return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
3360 }
3361
Chris Lattner15212982005-09-18 03:42:07 +00003362 // (A & C1)|(B & C2)
Chris Lattnerd4252a72004-07-30 07:50:03 +00003363 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattner15212982005-09-18 03:42:07 +00003364 match(Op1, m_And(m_Value(B), m_ConstantInt(C2)))) {
3365
3366 if (A == B) // (A & C1)|(A & C2) == A & (C1|C2)
3367 return BinaryOperator::createAnd(A, ConstantExpr::getOr(C1, C2));
3368
3369
Chris Lattner01f56c62005-09-18 06:02:59 +00003370 // If we have: ((V + N) & C1) | (V & C2)
3371 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
3372 // replace with V+N.
3373 if (C1 == ConstantExpr::getNot(C2)) {
Chris Lattner330628a2006-01-06 17:59:59 +00003374 Value *V1 = 0, *V2 = 0;
Chris Lattner01f56c62005-09-18 06:02:59 +00003375 if ((C2->getRawValue() & (C2->getRawValue()+1)) == 0 && // C2 == 0+1+
3376 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
3377 // Add commutes, try both ways.
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003378 if (V1 == B && MaskedValueIsZero(V2, C2->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003379 return ReplaceInstUsesWith(I, A);
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003380 if (V2 == B && MaskedValueIsZero(V1, C2->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003381 return ReplaceInstUsesWith(I, A);
3382 }
3383 // Or commutes, try both ways.
3384 if ((C1->getRawValue() & (C1->getRawValue()+1)) == 0 &&
3385 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
3386 // Add commutes, try both ways.
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003387 if (V1 == A && MaskedValueIsZero(V2, C1->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003388 return ReplaceInstUsesWith(I, B);
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003389 if (V2 == A && MaskedValueIsZero(V1, C1->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003390 return ReplaceInstUsesWith(I, B);
Chris Lattner15212982005-09-18 03:42:07 +00003391 }
3392 }
3393 }
Chris Lattner812aab72003-08-12 19:11:07 +00003394
Chris Lattnerd4252a72004-07-30 07:50:03 +00003395 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
3396 if (A == Op1) // ~A | A == -1
Misha Brukmanb1c93172005-04-21 23:48:37 +00003397 return ReplaceInstUsesWith(I,
Chris Lattnerd4252a72004-07-30 07:50:03 +00003398 ConstantIntegral::getAllOnesValue(I.getType()));
3399 } else {
3400 A = 0;
3401 }
Chris Lattner4294cec2005-05-07 23:49:08 +00003402 // Note, A is still live here!
Chris Lattnerd4252a72004-07-30 07:50:03 +00003403 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
3404 if (Op0 == B)
Misha Brukmanb1c93172005-04-21 23:48:37 +00003405 return ReplaceInstUsesWith(I,
Chris Lattnerd4252a72004-07-30 07:50:03 +00003406 ConstantIntegral::getAllOnesValue(I.getType()));
Chris Lattner3e327a42003-03-10 23:13:59 +00003407
Misha Brukman9c003d82004-07-30 12:50:08 +00003408 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattnerd4252a72004-07-30 07:50:03 +00003409 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3410 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
3411 I.getName()+".demorgan"), I);
3412 return BinaryOperator::createNot(And);
3413 }
Chris Lattner3e327a42003-03-10 23:13:59 +00003414 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00003415
Chris Lattner3ac7c262003-08-13 20:16:26 +00003416 // (setcc1 A, B) | (setcc2 A, B) --> (setcc3 A, B)
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003417 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1))) {
Chris Lattner3ac7c262003-08-13 20:16:26 +00003418 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
3419 return R;
3420
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003421 Value *LHSVal, *RHSVal;
3422 ConstantInt *LHSCst, *RHSCst;
3423 Instruction::BinaryOps LHSCC, RHSCC;
3424 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3425 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3426 if (LHSVal == RHSVal && // Found (X setcc C1) | (X setcc C2)
3427 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
Misha Brukmanb1c93172005-04-21 23:48:37 +00003428 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003429 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
3430 // Ensure that the larger constant is on the RHS.
3431 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
3432 SetCondInst *LHS = cast<SetCondInst>(Op0);
3433 if (cast<ConstantBool>(Cmp)->getValue()) {
3434 std::swap(LHS, RHS);
3435 std::swap(LHSCst, RHSCst);
3436 std::swap(LHSCC, RHSCC);
3437 }
3438
3439 // At this point, we know we have have two setcc instructions
3440 // comparing a value against two constants and or'ing the result
3441 // together. Because of the above check, we know that we only have
3442 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
3443 // FoldSetCCLogical check above), that the two constants are not
3444 // equal.
3445 assert(LHSCst != RHSCst && "Compares not folded above?");
3446
3447 switch (LHSCC) {
3448 default: assert(0 && "Unknown integer condition code!");
3449 case Instruction::SetEQ:
3450 switch (RHSCC) {
3451 default: assert(0 && "Unknown integer condition code!");
3452 case Instruction::SetEQ:
3453 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
3454 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3455 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3456 LHSVal->getName()+".off");
3457 InsertNewInstBefore(Add, I);
3458 const Type *UnsType = Add->getType()->getUnsignedVersion();
3459 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
3460 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
3461 AddCST = ConstantExpr::getCast(AddCST, UnsType);
3462 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
3463 }
3464 break; // (X == 13 | X == 15) -> no change
3465
Chris Lattner5c219462005-04-19 06:04:18 +00003466 case Instruction::SetGT: // (X == 13 | X > 14) -> no change
3467 break;
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003468 case Instruction::SetNE: // (X == 13 | X != 15) -> X != 15
3469 case Instruction::SetLT: // (X == 13 | X < 15) -> X < 15
3470 return ReplaceInstUsesWith(I, RHS);
3471 }
3472 break;
3473 case Instruction::SetNE:
3474 switch (RHSCC) {
3475 default: assert(0 && "Unknown integer condition code!");
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003476 case Instruction::SetEQ: // (X != 13 | X == 15) -> X != 13
3477 case Instruction::SetGT: // (X != 13 | X > 15) -> X != 13
3478 return ReplaceInstUsesWith(I, LHS);
3479 case Instruction::SetNE: // (X != 13 | X != 15) -> true
Chris Lattner2ceb6ee2005-06-17 03:59:17 +00003480 case Instruction::SetLT: // (X != 13 | X < 15) -> true
Chris Lattner6ab03f62006-09-28 23:35:22 +00003481 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003482 }
3483 break;
3484 case Instruction::SetLT:
3485 switch (RHSCC) {
3486 default: assert(0 && "Unknown integer condition code!");
3487 case Instruction::SetEQ: // (X < 13 | X == 14) -> no change
3488 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00003489 case Instruction::SetGT: // (X < 13 | X > 15) -> (X-13) > 2
3490 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false, I);
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003491 case Instruction::SetNE: // (X < 13 | X != 15) -> X != 15
3492 case Instruction::SetLT: // (X < 13 | X < 15) -> X < 15
3493 return ReplaceInstUsesWith(I, RHS);
3494 }
3495 break;
3496 case Instruction::SetGT:
3497 switch (RHSCC) {
3498 default: assert(0 && "Unknown integer condition code!");
3499 case Instruction::SetEQ: // (X > 13 | X == 15) -> X > 13
3500 case Instruction::SetGT: // (X > 13 | X > 15) -> X > 13
3501 return ReplaceInstUsesWith(I, LHS);
3502 case Instruction::SetNE: // (X > 13 | X != 15) -> true
3503 case Instruction::SetLT: // (X > 13 | X < 15) -> true
Chris Lattner6ab03f62006-09-28 23:35:22 +00003504 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003505 }
3506 }
3507 }
3508 }
Chris Lattner3af10532006-05-05 06:39:07 +00003509
3510 // fold (or (cast A), (cast B)) -> (cast (or A, B))
3511 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattnere745c7d2006-05-05 20:51:30 +00003512 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner3af10532006-05-05 06:39:07 +00003513 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Chris Lattnere745c7d2006-05-05 20:51:30 +00003514 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegral() &&
Chris Lattner1d441ad2006-05-06 09:00:16 +00003515 // Only do this if the casts both really cause code to be generated.
3516 ValueRequiresCast(Op0C->getOperand(0), I.getType(), TD) &&
3517 ValueRequiresCast(Op1C->getOperand(0), I.getType(), TD)) {
Chris Lattner3af10532006-05-05 06:39:07 +00003518 Instruction *NewOp = BinaryOperator::createOr(Op0C->getOperand(0),
3519 Op1C->getOperand(0),
3520 I.getName());
3521 InsertNewInstBefore(NewOp, I);
3522 return new CastInst(NewOp, I.getType());
3523 }
3524 }
3525
Chris Lattner15212982005-09-18 03:42:07 +00003526
Chris Lattner113f4f42002-06-25 16:13:24 +00003527 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003528}
3529
Chris Lattnerc2076352004-02-16 01:20:27 +00003530// XorSelf - Implements: X ^ X --> 0
3531struct XorSelf {
3532 Value *RHS;
3533 XorSelf(Value *rhs) : RHS(rhs) {}
3534 bool shouldApply(Value *LHS) const { return LHS == RHS; }
3535 Instruction *apply(BinaryOperator &Xor) const {
3536 return &Xor;
3537 }
3538};
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003539
3540
Chris Lattner113f4f42002-06-25 16:13:24 +00003541Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003542 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00003543 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003544
Chris Lattner81a7a232004-10-16 18:11:37 +00003545 if (isa<UndefValue>(Op1))
3546 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
3547
Chris Lattnerc2076352004-02-16 01:20:27 +00003548 // xor X, X = 0, even if X is nested in a sequence of Xor's.
3549 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
3550 assert(Result == &I && "AssociativeOpt didn't work?");
Chris Lattnere6794492002-08-12 21:17:25 +00003551 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc2076352004-02-16 01:20:27 +00003552 }
Chris Lattner5b2edb12006-02-12 08:02:11 +00003553
3554 // See if we can simplify any instructions used by the instruction whose sole
3555 // purpose is to compute bits we don't care about.
3556 uint64_t KnownZero, KnownOne;
Chris Lattnerd70d9f52006-03-25 21:58:26 +00003557 if (!isa<PackedType>(I.getType()) &&
3558 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
Chris Lattner5b2edb12006-02-12 08:02:11 +00003559 KnownZero, KnownOne))
3560 return &I;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003561
Chris Lattner97638592003-07-23 21:37:07 +00003562 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner97638592003-07-23 21:37:07 +00003563 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerb8d6e402002-08-20 18:24:26 +00003564 // xor (setcc A, B), true = not (setcc A, B) = setncc A, B
Chris Lattner97638592003-07-23 21:37:07 +00003565 if (SetCondInst *SCI = dyn_cast<SetCondInst>(Op0I))
Chris Lattner6ab03f62006-09-28 23:35:22 +00003566 if (RHS == ConstantBool::getTrue() && SCI->hasOneUse())
Chris Lattnerb8d6e402002-08-20 18:24:26 +00003567 return new SetCondInst(SCI->getInverseCondition(),
3568 SCI->getOperand(0), SCI->getOperand(1));
Chris Lattnere5806662003-11-04 23:50:51 +00003569
Chris Lattner8f2f5982003-11-05 01:06:05 +00003570 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003571 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
3572 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003573 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
3574 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003575 ConstantInt::get(I.getType(), 1));
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003576 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003577 }
Chris Lattner023a4832004-06-18 06:07:51 +00003578
3579 // ~(~X & Y) --> (X | ~Y)
3580 if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
3581 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
3582 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
3583 Instruction *NotY =
Misha Brukmanb1c93172005-04-21 23:48:37 +00003584 BinaryOperator::createNot(Op0I->getOperand(1),
Chris Lattner023a4832004-06-18 06:07:51 +00003585 Op0I->getOperand(1)->getName()+".not");
3586 InsertNewInstBefore(NotY, I);
3587 return BinaryOperator::createOr(Op0NotVal, NotY);
3588 }
3589 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003590
Chris Lattner97638592003-07-23 21:37:07 +00003591 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner5b2edb12006-02-12 08:02:11 +00003592 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner0f68fa62003-11-04 23:37:10 +00003593 // ~(X-c) --> (-c-1)-X
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003594 if (RHS->isAllOnesValue()) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003595 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
3596 return BinaryOperator::createSub(
3597 ConstantExpr::getSub(NegOp0CI,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003598 ConstantInt::get(I.getType(), 1)),
Chris Lattner0f68fa62003-11-04 23:37:10 +00003599 Op0I->getOperand(0));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003600 }
Chris Lattnerf78df7c2006-02-26 19:57:54 +00003601 } else if (Op0I->getOpcode() == Instruction::Or) {
3602 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
3603 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getZExtValue())) {
3604 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
3605 // Anything in both C1 and C2 is known to be zero, remove it from
3606 // NewRHS.
3607 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
3608 NewRHS = ConstantExpr::getAnd(NewRHS,
3609 ConstantExpr::getNot(CommonBits));
3610 WorkList.push_back(Op0I);
3611 I.setOperand(0, Op0I->getOperand(0));
3612 I.setOperand(1, NewRHS);
3613 return &I;
3614 }
Chris Lattner97638592003-07-23 21:37:07 +00003615 }
Chris Lattnerb8d6e402002-08-20 18:24:26 +00003616 }
Chris Lattner183b3362004-04-09 19:05:30 +00003617
3618 // Try to fold constant and into select arguments.
3619 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00003620 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00003621 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00003622 if (isa<PHINode>(Op0))
3623 if (Instruction *NV = FoldOpIntoPhi(I))
3624 return NV;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003625 }
3626
Chris Lattnerbb74e222003-03-10 23:06:50 +00003627 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00003628 if (X == Op1)
3629 return ReplaceInstUsesWith(I,
3630 ConstantIntegral::getAllOnesValue(I.getType()));
3631
Chris Lattnerbb74e222003-03-10 23:06:50 +00003632 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00003633 if (X == Op0)
3634 return ReplaceInstUsesWith(I,
3635 ConstantIntegral::getAllOnesValue(I.getType()));
3636
Chris Lattnerdcd07922006-04-01 08:03:55 +00003637 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1))
Chris Lattnerb36d9082004-02-16 03:54:20 +00003638 if (Op1I->getOpcode() == Instruction::Or) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003639 if (Op1I->getOperand(0) == Op0) { // B^(B|A) == (A|B)^B
Chris Lattnerdcd07922006-04-01 08:03:55 +00003640 Op1I->swapOperands();
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003641 I.swapOperands();
3642 std::swap(Op0, Op1);
3643 } else if (Op1I->getOperand(1) == Op0) { // B^(A|B) == (A|B)^B
Chris Lattnerdcd07922006-04-01 08:03:55 +00003644 I.swapOperands(); // Simplified below.
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003645 std::swap(Op0, Op1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003646 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00003647 } else if (Op1I->getOpcode() == Instruction::Xor) {
3648 if (Op0 == Op1I->getOperand(0)) // A^(A^B) == B
3649 return ReplaceInstUsesWith(I, Op1I->getOperand(1));
3650 else if (Op0 == Op1I->getOperand(1)) // A^(B^A) == B
3651 return ReplaceInstUsesWith(I, Op1I->getOperand(0));
Chris Lattnerdcd07922006-04-01 08:03:55 +00003652 } else if (Op1I->getOpcode() == Instruction::And && Op1I->hasOneUse()) {
3653 if (Op1I->getOperand(0) == Op0) // A^(A&B) -> A^(B&A)
3654 Op1I->swapOperands();
3655 if (Op0 == Op1I->getOperand(1)) { // A^(B&A) -> (B&A)^A
3656 I.swapOperands(); // Simplified below.
3657 std::swap(Op0, Op1);
3658 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00003659 }
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003660
Chris Lattnerdcd07922006-04-01 08:03:55 +00003661 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00003662 if (Op0I->getOpcode() == Instruction::Or && Op0I->hasOneUse()) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003663 if (Op0I->getOperand(0) == Op1) // (B|A)^B == (A|B)^B
Chris Lattnerdcd07922006-04-01 08:03:55 +00003664 Op0I->swapOperands();
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003665 if (Op0I->getOperand(1) == Op1) { // (A|B)^B == A & ~B
Chris Lattnerdcd07922006-04-01 08:03:55 +00003666 Instruction *NotB = BinaryOperator::createNot(Op1, "tmp");
3667 InsertNewInstBefore(NotB, I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003668 return BinaryOperator::createAnd(Op0I->getOperand(0), NotB);
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003669 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00003670 } else if (Op0I->getOpcode() == Instruction::Xor) {
3671 if (Op1 == Op0I->getOperand(0)) // (A^B)^A == B
3672 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
3673 else if (Op1 == Op0I->getOperand(1)) // (B^A)^A == B
3674 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattnerdcd07922006-04-01 08:03:55 +00003675 } else if (Op0I->getOpcode() == Instruction::And && Op0I->hasOneUse()) {
3676 if (Op0I->getOperand(0) == Op1) // (A&B)^A -> (B&A)^A
3677 Op0I->swapOperands();
Chris Lattner6cf49142006-04-01 22:05:01 +00003678 if (Op0I->getOperand(1) == Op1 && // (B&A)^A == ~B & A
3679 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattnerdcd07922006-04-01 08:03:55 +00003680 Instruction *N = BinaryOperator::createNot(Op0I->getOperand(0), "tmp");
3681 InsertNewInstBefore(N, I);
3682 return BinaryOperator::createAnd(N, Op1);
3683 }
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003684 }
3685
Chris Lattner3ac7c262003-08-13 20:16:26 +00003686 // (setcc1 A, B) ^ (setcc2 A, B) --> (setcc3 A, B)
3687 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
3688 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
3689 return R;
3690
Chris Lattner3af10532006-05-05 06:39:07 +00003691 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
3692 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattnere745c7d2006-05-05 20:51:30 +00003693 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner3af10532006-05-05 06:39:07 +00003694 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Chris Lattnere745c7d2006-05-05 20:51:30 +00003695 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegral() &&
Chris Lattner1d441ad2006-05-06 09:00:16 +00003696 // Only do this if the casts both really cause code to be generated.
3697 ValueRequiresCast(Op0C->getOperand(0), I.getType(), TD) &&
3698 ValueRequiresCast(Op1C->getOperand(0), I.getType(), TD)) {
Chris Lattner3af10532006-05-05 06:39:07 +00003699 Instruction *NewOp = BinaryOperator::createXor(Op0C->getOperand(0),
3700 Op1C->getOperand(0),
3701 I.getName());
3702 InsertNewInstBefore(NewOp, I);
3703 return new CastInst(NewOp, I.getType());
3704 }
3705 }
3706
Chris Lattner113f4f42002-06-25 16:13:24 +00003707 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003708}
3709
Chris Lattner6862fbd2004-09-29 17:40:11 +00003710/// MulWithOverflow - Compute Result = In1*In2, returning true if the result
3711/// overflowed for this type.
3712static bool MulWithOverflow(ConstantInt *&Result, ConstantInt *In1,
3713 ConstantInt *In2) {
3714 Result = cast<ConstantInt>(ConstantExpr::getMul(In1, In2));
3715 return !In2->isNullValue() && ConstantExpr::getDiv(Result, In2) != In1;
3716}
3717
3718static bool isPositive(ConstantInt *C) {
3719 return cast<ConstantSInt>(C)->getValue() >= 0;
3720}
3721
3722/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
3723/// overflowed for this type.
3724static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
3725 ConstantInt *In2) {
3726 Result = cast<ConstantInt>(ConstantExpr::getAdd(In1, In2));
3727
3728 if (In1->getType()->isUnsigned())
3729 return cast<ConstantUInt>(Result)->getValue() <
3730 cast<ConstantUInt>(In1)->getValue();
3731 if (isPositive(In1) != isPositive(In2))
3732 return false;
3733 if (isPositive(In1))
3734 return cast<ConstantSInt>(Result)->getValue() <
3735 cast<ConstantSInt>(In1)->getValue();
3736 return cast<ConstantSInt>(Result)->getValue() >
3737 cast<ConstantSInt>(In1)->getValue();
3738}
3739
Chris Lattner0798af32005-01-13 20:14:25 +00003740/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
3741/// code necessary to compute the offset from the base pointer (without adding
3742/// in the base pointer). Return the result as a signed integer of intptr size.
3743static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
3744 TargetData &TD = IC.getTargetData();
3745 gep_type_iterator GTI = gep_type_begin(GEP);
3746 const Type *UIntPtrTy = TD.getIntPtrType();
3747 const Type *SIntPtrTy = UIntPtrTy->getSignedVersion();
3748 Value *Result = Constant::getNullValue(SIntPtrTy);
3749
3750 // Build a mask for high order bits.
Chris Lattner77defba2006-02-07 07:00:41 +00003751 uint64_t PtrSizeMask = ~0ULL >> (64-TD.getPointerSize()*8);
Chris Lattner0798af32005-01-13 20:14:25 +00003752
Chris Lattner0798af32005-01-13 20:14:25 +00003753 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
3754 Value *Op = GEP->getOperand(i);
Chris Lattnerd35d2102005-01-13 23:26:48 +00003755 uint64_t Size = TD.getTypeSize(GTI.getIndexedType()) & PtrSizeMask;
Chris Lattner0798af32005-01-13 20:14:25 +00003756 Constant *Scale = ConstantExpr::getCast(ConstantUInt::get(UIntPtrTy, Size),
3757 SIntPtrTy);
3758 if (Constant *OpC = dyn_cast<Constant>(Op)) {
3759 if (!OpC->isNullValue()) {
Chris Lattner4cb9fa32005-01-13 20:40:58 +00003760 OpC = ConstantExpr::getCast(OpC, SIntPtrTy);
Chris Lattner0798af32005-01-13 20:14:25 +00003761 Scale = ConstantExpr::getMul(OpC, Scale);
3762 if (Constant *RC = dyn_cast<Constant>(Result))
3763 Result = ConstantExpr::getAdd(RC, Scale);
3764 else {
3765 // Emit an add instruction.
3766 Result = IC.InsertNewInstBefore(
3767 BinaryOperator::createAdd(Result, Scale,
3768 GEP->getName()+".offs"), I);
3769 }
3770 }
3771 } else {
Chris Lattner7aa41cf2005-01-14 17:17:59 +00003772 // Convert to correct type.
3773 Op = IC.InsertNewInstBefore(new CastInst(Op, SIntPtrTy,
3774 Op->getName()+".c"), I);
3775 if (Size != 1)
Chris Lattner4cb9fa32005-01-13 20:40:58 +00003776 // We'll let instcombine(mul) convert this to a shl if possible.
3777 Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
3778 GEP->getName()+".idx"), I);
Chris Lattner0798af32005-01-13 20:14:25 +00003779
3780 // Emit an add instruction.
Chris Lattner4cb9fa32005-01-13 20:40:58 +00003781 Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
Chris Lattner0798af32005-01-13 20:14:25 +00003782 GEP->getName()+".offs"), I);
3783 }
3784 }
3785 return Result;
3786}
3787
3788/// FoldGEPSetCC - Fold comparisons between a GEP instruction and something
3789/// else. At this point we know that the GEP is on the LHS of the comparison.
3790Instruction *InstCombiner::FoldGEPSetCC(User *GEPLHS, Value *RHS,
3791 Instruction::BinaryOps Cond,
3792 Instruction &I) {
3793 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattner81e84172005-01-13 22:25:21 +00003794
3795 if (CastInst *CI = dyn_cast<CastInst>(RHS))
3796 if (isa<PointerType>(CI->getOperand(0)->getType()))
3797 RHS = CI->getOperand(0);
3798
Chris Lattner0798af32005-01-13 20:14:25 +00003799 Value *PtrBase = GEPLHS->getOperand(0);
3800 if (PtrBase == RHS) {
3801 // As an optimization, we don't actually have to compute the actual value of
3802 // OFFSET if this is a seteq or setne comparison, just return whether each
3803 // index is zero or not.
Chris Lattner81e84172005-01-13 22:25:21 +00003804 if (Cond == Instruction::SetEQ || Cond == Instruction::SetNE) {
3805 Instruction *InVal = 0;
Chris Lattnercd517ff2005-01-28 19:32:01 +00003806 gep_type_iterator GTI = gep_type_begin(GEPLHS);
3807 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i, ++GTI) {
Chris Lattner81e84172005-01-13 22:25:21 +00003808 bool EmitIt = true;
3809 if (Constant *C = dyn_cast<Constant>(GEPLHS->getOperand(i))) {
3810 if (isa<UndefValue>(C)) // undef index -> undef.
3811 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
3812 if (C->isNullValue())
3813 EmitIt = false;
Chris Lattnercd517ff2005-01-28 19:32:01 +00003814 else if (TD->getTypeSize(GTI.getIndexedType()) == 0) {
3815 EmitIt = false; // This is indexing into a zero sized array?
Misha Brukmanb1c93172005-04-21 23:48:37 +00003816 } else if (isa<ConstantInt>(C))
Chris Lattner81e84172005-01-13 22:25:21 +00003817 return ReplaceInstUsesWith(I, // No comparison is needed here.
3818 ConstantBool::get(Cond == Instruction::SetNE));
3819 }
3820
3821 if (EmitIt) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00003822 Instruction *Comp =
Chris Lattner81e84172005-01-13 22:25:21 +00003823 new SetCondInst(Cond, GEPLHS->getOperand(i),
3824 Constant::getNullValue(GEPLHS->getOperand(i)->getType()));
3825 if (InVal == 0)
3826 InVal = Comp;
3827 else {
3828 InVal = InsertNewInstBefore(InVal, I);
3829 InsertNewInstBefore(Comp, I);
3830 if (Cond == Instruction::SetNE) // True if any are unequal
3831 InVal = BinaryOperator::createOr(InVal, Comp);
3832 else // True if all are equal
3833 InVal = BinaryOperator::createAnd(InVal, Comp);
3834 }
3835 }
3836 }
3837
3838 if (InVal)
3839 return InVal;
3840 else
3841 ReplaceInstUsesWith(I, // No comparison is needed here, all indexes = 0
3842 ConstantBool::get(Cond == Instruction::SetEQ));
3843 }
Chris Lattner0798af32005-01-13 20:14:25 +00003844
3845 // Only lower this if the setcc is the only user of the GEP or if we expect
3846 // the result to fold to a constant!
3847 if (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) {
3848 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
3849 Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
3850 return new SetCondInst(Cond, Offset,
3851 Constant::getNullValue(Offset->getType()));
3852 }
3853 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
Chris Lattnera21bf8d2005-04-25 20:17:30 +00003854 // If the base pointers are different, but the indices are the same, just
3855 // compare the base pointer.
3856 if (PtrBase != GEPRHS->getOperand(0)) {
3857 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00003858 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattnerbd43b9d2005-04-26 14:40:41 +00003859 GEPRHS->getOperand(0)->getType();
Chris Lattnera21bf8d2005-04-25 20:17:30 +00003860 if (IndicesTheSame)
3861 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
3862 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
3863 IndicesTheSame = false;
3864 break;
3865 }
3866
3867 // If all indices are the same, just compare the base pointers.
3868 if (IndicesTheSame)
3869 return new SetCondInst(Cond, GEPLHS->getOperand(0),
3870 GEPRHS->getOperand(0));
3871
3872 // Otherwise, the base pointers are different and the indices are
3873 // different, bail out.
Chris Lattner0798af32005-01-13 20:14:25 +00003874 return 0;
Chris Lattnera21bf8d2005-04-25 20:17:30 +00003875 }
Chris Lattner0798af32005-01-13 20:14:25 +00003876
Chris Lattner81e84172005-01-13 22:25:21 +00003877 // If one of the GEPs has all zero indices, recurse.
3878 bool AllZeros = true;
3879 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
3880 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
3881 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
3882 AllZeros = false;
3883 break;
3884 }
3885 if (AllZeros)
3886 return FoldGEPSetCC(GEPRHS, GEPLHS->getOperand(0),
3887 SetCondInst::getSwappedCondition(Cond), I);
Chris Lattner4fa89822005-01-14 00:20:05 +00003888
3889 // If the other GEP has all zero indices, recurse.
Chris Lattner81e84172005-01-13 22:25:21 +00003890 AllZeros = true;
3891 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
3892 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
3893 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
3894 AllZeros = false;
3895 break;
3896 }
3897 if (AllZeros)
3898 return FoldGEPSetCC(GEPLHS, GEPRHS->getOperand(0), Cond, I);
3899
Chris Lattner4fa89822005-01-14 00:20:05 +00003900 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
3901 // If the GEPs only differ by one index, compare it.
3902 unsigned NumDifferences = 0; // Keep track of # differences.
3903 unsigned DiffOperand = 0; // The operand that differs.
3904 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
3905 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003906 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
3907 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattnerfc4429e2005-01-21 23:06:49 +00003908 // Irreconcilable differences.
Chris Lattner4fa89822005-01-14 00:20:05 +00003909 NumDifferences = 2;
3910 break;
3911 } else {
3912 if (NumDifferences++) break;
3913 DiffOperand = i;
3914 }
3915 }
3916
3917 if (NumDifferences == 0) // SAME GEP?
3918 return ReplaceInstUsesWith(I, // No comparison is needed here.
3919 ConstantBool::get(Cond == Instruction::SetEQ));
3920 else if (NumDifferences == 1) {
Chris Lattnerfc4429e2005-01-21 23:06:49 +00003921 Value *LHSV = GEPLHS->getOperand(DiffOperand);
3922 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Chris Lattner247aef82005-07-18 23:07:33 +00003923
3924 // Convert the operands to signed values to make sure to perform a
3925 // signed comparison.
3926 const Type *NewTy = LHSV->getType()->getSignedVersion();
3927 if (LHSV->getType() != NewTy)
3928 LHSV = InsertNewInstBefore(new CastInst(LHSV, NewTy,
3929 LHSV->getName()), I);
3930 if (RHSV->getType() != NewTy)
3931 RHSV = InsertNewInstBefore(new CastInst(RHSV, NewTy,
3932 RHSV->getName()), I);
3933 return new SetCondInst(Cond, LHSV, RHSV);
Chris Lattner4fa89822005-01-14 00:20:05 +00003934 }
3935 }
3936
Chris Lattner0798af32005-01-13 20:14:25 +00003937 // Only lower this if the setcc is the only user of the GEP or if we expect
3938 // the result to fold to a constant!
3939 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
3940 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
3941 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
3942 Value *L = EmitGEPOffset(GEPLHS, I, *this);
3943 Value *R = EmitGEPOffset(GEPRHS, I, *this);
3944 return new SetCondInst(Cond, L, R);
3945 }
3946 }
3947 return 0;
3948}
3949
3950
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003951Instruction *InstCombiner::visitSetCondInst(SetCondInst &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003952 bool Changed = SimplifyCommutative(I);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003953 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3954 const Type *Ty = Op0->getType();
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003955
3956 // setcc X, X
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003957 if (Op0 == Op1)
3958 return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
Chris Lattner1fc23f32002-05-09 20:11:54 +00003959
Chris Lattner81a7a232004-10-16 18:11:37 +00003960 if (isa<UndefValue>(Op1)) // X setcc undef -> undef
3961 return ReplaceInstUsesWith(I, UndefValue::get(Type::BoolTy));
3962
Chris Lattner15ff1e12004-11-14 07:33:16 +00003963 // setcc <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
3964 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanb1c93172005-04-21 23:48:37 +00003965 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
3966 isa<ConstantPointerNull>(Op0)) &&
3967 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner15ff1e12004-11-14 07:33:16 +00003968 isa<ConstantPointerNull>(Op1)))
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003969 return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
3970
3971 // setcc's with boolean values can always be turned into bitwise operations
3972 if (Ty == Type::BoolTy) {
Chris Lattner4456da62004-08-11 00:50:51 +00003973 switch (I.getOpcode()) {
3974 default: assert(0 && "Invalid setcc instruction!");
3975 case Instruction::SetEQ: { // seteq bool %A, %B -> ~(A^B)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003976 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003977 InsertNewInstBefore(Xor, I);
Chris Lattner16930792003-11-03 04:25:02 +00003978 return BinaryOperator::createNot(Xor);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003979 }
Chris Lattner4456da62004-08-11 00:50:51 +00003980 case Instruction::SetNE:
3981 return BinaryOperator::createXor(Op0, Op1);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003982
Chris Lattner4456da62004-08-11 00:50:51 +00003983 case Instruction::SetGT:
3984 std::swap(Op0, Op1); // Change setgt -> setlt
3985 // FALL THROUGH
3986 case Instruction::SetLT: { // setlt bool A, B -> ~X & Y
3987 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
3988 InsertNewInstBefore(Not, I);
3989 return BinaryOperator::createAnd(Not, Op1);
3990 }
3991 case Instruction::SetGE:
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003992 std::swap(Op0, Op1); // Change setge -> setle
Chris Lattner4456da62004-08-11 00:50:51 +00003993 // FALL THROUGH
3994 case Instruction::SetLE: { // setle bool %A, %B -> ~A | B
3995 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
3996 InsertNewInstBefore(Not, I);
3997 return BinaryOperator::createOr(Not, Op1);
3998 }
3999 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004000 }
4001
Chris Lattner2dd01742004-06-09 04:24:29 +00004002 // See if we are doing a comparison between a constant and an instruction that
4003 // can be folded into the comparison.
Chris Lattner6d14f2a2002-08-09 23:47:40 +00004004 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner6862fbd2004-09-29 17:40:11 +00004005 // Check to see if we are comparing against the minimum or maximum value...
4006 if (CI->isMinValue()) {
4007 if (I.getOpcode() == Instruction::SetLT) // A < MIN -> FALSE
Chris Lattner6ab03f62006-09-28 23:35:22 +00004008 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattner6862fbd2004-09-29 17:40:11 +00004009 if (I.getOpcode() == Instruction::SetGE) // A >= MIN -> TRUE
Chris Lattner6ab03f62006-09-28 23:35:22 +00004010 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
Chris Lattner6862fbd2004-09-29 17:40:11 +00004011 if (I.getOpcode() == Instruction::SetLE) // A <= MIN -> A == MIN
4012 return BinaryOperator::createSetEQ(Op0, Op1);
4013 if (I.getOpcode() == Instruction::SetGT) // A > MIN -> A != MIN
4014 return BinaryOperator::createSetNE(Op0, Op1);
4015
4016 } else if (CI->isMaxValue()) {
4017 if (I.getOpcode() == Instruction::SetGT) // A > MAX -> FALSE
Chris Lattner6ab03f62006-09-28 23:35:22 +00004018 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattner6862fbd2004-09-29 17:40:11 +00004019 if (I.getOpcode() == Instruction::SetLE) // A <= MAX -> TRUE
Chris Lattner6ab03f62006-09-28 23:35:22 +00004020 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
Chris Lattner6862fbd2004-09-29 17:40:11 +00004021 if (I.getOpcode() == Instruction::SetGE) // A >= MAX -> A == MAX
4022 return BinaryOperator::createSetEQ(Op0, Op1);
4023 if (I.getOpcode() == Instruction::SetLT) // A < MAX -> A != MAX
4024 return BinaryOperator::createSetNE(Op0, Op1);
4025
4026 // Comparing against a value really close to min or max?
4027 } else if (isMinValuePlusOne(CI)) {
4028 if (I.getOpcode() == Instruction::SetLT) // A < MIN+1 -> A == MIN
4029 return BinaryOperator::createSetEQ(Op0, SubOne(CI));
4030 if (I.getOpcode() == Instruction::SetGE) // A >= MIN-1 -> A != MIN
4031 return BinaryOperator::createSetNE(Op0, SubOne(CI));
4032
4033 } else if (isMaxValueMinusOne(CI)) {
4034 if (I.getOpcode() == Instruction::SetGT) // A > MAX-1 -> A == MAX
4035 return BinaryOperator::createSetEQ(Op0, AddOne(CI));
4036 if (I.getOpcode() == Instruction::SetLE) // A <= MAX-1 -> A != MAX
4037 return BinaryOperator::createSetNE(Op0, AddOne(CI));
4038 }
4039
4040 // If we still have a setle or setge instruction, turn it into the
4041 // appropriate setlt or setgt instruction. Since the border cases have
4042 // already been handled above, this requires little checking.
4043 //
4044 if (I.getOpcode() == Instruction::SetLE)
4045 return BinaryOperator::createSetLT(Op0, AddOne(CI));
4046 if (I.getOpcode() == Instruction::SetGE)
4047 return BinaryOperator::createSetGT(Op0, SubOne(CI));
4048
Chris Lattneree0f2802006-02-12 02:07:56 +00004049
4050 // See if we can fold the comparison based on bits known to be zero or one
4051 // in the input.
4052 uint64_t KnownZero, KnownOne;
4053 if (SimplifyDemandedBits(Op0, Ty->getIntegralTypeMask(),
4054 KnownZero, KnownOne, 0))
4055 return &I;
4056
4057 // Given the known and unknown bits, compute a range that the LHS could be
4058 // in.
4059 if (KnownOne | KnownZero) {
4060 if (Ty->isUnsigned()) { // Unsigned comparison.
4061 uint64_t Min, Max;
4062 uint64_t RHSVal = CI->getZExtValue();
4063 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne,
4064 Min, Max);
4065 switch (I.getOpcode()) { // LE/GE have been folded already.
4066 default: assert(0 && "Unknown setcc opcode!");
4067 case Instruction::SetEQ:
4068 if (Max < RHSVal || Min > RHSVal)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004069 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattneree0f2802006-02-12 02:07:56 +00004070 break;
4071 case Instruction::SetNE:
4072 if (Max < RHSVal || Min > RHSVal)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004073 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
Chris Lattneree0f2802006-02-12 02:07:56 +00004074 break;
4075 case Instruction::SetLT:
Chris Lattner6ab03f62006-09-28 23:35:22 +00004076 if (Max < RHSVal)
4077 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4078 if (Min > RHSVal)
4079 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattneree0f2802006-02-12 02:07:56 +00004080 break;
4081 case Instruction::SetGT:
Chris Lattner6ab03f62006-09-28 23:35:22 +00004082 if (Min > RHSVal)
4083 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4084 if (Max < RHSVal)
4085 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattneree0f2802006-02-12 02:07:56 +00004086 break;
4087 }
4088 } else { // Signed comparison.
4089 int64_t Min, Max;
4090 int64_t RHSVal = CI->getSExtValue();
4091 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne,
4092 Min, Max);
4093 switch (I.getOpcode()) { // LE/GE have been folded already.
4094 default: assert(0 && "Unknown setcc opcode!");
4095 case Instruction::SetEQ:
4096 if (Max < RHSVal || Min > RHSVal)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004097 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattneree0f2802006-02-12 02:07:56 +00004098 break;
4099 case Instruction::SetNE:
4100 if (Max < RHSVal || Min > RHSVal)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004101 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
Chris Lattneree0f2802006-02-12 02:07:56 +00004102 break;
4103 case Instruction::SetLT:
Chris Lattner6ab03f62006-09-28 23:35:22 +00004104 if (Max < RHSVal)
4105 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4106 if (Min > RHSVal)
4107 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattneree0f2802006-02-12 02:07:56 +00004108 break;
4109 case Instruction::SetGT:
Chris Lattner6ab03f62006-09-28 23:35:22 +00004110 if (Min > RHSVal)
4111 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4112 if (Max < RHSVal)
4113 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattneree0f2802006-02-12 02:07:56 +00004114 break;
4115 }
4116 }
4117 }
4118
4119
Chris Lattnere1e10e12004-05-25 06:32:08 +00004120 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004121 switch (LHSI->getOpcode()) {
4122 case Instruction::And:
4123 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
4124 LHSI->getOperand(0)->hasOneUse()) {
Chris Lattner4922a0e2006-09-18 05:27:43 +00004125 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
4126
4127 // If an operand is an AND of a truncating cast, we can widen the
4128 // and/compare to be the input width without changing the value
4129 // produced, eliminating a cast.
4130 if (CastInst *Cast = dyn_cast<CastInst>(LHSI->getOperand(0))) {
4131 // We can do this transformation if either the AND constant does not
4132 // have its sign bit set or if it is an equality comparison.
4133 // Extending a relational comparison when we're checking the sign
4134 // bit would not work.
4135 if (Cast->hasOneUse() && Cast->isTruncIntCast() &&
4136 (I.isEquality() ||
4137 (AndCST->getZExtValue() == (uint64_t)AndCST->getSExtValue()) &&
4138 (CI->getZExtValue() == (uint64_t)CI->getSExtValue()))) {
4139 ConstantInt *NewCST;
4140 ConstantInt *NewCI;
4141 if (Cast->getOperand(0)->getType()->isSigned()) {
4142 NewCST = ConstantSInt::get(Cast->getOperand(0)->getType(),
4143 AndCST->getZExtValue());
4144 NewCI = ConstantSInt::get(Cast->getOperand(0)->getType(),
4145 CI->getZExtValue());
4146 } else {
4147 NewCST = ConstantUInt::get(Cast->getOperand(0)->getType(),
4148 AndCST->getZExtValue());
4149 NewCI = ConstantUInt::get(Cast->getOperand(0)->getType(),
4150 CI->getZExtValue());
4151 }
4152 Instruction *NewAnd =
4153 BinaryOperator::createAnd(Cast->getOperand(0), NewCST,
4154 LHSI->getName());
4155 InsertNewInstBefore(NewAnd, I);
4156 return new SetCondInst(I.getOpcode(), NewAnd, NewCI);
4157 }
4158 }
4159
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004160 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
4161 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
4162 // happens a LOT in code produced by the C front-end, for bitfield
4163 // access.
4164 ShiftInst *Shift = dyn_cast<ShiftInst>(LHSI->getOperand(0));
Chris Lattneree0f2802006-02-12 02:07:56 +00004165
4166 // Check to see if there is a noop-cast between the shift and the and.
4167 if (!Shift) {
4168 if (CastInst *CI = dyn_cast<CastInst>(LHSI->getOperand(0)))
4169 if (CI->getOperand(0)->getType()->isIntegral() &&
4170 CI->getOperand(0)->getType()->getPrimitiveSizeInBits() ==
4171 CI->getType()->getPrimitiveSizeInBits())
4172 Shift = dyn_cast<ShiftInst>(CI->getOperand(0));
4173 }
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004174
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004175 ConstantUInt *ShAmt;
4176 ShAmt = Shift ? dyn_cast<ConstantUInt>(Shift->getOperand(1)) : 0;
Chris Lattneree0f2802006-02-12 02:07:56 +00004177 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
4178 const Type *AndTy = AndCST->getType(); // Type of the and.
Misha Brukmanb1c93172005-04-21 23:48:37 +00004179
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004180 // We can fold this as long as we can't shift unknown bits
4181 // into the mask. This can only happen with signed shift
4182 // rights, as they sign-extend.
4183 if (ShAmt) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004184 bool CanFold = Shift->isLogicalShift();
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004185 if (!CanFold) {
4186 // To test for the bad case of the signed shr, see if any
4187 // of the bits shifted in could be tested after the mask.
Chris Lattnerc53cb9d2005-06-17 01:29:28 +00004188 int ShAmtVal = Ty->getPrimitiveSizeInBits()-ShAmt->getValue();
4189 if (ShAmtVal < 0) ShAmtVal = 0; // Out of range shift.
4190
4191 Constant *OShAmt = ConstantUInt::get(Type::UByteTy, ShAmtVal);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004192 Constant *ShVal =
Chris Lattneree0f2802006-02-12 02:07:56 +00004193 ConstantExpr::getShl(ConstantInt::getAllOnesValue(AndTy),
4194 OShAmt);
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004195 if (ConstantExpr::getAnd(ShVal, AndCST)->isNullValue())
4196 CanFold = true;
4197 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004198
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004199 if (CanFold) {
Chris Lattner6afc02f2004-09-28 17:54:07 +00004200 Constant *NewCst;
4201 if (Shift->getOpcode() == Instruction::Shl)
4202 NewCst = ConstantExpr::getUShr(CI, ShAmt);
4203 else
4204 NewCst = ConstantExpr::getShl(CI, ShAmt);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004205
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004206 // Check to see if we are shifting out any of the bits being
4207 // compared.
4208 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != CI){
4209 // If we shifted bits out, the fold is not going to work out.
4210 // As a special case, check to see if this means that the
4211 // result is always true or false now.
4212 if (I.getOpcode() == Instruction::SetEQ)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004213 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004214 if (I.getOpcode() == Instruction::SetNE)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004215 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004216 } else {
4217 I.setOperand(1, NewCst);
Chris Lattner6afc02f2004-09-28 17:54:07 +00004218 Constant *NewAndCST;
4219 if (Shift->getOpcode() == Instruction::Shl)
4220 NewAndCST = ConstantExpr::getUShr(AndCST, ShAmt);
4221 else
4222 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
4223 LHSI->setOperand(1, NewAndCST);
Chris Lattneree0f2802006-02-12 02:07:56 +00004224 if (AndTy == Ty)
4225 LHSI->setOperand(0, Shift->getOperand(0));
4226 else {
4227 Value *NewCast = InsertCastBefore(Shift->getOperand(0), AndTy,
4228 *Shift);
4229 LHSI->setOperand(0, NewCast);
4230 }
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004231 WorkList.push_back(Shift); // Shift is dead.
4232 AddUsesToWorkList(I);
4233 return &I;
Chris Lattner1638de42004-07-21 19:50:44 +00004234 }
4235 }
Chris Lattner35167c32004-06-09 07:59:58 +00004236 }
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004237
4238 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
4239 // preferable because it allows the C<<Y expression to be hoisted out
4240 // of a loop if Y is invariant and X is not.
4241 if (Shift && Shift->hasOneUse() && CI->isNullValue() &&
Chris Lattnerde077922006-09-18 18:27:05 +00004242 I.isEquality() && !Shift->isArithmeticShift() &&
4243 isa<Instruction>(Shift->getOperand(0))) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004244 // Compute C << Y.
4245 Value *NS;
4246 if (Shift->getOpcode() == Instruction::Shr) {
4247 NS = new ShiftInst(Instruction::Shl, AndCST, Shift->getOperand(1),
4248 "tmp");
4249 } else {
4250 // Make sure we insert a logical shift.
Chris Lattner4922a0e2006-09-18 05:27:43 +00004251 Constant *NewAndCST = AndCST;
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004252 if (AndCST->getType()->isSigned())
Chris Lattner4922a0e2006-09-18 05:27:43 +00004253 NewAndCST = ConstantExpr::getCast(AndCST,
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004254 AndCST->getType()->getUnsignedVersion());
Chris Lattner4922a0e2006-09-18 05:27:43 +00004255 NS = new ShiftInst(Instruction::Shr, NewAndCST,
4256 Shift->getOperand(1), "tmp");
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004257 }
4258 InsertNewInstBefore(cast<Instruction>(NS), I);
4259
4260 // If C's sign doesn't agree with the and, insert a cast now.
4261 if (NS->getType() != LHSI->getType())
4262 NS = InsertCastBefore(NS, LHSI->getType(), I);
4263
4264 Value *ShiftOp = Shift->getOperand(0);
4265 if (ShiftOp->getType() != LHSI->getType())
4266 ShiftOp = InsertCastBefore(ShiftOp, LHSI->getType(), I);
4267
4268 // Compute X & (C << Y).
4269 Instruction *NewAnd =
4270 BinaryOperator::createAnd(ShiftOp, NS, LHSI->getName());
4271 InsertNewInstBefore(NewAnd, I);
4272
4273 I.setOperand(0, NewAnd);
4274 return &I;
4275 }
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004276 }
4277 break;
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004278
Chris Lattner272d5ca2004-09-28 18:22:15 +00004279 case Instruction::Shl: // (setcc (shl X, ShAmt), CI)
4280 if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004281 if (I.isEquality()) {
Chris Lattner19b57f52005-06-15 20:53:31 +00004282 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
4283
4284 // Check that the shift amount is in range. If not, don't perform
4285 // undefined shifts. When the shift is visited it will be
4286 // simplified.
4287 if (ShAmt->getValue() >= TypeBits)
4288 break;
4289
Chris Lattner272d5ca2004-09-28 18:22:15 +00004290 // If we are comparing against bits always shifted out, the
4291 // comparison cannot succeed.
Misha Brukmanb1c93172005-04-21 23:48:37 +00004292 Constant *Comp =
Chris Lattner272d5ca2004-09-28 18:22:15 +00004293 ConstantExpr::getShl(ConstantExpr::getShr(CI, ShAmt), ShAmt);
4294 if (Comp != CI) {// Comparing against a bit that we know is zero.
4295 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
4296 Constant *Cst = ConstantBool::get(IsSetNE);
4297 return ReplaceInstUsesWith(I, Cst);
4298 }
4299
4300 if (LHSI->hasOneUse()) {
4301 // Otherwise strength reduce the shift into an and.
Chris Lattnerfdfe3e492005-01-08 19:42:22 +00004302 unsigned ShAmtVal = (unsigned)ShAmt->getValue();
Chris Lattner272d5ca2004-09-28 18:22:15 +00004303 uint64_t Val = (1ULL << (TypeBits-ShAmtVal))-1;
4304
4305 Constant *Mask;
4306 if (CI->getType()->isUnsigned()) {
4307 Mask = ConstantUInt::get(CI->getType(), Val);
4308 } else if (ShAmtVal != 0) {
4309 Mask = ConstantSInt::get(CI->getType(), Val);
4310 } else {
4311 Mask = ConstantInt::getAllOnesValue(CI->getType());
4312 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004313
Chris Lattner272d5ca2004-09-28 18:22:15 +00004314 Instruction *AndI =
4315 BinaryOperator::createAnd(LHSI->getOperand(0),
4316 Mask, LHSI->getName()+".mask");
4317 Value *And = InsertNewInstBefore(AndI, I);
4318 return new SetCondInst(I.getOpcode(), And,
4319 ConstantExpr::getUShr(CI, ShAmt));
4320 }
4321 }
Chris Lattner272d5ca2004-09-28 18:22:15 +00004322 }
4323 break;
4324
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004325 case Instruction::Shr: // (setcc (shr X, ShAmt), CI)
Chris Lattner1023b872004-09-27 16:18:50 +00004326 if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004327 if (I.isEquality()) {
Chris Lattner19b57f52005-06-15 20:53:31 +00004328 // Check that the shift amount is in range. If not, don't perform
4329 // undefined shifts. When the shift is visited it will be
4330 // simplified.
Chris Lattner104002b2005-06-16 01:52:07 +00004331 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
Chris Lattner19b57f52005-06-15 20:53:31 +00004332 if (ShAmt->getValue() >= TypeBits)
4333 break;
4334
Chris Lattner1023b872004-09-27 16:18:50 +00004335 // If we are comparing against bits always shifted out, the
4336 // comparison cannot succeed.
Misha Brukmanb1c93172005-04-21 23:48:37 +00004337 Constant *Comp =
Chris Lattner1023b872004-09-27 16:18:50 +00004338 ConstantExpr::getShr(ConstantExpr::getShl(CI, ShAmt), ShAmt);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004339
Chris Lattner1023b872004-09-27 16:18:50 +00004340 if (Comp != CI) {// Comparing against a bit that we know is zero.
4341 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
4342 Constant *Cst = ConstantBool::get(IsSetNE);
4343 return ReplaceInstUsesWith(I, Cst);
4344 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004345
Chris Lattner1023b872004-09-27 16:18:50 +00004346 if (LHSI->hasOneUse() || CI->isNullValue()) {
Chris Lattnerfdfe3e492005-01-08 19:42:22 +00004347 unsigned ShAmtVal = (unsigned)ShAmt->getValue();
Chris Lattner272d5ca2004-09-28 18:22:15 +00004348
Chris Lattner1023b872004-09-27 16:18:50 +00004349 // Otherwise strength reduce the shift into an and.
4350 uint64_t Val = ~0ULL; // All ones.
4351 Val <<= ShAmtVal; // Shift over to the right spot.
4352
4353 Constant *Mask;
4354 if (CI->getType()->isUnsigned()) {
Chris Lattner2f1457f2005-04-24 17:46:05 +00004355 Val &= ~0ULL >> (64-TypeBits);
Chris Lattner1023b872004-09-27 16:18:50 +00004356 Mask = ConstantUInt::get(CI->getType(), Val);
4357 } else {
4358 Mask = ConstantSInt::get(CI->getType(), Val);
4359 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004360
Chris Lattner1023b872004-09-27 16:18:50 +00004361 Instruction *AndI =
4362 BinaryOperator::createAnd(LHSI->getOperand(0),
4363 Mask, LHSI->getName()+".mask");
4364 Value *And = InsertNewInstBefore(AndI, I);
4365 return new SetCondInst(I.getOpcode(), And,
4366 ConstantExpr::getShl(CI, ShAmt));
4367 }
Chris Lattner1023b872004-09-27 16:18:50 +00004368 }
4369 }
4370 break;
Chris Lattner7e794272004-09-24 15:21:34 +00004371
Chris Lattner6862fbd2004-09-29 17:40:11 +00004372 case Instruction::Div:
4373 // Fold: (div X, C1) op C2 -> range check
4374 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
4375 // Fold this div into the comparison, producing a range check.
4376 // Determine, based on the divide type, what the range is being
4377 // checked. If there is an overflow on the low or high side, remember
4378 // it, otherwise compute the range [low, hi) bounding the new value.
4379 bool LoOverflow = false, HiOverflow = 0;
4380 ConstantInt *LoBound = 0, *HiBound = 0;
4381
4382 ConstantInt *Prod;
4383 bool ProdOV = MulWithOverflow(Prod, CI, DivRHS);
4384
Chris Lattnera92af962004-10-11 19:40:04 +00004385 Instruction::BinaryOps Opcode = I.getOpcode();
4386
Chris Lattner6862fbd2004-09-29 17:40:11 +00004387 if (DivRHS->isNullValue()) { // Don't hack on divide by zeros.
4388 } else if (LHSI->getType()->isUnsigned()) { // udiv
4389 LoBound = Prod;
4390 LoOverflow = ProdOV;
4391 HiOverflow = ProdOV || AddWithOverflow(HiBound, LoBound, DivRHS);
4392 } else if (isPositive(DivRHS)) { // Divisor is > 0.
4393 if (CI->isNullValue()) { // (X / pos) op 0
4394 // Can't overflow.
4395 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
4396 HiBound = DivRHS;
4397 } else if (isPositive(CI)) { // (X / pos) op pos
4398 LoBound = Prod;
4399 LoOverflow = ProdOV;
4400 HiOverflow = ProdOV || AddWithOverflow(HiBound, Prod, DivRHS);
4401 } else { // (X / pos) op neg
4402 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
4403 LoOverflow = AddWithOverflow(LoBound, Prod,
4404 cast<ConstantInt>(DivRHSH));
4405 HiBound = Prod;
4406 HiOverflow = ProdOV;
4407 }
4408 } else { // Divisor is < 0.
4409 if (CI->isNullValue()) { // (X / neg) op 0
4410 LoBound = AddOne(DivRHS);
4411 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner73bcba52005-06-17 02:05:55 +00004412 if (HiBound == DivRHS)
4413 LoBound = 0; // - INTMIN = INTMIN
Chris Lattner6862fbd2004-09-29 17:40:11 +00004414 } else if (isPositive(CI)) { // (X / neg) op pos
4415 HiOverflow = LoOverflow = ProdOV;
4416 if (!LoOverflow)
4417 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS));
4418 HiBound = AddOne(Prod);
4419 } else { // (X / neg) op neg
4420 LoBound = Prod;
4421 LoOverflow = HiOverflow = ProdOV;
4422 HiBound = cast<ConstantInt>(ConstantExpr::getSub(Prod, DivRHS));
4423 }
Chris Lattner0b41e862004-10-08 19:15:44 +00004424
Chris Lattnera92af962004-10-11 19:40:04 +00004425 // Dividing by a negate swaps the condition.
4426 Opcode = SetCondInst::getSwappedCondition(Opcode);
Chris Lattner6862fbd2004-09-29 17:40:11 +00004427 }
4428
4429 if (LoBound) {
4430 Value *X = LHSI->getOperand(0);
Chris Lattnera92af962004-10-11 19:40:04 +00004431 switch (Opcode) {
Chris Lattner6862fbd2004-09-29 17:40:11 +00004432 default: assert(0 && "Unhandled setcc opcode!");
4433 case Instruction::SetEQ:
4434 if (LoOverflow && HiOverflow)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004435 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattner6862fbd2004-09-29 17:40:11 +00004436 else if (HiOverflow)
4437 return new SetCondInst(Instruction::SetGE, X, LoBound);
4438 else if (LoOverflow)
4439 return new SetCondInst(Instruction::SetLT, X, HiBound);
4440 else
4441 return InsertRangeTest(X, LoBound, HiBound, true, I);
4442 case Instruction::SetNE:
4443 if (LoOverflow && HiOverflow)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004444 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
Chris Lattner6862fbd2004-09-29 17:40:11 +00004445 else if (HiOverflow)
4446 return new SetCondInst(Instruction::SetLT, X, LoBound);
4447 else if (LoOverflow)
4448 return new SetCondInst(Instruction::SetGE, X, HiBound);
4449 else
4450 return InsertRangeTest(X, LoBound, HiBound, false, I);
4451 case Instruction::SetLT:
4452 if (LoOverflow)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004453 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattner6862fbd2004-09-29 17:40:11 +00004454 return new SetCondInst(Instruction::SetLT, X, LoBound);
4455 case Instruction::SetGT:
4456 if (HiOverflow)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004457 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattner6862fbd2004-09-29 17:40:11 +00004458 return new SetCondInst(Instruction::SetGE, X, HiBound);
4459 }
4460 }
4461 }
4462 break;
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004463 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004464
Chris Lattnerd492a0b2003-07-23 17:02:11 +00004465 // Simplify seteq and setne instructions...
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004466 if (I.isEquality()) {
Chris Lattnerd492a0b2003-07-23 17:02:11 +00004467 bool isSetNE = I.getOpcode() == Instruction::SetNE;
4468
Chris Lattnercfbce7c2003-07-23 17:26:36 +00004469 // If the first operand is (and|or|xor) with a constant, and the second
Chris Lattnerd492a0b2003-07-23 17:02:11 +00004470 // operand is a constant, simplify a bit.
Chris Lattnerc992add2003-08-13 05:33:12 +00004471 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
4472 switch (BO->getOpcode()) {
Chris Lattner23b47b62004-07-06 07:38:18 +00004473 case Instruction::Rem:
4474 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
4475 if (CI->isNullValue() && isa<ConstantSInt>(BO->getOperand(1)) &&
4476 BO->hasOneUse() &&
Chris Lattner22d00a82005-08-02 19:16:58 +00004477 cast<ConstantSInt>(BO->getOperand(1))->getValue() > 1) {
4478 int64_t V = cast<ConstantSInt>(BO->getOperand(1))->getValue();
4479 if (isPowerOf2_64(V)) {
4480 unsigned L2 = Log2_64(V);
Chris Lattner23b47b62004-07-06 07:38:18 +00004481 const Type *UTy = BO->getType()->getUnsignedVersion();
4482 Value *NewX = InsertNewInstBefore(new CastInst(BO->getOperand(0),
4483 UTy, "tmp"), I);
4484 Constant *RHSCst = ConstantUInt::get(UTy, 1ULL << L2);
4485 Value *NewRem =InsertNewInstBefore(BinaryOperator::createRem(NewX,
4486 RHSCst, BO->getName()), I);
4487 return BinaryOperator::create(I.getOpcode(), NewRem,
4488 Constant::getNullValue(UTy));
4489 }
Chris Lattner22d00a82005-08-02 19:16:58 +00004490 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004491 break;
Chris Lattner23b47b62004-07-06 07:38:18 +00004492
Chris Lattnerc992add2003-08-13 05:33:12 +00004493 case Instruction::Add:
Chris Lattner6e079362004-06-27 22:51:36 +00004494 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
4495 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerb121ae12004-09-21 21:35:23 +00004496 if (BO->hasOneUse())
4497 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
4498 ConstantExpr::getSub(CI, BOp1C));
Chris Lattner6e079362004-06-27 22:51:36 +00004499 } else if (CI->isNullValue()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00004500 // Replace ((add A, B) != 0) with (A != -B) if A or B is
4501 // efficiently invertible, or if the add has just this one use.
4502 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004503
Chris Lattnerc992add2003-08-13 05:33:12 +00004504 if (Value *NegVal = dyn_castNegVal(BOp1))
4505 return new SetCondInst(I.getOpcode(), BOp0, NegVal);
4506 else if (Value *NegVal = dyn_castNegVal(BOp0))
4507 return new SetCondInst(I.getOpcode(), NegVal, BOp1);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00004508 else if (BO->hasOneUse()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00004509 Instruction *Neg = BinaryOperator::createNeg(BOp1, BO->getName());
4510 BO->setName("");
4511 InsertNewInstBefore(Neg, I);
4512 return new SetCondInst(I.getOpcode(), BOp0, Neg);
4513 }
4514 }
4515 break;
4516 case Instruction::Xor:
4517 // For the xor case, we can xor two constants together, eliminating
4518 // the explicit xor.
4519 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
4520 return BinaryOperator::create(I.getOpcode(), BO->getOperand(0),
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004521 ConstantExpr::getXor(CI, BOC));
Chris Lattnerc992add2003-08-13 05:33:12 +00004522
4523 // FALLTHROUGH
4524 case Instruction::Sub:
4525 // Replace (([sub|xor] A, B) != 0) with (A != B)
4526 if (CI->isNullValue())
4527 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
4528 BO->getOperand(1));
4529 break;
4530
4531 case Instruction::Or:
4532 // If bits are being or'd in that are not present in the constant we
4533 // are comparing against, then the comparison could never succeed!
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00004534 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Chris Lattnerc8e7e292004-06-10 02:12:35 +00004535 Constant *NotCI = ConstantExpr::getNot(CI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004536 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Chris Lattnerd492a0b2003-07-23 17:02:11 +00004537 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00004538 }
Chris Lattnerc992add2003-08-13 05:33:12 +00004539 break;
4540
4541 case Instruction::And:
4542 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerd492a0b2003-07-23 17:02:11 +00004543 // If bits are being compared against that are and'd out, then the
4544 // comparison can never succeed!
Chris Lattnerc8e7e292004-06-10 02:12:35 +00004545 if (!ConstantExpr::getAnd(CI,
4546 ConstantExpr::getNot(BOC))->isNullValue())
Chris Lattnerd492a0b2003-07-23 17:02:11 +00004547 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattnerc992add2003-08-13 05:33:12 +00004548
Chris Lattner35167c32004-06-09 07:59:58 +00004549 // If we have ((X & C) == C), turn it into ((X & C) != 0).
Chris Lattneree59d4b2004-06-10 02:33:20 +00004550 if (CI == BOC && isOneBitSet(CI))
Chris Lattner35167c32004-06-09 07:59:58 +00004551 return new SetCondInst(isSetNE ? Instruction::SetEQ :
4552 Instruction::SetNE, Op0,
4553 Constant::getNullValue(CI->getType()));
Chris Lattner35167c32004-06-09 07:59:58 +00004554
Chris Lattnerc992add2003-08-13 05:33:12 +00004555 // Replace (and X, (1 << size(X)-1) != 0) with x < 0, converting X
4556 // to be a signed value as appropriate.
4557 if (isSignBit(BOC)) {
4558 Value *X = BO->getOperand(0);
4559 // If 'X' is not signed, insert a cast now...
4560 if (!BOC->getType()->isSigned()) {
Chris Lattner97bfcea2004-06-17 18:16:02 +00004561 const Type *DestTy = BOC->getType()->getSignedVersion();
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004562 X = InsertCastBefore(X, DestTy, I);
Chris Lattnerc992add2003-08-13 05:33:12 +00004563 }
4564 return new SetCondInst(isSetNE ? Instruction::SetLT :
4565 Instruction::SetGE, X,
4566 Constant::getNullValue(X->getType()));
4567 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004568
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004569 // ((X & ~7) == 0) --> X < 8
Chris Lattner8fc5af42004-09-23 21:46:38 +00004570 if (CI->isNullValue() && isHighOnes(BOC)) {
4571 Value *X = BO->getOperand(0);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004572 Constant *NegX = ConstantExpr::getNeg(BOC);
Chris Lattner8fc5af42004-09-23 21:46:38 +00004573
4574 // If 'X' is signed, insert a cast now.
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004575 if (NegX->getType()->isSigned()) {
4576 const Type *DestTy = NegX->getType()->getUnsignedVersion();
4577 X = InsertCastBefore(X, DestTy, I);
4578 NegX = ConstantExpr::getCast(NegX, DestTy);
Chris Lattner8fc5af42004-09-23 21:46:38 +00004579 }
4580
4581 return new SetCondInst(isSetNE ? Instruction::SetGE :
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004582 Instruction::SetLT, X, NegX);
Chris Lattner8fc5af42004-09-23 21:46:38 +00004583 }
4584
Chris Lattnerd492a0b2003-07-23 17:02:11 +00004585 }
Chris Lattnerc992add2003-08-13 05:33:12 +00004586 default: break;
4587 }
4588 }
Chris Lattner2b55ea32004-02-23 07:16:20 +00004589 } else { // Not a SetEQ/SetNE
Misha Brukmanb1c93172005-04-21 23:48:37 +00004590 // If the LHS is a cast from an integral value of the same size,
Chris Lattner2b55ea32004-02-23 07:16:20 +00004591 if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
4592 Value *CastOp = Cast->getOperand(0);
4593 const Type *SrcTy = CastOp->getType();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004594 unsigned SrcTySize = SrcTy->getPrimitiveSizeInBits();
Chris Lattner2b55ea32004-02-23 07:16:20 +00004595 if (SrcTy != Cast->getType() && SrcTy->isInteger() &&
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004596 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00004597 assert((SrcTy->isSigned() ^ Cast->getType()->isSigned()) &&
Chris Lattner2b55ea32004-02-23 07:16:20 +00004598 "Source and destination signednesses should differ!");
4599 if (Cast->getType()->isSigned()) {
4600 // If this is a signed comparison, check for comparisons in the
4601 // vicinity of zero.
4602 if (I.getOpcode() == Instruction::SetLT && CI->isNullValue())
4603 // X < 0 => x > 127
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004604 return BinaryOperator::createSetGT(CastOp,
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004605 ConstantUInt::get(SrcTy, (1ULL << (SrcTySize-1))-1));
Chris Lattner2b55ea32004-02-23 07:16:20 +00004606 else if (I.getOpcode() == Instruction::SetGT &&
4607 cast<ConstantSInt>(CI)->getValue() == -1)
4608 // X > -1 => x < 128
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004609 return BinaryOperator::createSetLT(CastOp,
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004610 ConstantUInt::get(SrcTy, 1ULL << (SrcTySize-1)));
Chris Lattner2b55ea32004-02-23 07:16:20 +00004611 } else {
4612 ConstantUInt *CUI = cast<ConstantUInt>(CI);
4613 if (I.getOpcode() == Instruction::SetLT &&
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004614 CUI->getValue() == 1ULL << (SrcTySize-1))
Chris Lattner2b55ea32004-02-23 07:16:20 +00004615 // X < 128 => X > -1
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004616 return BinaryOperator::createSetGT(CastOp,
4617 ConstantSInt::get(SrcTy, -1));
Chris Lattner2b55ea32004-02-23 07:16:20 +00004618 else if (I.getOpcode() == Instruction::SetGT &&
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004619 CUI->getValue() == (1ULL << (SrcTySize-1))-1)
Chris Lattner2b55ea32004-02-23 07:16:20 +00004620 // X > 127 => X < 0
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004621 return BinaryOperator::createSetLT(CastOp,
4622 Constant::getNullValue(SrcTy));
Chris Lattner2b55ea32004-02-23 07:16:20 +00004623 }
4624 }
4625 }
Chris Lattnere967b342003-06-04 05:10:11 +00004626 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004627 }
4628
Chris Lattner77c32c32005-04-23 15:31:55 +00004629 // Handle setcc with constant RHS's that can be integer, FP or pointer.
4630 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
4631 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4632 switch (LHSI->getOpcode()) {
Chris Lattnera816eee2005-05-01 04:42:15 +00004633 case Instruction::GetElementPtr:
4634 if (RHSC->isNullValue()) {
4635 // Transform setcc GEP P, int 0, int 0, int 0, null -> setcc P, null
4636 bool isAllZeros = true;
4637 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
4638 if (!isa<Constant>(LHSI->getOperand(i)) ||
4639 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
4640 isAllZeros = false;
4641 break;
4642 }
4643 if (isAllZeros)
4644 return new SetCondInst(I.getOpcode(), LHSI->getOperand(0),
4645 Constant::getNullValue(LHSI->getOperand(0)->getType()));
4646 }
4647 break;
4648
Chris Lattner77c32c32005-04-23 15:31:55 +00004649 case Instruction::PHI:
4650 if (Instruction *NV = FoldOpIntoPhi(I))
4651 return NV;
4652 break;
4653 case Instruction::Select:
4654 // If either operand of the select is a constant, we can fold the
4655 // comparison into the select arms, which will cause one to be
4656 // constant folded and the select turned into a bitwise or.
4657 Value *Op1 = 0, *Op2 = 0;
4658 if (LHSI->hasOneUse()) {
4659 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
4660 // Fold the known value into the constant operand.
4661 Op1 = ConstantExpr::get(I.getOpcode(), C, RHSC);
4662 // Insert a new SetCC of the other select operand.
4663 Op2 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
4664 LHSI->getOperand(2), RHSC,
4665 I.getName()), I);
4666 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
4667 // Fold the known value into the constant operand.
4668 Op2 = ConstantExpr::get(I.getOpcode(), C, RHSC);
4669 // Insert a new SetCC of the other select operand.
4670 Op1 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
4671 LHSI->getOperand(1), RHSC,
4672 I.getName()), I);
4673 }
4674 }
Jeff Cohen82639852005-04-23 21:38:35 +00004675
Chris Lattner77c32c32005-04-23 15:31:55 +00004676 if (Op1)
4677 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
4678 break;
4679 }
4680 }
4681
Chris Lattner0798af32005-01-13 20:14:25 +00004682 // If we can optimize a 'setcc GEP, P' or 'setcc P, GEP', do so now.
4683 if (User *GEP = dyn_castGetElementPtr(Op0))
4684 if (Instruction *NI = FoldGEPSetCC(GEP, Op1, I.getOpcode(), I))
4685 return NI;
4686 if (User *GEP = dyn_castGetElementPtr(Op1))
4687 if (Instruction *NI = FoldGEPSetCC(GEP, Op0,
4688 SetCondInst::getSwappedCondition(I.getOpcode()), I))
4689 return NI;
4690
Chris Lattner16930792003-11-03 04:25:02 +00004691 // Test to see if the operands of the setcc are casted versions of other
4692 // values. If the cast can be stripped off both arguments, we do so now.
Chris Lattner6444c372003-11-03 05:17:03 +00004693 if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
4694 Value *CastOp0 = CI->getOperand(0);
4695 if (CastOp0->getType()->isLosslesslyConvertibleTo(CI->getType()) &&
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004696 (isa<Constant>(Op1) || isa<CastInst>(Op1)) && I.isEquality()) {
Chris Lattner16930792003-11-03 04:25:02 +00004697 // We keep moving the cast from the left operand over to the right
4698 // operand, where it can often be eliminated completely.
Chris Lattner6444c372003-11-03 05:17:03 +00004699 Op0 = CastOp0;
Misha Brukmanb1c93172005-04-21 23:48:37 +00004700
Chris Lattner16930792003-11-03 04:25:02 +00004701 // If operand #1 is a cast instruction, see if we can eliminate it as
4702 // well.
Chris Lattner6444c372003-11-03 05:17:03 +00004703 if (CastInst *CI2 = dyn_cast<CastInst>(Op1))
4704 if (CI2->getOperand(0)->getType()->isLosslesslyConvertibleTo(
Chris Lattner16930792003-11-03 04:25:02 +00004705 Op0->getType()))
Chris Lattner6444c372003-11-03 05:17:03 +00004706 Op1 = CI2->getOperand(0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004707
Chris Lattner16930792003-11-03 04:25:02 +00004708 // If Op1 is a constant, we can fold the cast into the constant.
4709 if (Op1->getType() != Op0->getType())
4710 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
4711 Op1 = ConstantExpr::getCast(Op1C, Op0->getType());
4712 } else {
4713 // Otherwise, cast the RHS right before the setcc
4714 Op1 = new CastInst(Op1, Op0->getType(), Op1->getName());
4715 InsertNewInstBefore(cast<Instruction>(Op1), I);
4716 }
4717 return BinaryOperator::create(I.getOpcode(), Op0, Op1);
4718 }
4719
Chris Lattner6444c372003-11-03 05:17:03 +00004720 // Handle the special case of: setcc (cast bool to X), <cst>
4721 // This comes up when you have code like
4722 // int X = A < B;
4723 // if (X) ...
4724 // For generality, we handle any zero-extension of any operand comparison
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004725 // with a constant or another cast from the same type.
4726 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
4727 if (Instruction *R = visitSetCondInstWithCastAndCast(I))
4728 return R;
Chris Lattner6444c372003-11-03 05:17:03 +00004729 }
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00004730
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004731 if (I.isEquality()) {
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00004732 Value *A, *B;
4733 if (match(Op0, m_Xor(m_Value(A), m_Value(B))) &&
4734 (A == Op1 || B == Op1)) {
4735 // (A^B) == A -> B == 0
4736 Value *OtherVal = A == Op1 ? B : A;
4737 return BinaryOperator::create(I.getOpcode(), OtherVal,
4738 Constant::getNullValue(A->getType()));
4739 } else if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
4740 (A == Op0 || B == Op0)) {
4741 // A == (A^B) -> B == 0
4742 Value *OtherVal = A == Op0 ? B : A;
4743 return BinaryOperator::create(I.getOpcode(), OtherVal,
4744 Constant::getNullValue(A->getType()));
4745 } else if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
4746 // (A-B) == A -> B == 0
4747 return BinaryOperator::create(I.getOpcode(), B,
4748 Constant::getNullValue(B->getType()));
4749 } else if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
4750 // A == (A-B) -> B == 0
4751 return BinaryOperator::create(I.getOpcode(), B,
4752 Constant::getNullValue(B->getType()));
4753 }
4754 }
Chris Lattner113f4f42002-06-25 16:13:24 +00004755 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004756}
4757
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004758// visitSetCondInstWithCastAndCast - Handle setcond (cast x to y), (cast/cst).
4759// We only handle extending casts so far.
4760//
4761Instruction *InstCombiner::visitSetCondInstWithCastAndCast(SetCondInst &SCI) {
4762 Value *LHSCIOp = cast<CastInst>(SCI.getOperand(0))->getOperand(0);
4763 const Type *SrcTy = LHSCIOp->getType();
4764 const Type *DestTy = SCI.getOperand(0)->getType();
4765 Value *RHSCIOp;
4766
4767 if (!DestTy->isIntegral() || !SrcTy->isIntegral())
Chris Lattner03f06f12005-01-17 03:20:02 +00004768 return 0;
4769
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004770 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
4771 unsigned DestBits = DestTy->getPrimitiveSizeInBits();
4772 if (SrcBits >= DestBits) return 0; // Only handle extending cast.
4773
4774 // Is this a sign or zero extension?
4775 bool isSignSrc = SrcTy->isSigned();
4776 bool isSignDest = DestTy->isSigned();
4777
4778 if (CastInst *CI = dyn_cast<CastInst>(SCI.getOperand(1))) {
4779 // Not an extension from the same type?
4780 RHSCIOp = CI->getOperand(0);
4781 if (RHSCIOp->getType() != LHSCIOp->getType()) return 0;
4782 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(SCI.getOperand(1))) {
4783 // Compute the constant that would happen if we truncated to SrcTy then
4784 // reextended to DestTy.
4785 Constant *Res = ConstantExpr::getCast(CI, SrcTy);
4786
4787 if (ConstantExpr::getCast(Res, DestTy) == CI) {
4788 RHSCIOp = Res;
4789 } else {
4790 // If the value cannot be represented in the shorter type, we cannot emit
4791 // a simple comparison.
4792 if (SCI.getOpcode() == Instruction::SetEQ)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004793 return ReplaceInstUsesWith(SCI, ConstantBool::getFalse());
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004794 if (SCI.getOpcode() == Instruction::SetNE)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004795 return ReplaceInstUsesWith(SCI, ConstantBool::getTrue());
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004796
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004797 // Evaluate the comparison for LT.
4798 Value *Result;
4799 if (DestTy->isSigned()) {
4800 // We're performing a signed comparison.
4801 if (isSignSrc) {
4802 // Signed extend and signed comparison.
4803 if (cast<ConstantSInt>(CI)->getValue() < 0) // X < (small) --> false
Chris Lattner6ab03f62006-09-28 23:35:22 +00004804 Result = ConstantBool::getFalse();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004805 else
Chris Lattner6ab03f62006-09-28 23:35:22 +00004806 Result = ConstantBool::getTrue(); // X < (large) --> true
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004807 } else {
4808 // Unsigned extend and signed comparison.
4809 if (cast<ConstantSInt>(CI)->getValue() < 0)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004810 Result = ConstantBool::getFalse();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004811 else
Chris Lattner6ab03f62006-09-28 23:35:22 +00004812 Result = ConstantBool::getTrue();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004813 }
4814 } else {
4815 // We're performing an unsigned comparison.
4816 if (!isSignSrc) {
4817 // Unsigned extend & compare -> always true.
Chris Lattner6ab03f62006-09-28 23:35:22 +00004818 Result = ConstantBool::getTrue();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004819 } else {
4820 // We're performing an unsigned comp with a sign extended value.
4821 // This is true if the input is >= 0. [aka >s -1]
4822 Constant *NegOne = ConstantIntegral::getAllOnesValue(SrcTy);
4823 Result = InsertNewInstBefore(BinaryOperator::createSetGT(LHSCIOp,
4824 NegOne, SCI.getName()), SCI);
4825 }
Reid Spencer279fa252004-11-28 21:31:15 +00004826 }
Chris Lattner03f06f12005-01-17 03:20:02 +00004827
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00004828 // Finally, return the value computed.
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004829 if (SCI.getOpcode() == Instruction::SetLT) {
4830 return ReplaceInstUsesWith(SCI, Result);
4831 } else {
4832 assert(SCI.getOpcode()==Instruction::SetGT &&"SetCC should be folded!");
4833 if (Constant *CI = dyn_cast<Constant>(Result))
4834 return ReplaceInstUsesWith(SCI, ConstantExpr::getNot(CI));
4835 else
4836 return BinaryOperator::createNot(Result);
4837 }
Chris Lattner03f06f12005-01-17 03:20:02 +00004838 }
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004839 } else {
4840 return 0;
Reid Spencer279fa252004-11-28 21:31:15 +00004841 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004842
Chris Lattner252a8452005-06-16 03:00:08 +00004843 // Okay, just insert a compare of the reduced operands now!
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004844 return BinaryOperator::create(SCI.getOpcode(), LHSCIOp, RHSCIOp);
4845}
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004846
Chris Lattnere8d6c602003-03-10 19:16:08 +00004847Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +00004848 assert(I.getOperand(1)->getType() == Type::UByteTy);
4849 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00004850 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004851
4852 // shl X, 0 == X and shr X, 0 == X
4853 // shl 0, X == 0 and shr 0, X == 0
4854 if (Op1 == Constant::getNullValue(Type::UByteTy) ||
Chris Lattnere6794492002-08-12 21:17:25 +00004855 Op0 == Constant::getNullValue(Op0->getType()))
4856 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf5b4ef72006-02-12 08:07:37 +00004857
Chris Lattner81a7a232004-10-16 18:11:37 +00004858 if (isa<UndefValue>(Op0)) { // undef >>s X -> undef
4859 if (!isLeftShift && I.getType()->isSigned())
Chris Lattner67f05452004-10-16 23:28:04 +00004860 return ReplaceInstUsesWith(I, Op0);
Chris Lattner81a7a232004-10-16 18:11:37 +00004861 else // undef << X -> 0 AND undef >>u X -> 0
4862 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4863 }
4864 if (isa<UndefValue>(Op1)) {
Chris Lattner18aa4d82005-07-20 18:49:28 +00004865 if (isLeftShift || I.getType()->isUnsigned())// X << undef, X >>u undef -> 0
Chris Lattner81a7a232004-10-16 18:11:37 +00004866 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4867 else
4868 return ReplaceInstUsesWith(I, Op0); // X >>s undef -> X
4869 }
4870
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00004871 // shr int -1, X = -1 (for any arithmetic shift rights of ~0)
4872 if (!isLeftShift)
4873 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
4874 if (CSI->isAllOnesValue())
4875 return ReplaceInstUsesWith(I, CSI);
4876
Chris Lattner183b3362004-04-09 19:05:30 +00004877 // Try to fold constant and into select arguments.
4878 if (isa<Constant>(Op0))
4879 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner86102b82005-01-01 16:22:27 +00004880 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00004881 return R;
4882
Chris Lattnerb18dbbf2005-05-08 17:34:56 +00004883 // See if we can turn a signed shr into an unsigned shr.
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004884 if (I.isArithmeticShift()) {
Chris Lattnerc3ebf402006-02-07 07:27:52 +00004885 if (MaskedValueIsZero(Op0,
4886 1ULL << (I.getType()->getPrimitiveSizeInBits()-1))) {
Chris Lattnerb18dbbf2005-05-08 17:34:56 +00004887 Value *V = InsertCastBefore(Op0, I.getType()->getUnsignedVersion(), I);
4888 V = InsertNewInstBefore(new ShiftInst(Instruction::Shr, V, Op1,
4889 I.getName()), I);
4890 return new CastInst(V, I.getType());
4891 }
4892 }
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00004893
Chris Lattner14553932006-01-06 07:12:35 +00004894 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op1))
4895 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
4896 return Res;
4897 return 0;
4898}
4899
4900Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantUInt *Op1,
4901 ShiftInst &I) {
4902 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattnerb3309392006-01-06 07:22:22 +00004903 bool isSignedShift = Op0->getType()->isSigned();
4904 bool isUnsignedShift = !isSignedShift;
Chris Lattner14553932006-01-06 07:12:35 +00004905
Chris Lattnerf5b4ef72006-02-12 08:07:37 +00004906 // See if we can simplify any instructions used by the instruction whose sole
4907 // purpose is to compute bits we don't care about.
4908 uint64_t KnownZero, KnownOne;
4909 if (SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
4910 KnownZero, KnownOne))
4911 return &I;
4912
Chris Lattner14553932006-01-06 07:12:35 +00004913 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
4914 // of a signed value.
4915 //
4916 unsigned TypeBits = Op0->getType()->getPrimitiveSizeInBits();
4917 if (Op1->getValue() >= TypeBits) {
Chris Lattnerb3309392006-01-06 07:22:22 +00004918 if (isUnsignedShift || isLeftShift)
Chris Lattner14553932006-01-06 07:12:35 +00004919 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
4920 else {
4921 I.setOperand(1, ConstantUInt::get(Type::UByteTy, TypeBits-1));
4922 return &I;
Chris Lattnerf5ce2542004-02-23 20:30:06 +00004923 }
Chris Lattner14553932006-01-06 07:12:35 +00004924 }
4925
4926 // ((X*C1) << C2) == (X * (C1 << C2))
4927 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
4928 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
4929 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
4930 return BinaryOperator::createMul(BO->getOperand(0),
4931 ConstantExpr::getShl(BOOp, Op1));
4932
4933 // Try to fold constant and into select arguments.
4934 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4935 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4936 return R;
4937 if (isa<PHINode>(Op0))
4938 if (Instruction *NV = FoldOpIntoPhi(I))
4939 return NV;
4940
4941 if (Op0->hasOneUse()) {
Chris Lattner14553932006-01-06 07:12:35 +00004942 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
4943 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
4944 Value *V1, *V2;
4945 ConstantInt *CC;
4946 switch (Op0BO->getOpcode()) {
Chris Lattner27cb9db2005-09-18 05:12:10 +00004947 default: break;
4948 case Instruction::Add:
4949 case Instruction::And:
4950 case Instruction::Or:
4951 case Instruction::Xor:
4952 // These operators commute.
4953 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner797dee72005-09-18 06:30:59 +00004954 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
4955 match(Op0BO->getOperand(1),
Chris Lattner14553932006-01-06 07:12:35 +00004956 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Chris Lattner797dee72005-09-18 06:30:59 +00004957 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00004958 Op0BO->getOperand(0), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00004959 Op0BO->getName());
4960 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner24cd2fa2006-02-09 07:41:14 +00004961 Instruction *X =
4962 BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
4963 Op0BO->getOperand(1)->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00004964 InsertNewInstBefore(X, I); // (X + (Y << C))
4965 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
Chris Lattner14553932006-01-06 07:12:35 +00004966 C2 = ConstantExpr::getShl(C2, Op1);
Chris Lattner797dee72005-09-18 06:30:59 +00004967 return BinaryOperator::createAnd(X, C2);
4968 }
Chris Lattner14553932006-01-06 07:12:35 +00004969
Chris Lattner797dee72005-09-18 06:30:59 +00004970 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
4971 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
4972 match(Op0BO->getOperand(1),
4973 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner14553932006-01-06 07:12:35 +00004974 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner24cd2fa2006-02-09 07:41:14 +00004975 cast<BinaryOperator>(Op0BO->getOperand(1))->getOperand(0)->hasOneUse()) {
Chris Lattner797dee72005-09-18 06:30:59 +00004976 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00004977 Op0BO->getOperand(0), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00004978 Op0BO->getName());
4979 InsertNewInstBefore(YS, I); // (Y << C)
4980 Instruction *XM =
Chris Lattner14553932006-01-06 07:12:35 +00004981 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner797dee72005-09-18 06:30:59 +00004982 V1->getName()+".mask");
4983 InsertNewInstBefore(XM, I); // X & (CC << C)
4984
4985 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
4986 }
Chris Lattner14553932006-01-06 07:12:35 +00004987
Chris Lattner797dee72005-09-18 06:30:59 +00004988 // FALL THROUGH.
Chris Lattner27cb9db2005-09-18 05:12:10 +00004989 case Instruction::Sub:
4990 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner797dee72005-09-18 06:30:59 +00004991 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
4992 match(Op0BO->getOperand(0),
Chris Lattner14553932006-01-06 07:12:35 +00004993 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Chris Lattner797dee72005-09-18 06:30:59 +00004994 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00004995 Op0BO->getOperand(1), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00004996 Op0BO->getName());
4997 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner24cd2fa2006-02-09 07:41:14 +00004998 Instruction *X =
Chris Lattner1df0e982006-05-31 21:14:00 +00004999 BinaryOperator::create(Op0BO->getOpcode(), V1, YS,
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005000 Op0BO->getOperand(0)->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00005001 InsertNewInstBefore(X, I); // (X + (Y << C))
5002 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
Chris Lattner14553932006-01-06 07:12:35 +00005003 C2 = ConstantExpr::getShl(C2, Op1);
Chris Lattner797dee72005-09-18 06:30:59 +00005004 return BinaryOperator::createAnd(X, C2);
5005 }
Chris Lattner14553932006-01-06 07:12:35 +00005006
Chris Lattner1df0e982006-05-31 21:14:00 +00005007 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner797dee72005-09-18 06:30:59 +00005008 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
5009 match(Op0BO->getOperand(0),
5010 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner14553932006-01-06 07:12:35 +00005011 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner24cd2fa2006-02-09 07:41:14 +00005012 cast<BinaryOperator>(Op0BO->getOperand(0))
5013 ->getOperand(0)->hasOneUse()) {
Chris Lattner797dee72005-09-18 06:30:59 +00005014 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00005015 Op0BO->getOperand(1), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00005016 Op0BO->getName());
5017 InsertNewInstBefore(YS, I); // (Y << C)
5018 Instruction *XM =
Chris Lattner14553932006-01-06 07:12:35 +00005019 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner797dee72005-09-18 06:30:59 +00005020 V1->getName()+".mask");
5021 InsertNewInstBefore(XM, I); // X & (CC << C)
5022
Chris Lattner1df0e982006-05-31 21:14:00 +00005023 return BinaryOperator::create(Op0BO->getOpcode(), XM, YS);
Chris Lattner797dee72005-09-18 06:30:59 +00005024 }
Chris Lattner14553932006-01-06 07:12:35 +00005025
Chris Lattner27cb9db2005-09-18 05:12:10 +00005026 break;
Chris Lattner14553932006-01-06 07:12:35 +00005027 }
5028
5029
5030 // If the operand is an bitwise operator with a constant RHS, and the
5031 // shift is the only use, we can pull it out of the shift.
5032 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
5033 bool isValid = true; // Valid only for And, Or, Xor
5034 bool highBitSet = false; // Transform if high bit of constant set?
5035
5036 switch (Op0BO->getOpcode()) {
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00005037 default: isValid = false; break; // Do not perform transform!
Chris Lattner44bd3922004-10-08 03:46:20 +00005038 case Instruction::Add:
5039 isValid = isLeftShift;
5040 break;
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00005041 case Instruction::Or:
5042 case Instruction::Xor:
5043 highBitSet = false;
5044 break;
5045 case Instruction::And:
5046 highBitSet = true;
5047 break;
Chris Lattner14553932006-01-06 07:12:35 +00005048 }
5049
5050 // If this is a signed shift right, and the high bit is modified
5051 // by the logical operation, do not perform the transformation.
5052 // The highBitSet boolean indicates the value of the high bit of
5053 // the constant which would cause it to be modified for this
5054 // operation.
5055 //
Chris Lattnerb3309392006-01-06 07:22:22 +00005056 if (isValid && !isLeftShift && isSignedShift) {
Chris Lattner14553932006-01-06 07:12:35 +00005057 uint64_t Val = Op0C->getRawValue();
5058 isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
5059 }
5060
5061 if (isValid) {
5062 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
5063
5064 Instruction *NewShift =
5065 new ShiftInst(I.getOpcode(), Op0BO->getOperand(0), Op1,
5066 Op0BO->getName());
5067 Op0BO->setName("");
5068 InsertNewInstBefore(NewShift, I);
5069
5070 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
5071 NewRHS);
5072 }
5073 }
5074 }
5075 }
5076
Chris Lattnereb372a02006-01-06 07:52:12 +00005077 // Find out if this is a shift of a shift by a constant.
5078 ShiftInst *ShiftOp = 0;
Chris Lattner14553932006-01-06 07:12:35 +00005079 if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0))
Chris Lattnereb372a02006-01-06 07:52:12 +00005080 ShiftOp = Op0SI;
5081 else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
5082 // If this is a noop-integer case of a shift instruction, use the shift.
5083 if (CI->getOperand(0)->getType()->isInteger() &&
5084 CI->getOperand(0)->getType()->getPrimitiveSizeInBits() ==
5085 CI->getType()->getPrimitiveSizeInBits() &&
5086 isa<ShiftInst>(CI->getOperand(0))) {
5087 ShiftOp = cast<ShiftInst>(CI->getOperand(0));
5088 }
5089 }
5090
5091 if (ShiftOp && isa<ConstantUInt>(ShiftOp->getOperand(1))) {
5092 // Find the operands and properties of the input shift. Note that the
5093 // signedness of the input shift may differ from the current shift if there
5094 // is a noop cast between the two.
5095 bool isShiftOfLeftShift = ShiftOp->getOpcode() == Instruction::Shl;
5096 bool isShiftOfSignedShift = ShiftOp->getType()->isSigned();
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005097 bool isShiftOfUnsignedShift = !isShiftOfSignedShift;
Chris Lattnereb372a02006-01-06 07:52:12 +00005098
5099 ConstantUInt *ShiftAmt1C = cast<ConstantUInt>(ShiftOp->getOperand(1));
5100
5101 unsigned ShiftAmt1 = (unsigned)ShiftAmt1C->getValue();
5102 unsigned ShiftAmt2 = (unsigned)Op1->getValue();
5103
5104 // Check for (A << c1) << c2 and (A >> c1) >> c2.
5105 if (isLeftShift == isShiftOfLeftShift) {
5106 // Do not fold these shifts if the first one is signed and the second one
5107 // is unsigned and this is a right shift. Further, don't do any folding
5108 // on them.
5109 if (isShiftOfSignedShift && isUnsignedShift && !isLeftShift)
5110 return 0;
Chris Lattner14553932006-01-06 07:12:35 +00005111
Chris Lattnereb372a02006-01-06 07:52:12 +00005112 unsigned Amt = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
5113 if (Amt > Op0->getType()->getPrimitiveSizeInBits())
5114 Amt = Op0->getType()->getPrimitiveSizeInBits();
Chris Lattner14553932006-01-06 07:12:35 +00005115
Chris Lattnereb372a02006-01-06 07:52:12 +00005116 Value *Op = ShiftOp->getOperand(0);
5117 if (isShiftOfSignedShift != isSignedShift)
5118 Op = InsertNewInstBefore(new CastInst(Op, I.getType(), "tmp"), I);
5119 return new ShiftInst(I.getOpcode(), Op,
5120 ConstantUInt::get(Type::UByteTy, Amt));
5121 }
5122
5123 // Check for (A << c1) >> c2 or (A >> c1) << c2. If we are dealing with
5124 // signed types, we can only support the (A >> c1) << c2 configuration,
5125 // because it can not turn an arbitrary bit of A into a sign bit.
5126 if (isUnsignedShift || isLeftShift) {
5127 // Calculate bitmask for what gets shifted off the edge.
5128 Constant *C = ConstantIntegral::getAllOnesValue(I.getType());
5129 if (isLeftShift)
5130 C = ConstantExpr::getShl(C, ShiftAmt1C);
5131 else
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005132 C = ConstantExpr::getUShr(C, ShiftAmt1C);
Chris Lattnereb372a02006-01-06 07:52:12 +00005133
5134 Value *Op = ShiftOp->getOperand(0);
5135 if (isShiftOfSignedShift != isSignedShift)
5136 Op = InsertNewInstBefore(new CastInst(Op, I.getType(),Op->getName()),I);
5137
5138 Instruction *Mask =
5139 BinaryOperator::createAnd(Op, C, Op->getName()+".mask");
5140 InsertNewInstBefore(Mask, I);
5141
5142 // Figure out what flavor of shift we should use...
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005143 if (ShiftAmt1 == ShiftAmt2) {
Chris Lattnereb372a02006-01-06 07:52:12 +00005144 return ReplaceInstUsesWith(I, Mask); // (A << c) >> c === A & c2
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005145 } else if (ShiftAmt1 < ShiftAmt2) {
Chris Lattnereb372a02006-01-06 07:52:12 +00005146 return new ShiftInst(I.getOpcode(), Mask,
5147 ConstantUInt::get(Type::UByteTy, ShiftAmt2-ShiftAmt1));
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005148 } else if (isShiftOfUnsignedShift || isShiftOfLeftShift) {
5149 if (isShiftOfUnsignedShift && !isShiftOfLeftShift && isSignedShift) {
5150 // Make sure to emit an unsigned shift right, not a signed one.
5151 Mask = InsertNewInstBefore(new CastInst(Mask,
5152 Mask->getType()->getUnsignedVersion(),
5153 Op->getName()), I);
5154 Mask = new ShiftInst(Instruction::Shr, Mask,
Chris Lattnereb372a02006-01-06 07:52:12 +00005155 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005156 InsertNewInstBefore(Mask, I);
5157 return new CastInst(Mask, I.getType());
5158 } else {
5159 return new ShiftInst(ShiftOp->getOpcode(), Mask,
5160 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
5161 }
5162 } else {
5163 // (X >>s C1) << C2 where C1 > C2 === (X >>s (C1-C2)) & mask
5164 Op = InsertNewInstBefore(new CastInst(Mask,
5165 I.getType()->getSignedVersion(),
5166 Mask->getName()), I);
5167 Instruction *Shift =
5168 new ShiftInst(ShiftOp->getOpcode(), Op,
5169 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
5170 InsertNewInstBefore(Shift, I);
5171
5172 C = ConstantIntegral::getAllOnesValue(Shift->getType());
5173 C = ConstantExpr::getShl(C, Op1);
5174 Mask = BinaryOperator::createAnd(Shift, C, Op->getName()+".mask");
5175 InsertNewInstBefore(Mask, I);
5176 return new CastInst(Mask, I.getType());
Chris Lattnereb372a02006-01-06 07:52:12 +00005177 }
5178 } else {
Chris Lattner9cbfbc22006-01-07 01:32:28 +00005179 // We can handle signed (X << C1) >>s C2 if it's a sign extend. In
Chris Lattnereb372a02006-01-06 07:52:12 +00005180 // this case, C1 == C2 and C1 is 8, 16, or 32.
5181 if (ShiftAmt1 == ShiftAmt2) {
5182 const Type *SExtType = 0;
Chris Lattner655d08f2006-04-28 22:21:41 +00005183 switch (Op0->getType()->getPrimitiveSizeInBits() - ShiftAmt1) {
Chris Lattnereb372a02006-01-06 07:52:12 +00005184 case 8 : SExtType = Type::SByteTy; break;
5185 case 16: SExtType = Type::ShortTy; break;
5186 case 32: SExtType = Type::IntTy; break;
5187 }
5188
5189 if (SExtType) {
5190 Instruction *NewTrunc = new CastInst(ShiftOp->getOperand(0),
5191 SExtType, "sext");
5192 InsertNewInstBefore(NewTrunc, I);
5193 return new CastInst(NewTrunc, I.getType());
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00005194 }
Chris Lattner27cb9db2005-09-18 05:12:10 +00005195 }
Chris Lattner86102b82005-01-01 16:22:27 +00005196 }
Chris Lattnereb372a02006-01-06 07:52:12 +00005197 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00005198 return 0;
5199}
5200
Chris Lattner48a44f72002-05-02 17:06:02 +00005201
Chris Lattner8f663e82005-10-29 04:36:15 +00005202/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
5203/// expression. If so, decompose it, returning some value X, such that Val is
5204/// X*Scale+Offset.
5205///
5206static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
5207 unsigned &Offset) {
5208 assert(Val->getType() == Type::UIntTy && "Unexpected allocation size type!");
5209 if (ConstantUInt *CI = dyn_cast<ConstantUInt>(Val)) {
5210 Offset = CI->getValue();
5211 Scale = 1;
5212 return ConstantUInt::get(Type::UIntTy, 0);
5213 } else if (Instruction *I = dyn_cast<Instruction>(Val)) {
5214 if (I->getNumOperands() == 2) {
5215 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(I->getOperand(1))) {
5216 if (I->getOpcode() == Instruction::Shl) {
5217 // This is a value scaled by '1 << the shift amt'.
5218 Scale = 1U << CUI->getValue();
5219 Offset = 0;
5220 return I->getOperand(0);
5221 } else if (I->getOpcode() == Instruction::Mul) {
5222 // This value is scaled by 'CUI'.
5223 Scale = CUI->getValue();
5224 Offset = 0;
5225 return I->getOperand(0);
5226 } else if (I->getOpcode() == Instruction::Add) {
5227 // We have X+C. Check to see if we really have (X*C2)+C1, where C1 is
5228 // divisible by C2.
5229 unsigned SubScale;
5230 Value *SubVal = DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
5231 Offset);
5232 Offset += CUI->getValue();
5233 if (SubScale > 1 && (Offset % SubScale == 0)) {
5234 Scale = SubScale;
5235 return SubVal;
5236 }
5237 }
5238 }
5239 }
5240 }
5241
5242 // Otherwise, we can't look past this.
5243 Scale = 1;
5244 Offset = 0;
5245 return Val;
5246}
5247
5248
Chris Lattner216be912005-10-24 06:03:58 +00005249/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
5250/// try to eliminate the cast by moving the type information into the alloc.
5251Instruction *InstCombiner::PromoteCastOfAllocation(CastInst &CI,
5252 AllocationInst &AI) {
5253 const PointerType *PTy = dyn_cast<PointerType>(CI.getType());
Chris Lattnerbb171802005-10-27 05:53:56 +00005254 if (!PTy) return 0; // Not casting the allocation to a pointer type.
Chris Lattner216be912005-10-24 06:03:58 +00005255
Chris Lattnerac87beb2005-10-24 06:22:12 +00005256 // Remove any uses of AI that are dead.
5257 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
5258 std::vector<Instruction*> DeadUsers;
5259 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
5260 Instruction *User = cast<Instruction>(*UI++);
5261 if (isInstructionTriviallyDead(User)) {
5262 while (UI != E && *UI == User)
5263 ++UI; // If this instruction uses AI more than once, don't break UI.
5264
5265 // Add operands to the worklist.
5266 AddUsesToWorkList(*User);
5267 ++NumDeadInst;
5268 DEBUG(std::cerr << "IC: DCE: " << *User);
5269
5270 User->eraseFromParent();
5271 removeFromWorkList(User);
5272 }
5273 }
5274
Chris Lattner216be912005-10-24 06:03:58 +00005275 // Get the type really allocated and the type casted to.
5276 const Type *AllocElTy = AI.getAllocatedType();
5277 const Type *CastElTy = PTy->getElementType();
5278 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner355ecc02005-10-24 06:26:18 +00005279
Chris Lattner7d190672006-10-01 19:40:58 +00005280 unsigned AllocElTyAlign = TD->getTypeAlignment(AllocElTy);
5281 unsigned CastElTyAlign = TD->getTypeAlignment(CastElTy);
Chris Lattner355ecc02005-10-24 06:26:18 +00005282 if (CastElTyAlign < AllocElTyAlign) return 0;
5283
Chris Lattner46705b22005-10-24 06:35:18 +00005284 // If the allocation has multiple uses, only promote it if we are strictly
5285 // increasing the alignment of the resultant allocation. If we keep it the
5286 // same, we open the door to infinite loops of various kinds.
5287 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
5288
Chris Lattner216be912005-10-24 06:03:58 +00005289 uint64_t AllocElTySize = TD->getTypeSize(AllocElTy);
5290 uint64_t CastElTySize = TD->getTypeSize(CastElTy);
Chris Lattnerbb171802005-10-27 05:53:56 +00005291 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner355ecc02005-10-24 06:26:18 +00005292
Chris Lattner8270c332005-10-29 03:19:53 +00005293 // See if we can satisfy the modulus by pulling a scale out of the array
5294 // size argument.
Chris Lattner8f663e82005-10-29 04:36:15 +00005295 unsigned ArraySizeScale, ArrayOffset;
5296 Value *NumElements = // See if the array size is a decomposable linear expr.
5297 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
5298
Chris Lattner8270c332005-10-29 03:19:53 +00005299 // If we can now satisfy the modulus, by using a non-1 scale, we really can
5300 // do the xform.
Chris Lattner8f663e82005-10-29 04:36:15 +00005301 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
5302 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattnerb3ecf962005-10-27 06:12:00 +00005303
Chris Lattner8270c332005-10-29 03:19:53 +00005304 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
5305 Value *Amt = 0;
5306 if (Scale == 1) {
5307 Amt = NumElements;
5308 } else {
5309 Amt = ConstantUInt::get(Type::UIntTy, Scale);
5310 if (ConstantUInt *CI = dyn_cast<ConstantUInt>(NumElements))
5311 Amt = ConstantExpr::getMul(CI, cast<ConstantUInt>(Amt));
5312 else if (Scale != 1) {
5313 Instruction *Tmp = BinaryOperator::createMul(Amt, NumElements, "tmp");
5314 Amt = InsertNewInstBefore(Tmp, AI);
Chris Lattnerb3ecf962005-10-27 06:12:00 +00005315 }
Chris Lattnerbb171802005-10-27 05:53:56 +00005316 }
5317
Chris Lattner8f663e82005-10-29 04:36:15 +00005318 if (unsigned Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
5319 Value *Off = ConstantUInt::get(Type::UIntTy, Offset);
5320 Instruction *Tmp = BinaryOperator::createAdd(Amt, Off, "tmp");
5321 Amt = InsertNewInstBefore(Tmp, AI);
5322 }
5323
Chris Lattner216be912005-10-24 06:03:58 +00005324 std::string Name = AI.getName(); AI.setName("");
5325 AllocationInst *New;
5326 if (isa<MallocInst>(AI))
Nate Begeman848622f2005-11-05 09:21:28 +00005327 New = new MallocInst(CastElTy, Amt, AI.getAlignment(), Name);
Chris Lattner216be912005-10-24 06:03:58 +00005328 else
Nate Begeman848622f2005-11-05 09:21:28 +00005329 New = new AllocaInst(CastElTy, Amt, AI.getAlignment(), Name);
Chris Lattner216be912005-10-24 06:03:58 +00005330 InsertNewInstBefore(New, AI);
Chris Lattner46705b22005-10-24 06:35:18 +00005331
5332 // If the allocation has multiple uses, insert a cast and change all things
5333 // that used it to use the new cast. This will also hack on CI, but it will
5334 // die soon.
5335 if (!AI.hasOneUse()) {
5336 AddUsesToWorkList(AI);
5337 CastInst *NewCast = new CastInst(New, AI.getType(), "tmpcast");
5338 InsertNewInstBefore(NewCast, AI);
5339 AI.replaceAllUsesWith(NewCast);
5340 }
Chris Lattner216be912005-10-24 06:03:58 +00005341 return ReplaceInstUsesWith(CI, New);
5342}
5343
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005344/// CanEvaluateInDifferentType - Return true if we can take the specified value
5345/// and return it without inserting any new casts. This is used by code that
5346/// tries to decide whether promoting or shrinking integer operations to wider
5347/// or smaller types will allow us to eliminate a truncate or extend.
5348static bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
5349 int &NumCastsRemoved) {
5350 if (isa<Constant>(V)) return true;
5351
5352 Instruction *I = dyn_cast<Instruction>(V);
5353 if (!I || !I->hasOneUse()) return false;
5354
5355 switch (I->getOpcode()) {
5356 case Instruction::And:
5357 case Instruction::Or:
5358 case Instruction::Xor:
5359 // These operators can all arbitrarily be extended or truncated.
5360 return CanEvaluateInDifferentType(I->getOperand(0), Ty, NumCastsRemoved) &&
5361 CanEvaluateInDifferentType(I->getOperand(1), Ty, NumCastsRemoved);
5362 case Instruction::Cast:
5363 // If this is a cast from the destination type, we can trivially eliminate
5364 // it, and this will remove a cast overall.
5365 if (I->getOperand(0)->getType() == Ty) {
Chris Lattner3fda3862006-06-28 17:34:50 +00005366 // If the first operand is itself a cast, and is eliminable, do not count
5367 // this as an eliminable cast. We would prefer to eliminate those two
5368 // casts first.
5369 if (CastInst *OpCast = dyn_cast<CastInst>(I->getOperand(0)))
5370 return true;
5371
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005372 ++NumCastsRemoved;
5373 return true;
5374 }
5375 // TODO: Can handle more cases here.
5376 break;
5377 }
5378
5379 return false;
5380}
5381
5382/// EvaluateInDifferentType - Given an expression that
5383/// CanEvaluateInDifferentType returns true for, actually insert the code to
5384/// evaluate the expression.
5385Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty) {
5386 if (Constant *C = dyn_cast<Constant>(V))
5387 return ConstantExpr::getCast(C, Ty);
5388
5389 // Otherwise, it must be an instruction.
5390 Instruction *I = cast<Instruction>(V);
Chris Lattnerd0622b62006-05-20 23:14:03 +00005391 Instruction *Res = 0;
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005392 switch (I->getOpcode()) {
5393 case Instruction::And:
5394 case Instruction::Or:
5395 case Instruction::Xor: {
5396 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty);
5397 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty);
5398 Res = BinaryOperator::create((Instruction::BinaryOps)I->getOpcode(),
5399 LHS, RHS, I->getName());
5400 break;
5401 }
5402 case Instruction::Cast:
5403 // If this is a cast from the destination type, return the input.
5404 if (I->getOperand(0)->getType() == Ty)
5405 return I->getOperand(0);
5406
5407 // TODO: Can handle more cases here.
5408 assert(0 && "Unreachable!");
5409 break;
5410 }
5411
5412 return InsertNewInstBefore(Res, *I);
5413}
5414
Chris Lattner216be912005-10-24 06:03:58 +00005415
Chris Lattner48a44f72002-05-02 17:06:02 +00005416// CastInst simplification
Chris Lattner260ab202002-04-18 17:39:14 +00005417//
Chris Lattner113f4f42002-06-25 16:13:24 +00005418Instruction *InstCombiner::visitCastInst(CastInst &CI) {
Chris Lattner55d4bda2003-06-23 21:59:52 +00005419 Value *Src = CI.getOperand(0);
5420
Chris Lattner48a44f72002-05-02 17:06:02 +00005421 // If the user is casting a value to the same type, eliminate this cast
5422 // instruction...
Chris Lattner55d4bda2003-06-23 21:59:52 +00005423 if (CI.getType() == Src->getType())
5424 return ReplaceInstUsesWith(CI, Src);
Chris Lattner48a44f72002-05-02 17:06:02 +00005425
Chris Lattner81a7a232004-10-16 18:11:37 +00005426 if (isa<UndefValue>(Src)) // cast undef -> undef
5427 return ReplaceInstUsesWith(CI, UndefValue::get(CI.getType()));
5428
Chris Lattner48a44f72002-05-02 17:06:02 +00005429 // If casting the result of another cast instruction, try to eliminate this
5430 // one!
5431 //
Chris Lattner86102b82005-01-01 16:22:27 +00005432 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
5433 Value *A = CSrc->getOperand(0);
5434 if (isEliminableCastOfCast(A->getType(), CSrc->getType(),
5435 CI.getType(), TD)) {
Chris Lattner48a44f72002-05-02 17:06:02 +00005436 // This instruction now refers directly to the cast's src operand. This
5437 // has a good chance of making CSrc dead.
Chris Lattner113f4f42002-06-25 16:13:24 +00005438 CI.setOperand(0, CSrc->getOperand(0));
5439 return &CI;
Chris Lattner48a44f72002-05-02 17:06:02 +00005440 }
5441
Chris Lattner650b6da2002-08-02 20:00:25 +00005442 // If this is an A->B->A cast, and we are dealing with integral types, try
5443 // to convert this into a logical 'and' instruction.
5444 //
Misha Brukmanb1c93172005-04-21 23:48:37 +00005445 if (A->getType()->isInteger() &&
Chris Lattnerb0b412e2002-09-03 01:08:28 +00005446 CI.getType()->isInteger() && CSrc->getType()->isInteger() &&
Chris Lattner86102b82005-01-01 16:22:27 +00005447 CSrc->getType()->isUnsigned() && // B->A cast must zero extend
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005448 CSrc->getType()->getPrimitiveSizeInBits() <
5449 CI.getType()->getPrimitiveSizeInBits()&&
5450 A->getType()->getPrimitiveSizeInBits() ==
5451 CI.getType()->getPrimitiveSizeInBits()) {
Chris Lattner650b6da2002-08-02 20:00:25 +00005452 assert(CSrc->getType() != Type::ULongTy &&
5453 "Cannot have type bigger than ulong!");
Chris Lattner77defba2006-02-07 07:00:41 +00005454 uint64_t AndValue = CSrc->getType()->getIntegralTypeMask();
Chris Lattner86102b82005-01-01 16:22:27 +00005455 Constant *AndOp = ConstantUInt::get(A->getType()->getUnsignedVersion(),
5456 AndValue);
5457 AndOp = ConstantExpr::getCast(AndOp, A->getType());
5458 Instruction *And = BinaryOperator::createAnd(CSrc->getOperand(0), AndOp);
5459 if (And->getType() != CI.getType()) {
5460 And->setName(CSrc->getName()+".mask");
5461 InsertNewInstBefore(And, CI);
5462 And = new CastInst(And, CI.getType());
5463 }
5464 return And;
Chris Lattner650b6da2002-08-02 20:00:25 +00005465 }
5466 }
Chris Lattner2590e512006-02-07 06:56:34 +00005467
Chris Lattner03841652004-05-25 04:29:21 +00005468 // If this is a cast to bool, turn it into the appropriate setne instruction.
5469 if (CI.getType() == Type::BoolTy)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00005470 return BinaryOperator::createSetNE(CI.getOperand(0),
Chris Lattner03841652004-05-25 04:29:21 +00005471 Constant::getNullValue(CI.getOperand(0)->getType()));
5472
Chris Lattner2590e512006-02-07 06:56:34 +00005473 // See if we can simplify any instructions used by the LHS whose sole
5474 // purpose is to compute bits we don't care about.
Chris Lattner0157e7f2006-02-11 09:31:47 +00005475 if (CI.getType()->isInteger() && CI.getOperand(0)->getType()->isIntegral()) {
5476 uint64_t KnownZero, KnownOne;
5477 if (SimplifyDemandedBits(&CI, CI.getType()->getIntegralTypeMask(),
5478 KnownZero, KnownOne))
5479 return &CI;
5480 }
Chris Lattner2590e512006-02-07 06:56:34 +00005481
Chris Lattnerd0d51602003-06-21 23:12:02 +00005482 // If casting the result of a getelementptr instruction with no offset, turn
5483 // this into a cast of the original pointer!
5484 //
Chris Lattner55d4bda2003-06-23 21:59:52 +00005485 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattnerd0d51602003-06-21 23:12:02 +00005486 bool AllZeroOperands = true;
5487 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
5488 if (!isa<Constant>(GEP->getOperand(i)) ||
5489 !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
5490 AllZeroOperands = false;
5491 break;
5492 }
5493 if (AllZeroOperands) {
5494 CI.setOperand(0, GEP->getOperand(0));
5495 return &CI;
5496 }
5497 }
5498
Chris Lattnerf4ad1652003-11-02 05:57:39 +00005499 // If we are casting a malloc or alloca to a pointer to a type of the same
5500 // size, rewrite the allocation instruction to allocate the "right" type.
5501 //
5502 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
Chris Lattner216be912005-10-24 06:03:58 +00005503 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
5504 return V;
Chris Lattnerf4ad1652003-11-02 05:57:39 +00005505
Chris Lattner86102b82005-01-01 16:22:27 +00005506 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
5507 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
5508 return NV;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00005509 if (isa<PHINode>(Src))
5510 if (Instruction *NV = FoldOpIntoPhi(CI))
5511 return NV;
Chris Lattnerb19a5c62006-04-12 18:09:35 +00005512
5513 // If the source and destination are pointers, and this cast is equivalent to
5514 // a getelementptr X, 0, 0, 0... turn it into the appropriate getelementptr.
5515 // This can enhance SROA and other transforms that want type-safe pointers.
5516 if (const PointerType *DstPTy = dyn_cast<PointerType>(CI.getType()))
5517 if (const PointerType *SrcPTy = dyn_cast<PointerType>(Src->getType())) {
5518 const Type *DstTy = DstPTy->getElementType();
5519 const Type *SrcTy = SrcPTy->getElementType();
5520
5521 Constant *ZeroUInt = Constant::getNullValue(Type::UIntTy);
5522 unsigned NumZeros = 0;
5523 while (SrcTy != DstTy &&
Chris Lattnerd2862702006-09-11 21:43:16 +00005524 isa<CompositeType>(SrcTy) && !isa<PointerType>(SrcTy) &&
5525 SrcTy->getNumContainedTypes() /* not "{}" */) {
Chris Lattnerb19a5c62006-04-12 18:09:35 +00005526 SrcTy = cast<CompositeType>(SrcTy)->getTypeAtIndex(ZeroUInt);
5527 ++NumZeros;
5528 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00005529
Chris Lattnerb19a5c62006-04-12 18:09:35 +00005530 // If we found a path from the src to dest, create the getelementptr now.
5531 if (SrcTy == DstTy) {
5532 std::vector<Value*> Idxs(NumZeros+1, ZeroUInt);
5533 return new GetElementPtrInst(Src, Idxs);
5534 }
5535 }
5536
Chris Lattnerdfae8be2003-07-24 17:35:25 +00005537 // If the source value is an instruction with only this use, we can attempt to
5538 // propagate the cast into the instruction. Also, only handle integral types
5539 // for now.
Chris Lattner99155be2006-05-25 23:24:33 +00005540 if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
Chris Lattnerf95d9b92003-10-15 16:48:29 +00005541 if (SrcI->hasOneUse() && Src->getType()->isIntegral() &&
Chris Lattnerdfae8be2003-07-24 17:35:25 +00005542 CI.getType()->isInteger()) { // Don't mess with casts to bool here
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005543
5544 int NumCastsRemoved = 0;
5545 if (CanEvaluateInDifferentType(SrcI, CI.getType(), NumCastsRemoved)) {
5546 // If this cast is a truncate, evaluting in a different type always
5547 // eliminates the cast, so it is always a win. If this is a noop-cast
5548 // this just removes a noop cast which isn't pointful, but simplifies
5549 // the code. If this is a zero-extension, we need to do an AND to
5550 // maintain the clear top-part of the computation, so we require that
5551 // the input have eliminated at least one cast. If this is a sign
5552 // extension, we insert two new casts (to do the extension) so we
5553 // require that two casts have been eliminated.
5554 bool DoXForm;
5555 switch (getCastType(Src->getType(), CI.getType())) {
5556 default: assert(0 && "Unknown cast type!");
5557 case Noop:
5558 case Truncate:
5559 DoXForm = true;
5560 break;
5561 case Zeroext:
5562 DoXForm = NumCastsRemoved >= 1;
5563 break;
5564 case Signext:
5565 DoXForm = NumCastsRemoved >= 2;
5566 break;
5567 }
5568
5569 if (DoXForm) {
5570 Value *Res = EvaluateInDifferentType(SrcI, CI.getType());
5571 assert(Res->getType() == CI.getType());
5572 switch (getCastType(Src->getType(), CI.getType())) {
5573 default: assert(0 && "Unknown cast type!");
5574 case Noop:
5575 case Truncate:
5576 // Just replace this cast with the result.
5577 return ReplaceInstUsesWith(CI, Res);
5578 case Zeroext: {
5579 // We need to emit an AND to clear the high bits.
5580 unsigned SrcBitSize = Src->getType()->getPrimitiveSizeInBits();
5581 unsigned DestBitSize = CI.getType()->getPrimitiveSizeInBits();
5582 assert(SrcBitSize < DestBitSize && "Not a zext?");
5583 Constant *C = ConstantUInt::get(Type::ULongTy, (1 << SrcBitSize)-1);
5584 C = ConstantExpr::getCast(C, CI.getType());
5585 return BinaryOperator::createAnd(Res, C);
5586 }
5587 case Signext:
5588 // We need to emit a cast to truncate, then a cast to sext.
5589 return new CastInst(InsertCastBefore(Res, Src->getType(), CI),
5590 CI.getType());
5591 }
5592 }
5593 }
5594
Chris Lattnerdfae8be2003-07-24 17:35:25 +00005595 const Type *DestTy = CI.getType();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005596 unsigned SrcBitSize = Src->getType()->getPrimitiveSizeInBits();
5597 unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
Chris Lattnerdfae8be2003-07-24 17:35:25 +00005598
5599 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
5600 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
5601
5602 switch (SrcI->getOpcode()) {
5603 case Instruction::Add:
5604 case Instruction::Mul:
5605 case Instruction::And:
5606 case Instruction::Or:
5607 case Instruction::Xor:
5608 // If we are discarding information, or just changing the sign, rewrite.
5609 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
5610 // Don't insert two casts if they cannot be eliminated. We allow two
5611 // casts to be inserted if the sizes are the same. This could only be
5612 // converting signedness, which is a noop.
Chris Lattner11ffd592004-07-20 05:21:00 +00005613 if (DestBitSize == SrcBitSize || !ValueRequiresCast(Op1, DestTy,TD) ||
5614 !ValueRequiresCast(Op0, DestTy, TD)) {
Chris Lattnerdfae8be2003-07-24 17:35:25 +00005615 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
5616 Value *Op1c = InsertOperandCastBefore(Op1, DestTy, SrcI);
5617 return BinaryOperator::create(cast<BinaryOperator>(SrcI)
5618 ->getOpcode(), Op0c, Op1c);
5619 }
5620 }
Chris Lattner72086162005-05-06 02:07:39 +00005621
5622 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
5623 if (SrcBitSize == 1 && SrcI->getOpcode() == Instruction::Xor &&
Chris Lattner6ab03f62006-09-28 23:35:22 +00005624 Op1 == ConstantBool::getTrue() &&
Chris Lattner72086162005-05-06 02:07:39 +00005625 (!Op0->hasOneUse() || !isa<SetCondInst>(Op0))) {
5626 Value *New = InsertOperandCastBefore(Op0, DestTy, &CI);
5627 return BinaryOperator::createXor(New,
5628 ConstantInt::get(CI.getType(), 1));
5629 }
Chris Lattnerdfae8be2003-07-24 17:35:25 +00005630 break;
5631 case Instruction::Shl:
5632 // Allow changing the sign of the source operand. Do not allow changing
5633 // the size of the shift, UNLESS the shift amount is a constant. We
5634 // mush not change variable sized shifts to a smaller size, because it
5635 // is undefined to shift more bits out than exist in the value.
5636 if (DestBitSize == SrcBitSize ||
5637 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
5638 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
5639 return new ShiftInst(Instruction::Shl, Op0c, Op1);
5640 }
5641 break;
Chris Lattner87380412005-05-06 04:18:52 +00005642 case Instruction::Shr:
5643 // If this is a signed shr, and if all bits shifted in are about to be
5644 // truncated off, turn it into an unsigned shr to allow greater
5645 // simplifications.
5646 if (DestBitSize < SrcBitSize && Src->getType()->isSigned() &&
5647 isa<ConstantInt>(Op1)) {
5648 unsigned ShiftAmt = cast<ConstantUInt>(Op1)->getValue();
5649 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
5650 // Convert to unsigned.
5651 Value *N1 = InsertOperandCastBefore(Op0,
5652 Op0->getType()->getUnsignedVersion(), &CI);
5653 // Insert the new shift, which is now unsigned.
5654 N1 = InsertNewInstBefore(new ShiftInst(Instruction::Shr, N1,
5655 Op1, Src->getName()), CI);
5656 return new CastInst(N1, CI.getType());
5657 }
5658 }
5659 break;
5660
Chris Lattnerc7bfed02006-02-27 02:38:23 +00005661 case Instruction::SetEQ:
Chris Lattner809dfac2005-05-04 19:10:26 +00005662 case Instruction::SetNE:
Chris Lattnerc7bfed02006-02-27 02:38:23 +00005663 // We if we are just checking for a seteq of a single bit and casting it
5664 // to an integer. If so, shift the bit to the appropriate place then
5665 // cast to integer to avoid the comparison.
Chris Lattner809dfac2005-05-04 19:10:26 +00005666 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerc7bfed02006-02-27 02:38:23 +00005667 uint64_t Op1CV = Op1C->getZExtValue();
5668 // cast (X == 0) to int --> X^1 iff X has only the low bit set.
5669 // cast (X == 0) to int --> (X>>1)^1 iff X has only the 2nd bit set.
5670 // cast (X == 1) to int --> X iff X has only the low bit set.
5671 // cast (X == 2) to int --> X>>1 iff X has only the 2nd bit set.
5672 // cast (X != 0) to int --> X iff X has only the low bit set.
5673 // cast (X != 0) to int --> X>>1 iff X has only the 2nd bit set.
5674 // cast (X != 1) to int --> X^1 iff X has only the low bit set.
5675 // cast (X != 2) to int --> (X>>1)^1 iff X has only the 2nd bit set.
5676 if (Op1CV == 0 || isPowerOf2_64(Op1CV)) {
5677 // If Op1C some other power of two, convert:
5678 uint64_t KnownZero, KnownOne;
5679 uint64_t TypeMask = Op1->getType()->getIntegralTypeMask();
5680 ComputeMaskedBits(Op0, TypeMask, KnownZero, KnownOne);
5681
5682 if (isPowerOf2_64(KnownZero^TypeMask)) { // Exactly one possible 1?
5683 bool isSetNE = SrcI->getOpcode() == Instruction::SetNE;
5684 if (Op1CV && (Op1CV != (KnownZero^TypeMask))) {
5685 // (X&4) == 2 --> false
5686 // (X&4) != 2 --> true
Chris Lattnerc5b6c9a2006-02-28 19:47:20 +00005687 Constant *Res = ConstantBool::get(isSetNE);
5688 Res = ConstantExpr::getCast(Res, CI.getType());
5689 return ReplaceInstUsesWith(CI, Res);
Chris Lattnerc7bfed02006-02-27 02:38:23 +00005690 }
5691
5692 unsigned ShiftAmt = Log2_64(KnownZero^TypeMask);
5693 Value *In = Op0;
5694 if (ShiftAmt) {
Chris Lattner4c2d3782005-05-06 01:53:19 +00005695 // Perform an unsigned shr by shiftamt. Convert input to
5696 // unsigned if it is signed.
Chris Lattner4c2d3782005-05-06 01:53:19 +00005697 if (In->getType()->isSigned())
5698 In = InsertNewInstBefore(new CastInst(In,
5699 In->getType()->getUnsignedVersion(), In->getName()),CI);
5700 // Insert the shift to put the result in the low bit.
5701 In = InsertNewInstBefore(new ShiftInst(Instruction::Shr, In,
Chris Lattnerc7bfed02006-02-27 02:38:23 +00005702 ConstantInt::get(Type::UByteTy, ShiftAmt),
5703 In->getName()+".lobit"), CI);
Chris Lattner4c2d3782005-05-06 01:53:19 +00005704 }
Chris Lattnerc7bfed02006-02-27 02:38:23 +00005705
5706 if ((Op1CV != 0) == isSetNE) { // Toggle the low bit.
5707 Constant *One = ConstantInt::get(In->getType(), 1);
5708 In = BinaryOperator::createXor(In, One, "tmp");
5709 InsertNewInstBefore(cast<Instruction>(In), CI);
Chris Lattner4c2d3782005-05-06 01:53:19 +00005710 }
Chris Lattnerc7bfed02006-02-27 02:38:23 +00005711
5712 if (CI.getType() == In->getType())
5713 return ReplaceInstUsesWith(CI, In);
5714 else
5715 return new CastInst(In, CI.getType());
Chris Lattner4c2d3782005-05-06 01:53:19 +00005716 }
Chris Lattner809dfac2005-05-04 19:10:26 +00005717 }
5718 }
5719 break;
Chris Lattnerdfae8be2003-07-24 17:35:25 +00005720 }
5721 }
Chris Lattner99155be2006-05-25 23:24:33 +00005722
5723 if (SrcI->hasOneUse()) {
5724 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(SrcI)) {
5725 // Okay, we have (cast (shuffle ..)). We know this cast is a bitconvert
5726 // because the inputs are known to be a vector. Check to see if this is
5727 // a cast to a vector with the same # elts.
5728 if (isa<PackedType>(CI.getType()) &&
5729 cast<PackedType>(CI.getType())->getNumElements() ==
5730 SVI->getType()->getNumElements()) {
5731 CastInst *Tmp;
5732 // If either of the operands is a cast from CI.getType(), then
5733 // evaluating the shuffle in the casted destination's type will allow
5734 // us to eliminate at least one cast.
5735 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
5736 Tmp->getOperand(0)->getType() == CI.getType()) ||
5737 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
Chris Lattner95cebb02006-06-06 22:26:02 +00005738 Tmp->getOperand(0)->getType() == CI.getType())) {
Chris Lattner99155be2006-05-25 23:24:33 +00005739 Value *LHS = InsertOperandCastBefore(SVI->getOperand(0),
5740 CI.getType(), &CI);
5741 Value *RHS = InsertOperandCastBefore(SVI->getOperand(1),
5742 CI.getType(), &CI);
5743 // Return a new shuffle vector. Use the same element ID's, as we
5744 // know the vector types match #elts.
5745 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
5746 }
5747 }
5748 }
5749 }
5750 }
Chris Lattnerbb171802005-10-27 05:53:56 +00005751
Chris Lattner260ab202002-04-18 17:39:14 +00005752 return 0;
Chris Lattnerca081252001-12-14 16:52:21 +00005753}
5754
Chris Lattner56e4d3d2004-04-09 23:46:01 +00005755/// GetSelectFoldableOperands - We want to turn code that looks like this:
5756/// %C = or %A, %B
5757/// %D = select %cond, %C, %A
5758/// into:
5759/// %C = select %cond, %B, 0
5760/// %D = or %A, %C
5761///
5762/// Assuming that the specified instruction is an operand to the select, return
5763/// a bitmask indicating which operands of this instruction are foldable if they
5764/// equal the other incoming value of the select.
5765///
5766static unsigned GetSelectFoldableOperands(Instruction *I) {
5767 switch (I->getOpcode()) {
5768 case Instruction::Add:
5769 case Instruction::Mul:
5770 case Instruction::And:
5771 case Instruction::Or:
5772 case Instruction::Xor:
5773 return 3; // Can fold through either operand.
5774 case Instruction::Sub: // Can only fold on the amount subtracted.
5775 case Instruction::Shl: // Can only fold on the shift amount.
5776 case Instruction::Shr:
Misha Brukmanb1c93172005-04-21 23:48:37 +00005777 return 1;
Chris Lattner56e4d3d2004-04-09 23:46:01 +00005778 default:
5779 return 0; // Cannot fold
5780 }
5781}
5782
5783/// GetSelectFoldableConstant - For the same transformation as the previous
5784/// function, return the identity constant that goes into the select.
5785static Constant *GetSelectFoldableConstant(Instruction *I) {
5786 switch (I->getOpcode()) {
5787 default: assert(0 && "This cannot happen!"); abort();
5788 case Instruction::Add:
5789 case Instruction::Sub:
5790 case Instruction::Or:
5791 case Instruction::Xor:
5792 return Constant::getNullValue(I->getType());
5793 case Instruction::Shl:
5794 case Instruction::Shr:
5795 return Constant::getNullValue(Type::UByteTy);
5796 case Instruction::And:
5797 return ConstantInt::getAllOnesValue(I->getType());
5798 case Instruction::Mul:
5799 return ConstantInt::get(I->getType(), 1);
5800 }
5801}
5802
Chris Lattner411336f2005-01-19 21:50:18 +00005803/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
5804/// have the same opcode and only one use each. Try to simplify this.
5805Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
5806 Instruction *FI) {
5807 if (TI->getNumOperands() == 1) {
5808 // If this is a non-volatile load or a cast from the same type,
5809 // merge.
5810 if (TI->getOpcode() == Instruction::Cast) {
5811 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
5812 return 0;
5813 } else {
5814 return 0; // unknown unary op.
5815 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00005816
Chris Lattner411336f2005-01-19 21:50:18 +00005817 // Fold this by inserting a select from the input values.
5818 SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
5819 FI->getOperand(0), SI.getName()+".v");
5820 InsertNewInstBefore(NewSI, SI);
5821 return new CastInst(NewSI, TI->getType());
5822 }
5823
5824 // Only handle binary operators here.
5825 if (!isa<ShiftInst>(TI) && !isa<BinaryOperator>(TI))
5826 return 0;
5827
5828 // Figure out if the operations have any operands in common.
5829 Value *MatchOp, *OtherOpT, *OtherOpF;
5830 bool MatchIsOpZero;
5831 if (TI->getOperand(0) == FI->getOperand(0)) {
5832 MatchOp = TI->getOperand(0);
5833 OtherOpT = TI->getOperand(1);
5834 OtherOpF = FI->getOperand(1);
5835 MatchIsOpZero = true;
5836 } else if (TI->getOperand(1) == FI->getOperand(1)) {
5837 MatchOp = TI->getOperand(1);
5838 OtherOpT = TI->getOperand(0);
5839 OtherOpF = FI->getOperand(0);
5840 MatchIsOpZero = false;
5841 } else if (!TI->isCommutative()) {
5842 return 0;
5843 } else if (TI->getOperand(0) == FI->getOperand(1)) {
5844 MatchOp = TI->getOperand(0);
5845 OtherOpT = TI->getOperand(1);
5846 OtherOpF = FI->getOperand(0);
5847 MatchIsOpZero = true;
5848 } else if (TI->getOperand(1) == FI->getOperand(0)) {
5849 MatchOp = TI->getOperand(1);
5850 OtherOpT = TI->getOperand(0);
5851 OtherOpF = FI->getOperand(1);
5852 MatchIsOpZero = true;
5853 } else {
5854 return 0;
5855 }
5856
5857 // If we reach here, they do have operations in common.
5858 SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
5859 OtherOpF, SI.getName()+".v");
5860 InsertNewInstBefore(NewSI, SI);
5861
5862 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
5863 if (MatchIsOpZero)
5864 return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
5865 else
5866 return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
5867 } else {
5868 if (MatchIsOpZero)
5869 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), MatchOp, NewSI);
5870 else
5871 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), NewSI, MatchOp);
5872 }
5873}
5874
Chris Lattnerb909e8b2004-03-12 05:52:32 +00005875Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattner533bc492004-03-30 19:37:13 +00005876 Value *CondVal = SI.getCondition();
5877 Value *TrueVal = SI.getTrueValue();
5878 Value *FalseVal = SI.getFalseValue();
5879
5880 // select true, X, Y -> X
5881 // select false, X, Y -> Y
5882 if (ConstantBool *C = dyn_cast<ConstantBool>(CondVal))
Chris Lattner6ab03f62006-09-28 23:35:22 +00005883 return ReplaceInstUsesWith(SI, C->getValue() ? TrueVal : FalseVal);
Chris Lattner533bc492004-03-30 19:37:13 +00005884
5885 // select C, X, X -> X
5886 if (TrueVal == FalseVal)
5887 return ReplaceInstUsesWith(SI, TrueVal);
5888
Chris Lattner81a7a232004-10-16 18:11:37 +00005889 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
5890 return ReplaceInstUsesWith(SI, FalseVal);
5891 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
5892 return ReplaceInstUsesWith(SI, TrueVal);
5893 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
5894 if (isa<Constant>(TrueVal))
5895 return ReplaceInstUsesWith(SI, TrueVal);
5896 else
5897 return ReplaceInstUsesWith(SI, FalseVal);
5898 }
5899
Chris Lattner1c631e82004-04-08 04:43:23 +00005900 if (SI.getType() == Type::BoolTy)
5901 if (ConstantBool *C = dyn_cast<ConstantBool>(TrueVal)) {
Chris Lattner6ab03f62006-09-28 23:35:22 +00005902 if (C->getValue()) {
Chris Lattner1c631e82004-04-08 04:43:23 +00005903 // Change: A = select B, true, C --> A = or B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00005904 return BinaryOperator::createOr(CondVal, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00005905 } else {
5906 // Change: A = select B, false, C --> A = and !B, C
5907 Value *NotCond =
5908 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
5909 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00005910 return BinaryOperator::createAnd(NotCond, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00005911 }
5912 } else if (ConstantBool *C = dyn_cast<ConstantBool>(FalseVal)) {
Chris Lattner6ab03f62006-09-28 23:35:22 +00005913 if (C->getValue() == false) {
Chris Lattner1c631e82004-04-08 04:43:23 +00005914 // Change: A = select B, C, false --> A = and B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00005915 return BinaryOperator::createAnd(CondVal, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00005916 } else {
5917 // Change: A = select B, C, true --> A = or !B, C
5918 Value *NotCond =
5919 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
5920 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00005921 return BinaryOperator::createOr(NotCond, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00005922 }
5923 }
5924
Chris Lattner183b3362004-04-09 19:05:30 +00005925 // Selecting between two integer constants?
5926 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
5927 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
5928 // select C, 1, 0 -> cast C to int
5929 if (FalseValC->isNullValue() && TrueValC->getRawValue() == 1) {
5930 return new CastInst(CondVal, SI.getType());
5931 } else if (TrueValC->isNullValue() && FalseValC->getRawValue() == 1) {
5932 // select C, 0, 1 -> cast !C to int
5933 Value *NotCond =
5934 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
Chris Lattnercf7baf32004-04-09 18:19:44 +00005935 "not."+CondVal->getName()), SI);
Chris Lattner183b3362004-04-09 19:05:30 +00005936 return new CastInst(NotCond, SI.getType());
Chris Lattnercf7baf32004-04-09 18:19:44 +00005937 }
Chris Lattner35167c32004-06-09 07:59:58 +00005938
Chris Lattner380c7e92006-09-20 04:44:59 +00005939 if (SetCondInst *IC = dyn_cast<SetCondInst>(SI.getCondition())) {
5940
5941 // (x <s 0) ? -1 : 0 -> sra x, 31
5942 // (x >u 2147483647) ? -1 : 0 -> sra x, 31
5943 if (TrueValC->isAllOnesValue() && FalseValC->isNullValue())
5944 if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
5945 bool CanXForm = false;
5946 if (CmpCst->getType()->isSigned())
5947 CanXForm = CmpCst->isNullValue() &&
5948 IC->getOpcode() == Instruction::SetLT;
5949 else {
5950 unsigned Bits = CmpCst->getType()->getPrimitiveSizeInBits();
5951 CanXForm = (CmpCst->getRawValue() == ~0ULL >> (64-Bits+1)) &&
5952 IC->getOpcode() == Instruction::SetGT;
5953 }
5954
5955 if (CanXForm) {
5956 // The comparison constant and the result are not neccessarily the
5957 // same width. In any case, the first step to do is make sure
5958 // that X is signed.
5959 Value *X = IC->getOperand(0);
5960 if (!X->getType()->isSigned())
5961 X = InsertCastBefore(X, X->getType()->getSignedVersion(), SI);
5962
5963 // Now that X is signed, we have to make the all ones value. Do
5964 // this by inserting a new SRA.
5965 unsigned Bits = X->getType()->getPrimitiveSizeInBits();
5966 Constant *ShAmt = ConstantUInt::get(Type::UByteTy, Bits-1);
5967 Instruction *SRA = new ShiftInst(Instruction::Shr, X,
5968 ShAmt, "ones");
5969 InsertNewInstBefore(SRA, SI);
5970
5971 // Finally, convert to the type of the select RHS. If this is
5972 // smaller than the compare value, it will truncate the ones to
5973 // fit. If it is larger, it will sext the ones to fit.
5974 return new CastInst(SRA, SI.getType());
5975 }
5976 }
5977
5978
5979 // If one of the constants is zero (we know they can't both be) and we
5980 // have a setcc instruction with zero, and we have an 'and' with the
5981 // non-constant value, eliminate this whole mess. This corresponds to
5982 // cases like this: ((X & 27) ? 27 : 0)
5983 if (TrueValC->isNullValue() || FalseValC->isNullValue())
Chris Lattnerb3f24c92006-09-18 04:22:48 +00005984 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner35167c32004-06-09 07:59:58 +00005985 cast<Constant>(IC->getOperand(1))->isNullValue())
5986 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
5987 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00005988 isa<ConstantInt>(ICA->getOperand(1)) &&
5989 (ICA->getOperand(1) == TrueValC ||
5990 ICA->getOperand(1) == FalseValC) &&
Chris Lattner35167c32004-06-09 07:59:58 +00005991 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
5992 // Okay, now we know that everything is set up, we just don't
5993 // know whether we have a setne or seteq and whether the true or
5994 // false val is the zero.
5995 bool ShouldNotVal = !TrueValC->isNullValue();
5996 ShouldNotVal ^= IC->getOpcode() == Instruction::SetNE;
5997 Value *V = ICA;
5998 if (ShouldNotVal)
5999 V = InsertNewInstBefore(BinaryOperator::create(
6000 Instruction::Xor, V, ICA->getOperand(1)), SI);
6001 return ReplaceInstUsesWith(SI, V);
6002 }
Chris Lattner380c7e92006-09-20 04:44:59 +00006003 }
Chris Lattner533bc492004-03-30 19:37:13 +00006004 }
Chris Lattner623fba12004-04-10 22:21:27 +00006005
6006 // See if we are selecting two values based on a comparison of the two values.
6007 if (SetCondInst *SCI = dyn_cast<SetCondInst>(CondVal)) {
6008 if (SCI->getOperand(0) == TrueVal && SCI->getOperand(1) == FalseVal) {
6009 // Transform (X == Y) ? X : Y -> Y
6010 if (SCI->getOpcode() == Instruction::SetEQ)
6011 return ReplaceInstUsesWith(SI, FalseVal);
6012 // Transform (X != Y) ? X : Y -> X
6013 if (SCI->getOpcode() == Instruction::SetNE)
6014 return ReplaceInstUsesWith(SI, TrueVal);
6015 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6016
6017 } else if (SCI->getOperand(0) == FalseVal && SCI->getOperand(1) == TrueVal){
6018 // Transform (X == Y) ? Y : X -> X
6019 if (SCI->getOpcode() == Instruction::SetEQ)
Chris Lattner24cf0202004-04-11 01:39:19 +00006020 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattner623fba12004-04-10 22:21:27 +00006021 // Transform (X != Y) ? Y : X -> Y
6022 if (SCI->getOpcode() == Instruction::SetNE)
Chris Lattner24cf0202004-04-11 01:39:19 +00006023 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattner623fba12004-04-10 22:21:27 +00006024 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6025 }
6026 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00006027
Chris Lattnera04c9042005-01-13 22:52:24 +00006028 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
6029 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
6030 if (TI->hasOneUse() && FI->hasOneUse()) {
6031 bool isInverse = false;
6032 Instruction *AddOp = 0, *SubOp = 0;
6033
Chris Lattner411336f2005-01-19 21:50:18 +00006034 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
6035 if (TI->getOpcode() == FI->getOpcode())
6036 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
6037 return IV;
6038
6039 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
6040 // even legal for FP.
Chris Lattnera04c9042005-01-13 22:52:24 +00006041 if (TI->getOpcode() == Instruction::Sub &&
6042 FI->getOpcode() == Instruction::Add) {
6043 AddOp = FI; SubOp = TI;
6044 } else if (FI->getOpcode() == Instruction::Sub &&
6045 TI->getOpcode() == Instruction::Add) {
6046 AddOp = TI; SubOp = FI;
6047 }
6048
6049 if (AddOp) {
6050 Value *OtherAddOp = 0;
6051 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
6052 OtherAddOp = AddOp->getOperand(1);
6053 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
6054 OtherAddOp = AddOp->getOperand(0);
6055 }
6056
6057 if (OtherAddOp) {
Chris Lattnerb580d262006-02-24 18:05:58 +00006058 // So at this point we know we have (Y -> OtherAddOp):
6059 // select C, (add X, Y), (sub X, Z)
6060 Value *NegVal; // Compute -Z
6061 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
6062 NegVal = ConstantExpr::getNeg(C);
6063 } else {
6064 NegVal = InsertNewInstBefore(
6065 BinaryOperator::createNeg(SubOp->getOperand(1), "tmp"), SI);
Chris Lattnera04c9042005-01-13 22:52:24 +00006066 }
Chris Lattnerb580d262006-02-24 18:05:58 +00006067
6068 Value *NewTrueOp = OtherAddOp;
6069 Value *NewFalseOp = NegVal;
6070 if (AddOp != TI)
6071 std::swap(NewTrueOp, NewFalseOp);
6072 Instruction *NewSel =
6073 new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
6074
6075 NewSel = InsertNewInstBefore(NewSel, SI);
6076 return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
Chris Lattnera04c9042005-01-13 22:52:24 +00006077 }
6078 }
6079 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00006080
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006081 // See if we can fold the select into one of our operands.
6082 if (SI.getType()->isInteger()) {
6083 // See the comment above GetSelectFoldableOperands for a description of the
6084 // transformation we are doing here.
6085 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
6086 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
6087 !isa<Constant>(FalseVal))
6088 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
6089 unsigned OpToFold = 0;
6090 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
6091 OpToFold = 1;
6092 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
6093 OpToFold = 2;
6094 }
6095
6096 if (OpToFold) {
6097 Constant *C = GetSelectFoldableConstant(TVI);
6098 std::string Name = TVI->getName(); TVI->setName("");
6099 Instruction *NewSel =
6100 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C,
6101 Name);
6102 InsertNewInstBefore(NewSel, SI);
6103 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
6104 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
6105 else if (ShiftInst *SI = dyn_cast<ShiftInst>(TVI))
6106 return new ShiftInst(SI->getOpcode(), FalseVal, NewSel);
6107 else {
6108 assert(0 && "Unknown instruction!!");
6109 }
6110 }
6111 }
Chris Lattner6862fbd2004-09-29 17:40:11 +00006112
Chris Lattner56e4d3d2004-04-09 23:46:01 +00006113 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
6114 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
6115 !isa<Constant>(TrueVal))
6116 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
6117 unsigned OpToFold = 0;
6118 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
6119 OpToFold = 1;
6120 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
6121 OpToFold = 2;
6122 }
6123
6124 if (OpToFold) {
6125 Constant *C = GetSelectFoldableConstant(FVI);
6126 std::string Name = FVI->getName(); FVI->setName("");
6127 Instruction *NewSel =
6128 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold),
6129 Name);
6130 InsertNewInstBefore(NewSel, SI);
6131 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
6132 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
6133 else if (ShiftInst *SI = dyn_cast<ShiftInst>(FVI))
6134 return new ShiftInst(SI->getOpcode(), TrueVal, NewSel);
6135 else {
6136 assert(0 && "Unknown instruction!!");
6137 }
6138 }
6139 }
6140 }
Chris Lattnerd6f636a2005-04-24 07:30:14 +00006141
6142 if (BinaryOperator::isNot(CondVal)) {
6143 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
6144 SI.setOperand(1, FalseVal);
6145 SI.setOperand(2, TrueVal);
6146 return &SI;
6147 }
6148
Chris Lattnerb909e8b2004-03-12 05:52:32 +00006149 return 0;
6150}
6151
Chris Lattner82f2ef22006-03-06 20:18:44 +00006152/// GetKnownAlignment - If the specified pointer has an alignment that we can
6153/// determine, return it, otherwise return 0.
6154static unsigned GetKnownAlignment(Value *V, TargetData *TD) {
6155 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
6156 unsigned Align = GV->getAlignment();
6157 if (Align == 0 && TD)
6158 Align = TD->getTypeAlignment(GV->getType()->getElementType());
6159 return Align;
6160 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
6161 unsigned Align = AI->getAlignment();
6162 if (Align == 0 && TD) {
6163 if (isa<AllocaInst>(AI))
6164 Align = TD->getTypeAlignment(AI->getType()->getElementType());
6165 else if (isa<MallocInst>(AI)) {
6166 // Malloc returns maximally aligned memory.
6167 Align = TD->getTypeAlignment(AI->getType()->getElementType());
6168 Align = std::max(Align, (unsigned)TD->getTypeAlignment(Type::DoubleTy));
6169 Align = std::max(Align, (unsigned)TD->getTypeAlignment(Type::LongTy));
6170 }
6171 }
6172 return Align;
Chris Lattner53ef5a02006-03-07 01:28:57 +00006173 } else if (isa<CastInst>(V) ||
6174 (isa<ConstantExpr>(V) &&
6175 cast<ConstantExpr>(V)->getOpcode() == Instruction::Cast)) {
6176 User *CI = cast<User>(V);
Chris Lattner82f2ef22006-03-06 20:18:44 +00006177 if (isa<PointerType>(CI->getOperand(0)->getType()))
6178 return GetKnownAlignment(CI->getOperand(0), TD);
6179 return 0;
Chris Lattner53ef5a02006-03-07 01:28:57 +00006180 } else if (isa<GetElementPtrInst>(V) ||
6181 (isa<ConstantExpr>(V) &&
6182 cast<ConstantExpr>(V)->getOpcode()==Instruction::GetElementPtr)) {
6183 User *GEPI = cast<User>(V);
Chris Lattner82f2ef22006-03-06 20:18:44 +00006184 unsigned BaseAlignment = GetKnownAlignment(GEPI->getOperand(0), TD);
6185 if (BaseAlignment == 0) return 0;
6186
6187 // If all indexes are zero, it is just the alignment of the base pointer.
6188 bool AllZeroOperands = true;
6189 for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
6190 if (!isa<Constant>(GEPI->getOperand(i)) ||
6191 !cast<Constant>(GEPI->getOperand(i))->isNullValue()) {
6192 AllZeroOperands = false;
6193 break;
6194 }
6195 if (AllZeroOperands)
6196 return BaseAlignment;
6197
6198 // Otherwise, if the base alignment is >= the alignment we expect for the
6199 // base pointer type, then we know that the resultant pointer is aligned at
6200 // least as much as its type requires.
6201 if (!TD) return 0;
6202
6203 const Type *BasePtrTy = GEPI->getOperand(0)->getType();
6204 if (TD->getTypeAlignment(cast<PointerType>(BasePtrTy)->getElementType())
Chris Lattner53ef5a02006-03-07 01:28:57 +00006205 <= BaseAlignment) {
6206 const Type *GEPTy = GEPI->getType();
6207 return TD->getTypeAlignment(cast<PointerType>(GEPTy)->getElementType());
6208 }
Chris Lattner82f2ef22006-03-06 20:18:44 +00006209 return 0;
6210 }
6211 return 0;
6212}
6213
Chris Lattnerb909e8b2004-03-12 05:52:32 +00006214
Chris Lattnerc66b2232006-01-13 20:11:04 +00006215/// visitCallInst - CallInst simplification. This mostly only handles folding
6216/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
6217/// the heavy lifting.
6218///
Chris Lattner970c33a2003-06-19 17:00:31 +00006219Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattnerc66b2232006-01-13 20:11:04 +00006220 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
6221 if (!II) return visitCallSite(&CI);
6222
Chris Lattner51ea1272004-02-28 05:22:00 +00006223 // Intrinsics cannot occur in an invoke, so handle them here instead of in
6224 // visitCallSite.
Chris Lattnerc66b2232006-01-13 20:11:04 +00006225 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner00648e12004-10-12 04:52:52 +00006226 bool Changed = false;
6227
6228 // memmove/cpy/set of zero bytes is a noop.
6229 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
6230 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
6231
Chris Lattner00648e12004-10-12 04:52:52 +00006232 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
6233 if (CI->getRawValue() == 1) {
6234 // Replace the instruction with just byte operations. We would
6235 // transform other cases to loads/stores, but we don't know if
6236 // alignment is sufficient.
6237 }
Chris Lattner51ea1272004-02-28 05:22:00 +00006238 }
6239
Chris Lattner00648e12004-10-12 04:52:52 +00006240 // If we have a memmove and the source operation is a constant global,
6241 // then the source and dest pointers can't alias, so we can change this
6242 // into a call to memcpy.
Chris Lattner82f2ef22006-03-06 20:18:44 +00006243 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(II)) {
Chris Lattner00648e12004-10-12 04:52:52 +00006244 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
6245 if (GVSrc->isConstant()) {
6246 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner681ef2f2006-03-03 01:34:17 +00006247 const char *Name;
6248 if (CI.getCalledFunction()->getFunctionType()->getParamType(3) ==
6249 Type::UIntTy)
6250 Name = "llvm.memcpy.i32";
6251 else
6252 Name = "llvm.memcpy.i64";
6253 Function *MemCpy = M->getOrInsertFunction(Name,
Chris Lattner00648e12004-10-12 04:52:52 +00006254 CI.getCalledFunction()->getFunctionType());
6255 CI.setOperand(0, MemCpy);
6256 Changed = true;
6257 }
Chris Lattner82f2ef22006-03-06 20:18:44 +00006258 }
Chris Lattner00648e12004-10-12 04:52:52 +00006259
Chris Lattner82f2ef22006-03-06 20:18:44 +00006260 // If we can determine a pointer alignment that is bigger than currently
6261 // set, update the alignment.
6262 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
6263 unsigned Alignment1 = GetKnownAlignment(MI->getOperand(1), TD);
6264 unsigned Alignment2 = GetKnownAlignment(MI->getOperand(2), TD);
6265 unsigned Align = std::min(Alignment1, Alignment2);
6266 if (MI->getAlignment()->getRawValue() < Align) {
6267 MI->setAlignment(ConstantUInt::get(Type::UIntTy, Align));
6268 Changed = true;
6269 }
6270 } else if (isa<MemSetInst>(MI)) {
6271 unsigned Alignment = GetKnownAlignment(MI->getDest(), TD);
6272 if (MI->getAlignment()->getRawValue() < Alignment) {
6273 MI->setAlignment(ConstantUInt::get(Type::UIntTy, Alignment));
6274 Changed = true;
6275 }
6276 }
6277
Chris Lattnerc66b2232006-01-13 20:11:04 +00006278 if (Changed) return II;
Chris Lattner503221f2006-01-13 21:28:09 +00006279 } else {
6280 switch (II->getIntrinsicID()) {
6281 default: break;
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00006282 case Intrinsic::ppc_altivec_lvx:
6283 case Intrinsic::ppc_altivec_lvxl:
Chris Lattner36dd7c92006-04-17 22:26:56 +00006284 case Intrinsic::x86_sse_loadu_ps:
6285 case Intrinsic::x86_sse2_loadu_pd:
6286 case Intrinsic::x86_sse2_loadu_dq:
6287 // Turn PPC lvx -> load if the pointer is known aligned.
6288 // Turn X86 loadups -> load if the pointer is known aligned.
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00006289 if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
Chris Lattnere79d2492006-04-06 19:19:17 +00006290 Value *Ptr = InsertCastBefore(II->getOperand(1),
6291 PointerType::get(II->getType()), CI);
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00006292 return new LoadInst(Ptr);
6293 }
6294 break;
6295 case Intrinsic::ppc_altivec_stvx:
6296 case Intrinsic::ppc_altivec_stvxl:
6297 // Turn stvx -> store if the pointer is known aligned.
6298 if (GetKnownAlignment(II->getOperand(2), TD) >= 16) {
Chris Lattnere79d2492006-04-06 19:19:17 +00006299 const Type *OpPtrTy = PointerType::get(II->getOperand(1)->getType());
6300 Value *Ptr = InsertCastBefore(II->getOperand(2), OpPtrTy, CI);
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00006301 return new StoreInst(II->getOperand(1), Ptr);
6302 }
6303 break;
Chris Lattner36dd7c92006-04-17 22:26:56 +00006304 case Intrinsic::x86_sse_storeu_ps:
6305 case Intrinsic::x86_sse2_storeu_pd:
6306 case Intrinsic::x86_sse2_storeu_dq:
6307 case Intrinsic::x86_sse2_storel_dq:
6308 // Turn X86 storeu -> store if the pointer is known aligned.
6309 if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
6310 const Type *OpPtrTy = PointerType::get(II->getOperand(2)->getType());
6311 Value *Ptr = InsertCastBefore(II->getOperand(1), OpPtrTy, CI);
6312 return new StoreInst(II->getOperand(2), Ptr);
6313 }
6314 break;
Chris Lattner2deeaea2006-10-05 06:55:50 +00006315
6316 case Intrinsic::x86_sse_cvttss2si: {
6317 // These intrinsics only demands the 0th element of its input vector. If
6318 // we can simplify the input based on that, do so now.
6319 uint64_t UndefElts;
6320 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1,
6321 UndefElts)) {
6322 II->setOperand(1, V);
6323 return II;
6324 }
6325 break;
6326 }
6327
Chris Lattnere79d2492006-04-06 19:19:17 +00006328 case Intrinsic::ppc_altivec_vperm:
6329 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
6330 if (ConstantPacked *Mask = dyn_cast<ConstantPacked>(II->getOperand(3))) {
6331 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
6332
6333 // Check that all of the elements are integer constants or undefs.
6334 bool AllEltsOk = true;
6335 for (unsigned i = 0; i != 16; ++i) {
6336 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
6337 !isa<UndefValue>(Mask->getOperand(i))) {
6338 AllEltsOk = false;
6339 break;
6340 }
6341 }
6342
6343 if (AllEltsOk) {
6344 // Cast the input vectors to byte vectors.
6345 Value *Op0 = InsertCastBefore(II->getOperand(1), Mask->getType(), CI);
6346 Value *Op1 = InsertCastBefore(II->getOperand(2), Mask->getType(), CI);
6347 Value *Result = UndefValue::get(Op0->getType());
6348
6349 // Only extract each element once.
6350 Value *ExtractedElts[32];
6351 memset(ExtractedElts, 0, sizeof(ExtractedElts));
6352
6353 for (unsigned i = 0; i != 16; ++i) {
6354 if (isa<UndefValue>(Mask->getOperand(i)))
6355 continue;
6356 unsigned Idx =cast<ConstantInt>(Mask->getOperand(i))->getRawValue();
6357 Idx &= 31; // Match the hardware behavior.
6358
6359 if (ExtractedElts[Idx] == 0) {
6360 Instruction *Elt =
Chris Lattner2deeaea2006-10-05 06:55:50 +00006361 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
Chris Lattnere79d2492006-04-06 19:19:17 +00006362 InsertNewInstBefore(Elt, CI);
6363 ExtractedElts[Idx] = Elt;
6364 }
6365
6366 // Insert this value into the result vector.
Chris Lattner2deeaea2006-10-05 06:55:50 +00006367 Result = new InsertElementInst(Result, ExtractedElts[Idx], i,"tmp");
Chris Lattnere79d2492006-04-06 19:19:17 +00006368 InsertNewInstBefore(cast<Instruction>(Result), CI);
6369 }
6370 return new CastInst(Result, CI.getType());
6371 }
6372 }
6373 break;
6374
Chris Lattner503221f2006-01-13 21:28:09 +00006375 case Intrinsic::stackrestore: {
6376 // If the save is right next to the restore, remove the restore. This can
6377 // happen when variable allocas are DCE'd.
6378 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
6379 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
6380 BasicBlock::iterator BI = SS;
6381 if (&*++BI == II)
6382 return EraseInstFromFunction(CI);
6383 }
6384 }
6385
6386 // If the stack restore is in a return/unwind block and if there are no
6387 // allocas or calls between the restore and the return, nuke the restore.
6388 TerminatorInst *TI = II->getParent()->getTerminator();
6389 if (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)) {
6390 BasicBlock::iterator BI = II;
6391 bool CannotRemove = false;
6392 for (++BI; &*BI != TI; ++BI) {
6393 if (isa<AllocaInst>(BI) ||
6394 (isa<CallInst>(BI) && !isa<IntrinsicInst>(BI))) {
6395 CannotRemove = true;
6396 break;
6397 }
6398 }
6399 if (!CannotRemove)
6400 return EraseInstFromFunction(CI);
6401 }
6402 break;
6403 }
6404 }
Chris Lattner00648e12004-10-12 04:52:52 +00006405 }
6406
Chris Lattnerc66b2232006-01-13 20:11:04 +00006407 return visitCallSite(II);
Chris Lattner970c33a2003-06-19 17:00:31 +00006408}
6409
6410// InvokeInst simplification
6411//
6412Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattneraec3d942003-10-07 22:32:43 +00006413 return visitCallSite(&II);
Chris Lattner970c33a2003-06-19 17:00:31 +00006414}
6415
Chris Lattneraec3d942003-10-07 22:32:43 +00006416// visitCallSite - Improvements for call and invoke instructions.
6417//
6418Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner75b4d1d2003-10-07 22:54:13 +00006419 bool Changed = false;
6420
6421 // If the callee is a constexpr cast of a function, attempt to move the cast
6422 // to the arguments of the call/invoke.
Chris Lattneraec3d942003-10-07 22:32:43 +00006423 if (transformConstExprCastCall(CS)) return 0;
6424
Chris Lattner75b4d1d2003-10-07 22:54:13 +00006425 Value *Callee = CS.getCalledValue();
Chris Lattner81a7a232004-10-16 18:11:37 +00006426
Chris Lattner61d9d812005-05-13 07:09:09 +00006427 if (Function *CalleeF = dyn_cast<Function>(Callee))
6428 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
6429 Instruction *OldCall = CS.getInstruction();
6430 // If the call and callee calling conventions don't match, this call must
6431 // be unreachable, as the call is undefined.
Chris Lattner6ab03f62006-09-28 23:35:22 +00006432 new StoreInst(ConstantBool::getTrue(),
Chris Lattner61d9d812005-05-13 07:09:09 +00006433 UndefValue::get(PointerType::get(Type::BoolTy)), OldCall);
6434 if (!OldCall->use_empty())
6435 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
6436 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
6437 return EraseInstFromFunction(*OldCall);
6438 return 0;
6439 }
6440
Chris Lattner8ba9ec92004-10-18 02:59:09 +00006441 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
6442 // This instruction is not reachable, just remove it. We insert a store to
6443 // undef so that we know that this code is not reachable, despite the fact
6444 // that we can't modify the CFG here.
Chris Lattner6ab03f62006-09-28 23:35:22 +00006445 new StoreInst(ConstantBool::getTrue(),
Chris Lattner8ba9ec92004-10-18 02:59:09 +00006446 UndefValue::get(PointerType::get(Type::BoolTy)),
6447 CS.getInstruction());
6448
6449 if (!CS.getInstruction()->use_empty())
6450 CS.getInstruction()->
6451 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
6452
6453 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
6454 // Don't break the CFG, insert a dummy cond branch.
6455 new BranchInst(II->getNormalDest(), II->getUnwindDest(),
Chris Lattner6ab03f62006-09-28 23:35:22 +00006456 ConstantBool::getTrue(), II);
Chris Lattner81a7a232004-10-16 18:11:37 +00006457 }
Chris Lattner8ba9ec92004-10-18 02:59:09 +00006458 return EraseInstFromFunction(*CS.getInstruction());
6459 }
Chris Lattner81a7a232004-10-16 18:11:37 +00006460
Chris Lattner75b4d1d2003-10-07 22:54:13 +00006461 const PointerType *PTy = cast<PointerType>(Callee->getType());
6462 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
6463 if (FTy->isVarArg()) {
6464 // See if we can optimize any arguments passed through the varargs area of
6465 // the call.
6466 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
6467 E = CS.arg_end(); I != E; ++I)
6468 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
6469 // If this cast does not effect the value passed through the varargs
6470 // area, we can eliminate the use of the cast.
6471 Value *Op = CI->getOperand(0);
6472 if (CI->getType()->isLosslesslyConvertibleTo(Op->getType())) {
6473 *I = Op;
6474 Changed = true;
6475 }
6476 }
6477 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00006478
Chris Lattner75b4d1d2003-10-07 22:54:13 +00006479 return Changed ? CS.getInstruction() : 0;
Chris Lattneraec3d942003-10-07 22:32:43 +00006480}
6481
Chris Lattner970c33a2003-06-19 17:00:31 +00006482// transformConstExprCastCall - If the callee is a constexpr cast of a function,
6483// attempt to move the cast to the arguments of the call/invoke.
6484//
6485bool InstCombiner::transformConstExprCastCall(CallSite CS) {
6486 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
6487 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Chris Lattnerf3edc492004-07-18 18:59:44 +00006488 if (CE->getOpcode() != Instruction::Cast || !isa<Function>(CE->getOperand(0)))
Chris Lattner970c33a2003-06-19 17:00:31 +00006489 return false;
Reid Spencer87436872004-07-18 00:38:32 +00006490 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner970c33a2003-06-19 17:00:31 +00006491 Instruction *Caller = CS.getInstruction();
6492
6493 // Okay, this is a cast from a function to a different type. Unless doing so
6494 // would cause a type conversion of one of our arguments, change this call to
6495 // be a direct call with arguments casted to the appropriate types.
6496 //
6497 const FunctionType *FT = Callee->getFunctionType();
6498 const Type *OldRetTy = Caller->getType();
6499
Chris Lattner1f7942f2004-01-14 06:06:08 +00006500 // Check to see if we are changing the return type...
6501 if (OldRetTy != FT->getReturnType()) {
6502 if (Callee->isExternal() &&
Andrew Lenharth61eae292006-04-20 14:56:47 +00006503 !(OldRetTy->isLosslesslyConvertibleTo(FT->getReturnType()) ||
6504 (isa<PointerType>(FT->getReturnType()) &&
Andrew Lenharthf89e6302006-04-20 15:41:37 +00006505 TD->getIntPtrType()->isLosslesslyConvertibleTo(OldRetTy)))
Andrew Lenharth61eae292006-04-20 14:56:47 +00006506 && !Caller->use_empty())
Chris Lattner1f7942f2004-01-14 06:06:08 +00006507 return false; // Cannot transform this return value...
6508
6509 // If the callsite is an invoke instruction, and the return value is used by
6510 // a PHI node in a successor, we cannot change the return type of the call
6511 // because there is no place to put the cast instruction (without breaking
6512 // the critical edge). Bail out in this case.
6513 if (!Caller->use_empty())
6514 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
6515 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
6516 UI != E; ++UI)
6517 if (PHINode *PN = dyn_cast<PHINode>(*UI))
6518 if (PN->getParent() == II->getNormalDest() ||
Chris Lattnerfae8ab32004-02-08 21:44:31 +00006519 PN->getParent() == II->getUnwindDest())
Chris Lattner1f7942f2004-01-14 06:06:08 +00006520 return false;
6521 }
Chris Lattner970c33a2003-06-19 17:00:31 +00006522
6523 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
6524 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanb1c93172005-04-21 23:48:37 +00006525
Chris Lattner970c33a2003-06-19 17:00:31 +00006526 CallSite::arg_iterator AI = CS.arg_begin();
6527 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
6528 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthebfa24e2006-06-28 01:01:52 +00006529 const Type *ActTy = (*AI)->getType();
6530 ConstantSInt* c = dyn_cast<ConstantSInt>(*AI);
6531 //Either we can cast directly, or we can upconvert the argument
6532 bool isConvertible = ActTy->isLosslesslyConvertibleTo(ParamTy) ||
6533 (ParamTy->isIntegral() && ActTy->isIntegral() &&
6534 ParamTy->isSigned() == ActTy->isSigned() &&
6535 ParamTy->getPrimitiveSize() >= ActTy->getPrimitiveSize()) ||
6536 (c && ParamTy->getPrimitiveSize() >= ActTy->getPrimitiveSize() &&
6537 c->getValue() > 0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00006538 if (Callee->isExternal() && !isConvertible) return false;
Chris Lattner970c33a2003-06-19 17:00:31 +00006539 }
6540
6541 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
6542 Callee->isExternal())
6543 return false; // Do not delete arguments unless we have a function body...
6544
6545 // Okay, we decided that this is a safe thing to do: go ahead and start
6546 // inserting cast instructions as necessary...
6547 std::vector<Value*> Args;
6548 Args.reserve(NumActualArgs);
6549
6550 AI = CS.arg_begin();
6551 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
6552 const Type *ParamTy = FT->getParamType(i);
6553 if ((*AI)->getType() == ParamTy) {
6554 Args.push_back(*AI);
6555 } else {
Chris Lattner1c631e82004-04-08 04:43:23 +00006556 Args.push_back(InsertNewInstBefore(new CastInst(*AI, ParamTy, "tmp"),
6557 *Caller));
Chris Lattner970c33a2003-06-19 17:00:31 +00006558 }
6559 }
6560
6561 // If the function takes more arguments than the call was taking, add them
6562 // now...
6563 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
6564 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
6565
6566 // If we are removing arguments to the function, emit an obnoxious warning...
6567 if (FT->getNumParams() < NumActualArgs)
6568 if (!FT->isVarArg()) {
6569 std::cerr << "WARNING: While resolving call to function '"
6570 << Callee->getName() << "' arguments were dropped!\n";
6571 } else {
6572 // Add all of the arguments in their promoted form to the arg list...
6573 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
6574 const Type *PTy = getPromotedType((*AI)->getType());
6575 if (PTy != (*AI)->getType()) {
6576 // Must promote to pass through va_arg area!
6577 Instruction *Cast = new CastInst(*AI, PTy, "tmp");
6578 InsertNewInstBefore(Cast, *Caller);
6579 Args.push_back(Cast);
6580 } else {
6581 Args.push_back(*AI);
6582 }
6583 }
6584 }
6585
6586 if (FT->getReturnType() == Type::VoidTy)
6587 Caller->setName(""); // Void type should not have a name...
6588
6589 Instruction *NC;
6590 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Chris Lattnerfae8ab32004-02-08 21:44:31 +00006591 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
Chris Lattner970c33a2003-06-19 17:00:31 +00006592 Args, Caller->getName(), Caller);
Chris Lattner05c703e2005-05-14 12:25:32 +00006593 cast<InvokeInst>(II)->setCallingConv(II->getCallingConv());
Chris Lattner970c33a2003-06-19 17:00:31 +00006594 } else {
6595 NC = new CallInst(Callee, Args, Caller->getName(), Caller);
Chris Lattner6aacb0f2005-05-06 06:48:21 +00006596 if (cast<CallInst>(Caller)->isTailCall())
6597 cast<CallInst>(NC)->setTailCall();
Chris Lattner05c703e2005-05-14 12:25:32 +00006598 cast<CallInst>(NC)->setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Chris Lattner970c33a2003-06-19 17:00:31 +00006599 }
6600
6601 // Insert a cast of the return type as necessary...
6602 Value *NV = NC;
6603 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
6604 if (NV->getType() != Type::VoidTy) {
6605 NV = NC = new CastInst(NC, Caller->getType(), "tmp");
Chris Lattner686767f2003-10-30 00:46:41 +00006606
6607 // If this is an invoke instruction, we should insert it after the first
6608 // non-phi, instruction in the normal successor block.
6609 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
6610 BasicBlock::iterator I = II->getNormalDest()->begin();
6611 while (isa<PHINode>(I)) ++I;
6612 InsertNewInstBefore(NC, *I);
6613 } else {
6614 // Otherwise, it's a call, just insert cast right after the call instr
6615 InsertNewInstBefore(NC, *Caller);
6616 }
Chris Lattner51ea1272004-02-28 05:22:00 +00006617 AddUsersToWorkList(*Caller);
Chris Lattner970c33a2003-06-19 17:00:31 +00006618 } else {
Chris Lattnere29d6342004-10-17 21:22:38 +00006619 NV = UndefValue::get(Caller->getType());
Chris Lattner970c33a2003-06-19 17:00:31 +00006620 }
6621 }
6622
6623 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
6624 Caller->replaceAllUsesWith(NV);
6625 Caller->getParent()->getInstList().erase(Caller);
6626 removeFromWorkList(Caller);
6627 return true;
6628}
6629
6630
Chris Lattner7515cab2004-11-14 19:13:23 +00006631// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
6632// operator and they all are only used by the PHI, PHI together their
6633// inputs, and do the operation once, to the result of the PHI.
6634Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
6635 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
6636
6637 // Scan the instruction, looking for input operations that can be folded away.
6638 // If all input operands to the phi are the same instruction (e.g. a cast from
6639 // the same type or "+42") we can pull the operation through the PHI, reducing
6640 // code size and simplifying code.
6641 Constant *ConstantOp = 0;
6642 const Type *CastSrcTy = 0;
6643 if (isa<CastInst>(FirstInst)) {
6644 CastSrcTy = FirstInst->getOperand(0)->getType();
6645 } else if (isa<BinaryOperator>(FirstInst) || isa<ShiftInst>(FirstInst)) {
6646 // Can fold binop or shift if the RHS is a constant.
6647 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
6648 if (ConstantOp == 0) return 0;
6649 } else {
6650 return 0; // Cannot fold this operation.
6651 }
6652
6653 // Check to see if all arguments are the same operation.
6654 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
6655 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
6656 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
6657 if (!I->hasOneUse() || I->getOpcode() != FirstInst->getOpcode())
6658 return 0;
6659 if (CastSrcTy) {
6660 if (I->getOperand(0)->getType() != CastSrcTy)
6661 return 0; // Cast operation must match.
6662 } else if (I->getOperand(1) != ConstantOp) {
6663 return 0;
6664 }
6665 }
6666
6667 // Okay, they are all the same operation. Create a new PHI node of the
6668 // correct type, and PHI together all of the LHS's of the instructions.
6669 PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
6670 PN.getName()+".in");
Chris Lattnerd8e20182005-01-29 00:39:08 +00006671 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattner46dd5a62004-11-14 19:29:34 +00006672
6673 Value *InVal = FirstInst->getOperand(0);
6674 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattner7515cab2004-11-14 19:13:23 +00006675
6676 // Add all operands to the new PHI.
Chris Lattner46dd5a62004-11-14 19:29:34 +00006677 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
6678 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
6679 if (NewInVal != InVal)
6680 InVal = 0;
6681 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
6682 }
6683
6684 Value *PhiVal;
6685 if (InVal) {
6686 // The new PHI unions all of the same values together. This is really
6687 // common, so we handle it intelligently here for compile-time speed.
6688 PhiVal = InVal;
6689 delete NewPN;
6690 } else {
6691 InsertNewInstBefore(NewPN, PN);
6692 PhiVal = NewPN;
6693 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00006694
Chris Lattner7515cab2004-11-14 19:13:23 +00006695 // Insert and return the new operation.
6696 if (isa<CastInst>(FirstInst))
Chris Lattner46dd5a62004-11-14 19:29:34 +00006697 return new CastInst(PhiVal, PN.getType());
Chris Lattner7515cab2004-11-14 19:13:23 +00006698 else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattner46dd5a62004-11-14 19:29:34 +00006699 return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattner7515cab2004-11-14 19:13:23 +00006700 else
6701 return new ShiftInst(cast<ShiftInst>(FirstInst)->getOpcode(),
Chris Lattner46dd5a62004-11-14 19:29:34 +00006702 PhiVal, ConstantOp);
Chris Lattner7515cab2004-11-14 19:13:23 +00006703}
Chris Lattner48a44f72002-05-02 17:06:02 +00006704
Chris Lattner71536432005-01-17 05:10:15 +00006705/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
6706/// that is dead.
6707static bool DeadPHICycle(PHINode *PN, std::set<PHINode*> &PotentiallyDeadPHIs) {
6708 if (PN->use_empty()) return true;
6709 if (!PN->hasOneUse()) return false;
6710
6711 // Remember this node, and if we find the cycle, return.
6712 if (!PotentiallyDeadPHIs.insert(PN).second)
6713 return true;
6714
6715 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
6716 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanb1c93172005-04-21 23:48:37 +00006717
Chris Lattner71536432005-01-17 05:10:15 +00006718 return false;
6719}
6720
Chris Lattnerbbbdd852002-05-06 18:06:38 +00006721// PHINode simplification
6722//
Chris Lattner113f4f42002-06-25 16:13:24 +00006723Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonbbf89902006-07-10 22:15:25 +00006724 // If LCSSA is around, don't mess with Phi nodes
6725 if (mustPreserveAnalysisID(LCSSAID)) return 0;
Owen Andersona6968f82006-07-10 19:03:49 +00006726
Owen Andersonae8aa642006-07-10 22:03:18 +00006727 if (Value *V = PN.hasConstantValue())
6728 return ReplaceInstUsesWith(PN, V);
6729
6730 // If the only user of this instruction is a cast instruction, and all of the
6731 // incoming values are constants, change this PHI to merge together the casted
6732 // constants.
6733 if (PN.hasOneUse())
6734 if (CastInst *CI = dyn_cast<CastInst>(PN.use_back()))
6735 if (CI->getType() != PN.getType()) { // noop casts will be folded
6736 bool AllConstant = true;
6737 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
6738 if (!isa<Constant>(PN.getIncomingValue(i))) {
6739 AllConstant = false;
6740 break;
6741 }
6742 if (AllConstant) {
6743 // Make a new PHI with all casted values.
6744 PHINode *New = new PHINode(CI->getType(), PN.getName(), &PN);
6745 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
6746 Constant *OldArg = cast<Constant>(PN.getIncomingValue(i));
6747 New->addIncoming(ConstantExpr::getCast(OldArg, New->getType()),
6748 PN.getIncomingBlock(i));
6749 }
6750
6751 // Update the cast instruction.
6752 CI->setOperand(0, New);
6753 WorkList.push_back(CI); // revisit the cast instruction to fold.
6754 WorkList.push_back(New); // Make sure to revisit the new Phi
6755 return &PN; // PN is now dead!
6756 }
6757 }
6758
6759 // If all PHI operands are the same operation, pull them through the PHI,
6760 // reducing code size.
6761 if (isa<Instruction>(PN.getIncomingValue(0)) &&
6762 PN.getIncomingValue(0)->hasOneUse())
6763 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
6764 return Result;
6765
6766 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
6767 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
6768 // PHI)... break the cycle.
6769 if (PN.hasOneUse())
6770 if (PHINode *PU = dyn_cast<PHINode>(PN.use_back())) {
6771 std::set<PHINode*> PotentiallyDeadPHIs;
6772 PotentiallyDeadPHIs.insert(&PN);
6773 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
6774 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
6775 }
6776
Chris Lattner91daeb52003-12-19 05:58:40 +00006777 return 0;
Chris Lattnerbbbdd852002-05-06 18:06:38 +00006778}
6779
Chris Lattner69193f92004-04-05 01:30:19 +00006780static Value *InsertSignExtendToPtrTy(Value *V, const Type *DTy,
6781 Instruction *InsertPoint,
6782 InstCombiner *IC) {
6783 unsigned PS = IC->getTargetData().getPointerSize();
6784 const Type *VTy = V->getType();
Chris Lattner69193f92004-04-05 01:30:19 +00006785 if (!VTy->isSigned() && VTy->getPrimitiveSize() < PS)
6786 // We must insert a cast to ensure we sign-extend.
6787 V = IC->InsertNewInstBefore(new CastInst(V, VTy->getSignedVersion(),
6788 V->getName()), *InsertPoint);
6789 return IC->InsertNewInstBefore(new CastInst(V, DTy, V->getName()),
6790 *InsertPoint);
6791}
6792
Chris Lattner48a44f72002-05-02 17:06:02 +00006793
Chris Lattner113f4f42002-06-25 16:13:24 +00006794Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner5f667a62004-05-07 22:09:22 +00006795 Value *PtrOp = GEP.getOperand(0);
Chris Lattner471bd762003-05-22 19:07:21 +00006796 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
Chris Lattner113f4f42002-06-25 16:13:24 +00006797 // If so, eliminate the noop.
Chris Lattner8d0bacb2004-02-22 05:25:17 +00006798 if (GEP.getNumOperands() == 1)
Chris Lattner5f667a62004-05-07 22:09:22 +00006799 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner8d0bacb2004-02-22 05:25:17 +00006800
Chris Lattner81a7a232004-10-16 18:11:37 +00006801 if (isa<UndefValue>(GEP.getOperand(0)))
6802 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
6803
Chris Lattner8d0bacb2004-02-22 05:25:17 +00006804 bool HasZeroPointerIndex = false;
6805 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
6806 HasZeroPointerIndex = C->isNullValue();
6807
6808 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner5f667a62004-05-07 22:09:22 +00006809 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner48a44f72002-05-02 17:06:02 +00006810
Chris Lattner69193f92004-04-05 01:30:19 +00006811 // Eliminate unneeded casts for indices.
6812 bool MadeChange = false;
Chris Lattner2b2412d2004-04-07 18:38:20 +00006813 gep_type_iterator GTI = gep_type_begin(GEP);
6814 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI)
6815 if (isa<SequentialType>(*GTI)) {
6816 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
6817 Value *Src = CI->getOperand(0);
6818 const Type *SrcTy = Src->getType();
6819 const Type *DestTy = CI->getType();
6820 if (Src->getType()->isInteger()) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00006821 if (SrcTy->getPrimitiveSizeInBits() ==
6822 DestTy->getPrimitiveSizeInBits()) {
Chris Lattner2b2412d2004-04-07 18:38:20 +00006823 // We can always eliminate a cast from ulong or long to the other.
6824 // We can always eliminate a cast from uint to int or the other on
6825 // 32-bit pointer platforms.
Chris Lattnerd1f46d32005-04-24 06:59:08 +00006826 if (DestTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()){
Chris Lattner2b2412d2004-04-07 18:38:20 +00006827 MadeChange = true;
6828 GEP.setOperand(i, Src);
6829 }
6830 } else if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
6831 SrcTy->getPrimitiveSize() == 4) {
6832 // We can always eliminate a cast from int to [u]long. We can
6833 // eliminate a cast from uint to [u]long iff the target is a 32-bit
6834 // pointer target.
Misha Brukmanb1c93172005-04-21 23:48:37 +00006835 if (SrcTy->isSigned() ||
Chris Lattnerd1f46d32005-04-24 06:59:08 +00006836 SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
Chris Lattner2b2412d2004-04-07 18:38:20 +00006837 MadeChange = true;
6838 GEP.setOperand(i, Src);
6839 }
Chris Lattner69193f92004-04-05 01:30:19 +00006840 }
6841 }
6842 }
Chris Lattner2b2412d2004-04-07 18:38:20 +00006843 // If we are using a wider index than needed for this platform, shrink it
6844 // to what we need. If the incoming value needs a cast instruction,
6845 // insert it. This explicit cast can make subsequent optimizations more
6846 // obvious.
6847 Value *Op = GEP.getOperand(i);
6848 if (Op->getType()->getPrimitiveSize() > TD->getPointerSize())
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00006849 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner44d0b952004-07-20 01:48:15 +00006850 GEP.setOperand(i, ConstantExpr::getCast(C,
6851 TD->getIntPtrType()->getSignedVersion()));
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00006852 MadeChange = true;
6853 } else {
Chris Lattner2b2412d2004-04-07 18:38:20 +00006854 Op = InsertNewInstBefore(new CastInst(Op, TD->getIntPtrType(),
6855 Op->getName()), GEP);
6856 GEP.setOperand(i, Op);
6857 MadeChange = true;
6858 }
Chris Lattner44d0b952004-07-20 01:48:15 +00006859
6860 // If this is a constant idx, make sure to canonicalize it to be a signed
6861 // operand, otherwise CSE and other optimizations are pessimized.
6862 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op)) {
6863 GEP.setOperand(i, ConstantExpr::getCast(CUI,
6864 CUI->getType()->getSignedVersion()));
6865 MadeChange = true;
6866 }
Chris Lattner69193f92004-04-05 01:30:19 +00006867 }
6868 if (MadeChange) return &GEP;
6869
Chris Lattnerae7a0d32002-08-02 19:29:35 +00006870 // Combine Indices - If the source pointer to this getelementptr instruction
6871 // is a getelementptr instruction, combine the indices of the two
6872 // getelementptr instructions into a single instruction.
6873 //
Chris Lattner57c67b02004-03-25 22:59:29 +00006874 std::vector<Value*> SrcGEPOperands;
Chris Lattner0798af32005-01-13 20:14:25 +00006875 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattner57c67b02004-03-25 22:59:29 +00006876 SrcGEPOperands.assign(Src->op_begin(), Src->op_end());
Chris Lattner57c67b02004-03-25 22:59:29 +00006877
6878 if (!SrcGEPOperands.empty()) {
Chris Lattner5f667a62004-05-07 22:09:22 +00006879 // Note that if our source is a gep chain itself that we wait for that
6880 // chain to be resolved before we perform this transformation. This
6881 // avoids us creating a TON of code in some cases.
6882 //
6883 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
6884 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
6885 return 0; // Wait until our source is folded to completion.
6886
Chris Lattnerae7a0d32002-08-02 19:29:35 +00006887 std::vector<Value *> Indices;
Chris Lattner5f667a62004-05-07 22:09:22 +00006888
6889 // Find out whether the last index in the source GEP is a sequential idx.
6890 bool EndsWithSequential = false;
6891 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
6892 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattner8ec5f882004-05-08 22:41:42 +00006893 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00006894
Chris Lattnerae7a0d32002-08-02 19:29:35 +00006895 // Can we combine the two pointer arithmetics offsets?
Chris Lattner5f667a62004-05-07 22:09:22 +00006896 if (EndsWithSequential) {
Chris Lattner235af562003-03-05 22:33:14 +00006897 // Replace: gep (gep %P, long B), long A, ...
6898 // With: T = long A+B; gep %P, T, ...
6899 //
Chris Lattner5f667a62004-05-07 22:09:22 +00006900 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner69193f92004-04-05 01:30:19 +00006901 if (SO1 == Constant::getNullValue(SO1->getType())) {
6902 Sum = GO1;
6903 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
6904 Sum = SO1;
6905 } else {
6906 // If they aren't the same type, convert both to an integer of the
6907 // target's pointer size.
6908 if (SO1->getType() != GO1->getType()) {
6909 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
6910 SO1 = ConstantExpr::getCast(SO1C, GO1->getType());
6911 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
6912 GO1 = ConstantExpr::getCast(GO1C, SO1->getType());
6913 } else {
6914 unsigned PS = TD->getPointerSize();
Chris Lattner69193f92004-04-05 01:30:19 +00006915 if (SO1->getType()->getPrimitiveSize() == PS) {
6916 // Convert GO1 to SO1's type.
6917 GO1 = InsertSignExtendToPtrTy(GO1, SO1->getType(), &GEP, this);
6918
6919 } else if (GO1->getType()->getPrimitiveSize() == PS) {
6920 // Convert SO1 to GO1's type.
6921 SO1 = InsertSignExtendToPtrTy(SO1, GO1->getType(), &GEP, this);
6922 } else {
6923 const Type *PT = TD->getIntPtrType();
6924 SO1 = InsertSignExtendToPtrTy(SO1, PT, &GEP, this);
6925 GO1 = InsertSignExtendToPtrTy(GO1, PT, &GEP, this);
6926 }
6927 }
6928 }
Chris Lattner5f667a62004-05-07 22:09:22 +00006929 if (isa<Constant>(SO1) && isa<Constant>(GO1))
6930 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
6931 else {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00006932 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
6933 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner5f667a62004-05-07 22:09:22 +00006934 }
Chris Lattner69193f92004-04-05 01:30:19 +00006935 }
Chris Lattner5f667a62004-05-07 22:09:22 +00006936
6937 // Recycle the GEP we already have if possible.
6938 if (SrcGEPOperands.size() == 2) {
6939 GEP.setOperand(0, SrcGEPOperands[0]);
6940 GEP.setOperand(1, Sum);
6941 return &GEP;
6942 } else {
6943 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
6944 SrcGEPOperands.end()-1);
6945 Indices.push_back(Sum);
6946 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
6947 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00006948 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner69193f92004-04-05 01:30:19 +00006949 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00006950 SrcGEPOperands.size() != 1) {
Chris Lattnerae7a0d32002-08-02 19:29:35 +00006951 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattner57c67b02004-03-25 22:59:29 +00006952 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
6953 SrcGEPOperands.end());
Chris Lattnerae7a0d32002-08-02 19:29:35 +00006954 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
6955 }
6956
6957 if (!Indices.empty())
Chris Lattner57c67b02004-03-25 22:59:29 +00006958 return new GetElementPtrInst(SrcGEPOperands[0], Indices, GEP.getName());
Chris Lattnerc59af1d2002-08-17 22:21:59 +00006959
Chris Lattner5f667a62004-05-07 22:09:22 +00006960 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattnerc59af1d2002-08-17 22:21:59 +00006961 // GEP of global variable. If all of the indices for this GEP are
6962 // constants, we can promote this to a constexpr instead of an instruction.
6963
6964 // Scan for nonconstants...
6965 std::vector<Constant*> Indices;
6966 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
6967 for (; I != E && isa<Constant>(*I); ++I)
6968 Indices.push_back(cast<Constant>(*I));
6969
6970 if (I == E) { // If they are all constants...
Chris Lattnerf3edc492004-07-18 18:59:44 +00006971 Constant *CE = ConstantExpr::getGetElementPtr(GV, Indices);
Chris Lattnerc59af1d2002-08-17 22:21:59 +00006972
6973 // Replace all uses of the GEP with the new constexpr...
6974 return ReplaceInstUsesWith(GEP, CE);
6975 }
Chris Lattner567b81f2005-09-13 00:40:14 +00006976 } else if (Value *X = isCast(PtrOp)) { // Is the operand a cast?
6977 if (!isa<PointerType>(X->getType())) {
6978 // Not interesting. Source pointer must be a cast from pointer.
6979 } else if (HasZeroPointerIndex) {
6980 // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
6981 // into : GEP [10 x ubyte]* X, long 0, ...
6982 //
6983 // This occurs when the program declares an array extern like "int X[];"
6984 //
6985 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
6986 const PointerType *XTy = cast<PointerType>(X->getType());
6987 if (const ArrayType *XATy =
6988 dyn_cast<ArrayType>(XTy->getElementType()))
6989 if (const ArrayType *CATy =
6990 dyn_cast<ArrayType>(CPTy->getElementType()))
6991 if (CATy->getElementType() == XATy->getElementType()) {
6992 // At this point, we know that the cast source type is a pointer
6993 // to an array of the same type as the destination pointer
6994 // array. Because the array type is never stepped over (there
6995 // is a leading zero) we can fold the cast into this GEP.
6996 GEP.setOperand(0, X);
6997 return &GEP;
6998 }
6999 } else if (GEP.getNumOperands() == 2) {
7000 // Transform things like:
Chris Lattner2a893292005-09-13 18:36:04 +00007001 // %t = getelementptr ubyte* cast ([2 x int]* %str to uint*), uint %V
7002 // into: %t1 = getelementptr [2 x int*]* %str, int 0, uint %V; cast
Chris Lattner567b81f2005-09-13 00:40:14 +00007003 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
7004 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
7005 if (isa<ArrayType>(SrcElTy) &&
7006 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
7007 TD->getTypeSize(ResElTy)) {
7008 Value *V = InsertNewInstBefore(
7009 new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
7010 GEP.getOperand(1), GEP.getName()), GEP);
7011 return new CastInst(V, GEP.getType());
Chris Lattner8d0bacb2004-02-22 05:25:17 +00007012 }
Chris Lattner2a893292005-09-13 18:36:04 +00007013
7014 // Transform things like:
7015 // getelementptr sbyte* cast ([100 x double]* X to sbyte*), int %tmp
7016 // (where tmp = 8*tmp2) into:
7017 // getelementptr [100 x double]* %arr, int 0, int %tmp.2
7018
7019 if (isa<ArrayType>(SrcElTy) &&
7020 (ResElTy == Type::SByteTy || ResElTy == Type::UByteTy)) {
7021 uint64_t ArrayEltSize =
7022 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType());
7023
7024 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
7025 // allow either a mul, shift, or constant here.
7026 Value *NewIdx = 0;
7027 ConstantInt *Scale = 0;
7028 if (ArrayEltSize == 1) {
7029 NewIdx = GEP.getOperand(1);
7030 Scale = ConstantInt::get(NewIdx->getType(), 1);
7031 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Chris Lattnera393e4d2005-09-14 17:32:56 +00007032 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner2a893292005-09-13 18:36:04 +00007033 Scale = CI;
7034 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
7035 if (Inst->getOpcode() == Instruction::Shl &&
7036 isa<ConstantInt>(Inst->getOperand(1))) {
7037 unsigned ShAmt =cast<ConstantUInt>(Inst->getOperand(1))->getValue();
7038 if (Inst->getType()->isSigned())
7039 Scale = ConstantSInt::get(Inst->getType(), 1ULL << ShAmt);
7040 else
7041 Scale = ConstantUInt::get(Inst->getType(), 1ULL << ShAmt);
7042 NewIdx = Inst->getOperand(0);
7043 } else if (Inst->getOpcode() == Instruction::Mul &&
7044 isa<ConstantInt>(Inst->getOperand(1))) {
7045 Scale = cast<ConstantInt>(Inst->getOperand(1));
7046 NewIdx = Inst->getOperand(0);
7047 }
7048 }
7049
7050 // If the index will be to exactly the right offset with the scale taken
7051 // out, perform the transformation.
7052 if (Scale && Scale->getRawValue() % ArrayEltSize == 0) {
7053 if (ConstantSInt *C = dyn_cast<ConstantSInt>(Scale))
7054 Scale = ConstantSInt::get(C->getType(),
Chris Lattnera393e4d2005-09-14 17:32:56 +00007055 (int64_t)C->getRawValue() /
7056 (int64_t)ArrayEltSize);
Chris Lattner2a893292005-09-13 18:36:04 +00007057 else
7058 Scale = ConstantUInt::get(Scale->getType(),
7059 Scale->getRawValue() / ArrayEltSize);
7060 if (Scale->getRawValue() != 1) {
7061 Constant *C = ConstantExpr::getCast(Scale, NewIdx->getType());
7062 Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
7063 NewIdx = InsertNewInstBefore(Sc, GEP);
7064 }
7065
7066 // Insert the new GEP instruction.
7067 Instruction *Idx =
7068 new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
7069 NewIdx, GEP.getName());
7070 Idx = InsertNewInstBefore(Idx, GEP);
7071 return new CastInst(Idx, GEP.getType());
7072 }
7073 }
Chris Lattner8d0bacb2004-02-22 05:25:17 +00007074 }
Chris Lattnerca081252001-12-14 16:52:21 +00007075 }
7076
Chris Lattnerca081252001-12-14 16:52:21 +00007077 return 0;
7078}
7079
Chris Lattner1085bdf2002-11-04 16:18:53 +00007080Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
7081 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
7082 if (AI.isArrayAllocation()) // Check C != 1
7083 if (const ConstantUInt *C = dyn_cast<ConstantUInt>(AI.getArraySize())) {
7084 const Type *NewTy = ArrayType::get(AI.getAllocatedType(), C->getValue());
Chris Lattnera2620ac2002-11-09 00:49:43 +00007085 AllocationInst *New = 0;
Chris Lattner1085bdf2002-11-04 16:18:53 +00007086
7087 // Create and insert the replacement instruction...
7088 if (isa<MallocInst>(AI))
Nate Begeman848622f2005-11-05 09:21:28 +00007089 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00007090 else {
7091 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Nate Begeman848622f2005-11-05 09:21:28 +00007092 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00007093 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00007094
7095 InsertNewInstBefore(New, AI);
Misha Brukmanb1c93172005-04-21 23:48:37 +00007096
Chris Lattner1085bdf2002-11-04 16:18:53 +00007097 // Scan to the end of the allocation instructions, to skip over a block of
7098 // allocas if possible...
7099 //
7100 BasicBlock::iterator It = New;
7101 while (isa<AllocationInst>(*It)) ++It;
7102
7103 // Now that I is pointing to the first non-allocation-inst in the block,
7104 // insert our getelementptr instruction...
7105 //
Chris Lattner809dfac2005-05-04 19:10:26 +00007106 Value *NullIdx = Constant::getNullValue(Type::IntTy);
7107 Value *V = new GetElementPtrInst(New, NullIdx, NullIdx,
7108 New->getName()+".sub", It);
Chris Lattner1085bdf2002-11-04 16:18:53 +00007109
7110 // Now make everything use the getelementptr instead of the original
7111 // allocation.
Chris Lattnerabb77c92004-03-19 06:08:10 +00007112 return ReplaceInstUsesWith(AI, V);
Chris Lattner81a7a232004-10-16 18:11:37 +00007113 } else if (isa<UndefValue>(AI.getArraySize())) {
7114 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner1085bdf2002-11-04 16:18:53 +00007115 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00007116
7117 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
7118 // Note that we only do this for alloca's, because malloc should allocate and
7119 // return a unique pointer, even for a zero byte allocation.
Misha Brukmanb1c93172005-04-21 23:48:37 +00007120 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
Chris Lattner49df6ce2004-07-02 22:55:47 +00007121 TD->getTypeSize(AI.getAllocatedType()) == 0)
Chris Lattnerabb77c92004-03-19 06:08:10 +00007122 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
7123
Chris Lattner1085bdf2002-11-04 16:18:53 +00007124 return 0;
7125}
7126
Chris Lattner8427bff2003-12-07 01:24:23 +00007127Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
7128 Value *Op = FI.getOperand(0);
7129
7130 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
7131 if (CastInst *CI = dyn_cast<CastInst>(Op))
7132 if (isa<PointerType>(CI->getOperand(0)->getType())) {
7133 FI.setOperand(0, CI->getOperand(0));
7134 return &FI;
7135 }
7136
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007137 // free undef -> unreachable.
7138 if (isa<UndefValue>(Op)) {
7139 // Insert a new store to null because we cannot modify the CFG here.
Chris Lattner6ab03f62006-09-28 23:35:22 +00007140 new StoreInst(ConstantBool::getTrue(),
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007141 UndefValue::get(PointerType::get(Type::BoolTy)), &FI);
7142 return EraseInstFromFunction(FI);
7143 }
7144
Chris Lattnerf3a36602004-02-28 04:57:37 +00007145 // If we have 'free null' delete the instruction. This can happen in stl code
7146 // when lots of inlining happens.
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007147 if (isa<ConstantPointerNull>(Op))
Chris Lattner51ea1272004-02-28 05:22:00 +00007148 return EraseInstFromFunction(FI);
Chris Lattnerf3a36602004-02-28 04:57:37 +00007149
Chris Lattner8427bff2003-12-07 01:24:23 +00007150 return 0;
7151}
7152
7153
Chris Lattner72684fe2005-01-31 05:51:45 +00007154/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Chris Lattner35e24772004-07-13 01:49:43 +00007155static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
7156 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00007157 Value *CastOp = CI->getOperand(0);
Chris Lattner35e24772004-07-13 01:49:43 +00007158
7159 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00007160 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Chris Lattner35e24772004-07-13 01:49:43 +00007161 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00007162
Chris Lattnerebca4762006-04-02 05:37:12 +00007163 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
7164 isa<PackedType>(DestPTy)) {
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00007165 // If the source is an array, the code below will not succeed. Check to
7166 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
7167 // constants.
7168 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
7169 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
7170 if (ASrcTy->getNumElements() != 0) {
7171 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
7172 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
7173 SrcTy = cast<PointerType>(CastOp->getType());
7174 SrcPTy = SrcTy->getElementType();
7175 }
7176
Chris Lattnerebca4762006-04-02 05:37:12 +00007177 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
7178 isa<PackedType>(SrcPTy)) &&
Chris Lattnerecfa9b52005-03-29 06:37:47 +00007179 // Do not allow turning this into a load of an integer, which is then
7180 // casted to a pointer, this pessimizes pointer analysis a lot.
7181 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00007182 IC.getTargetData().getTypeSize(SrcPTy) ==
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00007183 IC.getTargetData().getTypeSize(DestPTy)) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00007184
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00007185 // Okay, we are casting from one integer or pointer type to another of
7186 // the same size. Instead of casting the pointer before the load, cast
7187 // the result of the loaded value.
7188 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
7189 CI->getName(),
7190 LI.isVolatile()),LI);
7191 // Now cast the result of the load.
7192 return new CastInst(NewLoad, LI.getType());
7193 }
Chris Lattner35e24772004-07-13 01:49:43 +00007194 }
7195 }
7196 return 0;
7197}
7198
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00007199/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattnere6f13092004-09-19 19:18:10 +00007200/// from this value cannot trap. If it is not obviously safe to load from the
7201/// specified pointer, we do a quick local scan of the basic block containing
7202/// ScanFrom, to determine if the address is already accessed.
7203static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
7204 // If it is an alloca or global variable, it is always safe to load from.
7205 if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
7206
7207 // Otherwise, be a little bit agressive by scanning the local block where we
7208 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00007209 // from/to. If so, the previous load or store would have already trapped,
7210 // so there is no harm doing an extra load (also, CSE will later eliminate
7211 // the load entirely).
Chris Lattnere6f13092004-09-19 19:18:10 +00007212 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
7213
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00007214 while (BBI != E) {
Chris Lattnere6f13092004-09-19 19:18:10 +00007215 --BBI;
7216
7217 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
7218 if (LI->getOperand(0) == V) return true;
7219 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
7220 if (SI->getOperand(1) == V) return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +00007221
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00007222 }
Chris Lattnere6f13092004-09-19 19:18:10 +00007223 return false;
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00007224}
7225
Chris Lattner0f1d8a32003-06-26 05:06:25 +00007226Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
7227 Value *Op = LI.getOperand(0);
Chris Lattner7e8af382004-01-12 04:13:56 +00007228
Chris Lattnera9d84e32005-05-01 04:24:53 +00007229 // load (cast X) --> cast (load X) iff safe
7230 if (CastInst *CI = dyn_cast<CastInst>(Op))
7231 if (Instruction *Res = InstCombineLoadCast(*this, LI))
7232 return Res;
7233
7234 // None of the following transforms are legal for volatile loads.
7235 if (LI.isVolatile()) return 0;
Chris Lattnerb990f7d2005-09-12 22:00:15 +00007236
Chris Lattnerb990f7d2005-09-12 22:00:15 +00007237 if (&LI.getParent()->front() != &LI) {
7238 BasicBlock::iterator BBI = &LI; --BBI;
Chris Lattnere0bfdf12005-09-12 22:21:03 +00007239 // If the instruction immediately before this is a store to the same
7240 // address, do a simple form of store->load forwarding.
Chris Lattnerb990f7d2005-09-12 22:00:15 +00007241 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
7242 if (SI->getOperand(1) == LI.getOperand(0))
7243 return ReplaceInstUsesWith(LI, SI->getOperand(0));
Chris Lattnere0bfdf12005-09-12 22:21:03 +00007244 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
7245 if (LIB->getOperand(0) == LI.getOperand(0))
7246 return ReplaceInstUsesWith(LI, LIB);
Chris Lattnerb990f7d2005-09-12 22:00:15 +00007247 }
Chris Lattnera9d84e32005-05-01 04:24:53 +00007248
7249 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op))
7250 if (isa<ConstantPointerNull>(GEPI->getOperand(0)) ||
7251 isa<UndefValue>(GEPI->getOperand(0))) {
7252 // Insert a new store to null instruction before the load to indicate
7253 // that this code is not reachable. We do this instead of inserting
7254 // an unreachable instruction directly because we cannot modify the
7255 // CFG.
7256 new StoreInst(UndefValue::get(LI.getType()),
7257 Constant::getNullValue(Op->getType()), &LI);
7258 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
7259 }
7260
Chris Lattner81a7a232004-10-16 18:11:37 +00007261 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattnera9d84e32005-05-01 04:24:53 +00007262 // load null/undef -> undef
7263 if ((C->isNullValue() || isa<UndefValue>(C))) {
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007264 // Insert a new store to null instruction before the load to indicate that
7265 // this code is not reachable. We do this instead of inserting an
7266 // unreachable instruction directly because we cannot modify the CFG.
Chris Lattnera9d84e32005-05-01 04:24:53 +00007267 new StoreInst(UndefValue::get(LI.getType()),
7268 Constant::getNullValue(Op->getType()), &LI);
Chris Lattner81a7a232004-10-16 18:11:37 +00007269 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007270 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00007271
Chris Lattner81a7a232004-10-16 18:11:37 +00007272 // Instcombine load (constant global) into the value loaded.
7273 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
7274 if (GV->isConstant() && !GV->isExternal())
7275 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanb1c93172005-04-21 23:48:37 +00007276
Chris Lattner81a7a232004-10-16 18:11:37 +00007277 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
7278 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
7279 if (CE->getOpcode() == Instruction::GetElementPtr) {
7280 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
7281 if (GV->isConstant() && !GV->isExternal())
Chris Lattner0b011ec2005-09-26 05:28:06 +00007282 if (Constant *V =
7283 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
Chris Lattner81a7a232004-10-16 18:11:37 +00007284 return ReplaceInstUsesWith(LI, V);
Chris Lattnera9d84e32005-05-01 04:24:53 +00007285 if (CE->getOperand(0)->isNullValue()) {
7286 // Insert a new store to null instruction before the load to indicate
7287 // that this code is not reachable. We do this instead of inserting
7288 // an unreachable instruction directly because we cannot modify the
7289 // CFG.
7290 new StoreInst(UndefValue::get(LI.getType()),
7291 Constant::getNullValue(Op->getType()), &LI);
7292 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
7293 }
7294
Chris Lattner81a7a232004-10-16 18:11:37 +00007295 } else if (CE->getOpcode() == Instruction::Cast) {
7296 if (Instruction *Res = InstCombineLoadCast(*this, LI))
7297 return Res;
7298 }
7299 }
Chris Lattnere228ee52004-04-08 20:39:49 +00007300
Chris Lattnera9d84e32005-05-01 04:24:53 +00007301 if (Op->hasOneUse()) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00007302 // Change select and PHI nodes to select values instead of addresses: this
7303 // helps alias analysis out a lot, allows many others simplifications, and
7304 // exposes redundancy in the code.
7305 //
7306 // Note that we cannot do the transformation unless we know that the
7307 // introduced loads cannot trap! Something like this is valid as long as
7308 // the condition is always false: load (select bool %C, int* null, int* %G),
7309 // but it would not be valid if we transformed it to load from null
7310 // unconditionally.
7311 //
7312 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
7313 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattnere6f13092004-09-19 19:18:10 +00007314 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
7315 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00007316 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner42618552004-09-20 10:15:10 +00007317 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00007318 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner42618552004-09-20 10:15:10 +00007319 SI->getOperand(2)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00007320 return new SelectInst(SI->getCondition(), V1, V2);
7321 }
7322
Chris Lattnerbdcf41a2004-09-23 15:46:00 +00007323 // load (select (cond, null, P)) -> load P
7324 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
7325 if (C->isNullValue()) {
7326 LI.setOperand(0, SI->getOperand(2));
7327 return &LI;
7328 }
7329
7330 // load (select (cond, P, null)) -> load P
7331 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
7332 if (C->isNullValue()) {
7333 LI.setOperand(0, SI->getOperand(1));
7334 return &LI;
7335 }
7336
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00007337 } else if (PHINode *PN = dyn_cast<PHINode>(Op)) {
7338 // load (phi (&V1, &V2, &V3)) --> phi(load &V1, load &V2, load &V3)
Chris Lattner42618552004-09-20 10:15:10 +00007339 bool Safe = PN->getParent() == LI.getParent();
7340
7341 // Scan all of the instructions between the PHI and the load to make
7342 // sure there are no instructions that might possibly alter the value
7343 // loaded from the PHI.
7344 if (Safe) {
7345 BasicBlock::iterator I = &LI;
7346 for (--I; !isa<PHINode>(I); --I)
7347 if (isa<StoreInst>(I) || isa<CallInst>(I)) {
7348 Safe = false;
7349 break;
7350 }
7351 }
7352
7353 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e && Safe; ++i)
Chris Lattnere6f13092004-09-19 19:18:10 +00007354 if (!isSafeToLoadUnconditionally(PN->getIncomingValue(i),
Chris Lattner42618552004-09-20 10:15:10 +00007355 PN->getIncomingBlock(i)->getTerminator()))
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00007356 Safe = false;
Chris Lattner42618552004-09-20 10:15:10 +00007357
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00007358 if (Safe) {
7359 // Create the PHI.
7360 PHINode *NewPN = new PHINode(LI.getType(), PN->getName());
7361 InsertNewInstBefore(NewPN, *PN);
7362 std::map<BasicBlock*,Value*> LoadMap; // Don't insert duplicate loads
7363
7364 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
7365 BasicBlock *BB = PN->getIncomingBlock(i);
7366 Value *&TheLoad = LoadMap[BB];
7367 if (TheLoad == 0) {
7368 Value *InVal = PN->getIncomingValue(i);
7369 TheLoad = InsertNewInstBefore(new LoadInst(InVal,
7370 InVal->getName()+".val"),
7371 *BB->getTerminator());
7372 }
7373 NewPN->addIncoming(TheLoad, BB);
7374 }
7375 return ReplaceInstUsesWith(LI, NewPN);
7376 }
7377 }
7378 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00007379 return 0;
7380}
7381
Chris Lattner72684fe2005-01-31 05:51:45 +00007382/// InstCombineStoreToCast - Fold 'store V, (cast P)' -> store (cast V), P'
7383/// when possible.
7384static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
7385 User *CI = cast<User>(SI.getOperand(1));
7386 Value *CastOp = CI->getOperand(0);
7387
7388 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
7389 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
7390 const Type *SrcPTy = SrcTy->getElementType();
7391
7392 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
7393 // If the source is an array, the code below will not succeed. Check to
7394 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
7395 // constants.
7396 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
7397 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
7398 if (ASrcTy->getNumElements() != 0) {
7399 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
7400 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
7401 SrcTy = cast<PointerType>(CastOp->getType());
7402 SrcPTy = SrcTy->getElementType();
7403 }
7404
7405 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00007406 IC.getTargetData().getTypeSize(SrcPTy) ==
Chris Lattner72684fe2005-01-31 05:51:45 +00007407 IC.getTargetData().getTypeSize(DestPTy)) {
7408
7409 // Okay, we are casting from one integer or pointer type to another of
7410 // the same size. Instead of casting the pointer before the store, cast
7411 // the value to be stored.
7412 Value *NewCast;
7413 if (Constant *C = dyn_cast<Constant>(SI.getOperand(0)))
7414 NewCast = ConstantExpr::getCast(C, SrcPTy);
7415 else
7416 NewCast = IC.InsertNewInstBefore(new CastInst(SI.getOperand(0),
7417 SrcPTy,
7418 SI.getOperand(0)->getName()+".c"), SI);
7419
7420 return new StoreInst(NewCast, CastOp);
7421 }
7422 }
7423 }
7424 return 0;
7425}
7426
Chris Lattner31f486c2005-01-31 05:36:43 +00007427Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
7428 Value *Val = SI.getOperand(0);
7429 Value *Ptr = SI.getOperand(1);
7430
7431 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner5997cf92006-02-08 03:25:32 +00007432 EraseInstFromFunction(SI);
Chris Lattner31f486c2005-01-31 05:36:43 +00007433 ++NumCombined;
7434 return 0;
7435 }
7436
Chris Lattner5997cf92006-02-08 03:25:32 +00007437 // Do really simple DSE, to catch cases where there are several consequtive
7438 // stores to the same location, separated by a few arithmetic operations. This
7439 // situation often occurs with bitfield accesses.
7440 BasicBlock::iterator BBI = &SI;
7441 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
7442 --ScanInsts) {
7443 --BBI;
7444
7445 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
7446 // Prev store isn't volatile, and stores to the same location?
7447 if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
7448 ++NumDeadStore;
7449 ++BBI;
7450 EraseInstFromFunction(*PrevSI);
7451 continue;
7452 }
7453 break;
7454 }
7455
Chris Lattnerdab43b22006-05-26 19:19:20 +00007456 // If this is a load, we have to stop. However, if the loaded value is from
7457 // the pointer we're loading and is producing the pointer we're storing,
7458 // then *this* store is dead (X = load P; store X -> P).
7459 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
7460 if (LI == Val && LI->getOperand(0) == Ptr) {
7461 EraseInstFromFunction(SI);
7462 ++NumCombined;
7463 return 0;
7464 }
7465 // Otherwise, this is a load from some other location. Stores before it
7466 // may not be dead.
7467 break;
7468 }
7469
Chris Lattner5997cf92006-02-08 03:25:32 +00007470 // Don't skip over loads or things that can modify memory.
Chris Lattnerdab43b22006-05-26 19:19:20 +00007471 if (BBI->mayWriteToMemory())
Chris Lattner5997cf92006-02-08 03:25:32 +00007472 break;
7473 }
7474
7475
7476 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner31f486c2005-01-31 05:36:43 +00007477
7478 // store X, null -> turns into 'unreachable' in SimplifyCFG
7479 if (isa<ConstantPointerNull>(Ptr)) {
7480 if (!isa<UndefValue>(Val)) {
7481 SI.setOperand(0, UndefValue::get(Val->getType()));
7482 if (Instruction *U = dyn_cast<Instruction>(Val))
7483 WorkList.push_back(U); // Dropped a use.
7484 ++NumCombined;
7485 }
7486 return 0; // Do not modify these!
7487 }
7488
7489 // store undef, Ptr -> noop
7490 if (isa<UndefValue>(Val)) {
Chris Lattner5997cf92006-02-08 03:25:32 +00007491 EraseInstFromFunction(SI);
Chris Lattner31f486c2005-01-31 05:36:43 +00007492 ++NumCombined;
7493 return 0;
7494 }
7495
Chris Lattner72684fe2005-01-31 05:51:45 +00007496 // If the pointer destination is a cast, see if we can fold the cast into the
7497 // source instead.
7498 if (CastInst *CI = dyn_cast<CastInst>(Ptr))
7499 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
7500 return Res;
7501 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
7502 if (CE->getOpcode() == Instruction::Cast)
7503 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
7504 return Res;
7505
Chris Lattner219175c2005-09-12 23:23:25 +00007506
7507 // If this store is the last instruction in the basic block, and if the block
7508 // ends with an unconditional branch, try to move it to the successor block.
Chris Lattner5997cf92006-02-08 03:25:32 +00007509 BBI = &SI; ++BBI;
Chris Lattner219175c2005-09-12 23:23:25 +00007510 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
7511 if (BI->isUnconditional()) {
7512 // Check to see if the successor block has exactly two incoming edges. If
7513 // so, see if the other predecessor contains a store to the same location.
7514 // if so, insert a PHI node (if needed) and move the stores down.
7515 BasicBlock *Dest = BI->getSuccessor(0);
7516
7517 pred_iterator PI = pred_begin(Dest);
7518 BasicBlock *Other = 0;
7519 if (*PI != BI->getParent())
7520 Other = *PI;
7521 ++PI;
7522 if (PI != pred_end(Dest)) {
7523 if (*PI != BI->getParent())
7524 if (Other)
7525 Other = 0;
7526 else
7527 Other = *PI;
7528 if (++PI != pred_end(Dest))
7529 Other = 0;
7530 }
7531 if (Other) { // If only one other pred...
7532 BBI = Other->getTerminator();
7533 // Make sure this other block ends in an unconditional branch and that
7534 // there is an instruction before the branch.
7535 if (isa<BranchInst>(BBI) && cast<BranchInst>(BBI)->isUnconditional() &&
7536 BBI != Other->begin()) {
7537 --BBI;
7538 StoreInst *OtherStore = dyn_cast<StoreInst>(BBI);
7539
7540 // If this instruction is a store to the same location.
7541 if (OtherStore && OtherStore->getOperand(1) == SI.getOperand(1)) {
7542 // Okay, we know we can perform this transformation. Insert a PHI
7543 // node now if we need it.
7544 Value *MergedVal = OtherStore->getOperand(0);
7545 if (MergedVal != SI.getOperand(0)) {
7546 PHINode *PN = new PHINode(MergedVal->getType(), "storemerge");
7547 PN->reserveOperandSpace(2);
7548 PN->addIncoming(SI.getOperand(0), SI.getParent());
7549 PN->addIncoming(OtherStore->getOperand(0), Other);
7550 MergedVal = InsertNewInstBefore(PN, Dest->front());
7551 }
7552
7553 // Advance to a place where it is safe to insert the new store and
7554 // insert it.
7555 BBI = Dest->begin();
7556 while (isa<PHINode>(BBI)) ++BBI;
7557 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
7558 OtherStore->isVolatile()), *BBI);
7559
7560 // Nuke the old stores.
Chris Lattner5997cf92006-02-08 03:25:32 +00007561 EraseInstFromFunction(SI);
7562 EraseInstFromFunction(*OtherStore);
Chris Lattner219175c2005-09-12 23:23:25 +00007563 ++NumCombined;
7564 return 0;
7565 }
7566 }
7567 }
7568 }
7569
Chris Lattner31f486c2005-01-31 05:36:43 +00007570 return 0;
7571}
7572
7573
Chris Lattner9eef8a72003-06-04 04:46:00 +00007574Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
7575 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4fdd96c2005-06-18 17:37:34 +00007576 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00007577 BasicBlock *TrueDest;
7578 BasicBlock *FalseDest;
7579 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
7580 !isa<Constant>(X)) {
7581 // Swap Destinations and condition...
7582 BI.setCondition(X);
7583 BI.setSuccessor(0, FalseDest);
7584 BI.setSuccessor(1, TrueDest);
7585 return &BI;
7586 }
7587
7588 // Cannonicalize setne -> seteq
7589 Instruction::BinaryOps Op; Value *Y;
7590 if (match(&BI, m_Br(m_SetCond(Op, m_Value(X), m_Value(Y)),
7591 TrueDest, FalseDest)))
7592 if ((Op == Instruction::SetNE || Op == Instruction::SetLE ||
7593 Op == Instruction::SetGE) && BI.getCondition()->hasOneUse()) {
7594 SetCondInst *I = cast<SetCondInst>(BI.getCondition());
7595 std::string Name = I->getName(); I->setName("");
7596 Instruction::BinaryOps NewOpcode = SetCondInst::getInverseCondition(Op);
7597 Value *NewSCC = BinaryOperator::create(NewOpcode, X, Y, Name, I);
Chris Lattnere967b342003-06-04 05:10:11 +00007598 // Swap Destinations and condition...
Chris Lattnerd4252a72004-07-30 07:50:03 +00007599 BI.setCondition(NewSCC);
Chris Lattnere967b342003-06-04 05:10:11 +00007600 BI.setSuccessor(0, FalseDest);
7601 BI.setSuccessor(1, TrueDest);
Chris Lattnerd4252a72004-07-30 07:50:03 +00007602 removeFromWorkList(I);
7603 I->getParent()->getInstList().erase(I);
7604 WorkList.push_back(cast<Instruction>(NewSCC));
Chris Lattnere967b342003-06-04 05:10:11 +00007605 return &BI;
7606 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00007607
Chris Lattner9eef8a72003-06-04 04:46:00 +00007608 return 0;
7609}
Chris Lattner1085bdf2002-11-04 16:18:53 +00007610
Chris Lattner4c9c20a2004-07-03 00:26:11 +00007611Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
7612 Value *Cond = SI.getCondition();
7613 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
7614 if (I->getOpcode() == Instruction::Add)
7615 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7616 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
7617 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattner81a7a232004-10-16 18:11:37 +00007618 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner4c9c20a2004-07-03 00:26:11 +00007619 AddRHS));
7620 SI.setOperand(0, I->getOperand(0));
7621 WorkList.push_back(I);
7622 return &SI;
7623 }
7624 }
7625 return 0;
7626}
7627
Chris Lattner6bc98652006-03-05 00:22:33 +00007628/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
7629/// is to leave as a vector operation.
7630static bool CheapToScalarize(Value *V, bool isConstant) {
7631 if (isa<ConstantAggregateZero>(V))
7632 return true;
7633 if (ConstantPacked *C = dyn_cast<ConstantPacked>(V)) {
7634 if (isConstant) return true;
7635 // If all elts are the same, we can extract.
7636 Constant *Op0 = C->getOperand(0);
7637 for (unsigned i = 1; i < C->getNumOperands(); ++i)
7638 if (C->getOperand(i) != Op0)
7639 return false;
7640 return true;
7641 }
7642 Instruction *I = dyn_cast<Instruction>(V);
7643 if (!I) return false;
7644
7645 // Insert element gets simplified to the inserted element or is deleted if
7646 // this is constant idx extract element and its a constant idx insertelt.
7647 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
7648 isa<ConstantInt>(I->getOperand(2)))
7649 return true;
7650 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
7651 return true;
7652 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
7653 if (BO->hasOneUse() &&
7654 (CheapToScalarize(BO->getOperand(0), isConstant) ||
7655 CheapToScalarize(BO->getOperand(1), isConstant)))
7656 return true;
7657
7658 return false;
7659}
7660
Chris Lattner12249be2006-05-25 23:48:38 +00007661/// getShuffleMask - Read and decode a shufflevector mask. It turns undef
7662/// elements into values that are larger than the #elts in the input.
7663static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
7664 unsigned NElts = SVI->getType()->getNumElements();
7665 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
7666 return std::vector<unsigned>(NElts, 0);
7667 if (isa<UndefValue>(SVI->getOperand(2)))
7668 return std::vector<unsigned>(NElts, 2*NElts);
7669
7670 std::vector<unsigned> Result;
7671 const ConstantPacked *CP = cast<ConstantPacked>(SVI->getOperand(2));
7672 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
7673 if (isa<UndefValue>(CP->getOperand(i)))
7674 Result.push_back(NElts*2); // undef -> 8
7675 else
7676 Result.push_back(cast<ConstantUInt>(CP->getOperand(i))->getValue());
7677 return Result;
7678}
7679
Chris Lattner8d1d8d32006-03-31 23:01:56 +00007680/// FindScalarElement - Given a vector and an element number, see if the scalar
7681/// value is already around as a register, for example if it were inserted then
7682/// extracted from the vector.
7683static Value *FindScalarElement(Value *V, unsigned EltNo) {
7684 assert(isa<PackedType>(V->getType()) && "Not looking at a vector?");
7685 const PackedType *PTy = cast<PackedType>(V->getType());
Chris Lattner2d37f922006-04-10 23:06:36 +00007686 unsigned Width = PTy->getNumElements();
7687 if (EltNo >= Width) // Out of range access.
Chris Lattner8d1d8d32006-03-31 23:01:56 +00007688 return UndefValue::get(PTy->getElementType());
7689
7690 if (isa<UndefValue>(V))
7691 return UndefValue::get(PTy->getElementType());
7692 else if (isa<ConstantAggregateZero>(V))
7693 return Constant::getNullValue(PTy->getElementType());
7694 else if (ConstantPacked *CP = dyn_cast<ConstantPacked>(V))
7695 return CP->getOperand(EltNo);
7696 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
7697 // If this is an insert to a variable element, we don't know what it is.
7698 if (!isa<ConstantUInt>(III->getOperand(2))) return 0;
7699 unsigned IIElt = cast<ConstantUInt>(III->getOperand(2))->getValue();
7700
7701 // If this is an insert to the element we are looking for, return the
7702 // inserted value.
7703 if (EltNo == IIElt) return III->getOperand(1);
7704
7705 // Otherwise, the insertelement doesn't modify the value, recurse on its
7706 // vector input.
7707 return FindScalarElement(III->getOperand(0), EltNo);
Chris Lattner2d37f922006-04-10 23:06:36 +00007708 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Chris Lattner12249be2006-05-25 23:48:38 +00007709 unsigned InEl = getShuffleMask(SVI)[EltNo];
7710 if (InEl < Width)
7711 return FindScalarElement(SVI->getOperand(0), InEl);
7712 else if (InEl < Width*2)
7713 return FindScalarElement(SVI->getOperand(1), InEl - Width);
7714 else
7715 return UndefValue::get(PTy->getElementType());
Chris Lattner8d1d8d32006-03-31 23:01:56 +00007716 }
7717
7718 // Otherwise, we don't know.
7719 return 0;
7720}
7721
Robert Bocchinoa8352962006-01-13 22:48:06 +00007722Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Chris Lattner8d1d8d32006-03-31 23:01:56 +00007723
Chris Lattner92346c32006-03-31 18:25:14 +00007724 // If packed val is undef, replace extract with scalar undef.
7725 if (isa<UndefValue>(EI.getOperand(0)))
7726 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
7727
7728 // If packed val is constant 0, replace extract with scalar 0.
7729 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
7730 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
7731
Robert Bocchinoa8352962006-01-13 22:48:06 +00007732 if (ConstantPacked *C = dyn_cast<ConstantPacked>(EI.getOperand(0))) {
7733 // If packed val is constant with uniform operands, replace EI
7734 // with that operand
Chris Lattner6bc98652006-03-05 00:22:33 +00007735 Constant *op0 = C->getOperand(0);
Robert Bocchinoa8352962006-01-13 22:48:06 +00007736 for (unsigned i = 1; i < C->getNumOperands(); ++i)
Chris Lattner6bc98652006-03-05 00:22:33 +00007737 if (C->getOperand(i) != op0) {
7738 op0 = 0;
7739 break;
7740 }
7741 if (op0)
7742 return ReplaceInstUsesWith(EI, op0);
Robert Bocchinoa8352962006-01-13 22:48:06 +00007743 }
Chris Lattner6bc98652006-03-05 00:22:33 +00007744
Chris Lattner8d1d8d32006-03-31 23:01:56 +00007745 // If extracting a specified index from the vector, see if we can recursively
7746 // find a previously computed scalar that was inserted into the vector.
Chris Lattner2d37f922006-04-10 23:06:36 +00007747 if (ConstantUInt *IdxC = dyn_cast<ConstantUInt>(EI.getOperand(1))) {
Chris Lattner2deeaea2006-10-05 06:55:50 +00007748 // This instruction only demands the single element from the input vector.
7749 // If the input vector has a single use, simplify it based on this use
7750 // property.
7751 if (EI.getOperand(0)->hasOneUse()) {
7752 uint64_t UndefElts;
7753 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
7754 1 << IdxC->getValue(),
7755 UndefElts)) {
7756 EI.setOperand(0, V);
7757 return &EI;
7758 }
7759 }
7760
Chris Lattner8d1d8d32006-03-31 23:01:56 +00007761 if (Value *Elt = FindScalarElement(EI.getOperand(0), IdxC->getValue()))
7762 return ReplaceInstUsesWith(EI, Elt);
Chris Lattner2d37f922006-04-10 23:06:36 +00007763 }
Chris Lattner8d1d8d32006-03-31 23:01:56 +00007764
Chris Lattner83f65782006-05-25 22:53:38 +00007765 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Robert Bocchinoa8352962006-01-13 22:48:06 +00007766 if (I->hasOneUse()) {
7767 // Push extractelement into predecessor operation if legal and
7768 // profitable to do so
7769 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Chris Lattner6bc98652006-03-05 00:22:33 +00007770 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
7771 if (CheapToScalarize(BO, isConstantElt)) {
7772 ExtractElementInst *newEI0 =
7773 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
7774 EI.getName()+".lhs");
7775 ExtractElementInst *newEI1 =
7776 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
7777 EI.getName()+".rhs");
7778 InsertNewInstBefore(newEI0, EI);
7779 InsertNewInstBefore(newEI1, EI);
7780 return BinaryOperator::create(BO->getOpcode(), newEI0, newEI1);
7781 }
7782 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Robert Bocchinoa8352962006-01-13 22:48:06 +00007783 Value *Ptr = InsertCastBefore(I->getOperand(0),
7784 PointerType::get(EI.getType()), EI);
7785 GetElementPtrInst *GEP =
7786 new GetElementPtrInst(Ptr, EI.getOperand(1),
7787 I->getName() + ".gep");
7788 InsertNewInstBefore(GEP, EI);
7789 return new LoadInst(GEP);
Chris Lattner83f65782006-05-25 22:53:38 +00007790 }
7791 }
7792 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
7793 // Extracting the inserted element?
7794 if (IE->getOperand(2) == EI.getOperand(1))
7795 return ReplaceInstUsesWith(EI, IE->getOperand(1));
7796 // If the inserted and extracted elements are constants, they must not
7797 // be the same value, extract from the pre-inserted value instead.
7798 if (isa<Constant>(IE->getOperand(2)) &&
7799 isa<Constant>(EI.getOperand(1))) {
7800 AddUsesToWorkList(EI);
7801 EI.setOperand(0, IE->getOperand(0));
7802 return &EI;
7803 }
7804 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
7805 // If this is extracting an element from a shufflevector, figure out where
7806 // it came from and extract from the appropriate input element instead.
7807 if (ConstantUInt *Elt = dyn_cast<ConstantUInt>(EI.getOperand(1))) {
Chris Lattner12249be2006-05-25 23:48:38 +00007808 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getValue()];
7809 Value *Src;
7810 if (SrcIdx < SVI->getType()->getNumElements())
7811 Src = SVI->getOperand(0);
7812 else if (SrcIdx < SVI->getType()->getNumElements()*2) {
7813 SrcIdx -= SVI->getType()->getNumElements();
7814 Src = SVI->getOperand(1);
7815 } else {
7816 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattner612fa8e2006-03-30 22:02:40 +00007817 }
Chris Lattner2deeaea2006-10-05 06:55:50 +00007818 return new ExtractElementInst(Src, SrcIdx);
Robert Bocchinoa8352962006-01-13 22:48:06 +00007819 }
7820 }
Chris Lattner83f65782006-05-25 22:53:38 +00007821 }
Robert Bocchinoa8352962006-01-13 22:48:06 +00007822 return 0;
7823}
7824
Chris Lattner90951862006-04-16 00:51:47 +00007825/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
7826/// elements from either LHS or RHS, return the shuffle mask and true.
7827/// Otherwise, return false.
7828static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
7829 std::vector<Constant*> &Mask) {
7830 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
7831 "Invalid CollectSingleShuffleElements");
7832 unsigned NumElts = cast<PackedType>(V->getType())->getNumElements();
7833
7834 if (isa<UndefValue>(V)) {
7835 Mask.assign(NumElts, UndefValue::get(Type::UIntTy));
7836 return true;
7837 } else if (V == LHS) {
7838 for (unsigned i = 0; i != NumElts; ++i)
7839 Mask.push_back(ConstantUInt::get(Type::UIntTy, i));
7840 return true;
7841 } else if (V == RHS) {
7842 for (unsigned i = 0; i != NumElts; ++i)
7843 Mask.push_back(ConstantUInt::get(Type::UIntTy, i+NumElts));
7844 return true;
7845 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
7846 // If this is an insert of an extract from some other vector, include it.
7847 Value *VecOp = IEI->getOperand(0);
7848 Value *ScalarOp = IEI->getOperand(1);
7849 Value *IdxOp = IEI->getOperand(2);
7850
Chris Lattnerb6cb64b2006-04-27 21:14:21 +00007851 if (!isa<ConstantInt>(IdxOp))
7852 return false;
7853 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getRawValue();
7854
7855 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
7856 // Okay, we can handle this if the vector we are insertinting into is
7857 // transitively ok.
7858 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
7859 // If so, update the mask to reflect the inserted undef.
7860 Mask[InsertedIdx] = UndefValue::get(Type::UIntTy);
7861 return true;
7862 }
7863 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
7864 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner90951862006-04-16 00:51:47 +00007865 EI->getOperand(0)->getType() == V->getType()) {
7866 unsigned ExtractedIdx =
7867 cast<ConstantInt>(EI->getOperand(1))->getRawValue();
Chris Lattner90951862006-04-16 00:51:47 +00007868
7869 // This must be extracting from either LHS or RHS.
7870 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
7871 // Okay, we can handle this if the vector we are insertinting into is
7872 // transitively ok.
7873 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
7874 // If so, update the mask to reflect the inserted value.
7875 if (EI->getOperand(0) == LHS) {
7876 Mask[InsertedIdx & (NumElts-1)] =
7877 ConstantUInt::get(Type::UIntTy, ExtractedIdx);
7878 } else {
7879 assert(EI->getOperand(0) == RHS);
7880 Mask[InsertedIdx & (NumElts-1)] =
7881 ConstantUInt::get(Type::UIntTy, ExtractedIdx+NumElts);
7882
7883 }
7884 return true;
7885 }
7886 }
7887 }
7888 }
7889 }
7890 // TODO: Handle shufflevector here!
7891
7892 return false;
7893}
7894
7895/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
7896/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
7897/// that computes V and the LHS value of the shuffle.
Chris Lattner39fac442006-04-15 01:39:45 +00007898static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Chris Lattner90951862006-04-16 00:51:47 +00007899 Value *&RHS) {
7900 assert(isa<PackedType>(V->getType()) &&
7901 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattner39fac442006-04-15 01:39:45 +00007902 "Invalid shuffle!");
7903 unsigned NumElts = cast<PackedType>(V->getType())->getNumElements();
7904
7905 if (isa<UndefValue>(V)) {
7906 Mask.assign(NumElts, UndefValue::get(Type::UIntTy));
7907 return V;
7908 } else if (isa<ConstantAggregateZero>(V)) {
7909 Mask.assign(NumElts, ConstantUInt::get(Type::UIntTy, 0));
7910 return V;
7911 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
7912 // If this is an insert of an extract from some other vector, include it.
7913 Value *VecOp = IEI->getOperand(0);
7914 Value *ScalarOp = IEI->getOperand(1);
7915 Value *IdxOp = IEI->getOperand(2);
7916
7917 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
7918 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
7919 EI->getOperand(0)->getType() == V->getType()) {
7920 unsigned ExtractedIdx =
7921 cast<ConstantInt>(EI->getOperand(1))->getRawValue();
7922 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getRawValue();
7923
7924 // Either the extracted from or inserted into vector must be RHSVec,
7925 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner90951862006-04-16 00:51:47 +00007926 if (EI->getOperand(0) == RHS || RHS == 0) {
7927 RHS = EI->getOperand(0);
7928 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
Chris Lattner39fac442006-04-15 01:39:45 +00007929 Mask[InsertedIdx & (NumElts-1)] =
7930 ConstantUInt::get(Type::UIntTy, NumElts+ExtractedIdx);
7931 return V;
7932 }
7933
Chris Lattner90951862006-04-16 00:51:47 +00007934 if (VecOp == RHS) {
7935 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
Chris Lattner39fac442006-04-15 01:39:45 +00007936 // Everything but the extracted element is replaced with the RHS.
7937 for (unsigned i = 0; i != NumElts; ++i) {
7938 if (i != InsertedIdx)
7939 Mask[i] = ConstantUInt::get(Type::UIntTy, NumElts+i);
7940 }
7941 return V;
7942 }
Chris Lattner90951862006-04-16 00:51:47 +00007943
7944 // If this insertelement is a chain that comes from exactly these two
7945 // vectors, return the vector and the effective shuffle.
7946 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
7947 return EI->getOperand(0);
7948
Chris Lattner39fac442006-04-15 01:39:45 +00007949 }
7950 }
7951 }
Chris Lattner90951862006-04-16 00:51:47 +00007952 // TODO: Handle shufflevector here!
Chris Lattner39fac442006-04-15 01:39:45 +00007953
7954 // Otherwise, can't do anything fancy. Return an identity vector.
7955 for (unsigned i = 0; i != NumElts; ++i)
7956 Mask.push_back(ConstantUInt::get(Type::UIntTy, i));
7957 return V;
7958}
7959
7960Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
7961 Value *VecOp = IE.getOperand(0);
7962 Value *ScalarOp = IE.getOperand(1);
7963 Value *IdxOp = IE.getOperand(2);
7964
7965 // If the inserted element was extracted from some other vector, and if the
7966 // indexes are constant, try to turn this into a shufflevector operation.
7967 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
7968 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
7969 EI->getOperand(0)->getType() == IE.getType()) {
7970 unsigned NumVectorElts = IE.getType()->getNumElements();
7971 unsigned ExtractedIdx=cast<ConstantInt>(EI->getOperand(1))->getRawValue();
7972 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getRawValue();
7973
7974 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
7975 return ReplaceInstUsesWith(IE, VecOp);
7976
7977 if (InsertedIdx >= NumVectorElts) // Out of range insert.
7978 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
7979
7980 // If we are extracting a value from a vector, then inserting it right
7981 // back into the same place, just use the input vector.
7982 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
7983 return ReplaceInstUsesWith(IE, VecOp);
7984
7985 // We could theoretically do this for ANY input. However, doing so could
7986 // turn chains of insertelement instructions into a chain of shufflevector
7987 // instructions, and right now we do not merge shufflevectors. As such,
7988 // only do this in a situation where it is clear that there is benefit.
7989 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
7990 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
7991 // the values of VecOp, except then one read from EIOp0.
7992 // Build a new shuffle mask.
7993 std::vector<Constant*> Mask;
7994 if (isa<UndefValue>(VecOp))
7995 Mask.assign(NumVectorElts, UndefValue::get(Type::UIntTy));
7996 else {
7997 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
7998 Mask.assign(NumVectorElts, ConstantUInt::get(Type::UIntTy,
7999 NumVectorElts));
8000 }
8001 Mask[InsertedIdx] = ConstantUInt::get(Type::UIntTy, ExtractedIdx);
8002 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
8003 ConstantPacked::get(Mask));
8004 }
8005
8006 // If this insertelement isn't used by some other insertelement, turn it
8007 // (and any insertelements it points to), into one big shuffle.
8008 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
8009 std::vector<Constant*> Mask;
Chris Lattner90951862006-04-16 00:51:47 +00008010 Value *RHS = 0;
8011 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
8012 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
8013 // We now have a shuffle of LHS, RHS, Mask.
8014 return new ShuffleVectorInst(LHS, RHS, ConstantPacked::get(Mask));
Chris Lattner39fac442006-04-15 01:39:45 +00008015 }
8016 }
8017 }
8018
8019 return 0;
8020}
8021
8022
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008023Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
8024 Value *LHS = SVI.getOperand(0);
8025 Value *RHS = SVI.getOperand(1);
Chris Lattner12249be2006-05-25 23:48:38 +00008026 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008027
8028 bool MadeChange = false;
8029
Chris Lattner2deeaea2006-10-05 06:55:50 +00008030 // Undefined shuffle mask -> undefined value.
Chris Lattner12249be2006-05-25 23:48:38 +00008031 if (isa<UndefValue>(SVI.getOperand(2)))
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008032 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
8033
Chris Lattner39fac442006-04-15 01:39:45 +00008034 // TODO: If we have shuffle(x, undef, mask) and any elements of mask refer to
8035 // the undef, change them to undefs.
8036
Chris Lattner12249be2006-05-25 23:48:38 +00008037 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
8038 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
8039 if (LHS == RHS || isa<UndefValue>(LHS)) {
8040 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008041 // shuffle(undef,undef,mask) -> undef.
8042 return ReplaceInstUsesWith(SVI, LHS);
8043 }
8044
Chris Lattner12249be2006-05-25 23:48:38 +00008045 // Remap any references to RHS to use LHS.
8046 std::vector<Constant*> Elts;
8047 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner0e477162006-05-26 00:29:06 +00008048 if (Mask[i] >= 2*e)
Chris Lattner12249be2006-05-25 23:48:38 +00008049 Elts.push_back(UndefValue::get(Type::UIntTy));
Chris Lattner0e477162006-05-26 00:29:06 +00008050 else {
8051 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
8052 (Mask[i] < e && isa<UndefValue>(LHS)))
8053 Mask[i] = 2*e; // Turn into undef.
8054 else
8055 Mask[i] &= (e-1); // Force to LHS.
8056 Elts.push_back(ConstantUInt::get(Type::UIntTy, Mask[i]));
8057 }
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008058 }
Chris Lattner12249be2006-05-25 23:48:38 +00008059 SVI.setOperand(0, SVI.getOperand(1));
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008060 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Chris Lattner12249be2006-05-25 23:48:38 +00008061 SVI.setOperand(2, ConstantPacked::get(Elts));
Chris Lattner0e477162006-05-26 00:29:06 +00008062 LHS = SVI.getOperand(0);
8063 RHS = SVI.getOperand(1);
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008064 MadeChange = true;
8065 }
8066
Chris Lattner0e477162006-05-26 00:29:06 +00008067 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner12249be2006-05-25 23:48:38 +00008068 bool isLHSID = true, isRHSID = true;
Chris Lattner34cebe72006-04-16 00:03:56 +00008069
Chris Lattner12249be2006-05-25 23:48:38 +00008070 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
8071 if (Mask[i] >= e*2) continue; // Ignore undef values.
8072 // Is this an identity shuffle of the LHS value?
8073 isLHSID &= (Mask[i] == i);
8074
8075 // Is this an identity shuffle of the RHS value?
8076 isRHSID &= (Mask[i]-e == i);
Chris Lattner34cebe72006-04-16 00:03:56 +00008077 }
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008078
Chris Lattner12249be2006-05-25 23:48:38 +00008079 // Eliminate identity shuffles.
8080 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
8081 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008082
Chris Lattner0e477162006-05-26 00:29:06 +00008083 // If the LHS is a shufflevector itself, see if we can combine it with this
8084 // one without producing an unusual shuffle. Here we are really conservative:
8085 // we are absolutely afraid of producing a shuffle mask not in the input
8086 // program, because the code gen may not be smart enough to turn a merged
8087 // shuffle into two specific shuffles: it may produce worse code. As such,
8088 // we only merge two shuffles if the result is one of the two input shuffle
8089 // masks. In this case, merging the shuffles just removes one instruction,
8090 // which we know is safe. This is good for things like turning:
8091 // (splat(splat)) -> splat.
8092 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
8093 if (isa<UndefValue>(RHS)) {
8094 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
8095
8096 std::vector<unsigned> NewMask;
8097 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
8098 if (Mask[i] >= 2*e)
8099 NewMask.push_back(2*e);
8100 else
8101 NewMask.push_back(LHSMask[Mask[i]]);
8102
8103 // If the result mask is equal to the src shuffle or this shuffle mask, do
8104 // the replacement.
8105 if (NewMask == LHSMask || NewMask == Mask) {
8106 std::vector<Constant*> Elts;
8107 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
8108 if (NewMask[i] >= e*2) {
8109 Elts.push_back(UndefValue::get(Type::UIntTy));
8110 } else {
8111 Elts.push_back(ConstantUInt::get(Type::UIntTy, NewMask[i]));
8112 }
8113 }
8114 return new ShuffleVectorInst(LHSSVI->getOperand(0),
8115 LHSSVI->getOperand(1),
8116 ConstantPacked::get(Elts));
8117 }
8118 }
8119 }
8120
Chris Lattnerfbb77a42006-04-10 22:45:52 +00008121 return MadeChange ? &SVI : 0;
8122}
8123
8124
Robert Bocchinoa8352962006-01-13 22:48:06 +00008125
Chris Lattner99f48c62002-09-02 04:59:56 +00008126void InstCombiner::removeFromWorkList(Instruction *I) {
8127 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
8128 WorkList.end());
8129}
8130
Chris Lattner39c98bb2004-12-08 23:43:58 +00008131
8132/// TryToSinkInstruction - Try to move the specified instruction from its
8133/// current block into the beginning of DestBlock, which can only happen if it's
8134/// safe to move the instruction past all of the instructions between it and the
8135/// end of its block.
8136static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
8137 assert(I->hasOneUse() && "Invariants didn't hold!");
8138
Chris Lattnerc4f67e62005-10-27 17:13:11 +00008139 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
8140 if (isa<PHINode>(I) || I->mayWriteToMemory()) return false;
Misha Brukmanb1c93172005-04-21 23:48:37 +00008141
Chris Lattner39c98bb2004-12-08 23:43:58 +00008142 // Do not sink alloca instructions out of the entry block.
8143 if (isa<AllocaInst>(I) && I->getParent() == &DestBlock->getParent()->front())
8144 return false;
8145
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00008146 // We can only sink load instructions if there is nothing between the load and
8147 // the end of block that could change the value.
8148 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00008149 for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
8150 Scan != E; ++Scan)
8151 if (Scan->mayWriteToMemory())
8152 return false;
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00008153 }
Chris Lattner39c98bb2004-12-08 23:43:58 +00008154
8155 BasicBlock::iterator InsertPos = DestBlock->begin();
8156 while (isa<PHINode>(InsertPos)) ++InsertPos;
8157
Chris Lattner9f269e42005-08-08 19:11:57 +00008158 I->moveBefore(InsertPos);
Chris Lattner39c98bb2004-12-08 23:43:58 +00008159 ++NumSunkInst;
8160 return true;
8161}
8162
Chris Lattner1443bc52006-05-11 17:11:52 +00008163/// OptimizeConstantExpr - Given a constant expression and target data layout
8164/// information, symbolically evaluation the constant expr to something simpler
8165/// if possible.
8166static Constant *OptimizeConstantExpr(ConstantExpr *CE, const TargetData *TD) {
8167 if (!TD) return CE;
8168
8169 Constant *Ptr = CE->getOperand(0);
8170 if (CE->getOpcode() == Instruction::GetElementPtr && Ptr->isNullValue() &&
8171 cast<PointerType>(Ptr->getType())->getElementType()->isSized()) {
8172 // If this is a constant expr gep that is effectively computing an
8173 // "offsetof", fold it into 'cast int Size to T*' instead of 'gep 0, 0, 12'
8174 bool isFoldableGEP = true;
8175 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
8176 if (!isa<ConstantInt>(CE->getOperand(i)))
8177 isFoldableGEP = false;
8178 if (isFoldableGEP) {
8179 std::vector<Value*> Ops(CE->op_begin()+1, CE->op_end());
8180 uint64_t Offset = TD->getIndexedOffset(Ptr->getType(), Ops);
8181 Constant *C = ConstantUInt::get(Type::ULongTy, Offset);
8182 C = ConstantExpr::getCast(C, TD->getIntPtrType());
8183 return ConstantExpr::getCast(C, CE->getType());
8184 }
8185 }
8186
8187 return CE;
8188}
8189
Chris Lattnera36ee4e2006-05-10 19:00:36 +00008190
8191/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
8192/// all reachable code to the worklist.
8193///
8194/// This has a couple of tricks to make the code faster and more powerful. In
8195/// particular, we constant fold and DCE instructions as we go, to avoid adding
8196/// them to the worklist (this significantly speeds up instcombine on code where
8197/// many instructions are dead or constant). Additionally, if we find a branch
8198/// whose condition is a known constant, we only visit the reachable successors.
8199///
8200static void AddReachableCodeToWorklist(BasicBlock *BB,
8201 std::set<BasicBlock*> &Visited,
Chris Lattner1443bc52006-05-11 17:11:52 +00008202 std::vector<Instruction*> &WorkList,
8203 const TargetData *TD) {
Chris Lattnera36ee4e2006-05-10 19:00:36 +00008204 // We have now visited this block! If we've already been here, bail out.
8205 if (!Visited.insert(BB).second) return;
8206
8207 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
8208 Instruction *Inst = BBI++;
8209
8210 // DCE instruction if trivially dead.
8211 if (isInstructionTriviallyDead(Inst)) {
8212 ++NumDeadInst;
8213 DEBUG(std::cerr << "IC: DCE: " << *Inst);
8214 Inst->eraseFromParent();
8215 continue;
8216 }
8217
8218 // ConstantProp instruction if trivially constant.
8219 if (Constant *C = ConstantFoldInstruction(Inst)) {
Chris Lattner1443bc52006-05-11 17:11:52 +00008220 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
8221 C = OptimizeConstantExpr(CE, TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00008222 DEBUG(std::cerr << "IC: ConstFold to: " << *C << " from: " << *Inst);
8223 Inst->replaceAllUsesWith(C);
8224 ++NumConstProp;
8225 Inst->eraseFromParent();
8226 continue;
8227 }
8228
8229 WorkList.push_back(Inst);
8230 }
8231
8232 // Recursively visit successors. If this is a branch or switch on a constant,
8233 // only visit the reachable successor.
8234 TerminatorInst *TI = BB->getTerminator();
8235 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
8236 if (BI->isConditional() && isa<ConstantBool>(BI->getCondition())) {
8237 bool CondVal = cast<ConstantBool>(BI->getCondition())->getValue();
Chris Lattner1443bc52006-05-11 17:11:52 +00008238 AddReachableCodeToWorklist(BI->getSuccessor(!CondVal), Visited, WorkList,
8239 TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00008240 return;
8241 }
8242 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
8243 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
8244 // See if this is an explicit destination.
8245 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
8246 if (SI->getCaseValue(i) == Cond) {
Chris Lattner1443bc52006-05-11 17:11:52 +00008247 AddReachableCodeToWorklist(SI->getSuccessor(i), Visited, WorkList,TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00008248 return;
8249 }
8250
8251 // Otherwise it is the default destination.
Chris Lattner1443bc52006-05-11 17:11:52 +00008252 AddReachableCodeToWorklist(SI->getSuccessor(0), Visited, WorkList, TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00008253 return;
8254 }
8255 }
8256
8257 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
Chris Lattner1443bc52006-05-11 17:11:52 +00008258 AddReachableCodeToWorklist(TI->getSuccessor(i), Visited, WorkList, TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00008259}
8260
Chris Lattner113f4f42002-06-25 16:13:24 +00008261bool InstCombiner::runOnFunction(Function &F) {
Chris Lattner260ab202002-04-18 17:39:14 +00008262 bool Changed = false;
Chris Lattnerf4ad1652003-11-02 05:57:39 +00008263 TD = &getAnalysis<TargetData>();
Chris Lattnerca081252001-12-14 16:52:21 +00008264
Chris Lattner4ed40f72005-07-07 20:40:38 +00008265 {
Chris Lattnera36ee4e2006-05-10 19:00:36 +00008266 // Do a depth-first traversal of the function, populate the worklist with
8267 // the reachable instructions. Ignore blocks that are not reachable. Keep
8268 // track of which blocks we visit.
Chris Lattner4ed40f72005-07-07 20:40:38 +00008269 std::set<BasicBlock*> Visited;
Chris Lattner1443bc52006-05-11 17:11:52 +00008270 AddReachableCodeToWorklist(F.begin(), Visited, WorkList, TD);
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00008271
Chris Lattner4ed40f72005-07-07 20:40:38 +00008272 // Do a quick scan over the function. If we find any blocks that are
8273 // unreachable, remove any instructions inside of them. This prevents
8274 // the instcombine code from having to deal with some bad special cases.
8275 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
8276 if (!Visited.count(BB)) {
8277 Instruction *Term = BB->getTerminator();
8278 while (Term != BB->begin()) { // Remove instrs bottom-up
8279 BasicBlock::iterator I = Term; --I;
Chris Lattner2d3a7a62004-04-27 15:13:33 +00008280
Chris Lattner4ed40f72005-07-07 20:40:38 +00008281 DEBUG(std::cerr << "IC: DCE: " << *I);
8282 ++NumDeadInst;
8283
8284 if (!I->use_empty())
8285 I->replaceAllUsesWith(UndefValue::get(I->getType()));
8286 I->eraseFromParent();
8287 }
8288 }
8289 }
Chris Lattnerca081252001-12-14 16:52:21 +00008290
8291 while (!WorkList.empty()) {
8292 Instruction *I = WorkList.back(); // Get an instruction from the worklist
8293 WorkList.pop_back();
8294
Chris Lattner1443bc52006-05-11 17:11:52 +00008295 // Check to see if we can DCE the instruction.
Chris Lattner99f48c62002-09-02 04:59:56 +00008296 if (isInstructionTriviallyDead(I)) {
Chris Lattner1443bc52006-05-11 17:11:52 +00008297 // Add operands to the worklist.
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00008298 if (I->getNumOperands() < 4)
Chris Lattner51ea1272004-02-28 05:22:00 +00008299 AddUsesToWorkList(*I);
Chris Lattner99f48c62002-09-02 04:59:56 +00008300 ++NumDeadInst;
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00008301
Chris Lattnercd517ff2005-01-28 19:32:01 +00008302 DEBUG(std::cerr << "IC: DCE: " << *I);
8303
8304 I->eraseFromParent();
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00008305 removeFromWorkList(I);
8306 continue;
8307 }
Chris Lattner99f48c62002-09-02 04:59:56 +00008308
Chris Lattner1443bc52006-05-11 17:11:52 +00008309 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattner99f48c62002-09-02 04:59:56 +00008310 if (Constant *C = ConstantFoldInstruction(I)) {
Chris Lattner1443bc52006-05-11 17:11:52 +00008311 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
8312 C = OptimizeConstantExpr(CE, TD);
Chris Lattnercd517ff2005-01-28 19:32:01 +00008313 DEBUG(std::cerr << "IC: ConstFold to: " << *C << " from: " << *I);
8314
Chris Lattner1443bc52006-05-11 17:11:52 +00008315 // Add operands to the worklist.
Chris Lattner51ea1272004-02-28 05:22:00 +00008316 AddUsesToWorkList(*I);
Chris Lattnerc6509f42002-12-05 22:41:53 +00008317 ReplaceInstUsesWith(*I, C);
8318
Chris Lattner99f48c62002-09-02 04:59:56 +00008319 ++NumConstProp;
Chris Lattnera36ee4e2006-05-10 19:00:36 +00008320 I->eraseFromParent();
Chris Lattner800aaaf2003-10-07 15:17:02 +00008321 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00008322 continue;
Chris Lattner99f48c62002-09-02 04:59:56 +00008323 }
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00008324
Chris Lattner39c98bb2004-12-08 23:43:58 +00008325 // See if we can trivially sink this instruction to a successor basic block.
8326 if (I->hasOneUse()) {
8327 BasicBlock *BB = I->getParent();
8328 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
8329 if (UserParent != BB) {
8330 bool UserIsSuccessor = false;
8331 // See if the user is one of our successors.
8332 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
8333 if (*SI == UserParent) {
8334 UserIsSuccessor = true;
8335 break;
8336 }
8337
8338 // If the user is one of our immediate successors, and if that successor
8339 // only has us as a predecessors (we'd have to split the critical edge
8340 // otherwise), we can keep going.
8341 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
8342 next(pred_begin(UserParent)) == pred_end(UserParent))
8343 // Okay, the CFG is simple enough, try to sink this instruction.
8344 Changed |= TryToSinkInstruction(I, UserParent);
8345 }
8346 }
8347
Chris Lattnerca081252001-12-14 16:52:21 +00008348 // Now that we have an instruction, try combining it to simplify it...
Chris Lattnerae7a0d32002-08-02 19:29:35 +00008349 if (Instruction *Result = visit(*I)) {
Chris Lattner0b18c1d2002-05-10 15:38:35 +00008350 ++NumCombined;
Chris Lattner260ab202002-04-18 17:39:14 +00008351 // Should we replace the old instruction with a new one?
Chris Lattner053c0932002-05-14 15:24:07 +00008352 if (Result != I) {
Chris Lattner7d2a5392004-03-13 23:54:27 +00008353 DEBUG(std::cerr << "IC: Old = " << *I
8354 << " New = " << *Result);
8355
Chris Lattner396dbfe2004-06-09 05:08:07 +00008356 // Everything uses the new instruction now.
8357 I->replaceAllUsesWith(Result);
8358
8359 // Push the new instruction and any users onto the worklist.
8360 WorkList.push_back(Result);
8361 AddUsersToWorkList(*Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00008362
8363 // Move the name to the new instruction first...
8364 std::string OldName = I->getName(); I->setName("");
Chris Lattner950fc782003-10-07 22:58:41 +00008365 Result->setName(OldName);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00008366
8367 // Insert the new instruction into the basic block...
8368 BasicBlock *InstParent = I->getParent();
Chris Lattner7515cab2004-11-14 19:13:23 +00008369 BasicBlock::iterator InsertPos = I;
8370
8371 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
8372 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
8373 ++InsertPos;
8374
8375 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00008376
Chris Lattner63d75af2004-05-01 23:27:23 +00008377 // Make sure that we reprocess all operands now that we reduced their
8378 // use counts.
Chris Lattnerb643a9e2004-05-01 23:19:52 +00008379 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
8380 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
8381 WorkList.push_back(OpI);
8382
Chris Lattner396dbfe2004-06-09 05:08:07 +00008383 // Instructions can end up on the worklist more than once. Make sure
8384 // we do not process an instruction that has been deleted.
8385 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00008386
8387 // Erase the old instruction.
8388 InstParent->getInstList().erase(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00008389 } else {
Chris Lattner7d2a5392004-03-13 23:54:27 +00008390 DEBUG(std::cerr << "IC: MOD = " << *I);
8391
Chris Lattnerae7a0d32002-08-02 19:29:35 +00008392 // If the instruction was modified, it's possible that it is now dead.
8393 // if so, remove it.
Chris Lattner63d75af2004-05-01 23:27:23 +00008394 if (isInstructionTriviallyDead(I)) {
8395 // Make sure we process all operands now that we are reducing their
8396 // use counts.
8397 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
8398 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
8399 WorkList.push_back(OpI);
Misha Brukmanb1c93172005-04-21 23:48:37 +00008400
Chris Lattner63d75af2004-05-01 23:27:23 +00008401 // Instructions may end up in the worklist more than once. Erase all
Robert Bocchinoa8352962006-01-13 22:48:06 +00008402 // occurrences of this instruction.
Chris Lattner99f48c62002-09-02 04:59:56 +00008403 removeFromWorkList(I);
Chris Lattner31f486c2005-01-31 05:36:43 +00008404 I->eraseFromParent();
Chris Lattner396dbfe2004-06-09 05:08:07 +00008405 } else {
8406 WorkList.push_back(Result);
8407 AddUsersToWorkList(*Result);
Chris Lattnerae7a0d32002-08-02 19:29:35 +00008408 }
Chris Lattner053c0932002-05-14 15:24:07 +00008409 }
Chris Lattner260ab202002-04-18 17:39:14 +00008410 Changed = true;
Chris Lattnerca081252001-12-14 16:52:21 +00008411 }
8412 }
8413
Chris Lattner260ab202002-04-18 17:39:14 +00008414 return Changed;
Chris Lattner04805fa2002-02-26 21:46:54 +00008415}
8416
Brian Gaeke38b79e82004-07-27 17:43:21 +00008417FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattner260ab202002-04-18 17:39:14 +00008418 return new InstCombiner();
Chris Lattner04805fa2002-02-26 21:46:54 +00008419}
Brian Gaeke960707c2003-11-11 22:41:34 +00008420