blob: 3ba239b6a693cae2194ae7293dc894d1e8f5c353 [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 Lattner4ed40f72005-07-07 20:40:38 +000051#include "llvm/ADT/DepthFirstIterator.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000052#include "llvm/ADT/Statistic.h"
Chris Lattner39c98bb2004-12-08 23:43:58 +000053#include "llvm/ADT/STLExtras.h"
Chris Lattner053c0932002-05-14 15:24:07 +000054#include <algorithm>
Chris Lattner8427bff2003-12-07 01:24:23 +000055using namespace llvm;
Chris Lattnerd4252a72004-07-30 07:50:03 +000056using namespace llvm::PatternMatch;
Brian Gaeke960707c2003-11-11 22:41:34 +000057
Chris Lattner260ab202002-04-18 17:39:14 +000058namespace {
Chris Lattnerbf3a0992002-10-01 22:38:41 +000059 Statistic<> NumCombined ("instcombine", "Number of insts combined");
60 Statistic<> NumConstProp("instcombine", "Number of constant folds");
61 Statistic<> NumDeadInst ("instcombine", "Number of dead inst eliminated");
Chris Lattner39c98bb2004-12-08 23:43:58 +000062 Statistic<> NumSunkInst ("instcombine", "Number of instructions sunk");
Chris Lattnerbf3a0992002-10-01 22:38:41 +000063
Chris Lattnerc8e66542002-04-27 06:56:12 +000064 class InstCombiner : public FunctionPass,
Chris Lattner260ab202002-04-18 17:39:14 +000065 public InstVisitor<InstCombiner, Instruction*> {
66 // Worklist of all of the instructions that need to be simplified.
67 std::vector<Instruction*> WorkList;
Chris Lattnerf4ad1652003-11-02 05:57:39 +000068 TargetData *TD;
Chris Lattner260ab202002-04-18 17:39:14 +000069
Chris Lattner51ea1272004-02-28 05:22:00 +000070 /// AddUsersToWorkList - When an instruction is simplified, add all users of
71 /// the instruction to the work lists because they might get more simplified
72 /// now.
73 ///
74 void AddUsersToWorkList(Instruction &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +000075 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
Chris Lattner260ab202002-04-18 17:39:14 +000076 UI != UE; ++UI)
77 WorkList.push_back(cast<Instruction>(*UI));
78 }
79
Chris Lattner51ea1272004-02-28 05:22:00 +000080 /// AddUsesToWorkList - When an instruction is simplified, add operands to
81 /// the work lists because they might get more simplified now.
82 ///
83 void AddUsesToWorkList(Instruction &I) {
84 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
85 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i)))
86 WorkList.push_back(Op);
87 }
88
Chris Lattner99f48c62002-09-02 04:59:56 +000089 // removeFromWorkList - remove all instances of I from the worklist.
90 void removeFromWorkList(Instruction *I);
Chris Lattner260ab202002-04-18 17:39:14 +000091 public:
Chris Lattner113f4f42002-06-25 16:13:24 +000092 virtual bool runOnFunction(Function &F);
Chris Lattner260ab202002-04-18 17:39:14 +000093
Chris Lattnerf12cc842002-04-28 21:27:06 +000094 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnerf4ad1652003-11-02 05:57:39 +000095 AU.addRequired<TargetData>();
Chris Lattner820d9712002-10-21 20:00:28 +000096 AU.setPreservesCFG();
Chris Lattnerf12cc842002-04-28 21:27:06 +000097 }
98
Chris Lattner69193f92004-04-05 01:30:19 +000099 TargetData &getTargetData() const { return *TD; }
100
Chris Lattner260ab202002-04-18 17:39:14 +0000101 // Visitation implementation - Implement instruction combining for different
102 // instruction types. The semantics are as follows:
103 // Return Value:
104 // null - No change was made
Chris Lattnere6794492002-08-12 21:17:25 +0000105 // I - Change was made, I is still valid, I may be dead though
Chris Lattner260ab202002-04-18 17:39:14 +0000106 // otherwise - Change was made, replace I with returned instruction
Misha Brukmanb1c93172005-04-21 23:48:37 +0000107 //
Chris Lattner113f4f42002-06-25 16:13:24 +0000108 Instruction *visitAdd(BinaryOperator &I);
109 Instruction *visitSub(BinaryOperator &I);
110 Instruction *visitMul(BinaryOperator &I);
111 Instruction *visitDiv(BinaryOperator &I);
112 Instruction *visitRem(BinaryOperator &I);
113 Instruction *visitAnd(BinaryOperator &I);
114 Instruction *visitOr (BinaryOperator &I);
115 Instruction *visitXor(BinaryOperator &I);
Chris Lattnerd1f46d32005-04-24 06:59:08 +0000116 Instruction *visitSetCondInst(SetCondInst &I);
117 Instruction *visitSetCondInstWithCastAndCast(SetCondInst &SCI);
118
Chris Lattner0798af32005-01-13 20:14:25 +0000119 Instruction *FoldGEPSetCC(User *GEPLHS, Value *RHS,
120 Instruction::BinaryOps Cond, Instruction &I);
Chris Lattnere8d6c602003-03-10 19:16:08 +0000121 Instruction *visitShiftInst(ShiftInst &I);
Chris Lattner14553932006-01-06 07:12:35 +0000122 Instruction *FoldShiftByConstant(Value *Op0, ConstantUInt *Op1,
123 ShiftInst &I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000124 Instruction *visitCastInst(CastInst &CI);
Chris Lattner411336f2005-01-19 21:50:18 +0000125 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
126 Instruction *FI);
Chris Lattnerb909e8b2004-03-12 05:52:32 +0000127 Instruction *visitSelectInst(SelectInst &CI);
Chris Lattner970c33a2003-06-19 17:00:31 +0000128 Instruction *visitCallInst(CallInst &CI);
129 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner113f4f42002-06-25 16:13:24 +0000130 Instruction *visitPHINode(PHINode &PN);
131 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Chris Lattner1085bdf2002-11-04 16:18:53 +0000132 Instruction *visitAllocationInst(AllocationInst &AI);
Chris Lattner8427bff2003-12-07 01:24:23 +0000133 Instruction *visitFreeInst(FreeInst &FI);
Chris Lattner0f1d8a32003-06-26 05:06:25 +0000134 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattner31f486c2005-01-31 05:36:43 +0000135 Instruction *visitStoreInst(StoreInst &SI);
Chris Lattner9eef8a72003-06-04 04:46:00 +0000136 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner4c9c20a2004-07-03 00:26:11 +0000137 Instruction *visitSwitchInst(SwitchInst &SI);
Chris Lattner260ab202002-04-18 17:39:14 +0000138
139 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner113f4f42002-06-25 16:13:24 +0000140 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000141
Chris Lattner970c33a2003-06-19 17:00:31 +0000142 private:
Chris Lattneraec3d942003-10-07 22:32:43 +0000143 Instruction *visitCallSite(CallSite CS);
Chris Lattner970c33a2003-06-19 17:00:31 +0000144 bool transformConstExprCastCall(CallSite CS);
145
Chris Lattner69193f92004-04-05 01:30:19 +0000146 public:
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000147 // InsertNewInstBefore - insert an instruction New before instruction Old
148 // in the program. Add the new instruction to the worklist.
149 //
Chris Lattner623826c2004-09-28 21:48:02 +0000150 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattner65217ff2002-08-23 18:32:43 +0000151 assert(New && New->getParent() == 0 &&
152 "New instruction already inserted into a basic block!");
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000153 BasicBlock *BB = Old.getParent();
154 BB->getInstList().insert(&Old, New); // Insert inst
155 WorkList.push_back(New); // Add to worklist
Chris Lattnere79e8542004-02-23 06:38:22 +0000156 return New;
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000157 }
158
Chris Lattner7e794272004-09-24 15:21:34 +0000159 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
160 /// This also adds the cast to the worklist. Finally, this returns the
161 /// cast.
162 Value *InsertCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
163 if (V->getType() == Ty) return V;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000164
Chris Lattner7e794272004-09-24 15:21:34 +0000165 Instruction *C = new CastInst(V, Ty, V->getName(), &Pos);
166 WorkList.push_back(C);
167 return C;
168 }
169
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000170 // ReplaceInstUsesWith - This method is to be used when an instruction is
171 // found to be dead, replacable with another preexisting expression. Here
172 // we add all uses of I to the worklist, replace all uses of I with the new
173 // value, then return I, so that the inst combiner will know that I was
174 // modified.
175 //
176 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattner51ea1272004-02-28 05:22:00 +0000177 AddUsersToWorkList(I); // Add all modified instrs to worklist
Chris Lattner8953b902004-04-05 02:10:19 +0000178 if (&I != V) {
179 I.replaceAllUsesWith(V);
180 return &I;
181 } else {
182 // If we are replacing the instruction with itself, this must be in a
183 // segment of unreachable code, so just clobber the instruction.
Chris Lattner8ba9ec92004-10-18 02:59:09 +0000184 I.replaceAllUsesWith(UndefValue::get(I.getType()));
Chris Lattner8953b902004-04-05 02:10:19 +0000185 return &I;
186 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000187 }
Chris Lattner51ea1272004-02-28 05:22:00 +0000188
189 // EraseInstFromFunction - When dealing with an instruction that has side
190 // effects or produces a void value, we can't rely on DCE to delete the
191 // instruction. Instead, visit methods should return the value returned by
192 // this function.
193 Instruction *EraseInstFromFunction(Instruction &I) {
194 assert(I.use_empty() && "Cannot erase instruction that is used!");
195 AddUsesToWorkList(I);
196 removeFromWorkList(&I);
Chris Lattner95307542004-11-18 21:41:39 +0000197 I.eraseFromParent();
Chris Lattner51ea1272004-02-28 05:22:00 +0000198 return 0; // Don't do anything with FI
199 }
200
201
Chris Lattner3ac7c262003-08-13 20:16:26 +0000202 private:
Chris Lattnerdfae8be2003-07-24 17:35:25 +0000203 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
204 /// InsertBefore instruction. This is specialized a bit to avoid inserting
205 /// casts that are known to not do anything...
206 ///
207 Value *InsertOperandCastBefore(Value *V, const Type *DestTy,
208 Instruction *InsertBefore);
209
Chris Lattner7fb29e12003-03-11 00:12:48 +0000210 // SimplifyCommutative - This performs a few simplifications for commutative
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000211 // operators.
Chris Lattner7fb29e12003-03-11 00:12:48 +0000212 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerba1cb382003-09-19 17:17:26 +0000213
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000214
215 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
216 // PHI node as operand #0, see if we can fold the instruction into the PHI
217 // (which is only possible if all operands to the PHI are constants).
218 Instruction *FoldOpIntoPhi(Instruction &I);
219
Chris Lattner7515cab2004-11-14 19:13:23 +0000220 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
221 // operator and they all are only used by the PHI, PHI together their
222 // inputs, and do the operation once, to the result of the PHI.
223 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
224
Chris Lattnerba1cb382003-09-19 17:17:26 +0000225 Instruction *OptAndOp(Instruction *Op, ConstantIntegral *OpRHS,
226 ConstantIntegral *AndRHS, BinaryOperator &TheAnd);
Chris Lattneraf517572005-09-18 04:24:45 +0000227
228 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantIntegral *Mask,
229 bool isSub, Instruction &I);
Chris Lattner6862fbd2004-09-29 17:40:11 +0000230 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
231 bool Inside, Instruction &IB);
Chris Lattner216be912005-10-24 06:03:58 +0000232 Instruction *PromoteCastOfAllocation(CastInst &CI, AllocationInst &AI);
Chris Lattner260ab202002-04-18 17:39:14 +0000233 };
Chris Lattnerb28b6802002-07-23 18:06:35 +0000234
Chris Lattnerc8b70922002-07-26 21:12:46 +0000235 RegisterOpt<InstCombiner> X("instcombine", "Combine redundant instructions");
Chris Lattner260ab202002-04-18 17:39:14 +0000236}
237
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000238// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattner81a7a232004-10-16 18:11:37 +0000239// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000240static unsigned getComplexity(Value *V) {
241 if (isa<Instruction>(V)) {
242 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
Chris Lattner81a7a232004-10-16 18:11:37 +0000243 return 3;
244 return 4;
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000245 }
Chris Lattner81a7a232004-10-16 18:11:37 +0000246 if (isa<Argument>(V)) return 3;
247 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000248}
Chris Lattner260ab202002-04-18 17:39:14 +0000249
Chris Lattner7fb29e12003-03-11 00:12:48 +0000250// isOnlyUse - Return true if this instruction will be deleted if we stop using
251// it.
252static bool isOnlyUse(Value *V) {
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000253 return V->hasOneUse() || isa<Constant>(V);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000254}
255
Chris Lattnere79e8542004-02-23 06:38:22 +0000256// getPromotedType - Return the specified type promoted as it would be to pass
257// though a va_arg area...
258static const Type *getPromotedType(const Type *Ty) {
Chris Lattner97bfcea2004-06-17 18:16:02 +0000259 switch (Ty->getTypeID()) {
Chris Lattnere79e8542004-02-23 06:38:22 +0000260 case Type::SByteTyID:
261 case Type::ShortTyID: return Type::IntTy;
262 case Type::UByteTyID:
263 case Type::UShortTyID: return Type::UIntTy;
264 case Type::FloatTyID: return Type::DoubleTy;
265 default: return Ty;
266 }
267}
268
Chris Lattner567b81f2005-09-13 00:40:14 +0000269/// isCast - If the specified operand is a CastInst or a constant expr cast,
270/// return the operand value, otherwise return null.
271static Value *isCast(Value *V) {
272 if (CastInst *I = dyn_cast<CastInst>(V))
273 return I->getOperand(0);
274 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
275 if (CE->getOpcode() == Instruction::Cast)
276 return CE->getOperand(0);
277 return 0;
278}
279
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000280// SimplifyCommutative - This performs a few simplifications for commutative
281// operators:
Chris Lattner260ab202002-04-18 17:39:14 +0000282//
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000283// 1. Order operands such that they are listed from right (least complex) to
284// left (most complex). This puts constants before unary operators before
285// binary operators.
286//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000287// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
288// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000289//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000290bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000291 bool Changed = false;
292 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
293 Changed = !I.swapOperands();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000294
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000295 if (!I.isAssociative()) return Changed;
296 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattner7fb29e12003-03-11 00:12:48 +0000297 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
298 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
299 if (isa<Constant>(I.getOperand(1))) {
Chris Lattner34428442003-05-27 16:40:51 +0000300 Constant *Folded = ConstantExpr::get(I.getOpcode(),
301 cast<Constant>(I.getOperand(1)),
302 cast<Constant>(Op->getOperand(1)));
Chris Lattner7fb29e12003-03-11 00:12:48 +0000303 I.setOperand(0, Op->getOperand(0));
304 I.setOperand(1, Folded);
305 return true;
306 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
307 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
308 isOnlyUse(Op) && isOnlyUse(Op1)) {
309 Constant *C1 = cast<Constant>(Op->getOperand(1));
310 Constant *C2 = cast<Constant>(Op1->getOperand(1));
311
312 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner34428442003-05-27 16:40:51 +0000313 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000314 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
315 Op1->getOperand(0),
316 Op1->getName(), &I);
317 WorkList.push_back(New);
318 I.setOperand(0, New);
319 I.setOperand(1, Folded);
320 return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000321 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000322 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000323 return Changed;
Chris Lattner260ab202002-04-18 17:39:14 +0000324}
Chris Lattnerca081252001-12-14 16:52:21 +0000325
Chris Lattnerbb74e222003-03-10 23:06:50 +0000326// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
327// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattner9fa53de2002-05-06 16:49:18 +0000328//
Chris Lattnerbb74e222003-03-10 23:06:50 +0000329static inline Value *dyn_castNegVal(Value *V) {
330 if (BinaryOperator::isNeg(V))
Chris Lattnerd6f636a2005-04-24 07:30:14 +0000331 return BinaryOperator::getNegArgument(V);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000332
Chris Lattner9ad0d552004-12-14 20:08:06 +0000333 // Constants can be considered to be negated values if they can be folded.
334 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
335 return ConstantExpr::getNeg(C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000336 return 0;
Chris Lattner9fa53de2002-05-06 16:49:18 +0000337}
338
Chris Lattnerbb74e222003-03-10 23:06:50 +0000339static inline Value *dyn_castNotVal(Value *V) {
340 if (BinaryOperator::isNot(V))
Chris Lattnerd6f636a2005-04-24 07:30:14 +0000341 return BinaryOperator::getNotArgument(V);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000342
343 // Constants can be considered to be not'ed values...
Chris Lattnerdd65d862003-04-30 22:34:06 +0000344 if (ConstantIntegral *C = dyn_cast<ConstantIntegral>(V))
Chris Lattnerc8e7e292004-06-10 02:12:35 +0000345 return ConstantExpr::getNot(C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000346 return 0;
347}
348
Chris Lattner7fb29e12003-03-11 00:12:48 +0000349// dyn_castFoldableMul - If this value is a multiply that can be folded into
350// other computations (because it has a constant operand), return the
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000351// non-constant operand of the multiply, and set CST to point to the multiplier.
352// Otherwise, return null.
Chris Lattner7fb29e12003-03-11 00:12:48 +0000353//
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000354static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000355 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000356 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattner7fb29e12003-03-11 00:12:48 +0000357 if (I->getOpcode() == Instruction::Mul)
Chris Lattner970136362004-11-15 05:54:07 +0000358 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattner7fb29e12003-03-11 00:12:48 +0000359 return I->getOperand(0);
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000360 if (I->getOpcode() == Instruction::Shl)
Chris Lattner970136362004-11-15 05:54:07 +0000361 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000362 // The multiplier is really 1 << CST.
363 Constant *One = ConstantInt::get(V->getType(), 1);
364 CST = cast<ConstantInt>(ConstantExpr::getShl(One, CST));
365 return I->getOperand(0);
366 }
367 }
Chris Lattner7fb29e12003-03-11 00:12:48 +0000368 return 0;
Chris Lattner3082c5a2003-02-18 19:28:33 +0000369}
Chris Lattner31ae8632002-08-14 17:51:49 +0000370
Chris Lattner0798af32005-01-13 20:14:25 +0000371/// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
372/// expression, return it.
373static User *dyn_castGetElementPtr(Value *V) {
374 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
375 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
376 if (CE->getOpcode() == Instruction::GetElementPtr)
377 return cast<User>(V);
378 return false;
379}
380
Chris Lattner623826c2004-09-28 21:48:02 +0000381// AddOne, SubOne - Add or subtract a constant one from an integer constant...
Chris Lattner6862fbd2004-09-29 17:40:11 +0000382static ConstantInt *AddOne(ConstantInt *C) {
383 return cast<ConstantInt>(ConstantExpr::getAdd(C,
384 ConstantInt::get(C->getType(), 1)));
Chris Lattner623826c2004-09-28 21:48:02 +0000385}
Chris Lattner6862fbd2004-09-29 17:40:11 +0000386static ConstantInt *SubOne(ConstantInt *C) {
387 return cast<ConstantInt>(ConstantExpr::getSub(C,
388 ConstantInt::get(C->getType(), 1)));
Chris Lattner623826c2004-09-28 21:48:02 +0000389}
390
Chris Lattner0b3557f2005-09-24 23:43:33 +0000391/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
392/// this predicate to simplify operations downstream. V and Mask are known to
393/// be the same type.
Chris Lattner09efd4e2005-10-31 18:35:52 +0000394static bool MaskedValueIsZero(Value *V, ConstantIntegral *Mask,
395 unsigned Depth = 0) {
Chris Lattner0b3557f2005-09-24 23:43:33 +0000396 // Note, we cannot consider 'undef' to be "IsZero" here. The problem is that
397 // we cannot optimize based on the assumption that it is zero without changing
398 // to to an explicit zero. If we don't change it to zero, other code could
399 // optimized based on the contradictory assumption that it is non-zero.
400 // Because instcombine aggressively folds operations with undef args anyway,
401 // this won't lose us code quality.
402 if (Mask->isNullValue())
403 return true;
404 if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(V))
405 return ConstantExpr::getAnd(CI, Mask)->isNullValue();
Chris Lattner09efd4e2005-10-31 18:35:52 +0000406
407 if (Depth == 6) return false; // Limit search depth.
Chris Lattner0b3557f2005-09-24 23:43:33 +0000408
409 if (Instruction *I = dyn_cast<Instruction>(V)) {
410 switch (I->getOpcode()) {
Chris Lattner62010c42005-10-09 06:36:35 +0000411 case Instruction::And:
412 // (X & C1) & C2 == 0 iff C1 & C2 == 0.
Chris Lattner03b9eb52005-10-09 22:08:50 +0000413 if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(I->getOperand(1))) {
414 ConstantIntegral *C1C2 =
415 cast<ConstantIntegral>(ConstantExpr::getAnd(CI, Mask));
Chris Lattner09efd4e2005-10-31 18:35:52 +0000416 if (MaskedValueIsZero(I->getOperand(0), C1C2, Depth+1))
Chris Lattner62010c42005-10-09 06:36:35 +0000417 return true;
Chris Lattner03b9eb52005-10-09 22:08:50 +0000418 }
419 // If either the LHS or the RHS are MaskedValueIsZero, the result is zero.
Chris Lattner09efd4e2005-10-31 18:35:52 +0000420 return MaskedValueIsZero(I->getOperand(1), Mask, Depth+1) ||
421 MaskedValueIsZero(I->getOperand(0), Mask, Depth+1);
Chris Lattner62010c42005-10-09 06:36:35 +0000422 case Instruction::Or:
Chris Lattner03b9eb52005-10-09 22:08:50 +0000423 case Instruction::Xor:
Chris Lattner62010c42005-10-09 06:36:35 +0000424 // If the LHS and the RHS are MaskedValueIsZero, the result is also zero.
Chris Lattner09efd4e2005-10-31 18:35:52 +0000425 return MaskedValueIsZero(I->getOperand(1), Mask, Depth+1) &&
426 MaskedValueIsZero(I->getOperand(0), Mask, Depth+1);
Chris Lattner62010c42005-10-09 06:36:35 +0000427 case Instruction::Select:
428 // If the T and F values are MaskedValueIsZero, the result is also zero.
Chris Lattner09efd4e2005-10-31 18:35:52 +0000429 return MaskedValueIsZero(I->getOperand(2), Mask, Depth+1) &&
430 MaskedValueIsZero(I->getOperand(1), Mask, Depth+1);
Chris Lattner62010c42005-10-09 06:36:35 +0000431 case Instruction::Cast: {
432 const Type *SrcTy = I->getOperand(0)->getType();
433 if (SrcTy == Type::BoolTy)
434 return (Mask->getRawValue() & 1) == 0;
435
436 if (SrcTy->isInteger()) {
437 // (cast <ty> X to int) & C2 == 0 iff <ty> could not have contained C2.
438 if (SrcTy->isUnsigned() && // Only handle zero ext.
439 ConstantExpr::getCast(Mask, SrcTy)->isNullValue())
440 return true;
Chris Lattner0b3557f2005-09-24 23:43:33 +0000441
Chris Lattner62010c42005-10-09 06:36:35 +0000442 // If this is a noop cast, recurse.
443 if ((SrcTy->isSigned() && SrcTy->getUnsignedVersion() == I->getType())||
444 SrcTy->getSignedVersion() == I->getType()) {
445 Constant *NewMask =
446 ConstantExpr::getCast(Mask, I->getOperand(0)->getType());
Chris Lattner0b3557f2005-09-24 23:43:33 +0000447 return MaskedValueIsZero(I->getOperand(0),
Chris Lattner09efd4e2005-10-31 18:35:52 +0000448 cast<ConstantIntegral>(NewMask), Depth+1);
Chris Lattner62010c42005-10-09 06:36:35 +0000449 }
450 }
451 break;
452 }
453 case Instruction::Shl:
454 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
455 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1)))
456 return MaskedValueIsZero(I->getOperand(0),
Chris Lattner09efd4e2005-10-31 18:35:52 +0000457 cast<ConstantIntegral>(ConstantExpr::getUShr(Mask, SA)),
458 Depth+1);
Chris Lattner62010c42005-10-09 06:36:35 +0000459 break;
460 case Instruction::Shr:
461 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
462 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1)))
463 if (I->getType()->isUnsigned()) {
464 Constant *C1 = ConstantIntegral::getAllOnesValue(I->getType());
465 C1 = ConstantExpr::getShr(C1, SA);
466 C1 = ConstantExpr::getAnd(C1, Mask);
467 if (C1->isNullValue())
468 return true;
469 }
470 break;
Chris Lattner0b3557f2005-09-24 23:43:33 +0000471 }
472 }
473
474 return false;
475}
476
Chris Lattner623826c2004-09-28 21:48:02 +0000477// isTrueWhenEqual - Return true if the specified setcondinst instruction is
478// true when both operands are equal...
479//
480static bool isTrueWhenEqual(Instruction &I) {
481 return I.getOpcode() == Instruction::SetEQ ||
482 I.getOpcode() == Instruction::SetGE ||
483 I.getOpcode() == Instruction::SetLE;
484}
Chris Lattnerb8b97502003-08-13 19:01:45 +0000485
486/// AssociativeOpt - Perform an optimization on an associative operator. This
487/// function is designed to check a chain of associative operators for a
488/// potential to apply a certain optimization. Since the optimization may be
489/// applicable if the expression was reassociated, this checks the chain, then
490/// reassociates the expression as necessary to expose the optimization
491/// opportunity. This makes use of a special Functor, which must define
492/// 'shouldApply' and 'apply' methods.
493///
494template<typename Functor>
495Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
496 unsigned Opcode = Root.getOpcode();
497 Value *LHS = Root.getOperand(0);
498
499 // Quick check, see if the immediate LHS matches...
500 if (F.shouldApply(LHS))
501 return F.apply(Root);
502
503 // Otherwise, if the LHS is not of the same opcode as the root, return.
504 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000505 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattnerb8b97502003-08-13 19:01:45 +0000506 // Should we apply this transform to the RHS?
507 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
508
509 // If not to the RHS, check to see if we should apply to the LHS...
510 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
511 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
512 ShouldApply = true;
513 }
514
515 // If the functor wants to apply the optimization to the RHS of LHSI,
516 // reassociate the expression from ((? op A) op B) to (? op (A op B))
517 if (ShouldApply) {
518 BasicBlock *BB = Root.getParent();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000519
Chris Lattnerb8b97502003-08-13 19:01:45 +0000520 // Now all of the instructions are in the current basic block, go ahead
521 // and perform the reassociation.
522 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
523
524 // First move the selected RHS to the LHS of the root...
525 Root.setOperand(0, LHSI->getOperand(1));
526
527 // Make what used to be the LHS of the root be the user of the root...
528 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner284d3b02004-04-16 18:08:07 +0000529 if (&Root == TmpLHSI) {
Chris Lattner8953b902004-04-05 02:10:19 +0000530 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
531 return 0;
532 }
Chris Lattner284d3b02004-04-16 18:08:07 +0000533 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattnerb8b97502003-08-13 19:01:45 +0000534 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner284d3b02004-04-16 18:08:07 +0000535 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
536 BasicBlock::iterator ARI = &Root; ++ARI;
537 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
538 ARI = Root;
Chris Lattnerb8b97502003-08-13 19:01:45 +0000539
540 // Now propagate the ExtraOperand down the chain of instructions until we
541 // get to LHSI.
542 while (TmpLHSI != LHSI) {
543 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner284d3b02004-04-16 18:08:07 +0000544 // Move the instruction to immediately before the chain we are
545 // constructing to avoid breaking dominance properties.
546 NextLHSI->getParent()->getInstList().remove(NextLHSI);
547 BB->getInstList().insert(ARI, NextLHSI);
548 ARI = NextLHSI;
549
Chris Lattnerb8b97502003-08-13 19:01:45 +0000550 Value *NextOp = NextLHSI->getOperand(1);
551 NextLHSI->setOperand(1, ExtraOperand);
552 TmpLHSI = NextLHSI;
553 ExtraOperand = NextOp;
554 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000555
Chris Lattnerb8b97502003-08-13 19:01:45 +0000556 // Now that the instructions are reassociated, have the functor perform
557 // the transformation...
558 return F.apply(Root);
559 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000560
Chris Lattnerb8b97502003-08-13 19:01:45 +0000561 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
562 }
563 return 0;
564}
565
566
567// AddRHS - Implements: X + X --> X << 1
568struct AddRHS {
569 Value *RHS;
570 AddRHS(Value *rhs) : RHS(rhs) {}
571 bool shouldApply(Value *LHS) const { return LHS == RHS; }
572 Instruction *apply(BinaryOperator &Add) const {
573 return new ShiftInst(Instruction::Shl, Add.getOperand(0),
574 ConstantInt::get(Type::UByteTy, 1));
575 }
576};
577
578// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
579// iff C1&C2 == 0
580struct AddMaskingAnd {
581 Constant *C2;
582 AddMaskingAnd(Constant *c) : C2(c) {}
583 bool shouldApply(Value *LHS) const {
Chris Lattnerd4252a72004-07-30 07:50:03 +0000584 ConstantInt *C1;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000585 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Chris Lattnerd4252a72004-07-30 07:50:03 +0000586 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattnerb8b97502003-08-13 19:01:45 +0000587 }
588 Instruction *apply(BinaryOperator &Add) const {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000589 return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattnerb8b97502003-08-13 19:01:45 +0000590 }
591};
592
Chris Lattner86102b82005-01-01 16:22:27 +0000593static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner183b3362004-04-09 19:05:30 +0000594 InstCombiner *IC) {
Chris Lattner86102b82005-01-01 16:22:27 +0000595 if (isa<CastInst>(I)) {
596 if (Constant *SOC = dyn_cast<Constant>(SO))
597 return ConstantExpr::getCast(SOC, I.getType());
Misha Brukmanb1c93172005-04-21 23:48:37 +0000598
Chris Lattner86102b82005-01-01 16:22:27 +0000599 return IC->InsertNewInstBefore(new CastInst(SO, I.getType(),
600 SO->getName() + ".cast"), I);
601 }
602
Chris Lattner183b3362004-04-09 19:05:30 +0000603 // Figure out if the constant is the left or the right argument.
Chris Lattner86102b82005-01-01 16:22:27 +0000604 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
605 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattnerb8b97502003-08-13 19:01:45 +0000606
Chris Lattner183b3362004-04-09 19:05:30 +0000607 if (Constant *SOC = dyn_cast<Constant>(SO)) {
608 if (ConstIsRHS)
Chris Lattner86102b82005-01-01 16:22:27 +0000609 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
610 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner183b3362004-04-09 19:05:30 +0000611 }
612
613 Value *Op0 = SO, *Op1 = ConstOperand;
614 if (!ConstIsRHS)
615 std::swap(Op0, Op1);
616 Instruction *New;
Chris Lattner86102b82005-01-01 16:22:27 +0000617 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
618 New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
619 else if (ShiftInst *SI = dyn_cast<ShiftInst>(&I))
620 New = new ShiftInst(SI->getOpcode(), Op0, Op1, SO->getName()+".sh");
Chris Lattnerf9d96652004-04-10 19:15:56 +0000621 else {
Chris Lattner183b3362004-04-09 19:05:30 +0000622 assert(0 && "Unknown binary instruction type!");
Chris Lattnerf9d96652004-04-10 19:15:56 +0000623 abort();
624 }
Chris Lattner86102b82005-01-01 16:22:27 +0000625 return IC->InsertNewInstBefore(New, I);
626}
627
628// FoldOpIntoSelect - Given an instruction with a select as one operand and a
629// constant as the other operand, try to fold the binary operator into the
630// select arguments. This also works for Cast instructions, which obviously do
631// not have a second operand.
632static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
633 InstCombiner *IC) {
634 // Don't modify shared select instructions
635 if (!SI->hasOneUse()) return 0;
636 Value *TV = SI->getOperand(1);
637 Value *FV = SI->getOperand(2);
638
639 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner374e6592005-04-21 05:43:13 +0000640 // Bool selects with constant operands can be folded to logical ops.
641 if (SI->getType() == Type::BoolTy) return 0;
642
Chris Lattner86102b82005-01-01 16:22:27 +0000643 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
644 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
645
646 return new SelectInst(SI->getCondition(), SelectTrueVal,
647 SelectFalseVal);
648 }
649 return 0;
Chris Lattner183b3362004-04-09 19:05:30 +0000650}
651
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000652
653/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
654/// node as operand #0, see if we can fold the instruction into the PHI (which
655/// is only possible if all operands to the PHI are constants).
656Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
657 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattner7515cab2004-11-14 19:13:23 +0000658 unsigned NumPHIValues = PN->getNumIncomingValues();
659 if (!PN->hasOneUse() || NumPHIValues == 0 ||
660 !isa<Constant>(PN->getIncomingValue(0))) return 0;
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000661
662 // Check to see if all of the operands of the PHI are constants. If not, we
663 // cannot do the transformation.
Chris Lattner7515cab2004-11-14 19:13:23 +0000664 for (unsigned i = 1; i != NumPHIValues; ++i)
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000665 if (!isa<Constant>(PN->getIncomingValue(i)))
666 return 0;
667
668 // Okay, we can do the transformation: create the new PHI node.
669 PHINode *NewPN = new PHINode(I.getType(), I.getName());
670 I.setName("");
Chris Lattnerd8e20182005-01-29 00:39:08 +0000671 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000672 InsertNewInstBefore(NewPN, *PN);
673
674 // Next, add all of the operands to the PHI.
675 if (I.getNumOperands() == 2) {
676 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattner7515cab2004-11-14 19:13:23 +0000677 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000678 Constant *InV = cast<Constant>(PN->getIncomingValue(i));
679 NewPN->addIncoming(ConstantExpr::get(I.getOpcode(), InV, C),
680 PN->getIncomingBlock(i));
681 }
682 } else {
683 assert(isa<CastInst>(I) && "Unary op should be a cast!");
684 const Type *RetTy = I.getType();
Chris Lattner7515cab2004-11-14 19:13:23 +0000685 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000686 Constant *InV = cast<Constant>(PN->getIncomingValue(i));
687 NewPN->addIncoming(ConstantExpr::getCast(InV, RetTy),
688 PN->getIncomingBlock(i));
689 }
690 }
691 return ReplaceInstUsesWith(I, NewPN);
692}
693
Chris Lattner113f4f42002-06-25 16:13:24 +0000694Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000695 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000696 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000697
Chris Lattnercf4a9962004-04-10 22:01:55 +0000698 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattner81a7a232004-10-16 18:11:37 +0000699 // X + undef -> undef
700 if (isa<UndefValue>(RHS))
701 return ReplaceInstUsesWith(I, RHS);
702
Chris Lattnercf4a9962004-04-10 22:01:55 +0000703 // X + 0 --> X
Chris Lattner7fde91e2005-10-17 17:56:38 +0000704 if (!I.getType()->isFloatingPoint()) { // NOTE: -0 + +0 = +0.
705 if (RHSC->isNullValue())
706 return ReplaceInstUsesWith(I, LHS);
Chris Lattnerda1b1522005-10-17 20:18:38 +0000707 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
708 if (CFP->isExactlyValue(-0.0))
709 return ReplaceInstUsesWith(I, LHS);
Chris Lattner7fde91e2005-10-17 17:56:38 +0000710 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000711
Chris Lattnercf4a9962004-04-10 22:01:55 +0000712 // X + (signbit) --> X ^ signbit
713 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +0000714 unsigned NumBits = CI->getType()->getPrimitiveSizeInBits();
Andrew Lenharth66229552005-11-02 18:35:40 +0000715 uint64_t Val = CI->getRawValue() & (~0ULL >> (64- NumBits));
Chris Lattner33eb9092004-11-05 04:45:43 +0000716 if (Val == (1ULL << (NumBits-1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000717 return BinaryOperator::createXor(LHS, RHS);
Chris Lattnercf4a9962004-04-10 22:01:55 +0000718 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000719
720 if (isa<PHINode>(LHS))
721 if (Instruction *NV = FoldOpIntoPhi(I))
722 return NV;
Chris Lattner0b3557f2005-09-24 23:43:33 +0000723
724 ConstantInt *XorRHS;
725 Value *XorLHS;
726 if (match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
727 unsigned TySizeBits = I.getType()->getPrimitiveSizeInBits();
728 int64_t RHSSExt = cast<ConstantInt>(RHSC)->getSExtValue();
729 uint64_t RHSZExt = cast<ConstantInt>(RHSC)->getZExtValue();
730
731 uint64_t C0080Val = 1ULL << 31;
732 int64_t CFF80Val = -C0080Val;
733 unsigned Size = 32;
734 do {
735 if (TySizeBits > Size) {
736 bool Found = false;
737 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
738 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
739 if (RHSSExt == CFF80Val) {
740 if (XorRHS->getZExtValue() == C0080Val)
741 Found = true;
742 } else if (RHSZExt == C0080Val) {
743 if (XorRHS->getSExtValue() == CFF80Val)
744 Found = true;
745 }
746 if (Found) {
747 // This is a sign extend if the top bits are known zero.
748 Constant *Mask = ConstantInt::getAllOnesValue(XorLHS->getType());
749 Mask = ConstantExpr::getShl(Mask,
750 ConstantInt::get(Type::UByteTy, 64-TySizeBits-Size));
751 if (!MaskedValueIsZero(XorLHS, cast<ConstantInt>(Mask)))
752 Size = 0; // Not a sign ext, but can't be any others either.
753 goto FoundSExt;
754 }
755 }
756 Size >>= 1;
757 C0080Val >>= Size;
758 CFF80Val >>= Size;
759 } while (Size >= 8);
760
761FoundSExt:
762 const Type *MiddleType = 0;
763 switch (Size) {
764 default: break;
765 case 32: MiddleType = Type::IntTy; break;
766 case 16: MiddleType = Type::ShortTy; break;
767 case 8: MiddleType = Type::SByteTy; break;
768 }
769 if (MiddleType) {
770 Instruction *NewTrunc = new CastInst(XorLHS, MiddleType, "sext");
771 InsertNewInstBefore(NewTrunc, I);
772 return new CastInst(NewTrunc, I.getType());
773 }
774 }
Chris Lattnercf4a9962004-04-10 22:01:55 +0000775 }
Chris Lattner9fa53de2002-05-06 16:49:18 +0000776
Chris Lattnerb8b97502003-08-13 19:01:45 +0000777 // X + X --> X << 1
Robert Bocchino7b5b86c2004-07-27 21:02:21 +0000778 if (I.getType()->isInteger()) {
Chris Lattnerb8b97502003-08-13 19:01:45 +0000779 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Chris Lattner47060462005-04-07 17:14:51 +0000780
781 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
782 if (RHSI->getOpcode() == Instruction::Sub)
783 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
784 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
785 }
786 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
787 if (LHSI->getOpcode() == Instruction::Sub)
788 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
789 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
790 }
Robert Bocchino7b5b86c2004-07-27 21:02:21 +0000791 }
Chris Lattnerede3fe02003-08-13 04:18:28 +0000792
Chris Lattner147e9752002-05-08 22:46:53 +0000793 // -A + B --> B - A
Chris Lattnerbb74e222003-03-10 23:06:50 +0000794 if (Value *V = dyn_castNegVal(LHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000795 return BinaryOperator::createSub(RHS, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000796
797 // A + -B --> A - B
Chris Lattnerbb74e222003-03-10 23:06:50 +0000798 if (!isa<Constant>(RHS))
799 if (Value *V = dyn_castNegVal(RHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000800 return BinaryOperator::createSub(LHS, V);
Chris Lattner260ab202002-04-18 17:39:14 +0000801
Misha Brukmanb1c93172005-04-21 23:48:37 +0000802
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000803 ConstantInt *C2;
804 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
805 if (X == RHS) // X*C + X --> X * (C+1)
806 return BinaryOperator::createMul(RHS, AddOne(C2));
807
808 // X*C1 + X*C2 --> X * (C1+C2)
809 ConstantInt *C1;
810 if (X == dyn_castFoldableMul(RHS, C1))
811 return BinaryOperator::createMul(X, ConstantExpr::getAdd(C1, C2));
Chris Lattner57c8d992003-02-18 19:57:07 +0000812 }
813
814 // X + X*C --> X * (C+1)
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000815 if (dyn_castFoldableMul(RHS, C2) == LHS)
816 return BinaryOperator::createMul(LHS, AddOne(C2));
817
Chris Lattner57c8d992003-02-18 19:57:07 +0000818
Chris Lattnerb8b97502003-08-13 19:01:45 +0000819 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattnerd4252a72004-07-30 07:50:03 +0000820 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattnerb8b97502003-08-13 19:01:45 +0000821 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2))) return R;
Chris Lattner7fb29e12003-03-11 00:12:48 +0000822
Chris Lattnerb9cde762003-10-02 15:11:26 +0000823 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattnerd4252a72004-07-30 07:50:03 +0000824 Value *X;
825 if (match(LHS, m_Not(m_Value(X)))) { // ~X + C --> (C-1) - X
826 Constant *C= ConstantExpr::getSub(CRHS, ConstantInt::get(I.getType(), 1));
827 return BinaryOperator::createSub(C, X);
Chris Lattnerb9cde762003-10-02 15:11:26 +0000828 }
Chris Lattnerd4252a72004-07-30 07:50:03 +0000829
Chris Lattnerbff91d92004-10-08 05:07:56 +0000830 // (X & FF00) + xx00 -> (X+xx00) & FF00
831 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
832 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
833 if (Anded == CRHS) {
834 // See if all bits from the first bit set in the Add RHS up are included
835 // in the mask. First, get the rightmost bit.
836 uint64_t AddRHSV = CRHS->getRawValue();
837
838 // Form a mask of all bits from the lowest bit added through the top.
839 uint64_t AddRHSHighBits = ~((AddRHSV & -AddRHSV)-1);
Chris Lattner2f1457f2005-04-24 17:46:05 +0000840 AddRHSHighBits &= ~0ULL >> (64-C2->getType()->getPrimitiveSizeInBits());
Chris Lattnerbff91d92004-10-08 05:07:56 +0000841
842 // See if the and mask includes all of these bits.
843 uint64_t AddRHSHighBitsAnd = AddRHSHighBits & C2->getRawValue();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000844
Chris Lattnerbff91d92004-10-08 05:07:56 +0000845 if (AddRHSHighBits == AddRHSHighBitsAnd) {
846 // Okay, the xform is safe. Insert the new add pronto.
847 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
848 LHS->getName()), I);
849 return BinaryOperator::createAnd(NewAdd, C2);
850 }
851 }
852 }
853
Chris Lattnerd4252a72004-07-30 07:50:03 +0000854 // Try to fold constant add into select arguments.
855 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner86102b82005-01-01 16:22:27 +0000856 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattnerd4252a72004-07-30 07:50:03 +0000857 return R;
Chris Lattnerb9cde762003-10-02 15:11:26 +0000858 }
859
Chris Lattner113f4f42002-06-25 16:13:24 +0000860 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +0000861}
862
Chris Lattnerbdb0ce02003-07-22 21:46:59 +0000863// isSignBit - Return true if the value represented by the constant only has the
864// highest order bit set.
865static bool isSignBit(ConstantInt *CI) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +0000866 unsigned NumBits = CI->getType()->getPrimitiveSizeInBits();
Chris Lattner2f1457f2005-04-24 17:46:05 +0000867 return (CI->getRawValue() & (~0ULL >> (64-NumBits))) == (1ULL << (NumBits-1));
Chris Lattnerbdb0ce02003-07-22 21:46:59 +0000868}
869
Chris Lattner022167f2004-03-13 00:11:49 +0000870/// RemoveNoopCast - Strip off nonconverting casts from the value.
871///
872static Value *RemoveNoopCast(Value *V) {
873 if (CastInst *CI = dyn_cast<CastInst>(V)) {
874 const Type *CTy = CI->getType();
875 const Type *OpTy = CI->getOperand(0)->getType();
876 if (CTy->isInteger() && OpTy->isInteger()) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +0000877 if (CTy->getPrimitiveSizeInBits() == OpTy->getPrimitiveSizeInBits())
Chris Lattner022167f2004-03-13 00:11:49 +0000878 return RemoveNoopCast(CI->getOperand(0));
879 } else if (isa<PointerType>(CTy) && isa<PointerType>(OpTy))
880 return RemoveNoopCast(CI->getOperand(0));
881 }
882 return V;
883}
884
Chris Lattner113f4f42002-06-25 16:13:24 +0000885Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +0000886 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000887
Chris Lattnere6794492002-08-12 21:17:25 +0000888 if (Op0 == Op1) // sub X, X -> 0
889 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner260ab202002-04-18 17:39:14 +0000890
Chris Lattnere6794492002-08-12 21:17:25 +0000891 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattnerbb74e222003-03-10 23:06:50 +0000892 if (Value *V = dyn_castNegVal(Op1))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000893 return BinaryOperator::createAdd(Op0, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000894
Chris Lattner81a7a232004-10-16 18:11:37 +0000895 if (isa<UndefValue>(Op0))
896 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
897 if (isa<UndefValue>(Op1))
898 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
899
Chris Lattner8f2f5982003-11-05 01:06:05 +0000900 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
901 // Replace (-1 - A) with (~A)...
Chris Lattner3082c5a2003-02-18 19:28:33 +0000902 if (C->isAllOnesValue())
903 return BinaryOperator::createNot(Op1);
Chris Lattnerad3c4952002-05-09 01:29:19 +0000904
Chris Lattner8f2f5982003-11-05 01:06:05 +0000905 // C - ~X == X + (1+C)
Reid Spencer4fdd96c2005-06-18 17:37:34 +0000906 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +0000907 if (match(Op1, m_Not(m_Value(X))))
908 return BinaryOperator::createAdd(X,
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000909 ConstantExpr::getAdd(C, ConstantInt::get(I.getType(), 1)));
Chris Lattner92295c52004-03-12 23:53:13 +0000910 // -((uint)X >> 31) -> ((int)X >> 31)
911 // -((int)X >> 31) -> ((uint)X >> 31)
Chris Lattner022167f2004-03-13 00:11:49 +0000912 if (C->isNullValue()) {
913 Value *NoopCastedRHS = RemoveNoopCast(Op1);
914 if (ShiftInst *SI = dyn_cast<ShiftInst>(NoopCastedRHS))
Chris Lattner92295c52004-03-12 23:53:13 +0000915 if (SI->getOpcode() == Instruction::Shr)
916 if (ConstantUInt *CU = dyn_cast<ConstantUInt>(SI->getOperand(1))) {
917 const Type *NewTy;
Chris Lattner022167f2004-03-13 00:11:49 +0000918 if (SI->getType()->isSigned())
Chris Lattner97bfcea2004-06-17 18:16:02 +0000919 NewTy = SI->getType()->getUnsignedVersion();
Chris Lattner92295c52004-03-12 23:53:13 +0000920 else
Chris Lattner97bfcea2004-06-17 18:16:02 +0000921 NewTy = SI->getType()->getSignedVersion();
Chris Lattner92295c52004-03-12 23:53:13 +0000922 // Check to see if we are shifting out everything but the sign bit.
Chris Lattnerd1f46d32005-04-24 06:59:08 +0000923 if (CU->getValue() == SI->getType()->getPrimitiveSizeInBits()-1) {
Chris Lattner92295c52004-03-12 23:53:13 +0000924 // Ok, the transformation is safe. Insert a cast of the incoming
925 // value, then the new shift, then the new cast.
926 Instruction *FirstCast = new CastInst(SI->getOperand(0), NewTy,
927 SI->getOperand(0)->getName());
928 Value *InV = InsertNewInstBefore(FirstCast, I);
929 Instruction *NewShift = new ShiftInst(Instruction::Shr, FirstCast,
930 CU, SI->getName());
Chris Lattner022167f2004-03-13 00:11:49 +0000931 if (NewShift->getType() == I.getType())
932 return NewShift;
933 else {
934 InV = InsertNewInstBefore(NewShift, I);
935 return new CastInst(NewShift, I.getType());
936 }
Chris Lattner92295c52004-03-12 23:53:13 +0000937 }
938 }
Chris Lattner022167f2004-03-13 00:11:49 +0000939 }
Chris Lattner183b3362004-04-09 19:05:30 +0000940
941 // Try to fold constant sub into select arguments.
942 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner86102b82005-01-01 16:22:27 +0000943 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +0000944 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000945
946 if (isa<PHINode>(Op0))
947 if (Instruction *NV = FoldOpIntoPhi(I))
948 return NV;
Chris Lattner8f2f5982003-11-05 01:06:05 +0000949 }
950
Chris Lattnera9be4492005-04-07 16:15:25 +0000951 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
952 if (Op1I->getOpcode() == Instruction::Add &&
953 !Op0->getType()->isFloatingPoint()) {
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +0000954 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Chris Lattnera9be4492005-04-07 16:15:25 +0000955 return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +0000956 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Chris Lattnera9be4492005-04-07 16:15:25 +0000957 return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +0000958 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
959 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
960 // C1-(X+C2) --> (C1-C2)-X
961 return BinaryOperator::createSub(ConstantExpr::getSub(CI1, CI2),
962 Op1I->getOperand(0));
963 }
Chris Lattnera9be4492005-04-07 16:15:25 +0000964 }
965
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000966 if (Op1I->hasOneUse()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +0000967 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
968 // is not used by anyone else...
969 //
Chris Lattnerc2f0aa52004-02-02 20:09:56 +0000970 if (Op1I->getOpcode() == Instruction::Sub &&
971 !Op1I->getType()->isFloatingPoint()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +0000972 // Swap the two operands of the subexpr...
973 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
974 Op1I->setOperand(0, IIOp1);
975 Op1I->setOperand(1, IIOp0);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000976
Chris Lattner3082c5a2003-02-18 19:28:33 +0000977 // Create the new top level add instruction...
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000978 return BinaryOperator::createAdd(Op0, Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000979 }
980
981 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
982 //
983 if (Op1I->getOpcode() == Instruction::And &&
984 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
985 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
986
Chris Lattner396dbfe2004-06-09 05:08:07 +0000987 Value *NewNot =
988 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000989 return BinaryOperator::createAnd(Op0, NewNot);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000990 }
Chris Lattner57c8d992003-02-18 19:57:07 +0000991
Chris Lattner0aee4b72004-10-06 15:08:25 +0000992 // -(X sdiv C) -> (X sdiv -C)
993 if (Op1I->getOpcode() == Instruction::Div)
994 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
Chris Lattnera9be4492005-04-07 16:15:25 +0000995 if (CSI->isNullValue())
Chris Lattner0aee4b72004-10-06 15:08:25 +0000996 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Misha Brukmanb1c93172005-04-21 23:48:37 +0000997 return BinaryOperator::createDiv(Op1I->getOperand(0),
Chris Lattner0aee4b72004-10-06 15:08:25 +0000998 ConstantExpr::getNeg(DivRHS));
999
Chris Lattner57c8d992003-02-18 19:57:07 +00001000 // X - X*C --> X * (1-C)
Reid Spencer4fdd96c2005-06-18 17:37:34 +00001001 ConstantInt *C2 = 0;
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001002 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00001003 Constant *CP1 =
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001004 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1), C2);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001005 return BinaryOperator::createMul(Op0, CP1);
Chris Lattner57c8d992003-02-18 19:57:07 +00001006 }
Chris Lattnerad3c4952002-05-09 01:29:19 +00001007 }
Chris Lattnera9be4492005-04-07 16:15:25 +00001008 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00001009
Chris Lattner47060462005-04-07 17:14:51 +00001010 if (!Op0->getType()->isFloatingPoint())
1011 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
1012 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner411336f2005-01-19 21:50:18 +00001013 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
1014 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
1015 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
1016 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner47060462005-04-07 17:14:51 +00001017 } else if (Op0I->getOpcode() == Instruction::Sub) {
1018 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
1019 return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
Chris Lattner411336f2005-01-19 21:50:18 +00001020 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001021
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001022 ConstantInt *C1;
1023 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
1024 if (X == Op1) { // X*C - X --> X * (C-1)
1025 Constant *CP1 = ConstantExpr::getSub(C1, ConstantInt::get(I.getType(),1));
1026 return BinaryOperator::createMul(Op1, CP1);
1027 }
Chris Lattner57c8d992003-02-18 19:57:07 +00001028
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001029 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
1030 if (X == dyn_castFoldableMul(Op1, C2))
1031 return BinaryOperator::createMul(Op1, ConstantExpr::getSub(C1, C2));
1032 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001033 return 0;
Chris Lattner260ab202002-04-18 17:39:14 +00001034}
1035
Chris Lattnere79e8542004-02-23 06:38:22 +00001036/// isSignBitCheck - Given an exploded setcc instruction, return true if it is
1037/// really just returns true if the most significant (sign) bit is set.
1038static bool isSignBitCheck(unsigned Opcode, Value *LHS, ConstantInt *RHS) {
1039 if (RHS->getType()->isSigned()) {
1040 // True if source is LHS < 0 or LHS <= -1
1041 return Opcode == Instruction::SetLT && RHS->isNullValue() ||
1042 Opcode == Instruction::SetLE && RHS->isAllOnesValue();
1043 } else {
1044 ConstantUInt *RHSC = cast<ConstantUInt>(RHS);
1045 // True if source is LHS > 127 or LHS >= 128, where the constants depend on
1046 // the size of the integer type.
1047 if (Opcode == Instruction::SetGE)
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001048 return RHSC->getValue() ==
1049 1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1);
Chris Lattnere79e8542004-02-23 06:38:22 +00001050 if (Opcode == Instruction::SetGT)
1051 return RHSC->getValue() ==
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001052 (1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1))-1;
Chris Lattnere79e8542004-02-23 06:38:22 +00001053 }
1054 return false;
1055}
1056
Chris Lattner113f4f42002-06-25 16:13:24 +00001057Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001058 bool Changed = SimplifyCommutative(I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001059 Value *Op0 = I.getOperand(0);
Chris Lattner260ab202002-04-18 17:39:14 +00001060
Chris Lattner81a7a232004-10-16 18:11:37 +00001061 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
1062 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1063
Chris Lattnere6794492002-08-12 21:17:25 +00001064 // Simplify mul instructions with a constant RHS...
Chris Lattner3082c5a2003-02-18 19:28:33 +00001065 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
1066 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerede3fe02003-08-13 04:18:28 +00001067
1068 // ((X << C1)*C2) == (X * (C2 << C1))
1069 if (ShiftInst *SI = dyn_cast<ShiftInst>(Op0))
1070 if (SI->getOpcode() == Instruction::Shl)
1071 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001072 return BinaryOperator::createMul(SI->getOperand(0),
1073 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanb1c93172005-04-21 23:48:37 +00001074
Chris Lattnercce81be2003-09-11 22:24:54 +00001075 if (CI->isNullValue())
1076 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
1077 if (CI->equalsInt(1)) // X * 1 == X
1078 return ReplaceInstUsesWith(I, Op0);
1079 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Chris Lattner35236d82003-06-25 17:09:20 +00001080 return BinaryOperator::createNeg(Op0, I.getName());
Chris Lattner31ba1292002-04-29 22:24:47 +00001081
Chris Lattnercce81be2003-09-11 22:24:54 +00001082 int64_t Val = (int64_t)cast<ConstantInt>(CI)->getRawValue();
Chris Lattner22d00a82005-08-02 19:16:58 +00001083 if (isPowerOf2_64(Val)) { // Replace X*(2^C) with X << C
1084 uint64_t C = Log2_64(Val);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001085 return new ShiftInst(Instruction::Shl, Op0,
1086 ConstantUInt::get(Type::UByteTy, C));
Chris Lattner22d00a82005-08-02 19:16:58 +00001087 }
Robert Bocchino7b5b86c2004-07-27 21:02:21 +00001088 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00001089 if (Op1F->isNullValue())
1090 return ReplaceInstUsesWith(I, Op1);
Chris Lattner31ba1292002-04-29 22:24:47 +00001091
Chris Lattner3082c5a2003-02-18 19:28:33 +00001092 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
1093 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
1094 if (Op1F->getValue() == 1.0)
1095 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
1096 }
Chris Lattner183b3362004-04-09 19:05:30 +00001097
1098 // Try to fold constant mul into select arguments.
1099 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00001100 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00001101 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001102
1103 if (isa<PHINode>(Op0))
1104 if (Instruction *NV = FoldOpIntoPhi(I))
1105 return NV;
Chris Lattner260ab202002-04-18 17:39:14 +00001106 }
1107
Chris Lattner934a64cf2003-03-10 23:23:04 +00001108 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
1109 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001110 return BinaryOperator::createMul(Op0v, Op1v);
Chris Lattner934a64cf2003-03-10 23:23:04 +00001111
Chris Lattner2635b522004-02-23 05:39:21 +00001112 // If one of the operands of the multiply is a cast from a boolean value, then
1113 // we know the bool is either zero or one, so this is a 'masking' multiply.
1114 // See if we can simplify things based on how the boolean was originally
1115 // formed.
1116 CastInst *BoolCast = 0;
1117 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(0)))
1118 if (CI->getOperand(0)->getType() == Type::BoolTy)
1119 BoolCast = CI;
1120 if (!BoolCast)
1121 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(1)))
1122 if (CI->getOperand(0)->getType() == Type::BoolTy)
1123 BoolCast = CI;
1124 if (BoolCast) {
1125 if (SetCondInst *SCI = dyn_cast<SetCondInst>(BoolCast->getOperand(0))) {
1126 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
1127 const Type *SCOpTy = SCIOp0->getType();
1128
Chris Lattnere79e8542004-02-23 06:38:22 +00001129 // If the setcc is true iff the sign bit of X is set, then convert this
1130 // multiply into a shift/and combination.
1131 if (isa<ConstantInt>(SCIOp1) &&
1132 isSignBitCheck(SCI->getOpcode(), SCIOp0, cast<ConstantInt>(SCIOp1))) {
Chris Lattner2635b522004-02-23 05:39:21 +00001133 // Shift the X value right to turn it into "all signbits".
1134 Constant *Amt = ConstantUInt::get(Type::UByteTy,
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001135 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattnere79e8542004-02-23 06:38:22 +00001136 if (SCIOp0->getType()->isUnsigned()) {
Chris Lattner97bfcea2004-06-17 18:16:02 +00001137 const Type *NewTy = SCIOp0->getType()->getSignedVersion();
Chris Lattnere79e8542004-02-23 06:38:22 +00001138 SCIOp0 = InsertNewInstBefore(new CastInst(SCIOp0, NewTy,
1139 SCIOp0->getName()), I);
1140 }
1141
1142 Value *V =
1143 InsertNewInstBefore(new ShiftInst(Instruction::Shr, SCIOp0, Amt,
1144 BoolCast->getOperand(0)->getName()+
1145 ".mask"), I);
Chris Lattner2635b522004-02-23 05:39:21 +00001146
1147 // If the multiply type is not the same as the source type, sign extend
1148 // or truncate to the multiply type.
1149 if (I.getType() != V->getType())
Chris Lattnere79e8542004-02-23 06:38:22 +00001150 V = InsertNewInstBefore(new CastInst(V, I.getType(), V->getName()),I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001151
Chris Lattner2635b522004-02-23 05:39:21 +00001152 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001153 return BinaryOperator::createAnd(V, OtherOp);
Chris Lattner2635b522004-02-23 05:39:21 +00001154 }
1155 }
1156 }
1157
Chris Lattner113f4f42002-06-25 16:13:24 +00001158 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +00001159}
1160
Chris Lattner113f4f42002-06-25 16:13:24 +00001161Instruction *InstCombiner::visitDiv(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001162 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner81a7a232004-10-16 18:11:37 +00001163
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001164 if (isa<UndefValue>(Op0)) // undef / X -> 0
1165 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1166 if (isa<UndefValue>(Op1))
1167 return ReplaceInstUsesWith(I, Op1); // X / undef -> undef
1168
1169 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnere20c3342004-04-26 14:01:59 +00001170 // div X, 1 == X
Chris Lattnere6794492002-08-12 21:17:25 +00001171 if (RHS->equalsInt(1))
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001172 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001173
Chris Lattnere20c3342004-04-26 14:01:59 +00001174 // div X, -1 == -X
1175 if (RHS->isAllOnesValue())
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001176 return BinaryOperator::createNeg(Op0);
Chris Lattnere20c3342004-04-26 14:01:59 +00001177
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001178 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
Chris Lattner272d5ca2004-09-28 18:22:15 +00001179 if (LHS->getOpcode() == Instruction::Div)
1180 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Chris Lattner272d5ca2004-09-28 18:22:15 +00001181 // (X / C1) / C2 -> X / (C1*C2)
1182 return BinaryOperator::createDiv(LHS->getOperand(0),
1183 ConstantExpr::getMul(RHS, LHSRHS));
1184 }
1185
Chris Lattner3082c5a2003-02-18 19:28:33 +00001186 // Check to see if this is an unsigned division with an exact power of 2,
1187 // if so, convert to a right shift.
1188 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
1189 if (uint64_t Val = C->getValue()) // Don't break X / 0
Chris Lattner22d00a82005-08-02 19:16:58 +00001190 if (isPowerOf2_64(Val)) {
1191 uint64_t C = Log2_64(Val);
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001192 return new ShiftInst(Instruction::Shr, Op0,
Chris Lattner3082c5a2003-02-18 19:28:33 +00001193 ConstantUInt::get(Type::UByteTy, C));
Chris Lattner22d00a82005-08-02 19:16:58 +00001194 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001195
Chris Lattner4ad08352004-10-09 02:50:40 +00001196 // -X/C -> X/-C
1197 if (RHS->getType()->isSigned())
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001198 if (Value *LHSNeg = dyn_castNegVal(Op0))
Chris Lattner4ad08352004-10-09 02:50:40 +00001199 return BinaryOperator::createDiv(LHSNeg, ConstantExpr::getNeg(RHS));
1200
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001201 if (!RHS->isNullValue()) {
1202 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00001203 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001204 return R;
1205 if (isa<PHINode>(Op0))
1206 if (Instruction *NV = FoldOpIntoPhi(I))
1207 return NV;
1208 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00001209 }
1210
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001211 // If this is 'udiv X, (Cond ? C1, C2)' where C1&C2 are powers of two,
1212 // transform this into: '(Cond ? (udiv X, C1) : (udiv X, C2))'.
1213 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1214 if (ConstantUInt *STO = dyn_cast<ConstantUInt>(SI->getOperand(1)))
1215 if (ConstantUInt *SFO = dyn_cast<ConstantUInt>(SI->getOperand(2))) {
1216 if (STO->getValue() == 0) { // Couldn't be this argument.
1217 I.setOperand(1, SFO);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001218 return &I;
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001219 } else if (SFO->getValue() == 0) {
Chris Lattner89dc4f12005-06-16 04:55:52 +00001220 I.setOperand(1, STO);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001221 return &I;
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001222 }
1223
Chris Lattner42362612005-04-08 04:03:26 +00001224 uint64_t TVA = STO->getValue(), FVA = SFO->getValue();
Chris Lattner22d00a82005-08-02 19:16:58 +00001225 if (isPowerOf2_64(TVA) && isPowerOf2_64(FVA)) {
1226 unsigned TSA = Log2_64(TVA), FSA = Log2_64(FVA);
Chris Lattner42362612005-04-08 04:03:26 +00001227 Constant *TC = ConstantUInt::get(Type::UByteTy, TSA);
1228 Instruction *TSI = new ShiftInst(Instruction::Shr, Op0,
1229 TC, SI->getName()+".t");
1230 TSI = InsertNewInstBefore(TSI, I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001231
Chris Lattner42362612005-04-08 04:03:26 +00001232 Constant *FC = ConstantUInt::get(Type::UByteTy, FSA);
1233 Instruction *FSI = new ShiftInst(Instruction::Shr, Op0,
1234 FC, SI->getName()+".f");
1235 FSI = InsertNewInstBefore(FSI, I);
1236 return new SelectInst(SI->getOperand(0), TSI, FSI);
1237 }
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001238 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001239
Chris Lattner3082c5a2003-02-18 19:28:33 +00001240 // 0 / X == 0, we don't need to preserve faults!
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001241 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattner3082c5a2003-02-18 19:28:33 +00001242 if (LHS->equalsInt(0))
1243 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1244
Chris Lattnerdd0c1742005-11-05 07:40:31 +00001245 if (I.getType()->isSigned()) {
1246 // If the top bits of both operands are zero (i.e. we can prove they are
1247 // unsigned inputs), turn this into a udiv.
1248 ConstantIntegral *MaskV = ConstantSInt::getMinValue(I.getType());
1249 if (MaskedValueIsZero(Op1, MaskV) && MaskedValueIsZero(Op0, MaskV)) {
1250 const Type *NTy = Op0->getType()->getUnsignedVersion();
1251 Instruction *LHS = new CastInst(Op0, NTy, Op0->getName());
1252 InsertNewInstBefore(LHS, I);
1253 Value *RHS;
1254 if (Constant *R = dyn_cast<Constant>(Op1))
1255 RHS = ConstantExpr::getCast(R, NTy);
1256 else
1257 RHS = InsertNewInstBefore(new CastInst(Op1, NTy, Op1->getName()), I);
1258 Instruction *Div = BinaryOperator::createDiv(LHS, RHS, I.getName());
1259 InsertNewInstBefore(Div, I);
1260 return new CastInst(Div, I.getType());
1261 }
1262 }
1263
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001264 return 0;
1265}
1266
1267
Chris Lattner113f4f42002-06-25 16:13:24 +00001268Instruction *InstCombiner::visitRem(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001269 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnere9ff0ea2005-11-05 07:28:37 +00001270 if (I.getType()->isSigned()) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001271 if (Value *RHSNeg = dyn_castNegVal(Op1))
Chris Lattner98c6bdf2004-07-06 07:11:42 +00001272 if (!isa<ConstantSInt>(RHSNeg) ||
Chris Lattner8e726062004-08-09 21:05:48 +00001273 cast<ConstantSInt>(RHSNeg)->getValue() > 0) {
Chris Lattner7fd5f072004-07-06 07:01:22 +00001274 // X % -Y -> X % Y
1275 AddUsesToWorkList(I);
1276 I.setOperand(1, RHSNeg);
1277 return &I;
1278 }
Chris Lattnere9ff0ea2005-11-05 07:28:37 +00001279
1280 // If the top bits of both operands are zero (i.e. we can prove they are
1281 // unsigned inputs), turn this into a urem.
1282 ConstantIntegral *MaskV = ConstantSInt::getMinValue(I.getType());
1283 if (MaskedValueIsZero(Op1, MaskV) && MaskedValueIsZero(Op0, MaskV)) {
1284 const Type *NTy = Op0->getType()->getUnsignedVersion();
1285 Instruction *LHS = new CastInst(Op0, NTy, Op0->getName());
1286 InsertNewInstBefore(LHS, I);
1287 Value *RHS;
1288 if (Constant *R = dyn_cast<Constant>(Op1))
1289 RHS = ConstantExpr::getCast(R, NTy);
1290 else
1291 RHS = InsertNewInstBefore(new CastInst(Op1, NTy, Op1->getName()), I);
1292 Instruction *Rem = BinaryOperator::createRem(LHS, RHS, I.getName());
1293 InsertNewInstBefore(Rem, I);
1294 return new CastInst(Rem, I.getType());
1295 }
1296 }
Chris Lattner7fd5f072004-07-06 07:01:22 +00001297
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001298 if (isa<UndefValue>(Op0)) // undef % X -> 0
Chris Lattner81a7a232004-10-16 18:11:37 +00001299 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001300 if (isa<UndefValue>(Op1))
1301 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Chris Lattner81a7a232004-10-16 18:11:37 +00001302
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001303 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00001304 if (RHS->equalsInt(1)) // X % 1 == 0
1305 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1306
1307 // Check to see if this is an unsigned remainder with an exact power of 2,
1308 // if so, convert to a bitwise and.
1309 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
1310 if (uint64_t Val = C->getValue()) // Don't break X % 0 (divide by zero)
Chris Lattnerd9e58132004-05-07 15:35:56 +00001311 if (!(Val & (Val-1))) // Power of 2
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001312 return BinaryOperator::createAnd(Op0,
1313 ConstantUInt::get(I.getType(), Val-1));
1314
1315 if (!RHS->isNullValue()) {
1316 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00001317 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001318 return R;
1319 if (isa<PHINode>(Op0))
1320 if (Instruction *NV = FoldOpIntoPhi(I))
1321 return NV;
1322 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00001323 }
1324
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001325 // If this is 'urem X, (Cond ? C1, C2)' where C1&C2 are powers of two,
1326 // transform this into: '(Cond ? (urem X, C1) : (urem X, C2))'.
1327 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1328 if (ConstantUInt *STO = dyn_cast<ConstantUInt>(SI->getOperand(1)))
1329 if (ConstantUInt *SFO = dyn_cast<ConstantUInt>(SI->getOperand(2))) {
1330 if (STO->getValue() == 0) { // Couldn't be this argument.
1331 I.setOperand(1, SFO);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001332 return &I;
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001333 } else if (SFO->getValue() == 0) {
1334 I.setOperand(1, STO);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001335 return &I;
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001336 }
1337
1338 if (!(STO->getValue() & (STO->getValue()-1)) &&
1339 !(SFO->getValue() & (SFO->getValue()-1))) {
1340 Value *TrueAnd = InsertNewInstBefore(BinaryOperator::createAnd(Op0,
1341 SubOne(STO), SI->getName()+".t"), I);
1342 Value *FalseAnd = InsertNewInstBefore(BinaryOperator::createAnd(Op0,
1343 SubOne(SFO), SI->getName()+".f"), I);
1344 return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
1345 }
1346 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001347
Chris Lattner3082c5a2003-02-18 19:28:33 +00001348 // 0 % X == 0, we don't need to preserve faults!
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001349 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattner3082c5a2003-02-18 19:28:33 +00001350 if (LHS->equalsInt(0))
Chris Lattnere6794492002-08-12 21:17:25 +00001351 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1352
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001353 return 0;
1354}
1355
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001356// isMaxValueMinusOne - return true if this is Max-1
Chris Lattnere6794492002-08-12 21:17:25 +00001357static bool isMaxValueMinusOne(const ConstantInt *C) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001358 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C)) {
1359 // Calculate -1 casted to the right type...
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001360 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001361 uint64_t Val = ~0ULL; // All ones
1362 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
1363 return CU->getValue() == Val-1;
1364 }
1365
1366 const ConstantSInt *CS = cast<ConstantSInt>(C);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001367
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001368 // Calculate 0111111111..11111
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001369 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001370 int64_t Val = INT64_MAX; // All ones
1371 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
1372 return CS->getValue() == Val-1;
1373}
1374
1375// isMinValuePlusOne - return true if this is Min+1
Chris Lattnere6794492002-08-12 21:17:25 +00001376static bool isMinValuePlusOne(const ConstantInt *C) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001377 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
1378 return CU->getValue() == 1;
1379
1380 const ConstantSInt *CS = cast<ConstantSInt>(C);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001381
1382 // Calculate 1111111111000000000000
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001383 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001384 int64_t Val = -1; // All ones
1385 Val <<= TypeBits-1; // Shift over to the right spot
1386 return CS->getValue() == Val+1;
1387}
1388
Chris Lattner35167c32004-06-09 07:59:58 +00001389// isOneBitSet - Return true if there is exactly one bit set in the specified
1390// constant.
1391static bool isOneBitSet(const ConstantInt *CI) {
1392 uint64_t V = CI->getRawValue();
1393 return V && (V & (V-1)) == 0;
1394}
1395
Chris Lattner8fc5af42004-09-23 21:46:38 +00001396#if 0 // Currently unused
1397// isLowOnes - Return true if the constant is of the form 0+1+.
1398static bool isLowOnes(const ConstantInt *CI) {
1399 uint64_t V = CI->getRawValue();
1400
1401 // There won't be bits set in parts that the type doesn't contain.
1402 V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
1403
1404 uint64_t U = V+1; // If it is low ones, this should be a power of two.
1405 return U && V && (U & V) == 0;
1406}
1407#endif
1408
1409// isHighOnes - Return true if the constant is of the form 1+0+.
1410// This is the same as lowones(~X).
1411static bool isHighOnes(const ConstantInt *CI) {
1412 uint64_t V = ~CI->getRawValue();
Chris Lattner2c14cf72005-08-07 07:03:10 +00001413 if (~V == 0) return false; // 0's does not match "1+"
Chris Lattner8fc5af42004-09-23 21:46:38 +00001414
1415 // There won't be bits set in parts that the type doesn't contain.
1416 V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
1417
1418 uint64_t U = V+1; // If it is low ones, this should be a power of two.
1419 return U && V && (U & V) == 0;
1420}
1421
1422
Chris Lattner3ac7c262003-08-13 20:16:26 +00001423/// getSetCondCode - Encode a setcc opcode into a three bit mask. These bits
1424/// are carefully arranged to allow folding of expressions such as:
1425///
1426/// (A < B) | (A > B) --> (A != B)
1427///
1428/// Bit value '4' represents that the comparison is true if A > B, bit value '2'
1429/// represents that the comparison is true if A == B, and bit value '1' is true
1430/// if A < B.
1431///
1432static unsigned getSetCondCode(const SetCondInst *SCI) {
1433 switch (SCI->getOpcode()) {
1434 // False -> 0
1435 case Instruction::SetGT: return 1;
1436 case Instruction::SetEQ: return 2;
1437 case Instruction::SetGE: return 3;
1438 case Instruction::SetLT: return 4;
1439 case Instruction::SetNE: return 5;
1440 case Instruction::SetLE: return 6;
1441 // True -> 7
1442 default:
1443 assert(0 && "Invalid SetCC opcode!");
1444 return 0;
1445 }
1446}
1447
1448/// getSetCCValue - This is the complement of getSetCondCode, which turns an
1449/// opcode and two operands into either a constant true or false, or a brand new
1450/// SetCC instruction.
1451static Value *getSetCCValue(unsigned Opcode, Value *LHS, Value *RHS) {
1452 switch (Opcode) {
1453 case 0: return ConstantBool::False;
1454 case 1: return new SetCondInst(Instruction::SetGT, LHS, RHS);
1455 case 2: return new SetCondInst(Instruction::SetEQ, LHS, RHS);
1456 case 3: return new SetCondInst(Instruction::SetGE, LHS, RHS);
1457 case 4: return new SetCondInst(Instruction::SetLT, LHS, RHS);
1458 case 5: return new SetCondInst(Instruction::SetNE, LHS, RHS);
1459 case 6: return new SetCondInst(Instruction::SetLE, LHS, RHS);
1460 case 7: return ConstantBool::True;
1461 default: assert(0 && "Illegal SetCCCode!"); return 0;
1462 }
1463}
1464
1465// FoldSetCCLogical - Implements (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
1466struct FoldSetCCLogical {
1467 InstCombiner &IC;
1468 Value *LHS, *RHS;
1469 FoldSetCCLogical(InstCombiner &ic, SetCondInst *SCI)
1470 : IC(ic), LHS(SCI->getOperand(0)), RHS(SCI->getOperand(1)) {}
1471 bool shouldApply(Value *V) const {
1472 if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
1473 return (SCI->getOperand(0) == LHS && SCI->getOperand(1) == RHS ||
1474 SCI->getOperand(0) == RHS && SCI->getOperand(1) == LHS);
1475 return false;
1476 }
1477 Instruction *apply(BinaryOperator &Log) const {
1478 SetCondInst *SCI = cast<SetCondInst>(Log.getOperand(0));
1479 if (SCI->getOperand(0) != LHS) {
1480 assert(SCI->getOperand(1) == LHS);
1481 SCI->swapOperands(); // Swap the LHS and RHS of the SetCC
1482 }
1483
1484 unsigned LHSCode = getSetCondCode(SCI);
1485 unsigned RHSCode = getSetCondCode(cast<SetCondInst>(Log.getOperand(1)));
1486 unsigned Code;
1487 switch (Log.getOpcode()) {
1488 case Instruction::And: Code = LHSCode & RHSCode; break;
1489 case Instruction::Or: Code = LHSCode | RHSCode; break;
1490 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner2caaaba2003-09-22 20:33:34 +00001491 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattner3ac7c262003-08-13 20:16:26 +00001492 }
1493
1494 Value *RV = getSetCCValue(Code, LHS, RHS);
1495 if (Instruction *I = dyn_cast<Instruction>(RV))
1496 return I;
1497 // Otherwise, it's a constant boolean value...
1498 return IC.ReplaceInstUsesWith(Log, RV);
1499 }
1500};
1501
Chris Lattnerba1cb382003-09-19 17:17:26 +00001502// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
1503// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
1504// guaranteed to be either a shift instruction or a binary operator.
1505Instruction *InstCombiner::OptAndOp(Instruction *Op,
1506 ConstantIntegral *OpRHS,
1507 ConstantIntegral *AndRHS,
1508 BinaryOperator &TheAnd) {
1509 Value *X = Op->getOperand(0);
Chris Lattnerfcf21a72004-01-12 19:47:05 +00001510 Constant *Together = 0;
1511 if (!isa<ShiftInst>(Op))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001512 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001513
Chris Lattnerba1cb382003-09-19 17:17:26 +00001514 switch (Op->getOpcode()) {
1515 case Instruction::Xor:
Chris Lattner86102b82005-01-01 16:22:27 +00001516 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001517 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
1518 std::string OpName = Op->getName(); Op->setName("");
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001519 Instruction *And = BinaryOperator::createAnd(X, AndRHS, OpName);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001520 InsertNewInstBefore(And, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001521 return BinaryOperator::createXor(And, Together);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001522 }
1523 break;
1524 case Instruction::Or:
Chris Lattner86102b82005-01-01 16:22:27 +00001525 if (Together == AndRHS) // (X | C) & C --> C
1526 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001527
Chris Lattner86102b82005-01-01 16:22:27 +00001528 if (Op->hasOneUse() && Together != OpRHS) {
1529 // (X | C1) & C2 --> (X | (C1&C2)) & C2
1530 std::string Op0Name = Op->getName(); Op->setName("");
1531 Instruction *Or = BinaryOperator::createOr(X, Together, Op0Name);
1532 InsertNewInstBefore(Or, TheAnd);
1533 return BinaryOperator::createAnd(Or, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001534 }
1535 break;
1536 case Instruction::Add:
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001537 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001538 // Adding a one to a single bit bit-field should be turned into an XOR
1539 // of the bit. First thing to check is to see if this AND is with a
1540 // single bit constant.
Chris Lattner35167c32004-06-09 07:59:58 +00001541 uint64_t AndRHSV = cast<ConstantInt>(AndRHS)->getRawValue();
Chris Lattnerba1cb382003-09-19 17:17:26 +00001542
1543 // Clear bits that are not part of the constant.
Chris Lattner2f1457f2005-04-24 17:46:05 +00001544 AndRHSV &= ~0ULL >> (64-AndRHS->getType()->getPrimitiveSizeInBits());
Chris Lattnerba1cb382003-09-19 17:17:26 +00001545
1546 // If there is only one bit set...
Chris Lattner35167c32004-06-09 07:59:58 +00001547 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001548 // Ok, at this point, we know that we are masking the result of the
1549 // ADD down to exactly one bit. If the constant we are adding has
1550 // no bits set below this bit, then we can eliminate the ADD.
Chris Lattner35167c32004-06-09 07:59:58 +00001551 uint64_t AddRHS = cast<ConstantInt>(OpRHS)->getRawValue();
Misha Brukmanb1c93172005-04-21 23:48:37 +00001552
Chris Lattnerba1cb382003-09-19 17:17:26 +00001553 // Check to see if any bits below the one bit set in AndRHSV are set.
1554 if ((AddRHS & (AndRHSV-1)) == 0) {
1555 // If not, the only thing that can effect the output of the AND is
1556 // the bit specified by AndRHSV. If that bit is set, the effect of
1557 // the XOR is to toggle the bit. If it is clear, then the ADD has
1558 // no effect.
1559 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
1560 TheAnd.setOperand(0, X);
1561 return &TheAnd;
1562 } else {
1563 std::string Name = Op->getName(); Op->setName("");
1564 // Pull the XOR out of the AND.
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001565 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS, Name);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001566 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001567 return BinaryOperator::createXor(NewAnd, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001568 }
1569 }
1570 }
1571 }
1572 break;
Chris Lattner2da29172003-09-19 19:05:02 +00001573
1574 case Instruction::Shl: {
1575 // We know that the AND will not produce any of the bits shifted in, so if
1576 // the anded constant includes them, clear them now!
1577 //
1578 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner7e794272004-09-24 15:21:34 +00001579 Constant *ShlMask = ConstantExpr::getShl(AllOne, OpRHS);
1580 Constant *CI = ConstantExpr::getAnd(AndRHS, ShlMask);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001581
Chris Lattner7e794272004-09-24 15:21:34 +00001582 if (CI == ShlMask) { // Masking out bits that the shift already masks
1583 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
1584 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner2da29172003-09-19 19:05:02 +00001585 TheAnd.setOperand(1, CI);
1586 return &TheAnd;
1587 }
1588 break;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001589 }
Chris Lattner2da29172003-09-19 19:05:02 +00001590 case Instruction::Shr:
1591 // We know that the AND will not produce any of the bits shifted in, so if
1592 // the anded constant includes them, clear them now! This only applies to
1593 // unsigned shifts, because a signed shr may bring in set bits!
1594 //
1595 if (AndRHS->getType()->isUnsigned()) {
1596 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner7e794272004-09-24 15:21:34 +00001597 Constant *ShrMask = ConstantExpr::getShr(AllOne, OpRHS);
1598 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
1599
1600 if (CI == ShrMask) { // Masking out bits that the shift already masks.
1601 return ReplaceInstUsesWith(TheAnd, Op);
1602 } else if (CI != AndRHS) {
1603 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
Chris Lattner2da29172003-09-19 19:05:02 +00001604 return &TheAnd;
1605 }
Chris Lattner7e794272004-09-24 15:21:34 +00001606 } else { // Signed shr.
1607 // See if this is shifting in some sign extension, then masking it out
1608 // with an and.
1609 if (Op->hasOneUse()) {
1610 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
1611 Constant *ShrMask = ConstantExpr::getUShr(AllOne, OpRHS);
1612 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
Chris Lattner5c3c21e2004-10-22 04:53:16 +00001613 if (CI == AndRHS) { // Masking out bits shifted in.
Chris Lattner7e794272004-09-24 15:21:34 +00001614 // Make the argument unsigned.
1615 Value *ShVal = Op->getOperand(0);
1616 ShVal = InsertCastBefore(ShVal,
1617 ShVal->getType()->getUnsignedVersion(),
1618 TheAnd);
1619 ShVal = InsertNewInstBefore(new ShiftInst(Instruction::Shr, ShVal,
1620 OpRHS, Op->getName()),
1621 TheAnd);
Chris Lattner70c20392004-10-27 05:57:15 +00001622 Value *AndRHS2 = ConstantExpr::getCast(AndRHS, ShVal->getType());
1623 ShVal = InsertNewInstBefore(BinaryOperator::createAnd(ShVal, AndRHS2,
1624 TheAnd.getName()),
1625 TheAnd);
Chris Lattner7e794272004-09-24 15:21:34 +00001626 return new CastInst(ShVal, Op->getType());
1627 }
1628 }
Chris Lattner2da29172003-09-19 19:05:02 +00001629 }
1630 break;
Chris Lattnerba1cb382003-09-19 17:17:26 +00001631 }
1632 return 0;
1633}
1634
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001635
Chris Lattner6862fbd2004-09-29 17:40:11 +00001636/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
1637/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
1638/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. IB is the location to
1639/// insert new instructions.
1640Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
1641 bool Inside, Instruction &IB) {
1642 assert(cast<ConstantBool>(ConstantExpr::getSetLE(Lo, Hi))->getValue() &&
1643 "Lo is not <= Hi in range emission code!");
1644 if (Inside) {
1645 if (Lo == Hi) // Trivially false.
1646 return new SetCondInst(Instruction::SetNE, V, V);
1647 if (cast<ConstantIntegral>(Lo)->isMinValue())
1648 return new SetCondInst(Instruction::SetLT, V, Hi);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001649
Chris Lattner6862fbd2004-09-29 17:40:11 +00001650 Constant *AddCST = ConstantExpr::getNeg(Lo);
1651 Instruction *Add = BinaryOperator::createAdd(V, AddCST,V->getName()+".off");
1652 InsertNewInstBefore(Add, IB);
1653 // Convert to unsigned for the comparison.
1654 const Type *UnsType = Add->getType()->getUnsignedVersion();
1655 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
1656 AddCST = ConstantExpr::getAdd(AddCST, Hi);
1657 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1658 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
1659 }
1660
1661 if (Lo == Hi) // Trivially true.
1662 return new SetCondInst(Instruction::SetEQ, V, V);
1663
1664 Hi = SubOne(cast<ConstantInt>(Hi));
1665 if (cast<ConstantIntegral>(Lo)->isMinValue()) // V < 0 || V >= Hi ->'V > Hi-1'
1666 return new SetCondInst(Instruction::SetGT, V, Hi);
1667
1668 // Emit X-Lo > Hi-Lo-1
1669 Constant *AddCST = ConstantExpr::getNeg(Lo);
1670 Instruction *Add = BinaryOperator::createAdd(V, AddCST, V->getName()+".off");
1671 InsertNewInstBefore(Add, IB);
1672 // Convert to unsigned for the comparison.
1673 const Type *UnsType = Add->getType()->getUnsignedVersion();
1674 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
1675 AddCST = ConstantExpr::getAdd(AddCST, Hi);
1676 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1677 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
1678}
1679
Chris Lattnerb4b25302005-09-18 07:22:02 +00001680// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
1681// any number of 0s on either side. The 1s are allowed to wrap from LSB to
1682// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
1683// not, since all 1s are not contiguous.
1684static bool isRunOfOnes(ConstantIntegral *Val, unsigned &MB, unsigned &ME) {
1685 uint64_t V = Val->getRawValue();
1686 if (!isShiftedMask_64(V)) return false;
1687
1688 // look for the first zero bit after the run of ones
1689 MB = 64-CountLeadingZeros_64((V - 1) ^ V);
1690 // look for the first non-zero bit
1691 ME = 64-CountLeadingZeros_64(V);
1692 return true;
1693}
1694
1695
1696
1697/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
1698/// where isSub determines whether the operator is a sub. If we can fold one of
1699/// the following xforms:
Chris Lattneraf517572005-09-18 04:24:45 +00001700///
1701/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
1702/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
1703/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
1704///
1705/// return (A +/- B).
1706///
1707Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
1708 ConstantIntegral *Mask, bool isSub,
1709 Instruction &I) {
1710 Instruction *LHSI = dyn_cast<Instruction>(LHS);
1711 if (!LHSI || LHSI->getNumOperands() != 2 ||
1712 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
1713
1714 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
1715
1716 switch (LHSI->getOpcode()) {
1717 default: return 0;
1718 case Instruction::And:
Chris Lattnerb4b25302005-09-18 07:22:02 +00001719 if (ConstantExpr::getAnd(N, Mask) == Mask) {
1720 // If the AndRHS is a power of two minus one (0+1+), this is simple.
1721 if ((Mask->getRawValue() & Mask->getRawValue()+1) == 0)
1722 break;
1723
1724 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
1725 // part, we don't need any explicit masks to take them out of A. If that
1726 // is all N is, ignore it.
1727 unsigned MB, ME;
1728 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
1729 Constant *Mask = ConstantInt::getAllOnesValue(RHS->getType());
1730 Mask = ConstantExpr::getUShr(Mask,
1731 ConstantInt::get(Type::UByteTy,
1732 (64-MB+1)));
1733 if (MaskedValueIsZero(RHS, cast<ConstantIntegral>(Mask)))
1734 break;
1735 }
1736 }
Chris Lattneraf517572005-09-18 04:24:45 +00001737 return 0;
1738 case Instruction::Or:
1739 case Instruction::Xor:
Chris Lattnerb4b25302005-09-18 07:22:02 +00001740 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
1741 if ((Mask->getRawValue() & Mask->getRawValue()+1) == 0 &&
1742 ConstantExpr::getAnd(N, Mask)->isNullValue())
Chris Lattneraf517572005-09-18 04:24:45 +00001743 break;
1744 return 0;
1745 }
1746
1747 Instruction *New;
1748 if (isSub)
1749 New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
1750 else
1751 New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
1752 return InsertNewInstBefore(New, I);
1753}
1754
Chris Lattner113f4f42002-06-25 16:13:24 +00001755Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001756 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00001757 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001758
Chris Lattner81a7a232004-10-16 18:11:37 +00001759 if (isa<UndefValue>(Op1)) // X & undef -> 0
1760 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1761
Chris Lattner86102b82005-01-01 16:22:27 +00001762 // and X, X = X
1763 if (Op0 == Op1)
Chris Lattnere6794492002-08-12 21:17:25 +00001764 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001765
Chris Lattner86102b82005-01-01 16:22:27 +00001766 if (ConstantIntegral *AndRHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00001767 // and X, -1 == X
1768 if (AndRHS->isAllOnesValue())
Chris Lattnere6794492002-08-12 21:17:25 +00001769 return ReplaceInstUsesWith(I, Op0);
Chris Lattner38a1b002005-10-26 17:18:16 +00001770
1771 // and (and X, c1), c2 -> and (x, c1&c2). Handle this case here, before
1772 // calling MaskedValueIsZero, to avoid inefficient cases where we traipse
1773 // through many levels of ands.
1774 {
1775 Value *X; ConstantInt *C1;
1776 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))))
1777 return BinaryOperator::createAnd(X, ConstantExpr::getAnd(C1, AndRHS));
1778 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001779
Chris Lattner86102b82005-01-01 16:22:27 +00001780 if (MaskedValueIsZero(Op0, AndRHS)) // LHS & RHS == 0
1781 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1782
1783 // If the mask is not masking out any bits, there is no reason to do the
1784 // and in the first place.
Misha Brukmanb1c93172005-04-21 23:48:37 +00001785 ConstantIntegral *NotAndRHS =
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00001786 cast<ConstantIntegral>(ConstantExpr::getNot(AndRHS));
Misha Brukmanb1c93172005-04-21 23:48:37 +00001787 if (MaskedValueIsZero(Op0, NotAndRHS))
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00001788 return ReplaceInstUsesWith(I, Op0);
Chris Lattner86102b82005-01-01 16:22:27 +00001789
Chris Lattnerba1cb382003-09-19 17:17:26 +00001790 // Optimize a variety of ((val OP C1) & C2) combinations...
1791 if (isa<BinaryOperator>(Op0) || isa<ShiftInst>(Op0)) {
1792 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner86102b82005-01-01 16:22:27 +00001793 Value *Op0LHS = Op0I->getOperand(0);
1794 Value *Op0RHS = Op0I->getOperand(1);
1795 switch (Op0I->getOpcode()) {
1796 case Instruction::Xor:
1797 case Instruction::Or:
1798 // (X ^ V) & C2 --> (X & C2) iff (V & C2) == 0
1799 // (X | V) & C2 --> (X & C2) iff (V & C2) == 0
1800 if (MaskedValueIsZero(Op0LHS, AndRHS))
Misha Brukmanb1c93172005-04-21 23:48:37 +00001801 return BinaryOperator::createAnd(Op0RHS, AndRHS);
Chris Lattner86102b82005-01-01 16:22:27 +00001802 if (MaskedValueIsZero(Op0RHS, AndRHS))
Misha Brukmanb1c93172005-04-21 23:48:37 +00001803 return BinaryOperator::createAnd(Op0LHS, AndRHS);
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00001804
1805 // If the mask is only needed on one incoming arm, push it up.
1806 if (Op0I->hasOneUse()) {
1807 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
1808 // Not masking anything out for the LHS, move to RHS.
1809 Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
1810 Op0RHS->getName()+".masked");
1811 InsertNewInstBefore(NewRHS, I);
1812 return BinaryOperator::create(
1813 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001814 }
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00001815 if (!isa<Constant>(NotAndRHS) &&
1816 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
1817 // Not masking anything out for the RHS, move to LHS.
1818 Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
1819 Op0LHS->getName()+".masked");
1820 InsertNewInstBefore(NewLHS, I);
1821 return BinaryOperator::create(
1822 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
1823 }
1824 }
1825
Chris Lattner86102b82005-01-01 16:22:27 +00001826 break;
1827 case Instruction::And:
1828 // (X & V) & C2 --> 0 iff (V & C2) == 0
1829 if (MaskedValueIsZero(Op0LHS, AndRHS) ||
1830 MaskedValueIsZero(Op0RHS, AndRHS))
1831 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1832 break;
Chris Lattneraf517572005-09-18 04:24:45 +00001833 case Instruction::Add:
Chris Lattnerb4b25302005-09-18 07:22:02 +00001834 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
1835 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
1836 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
1837 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
1838 return BinaryOperator::createAnd(V, AndRHS);
1839 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
1840 return BinaryOperator::createAnd(V, AndRHS); // Add commutes
Chris Lattneraf517572005-09-18 04:24:45 +00001841 break;
1842
1843 case Instruction::Sub:
Chris Lattnerb4b25302005-09-18 07:22:02 +00001844 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
1845 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
1846 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
1847 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
1848 return BinaryOperator::createAnd(V, AndRHS);
Chris Lattneraf517572005-09-18 04:24:45 +00001849 break;
Chris Lattner86102b82005-01-01 16:22:27 +00001850 }
1851
Chris Lattner16464b32003-07-23 19:25:52 +00001852 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner86102b82005-01-01 16:22:27 +00001853 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerba1cb382003-09-19 17:17:26 +00001854 return Res;
Chris Lattner86102b82005-01-01 16:22:27 +00001855 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
1856 const Type *SrcTy = CI->getOperand(0)->getType();
1857
Chris Lattner2c14cf72005-08-07 07:03:10 +00001858 // If this is an integer truncation or change from signed-to-unsigned, and
1859 // if the source is an and/or with immediate, transform it. This
1860 // frequently occurs for bitfield accesses.
1861 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
1862 if (SrcTy->getPrimitiveSizeInBits() >=
1863 I.getType()->getPrimitiveSizeInBits() &&
1864 CastOp->getNumOperands() == 2)
1865 if (ConstantInt *AndCI =dyn_cast<ConstantInt>(CastOp->getOperand(1)))
1866 if (CastOp->getOpcode() == Instruction::And) {
1867 // Change: and (cast (and X, C1) to T), C2
1868 // into : and (cast X to T), trunc(C1)&C2
1869 // This will folds the two ands together, which may allow other
1870 // simplifications.
1871 Instruction *NewCast =
1872 new CastInst(CastOp->getOperand(0), I.getType(),
1873 CastOp->getName()+".shrunk");
1874 NewCast = InsertNewInstBefore(NewCast, I);
1875
1876 Constant *C3=ConstantExpr::getCast(AndCI, I.getType());//trunc(C1)
1877 C3 = ConstantExpr::getAnd(C3, AndRHS); // trunc(C1)&C2
1878 return BinaryOperator::createAnd(NewCast, C3);
1879 } else if (CastOp->getOpcode() == Instruction::Or) {
1880 // Change: and (cast (or X, C1) to T), C2
1881 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
1882 Constant *C3=ConstantExpr::getCast(AndCI, I.getType());//trunc(C1)
1883 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
1884 return ReplaceInstUsesWith(I, AndRHS);
1885 }
1886 }
1887
1888
Chris Lattner86102b82005-01-01 16:22:27 +00001889 // If this is an integer sign or zero extension instruction.
1890 if (SrcTy->isIntegral() &&
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001891 SrcTy->getPrimitiveSizeInBits() <
1892 CI->getType()->getPrimitiveSizeInBits()) {
Chris Lattner86102b82005-01-01 16:22:27 +00001893
1894 if (SrcTy->isUnsigned()) {
1895 // See if this and is clearing out bits that are known to be zero
1896 // anyway (due to the zero extension).
1897 Constant *Mask = ConstantIntegral::getAllOnesValue(SrcTy);
1898 Mask = ConstantExpr::getZeroExtend(Mask, CI->getType());
1899 Constant *Result = ConstantExpr::getAnd(Mask, AndRHS);
1900 if (Result == Mask) // The "and" isn't doing anything, remove it.
1901 return ReplaceInstUsesWith(I, CI);
1902 if (Result != AndRHS) { // Reduce the and RHS constant.
1903 I.setOperand(1, Result);
1904 return &I;
1905 }
1906
1907 } else {
1908 if (CI->hasOneUse() && SrcTy->isInteger()) {
1909 // We can only do this if all of the sign bits brought in are masked
1910 // out. Compute this by first getting 0000011111, then inverting
1911 // it.
1912 Constant *Mask = ConstantIntegral::getAllOnesValue(SrcTy);
1913 Mask = ConstantExpr::getZeroExtend(Mask, CI->getType());
1914 Mask = ConstantExpr::getNot(Mask); // 1's in the new bits.
1915 if (ConstantExpr::getAnd(Mask, AndRHS)->isNullValue()) {
1916 // If the and is clearing all of the sign bits, change this to a
1917 // zero extension cast. To do this, cast the cast input to
1918 // unsigned, then to the requested size.
1919 Value *CastOp = CI->getOperand(0);
1920 Instruction *NC =
1921 new CastInst(CastOp, CastOp->getType()->getUnsignedVersion(),
1922 CI->getName()+".uns");
1923 NC = InsertNewInstBefore(NC, I);
1924 // Finally, insert a replacement for CI.
1925 NC = new CastInst(NC, CI->getType(), CI->getName());
1926 CI->setName("");
1927 NC = InsertNewInstBefore(NC, I);
1928 WorkList.push_back(CI); // Delete CI later.
1929 I.setOperand(0, NC);
1930 return &I; // The AND operand was modified.
1931 }
1932 }
1933 }
1934 }
Chris Lattner33217db2003-07-23 19:36:21 +00001935 }
Chris Lattner183b3362004-04-09 19:05:30 +00001936
1937 // Try to fold constant and into select arguments.
1938 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00001939 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00001940 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001941 if (isa<PHINode>(Op0))
1942 if (Instruction *NV = FoldOpIntoPhi(I))
1943 return NV;
Chris Lattner49b47ae2003-07-23 17:57:01 +00001944 }
1945
Chris Lattnerbb74e222003-03-10 23:06:50 +00001946 Value *Op0NotVal = dyn_castNotVal(Op0);
1947 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001948
Chris Lattner023a4832004-06-18 06:07:51 +00001949 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
1950 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1951
Misha Brukman9c003d82004-07-30 12:50:08 +00001952 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattnerbb74e222003-03-10 23:06:50 +00001953 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001954 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
1955 I.getName()+".demorgan");
Chris Lattner49b47ae2003-07-23 17:57:01 +00001956 InsertNewInstBefore(Or, I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001957 return BinaryOperator::createNot(Or);
1958 }
1959
Chris Lattner623826c2004-09-28 21:48:02 +00001960 if (SetCondInst *RHS = dyn_cast<SetCondInst>(Op1)) {
1961 // (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
Chris Lattner3ac7c262003-08-13 20:16:26 +00001962 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
1963 return R;
1964
Chris Lattner623826c2004-09-28 21:48:02 +00001965 Value *LHSVal, *RHSVal;
1966 ConstantInt *LHSCst, *RHSCst;
1967 Instruction::BinaryOps LHSCC, RHSCC;
1968 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
1969 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
1970 if (LHSVal == RHSVal && // Found (X setcc C1) & (X setcc C2)
1971 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
Misha Brukmanb1c93172005-04-21 23:48:37 +00001972 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
Chris Lattner623826c2004-09-28 21:48:02 +00001973 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
1974 // Ensure that the larger constant is on the RHS.
1975 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
1976 SetCondInst *LHS = cast<SetCondInst>(Op0);
1977 if (cast<ConstantBool>(Cmp)->getValue()) {
1978 std::swap(LHS, RHS);
1979 std::swap(LHSCst, RHSCst);
1980 std::swap(LHSCC, RHSCC);
1981 }
1982
1983 // At this point, we know we have have two setcc instructions
1984 // comparing a value against two constants and and'ing the result
1985 // together. Because of the above check, we know that we only have
1986 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
1987 // FoldSetCCLogical check above), that the two constants are not
1988 // equal.
1989 assert(LHSCst != RHSCst && "Compares not folded above?");
1990
1991 switch (LHSCC) {
1992 default: assert(0 && "Unknown integer condition code!");
1993 case Instruction::SetEQ:
1994 switch (RHSCC) {
1995 default: assert(0 && "Unknown integer condition code!");
1996 case Instruction::SetEQ: // (X == 13 & X == 15) -> false
1997 case Instruction::SetGT: // (X == 13 & X > 15) -> false
1998 return ReplaceInstUsesWith(I, ConstantBool::False);
1999 case Instruction::SetNE: // (X == 13 & X != 15) -> X == 13
2000 case Instruction::SetLT: // (X == 13 & X < 15) -> X == 13
2001 return ReplaceInstUsesWith(I, LHS);
2002 }
2003 case Instruction::SetNE:
2004 switch (RHSCC) {
2005 default: assert(0 && "Unknown integer condition code!");
2006 case Instruction::SetLT:
2007 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X < 14) -> X < 13
2008 return new SetCondInst(Instruction::SetLT, LHSVal, LHSCst);
2009 break; // (X != 13 & X < 15) -> no change
2010 case Instruction::SetEQ: // (X != 13 & X == 15) -> X == 15
2011 case Instruction::SetGT: // (X != 13 & X > 15) -> X > 15
2012 return ReplaceInstUsesWith(I, RHS);
2013 case Instruction::SetNE:
2014 if (LHSCst == SubOne(RHSCst)) {// (X != 13 & X != 14) -> X-13 >u 1
2015 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
2016 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
2017 LHSVal->getName()+".off");
2018 InsertNewInstBefore(Add, I);
2019 const Type *UnsType = Add->getType()->getUnsignedVersion();
2020 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
2021 AddCST = ConstantExpr::getSub(RHSCst, LHSCst);
2022 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2023 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
2024 }
2025 break; // (X != 13 & X != 15) -> no change
2026 }
2027 break;
2028 case Instruction::SetLT:
2029 switch (RHSCC) {
2030 default: assert(0 && "Unknown integer condition code!");
2031 case Instruction::SetEQ: // (X < 13 & X == 15) -> false
2032 case Instruction::SetGT: // (X < 13 & X > 15) -> false
2033 return ReplaceInstUsesWith(I, ConstantBool::False);
2034 case Instruction::SetNE: // (X < 13 & X != 15) -> X < 13
2035 case Instruction::SetLT: // (X < 13 & X < 15) -> X < 13
2036 return ReplaceInstUsesWith(I, LHS);
2037 }
2038 case Instruction::SetGT:
2039 switch (RHSCC) {
2040 default: assert(0 && "Unknown integer condition code!");
2041 case Instruction::SetEQ: // (X > 13 & X == 15) -> X > 13
2042 return ReplaceInstUsesWith(I, LHS);
2043 case Instruction::SetGT: // (X > 13 & X > 15) -> X > 15
2044 return ReplaceInstUsesWith(I, RHS);
2045 case Instruction::SetNE:
2046 if (RHSCst == AddOne(LHSCst)) // (X > 13 & X != 14) -> X > 14
2047 return new SetCondInst(Instruction::SetGT, LHSVal, RHSCst);
2048 break; // (X > 13 & X != 15) -> no change
Chris Lattner6862fbd2004-09-29 17:40:11 +00002049 case Instruction::SetLT: // (X > 13 & X < 15) -> (X-14) <u 1
2050 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true, I);
Chris Lattner623826c2004-09-28 21:48:02 +00002051 }
2052 }
2053 }
2054 }
2055
Chris Lattner113f4f42002-06-25 16:13:24 +00002056 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002057}
2058
Chris Lattner113f4f42002-06-25 16:13:24 +00002059Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00002060 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00002061 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002062
Chris Lattner81a7a232004-10-16 18:11:37 +00002063 if (isa<UndefValue>(Op1))
2064 return ReplaceInstUsesWith(I, // X | undef -> -1
2065 ConstantIntegral::getAllOnesValue(I.getType()));
2066
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002067 // or X, X = X or X, 0 == X
Chris Lattnere6794492002-08-12 21:17:25 +00002068 if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
2069 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002070
2071 // or X, -1 == -1
Chris Lattner8f0d1562003-07-23 18:29:44 +00002072 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner86102b82005-01-01 16:22:27 +00002073 // If X is known to only contain bits that already exist in RHS, just
2074 // replace this instruction with RHS directly.
2075 if (MaskedValueIsZero(Op0,
2076 cast<ConstantIntegral>(ConstantExpr::getNot(RHS))))
2077 return ReplaceInstUsesWith(I, RHS);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002078
Chris Lattnerd4252a72004-07-30 07:50:03 +00002079 ConstantInt *C1; Value *X;
2080 // (X & C1) | C2 --> (X | C2) & (C1|C2)
2081 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Chris Lattnerb62f5082005-05-09 04:58:36 +00002082 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0->getName());
2083 Op0->setName("");
Chris Lattnerd4252a72004-07-30 07:50:03 +00002084 InsertNewInstBefore(Or, I);
2085 return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, C1));
2086 }
Chris Lattner8f0d1562003-07-23 18:29:44 +00002087
Chris Lattnerd4252a72004-07-30 07:50:03 +00002088 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
2089 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
2090 std::string Op0Name = Op0->getName(); Op0->setName("");
2091 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
2092 InsertNewInstBefore(Or, I);
2093 return BinaryOperator::createXor(Or,
2094 ConstantExpr::getAnd(C1, ConstantExpr::getNot(RHS)));
Chris Lattner8f0d1562003-07-23 18:29:44 +00002095 }
Chris Lattner183b3362004-04-09 19:05:30 +00002096
2097 // Try to fold constant and into select arguments.
2098 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00002099 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00002100 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002101 if (isa<PHINode>(Op0))
2102 if (Instruction *NV = FoldOpIntoPhi(I))
2103 return NV;
Chris Lattner8f0d1562003-07-23 18:29:44 +00002104 }
2105
Chris Lattnerd4252a72004-07-30 07:50:03 +00002106 Value *A, *B; ConstantInt *C1, *C2;
Chris Lattner4294cec2005-05-07 23:49:08 +00002107
2108 if (match(Op0, m_And(m_Value(A), m_Value(B))))
2109 if (A == Op1 || B == Op1) // (A & ?) | A --> A
2110 return ReplaceInstUsesWith(I, Op1);
2111 if (match(Op1, m_And(m_Value(A), m_Value(B))))
2112 if (A == Op0 || B == Op0) // A | (A & ?) --> A
2113 return ReplaceInstUsesWith(I, Op0);
2114
Chris Lattnerb62f5082005-05-09 04:58:36 +00002115 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
2116 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
2117 MaskedValueIsZero(Op1, C1)) {
2118 Instruction *NOr = BinaryOperator::createOr(A, Op1, Op0->getName());
2119 Op0->setName("");
2120 return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
2121 }
2122
2123 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
2124 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
2125 MaskedValueIsZero(Op0, C1)) {
2126 Instruction *NOr = BinaryOperator::createOr(A, Op0, Op1->getName());
2127 Op0->setName("");
2128 return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
2129 }
2130
Chris Lattner15212982005-09-18 03:42:07 +00002131 // (A & C1)|(B & C2)
Chris Lattnerd4252a72004-07-30 07:50:03 +00002132 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattner15212982005-09-18 03:42:07 +00002133 match(Op1, m_And(m_Value(B), m_ConstantInt(C2)))) {
2134
2135 if (A == B) // (A & C1)|(A & C2) == A & (C1|C2)
2136 return BinaryOperator::createAnd(A, ConstantExpr::getOr(C1, C2));
2137
2138
Chris Lattner01f56c62005-09-18 06:02:59 +00002139 // If we have: ((V + N) & C1) | (V & C2)
2140 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
2141 // replace with V+N.
2142 if (C1 == ConstantExpr::getNot(C2)) {
2143 Value *V1, *V2;
2144 if ((C2->getRawValue() & (C2->getRawValue()+1)) == 0 && // C2 == 0+1+
2145 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
2146 // Add commutes, try both ways.
2147 if (V1 == B && MaskedValueIsZero(V2, C2))
2148 return ReplaceInstUsesWith(I, A);
2149 if (V2 == B && MaskedValueIsZero(V1, C2))
2150 return ReplaceInstUsesWith(I, A);
2151 }
2152 // Or commutes, try both ways.
2153 if ((C1->getRawValue() & (C1->getRawValue()+1)) == 0 &&
2154 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
2155 // Add commutes, try both ways.
2156 if (V1 == A && MaskedValueIsZero(V2, C1))
2157 return ReplaceInstUsesWith(I, B);
2158 if (V2 == A && MaskedValueIsZero(V1, C1))
2159 return ReplaceInstUsesWith(I, B);
Chris Lattner15212982005-09-18 03:42:07 +00002160 }
2161 }
2162 }
Chris Lattner812aab72003-08-12 19:11:07 +00002163
Chris Lattnerd4252a72004-07-30 07:50:03 +00002164 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
2165 if (A == Op1) // ~A | A == -1
Misha Brukmanb1c93172005-04-21 23:48:37 +00002166 return ReplaceInstUsesWith(I,
Chris Lattnerd4252a72004-07-30 07:50:03 +00002167 ConstantIntegral::getAllOnesValue(I.getType()));
2168 } else {
2169 A = 0;
2170 }
Chris Lattner4294cec2005-05-07 23:49:08 +00002171 // Note, A is still live here!
Chris Lattnerd4252a72004-07-30 07:50:03 +00002172 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
2173 if (Op0 == B)
Misha Brukmanb1c93172005-04-21 23:48:37 +00002174 return ReplaceInstUsesWith(I,
Chris Lattnerd4252a72004-07-30 07:50:03 +00002175 ConstantIntegral::getAllOnesValue(I.getType()));
Chris Lattner3e327a42003-03-10 23:13:59 +00002176
Misha Brukman9c003d82004-07-30 12:50:08 +00002177 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattnerd4252a72004-07-30 07:50:03 +00002178 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
2179 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
2180 I.getName()+".demorgan"), I);
2181 return BinaryOperator::createNot(And);
2182 }
Chris Lattner3e327a42003-03-10 23:13:59 +00002183 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00002184
Chris Lattner3ac7c262003-08-13 20:16:26 +00002185 // (setcc1 A, B) | (setcc2 A, B) --> (setcc3 A, B)
Chris Lattnerdcf756e2004-09-28 22:33:08 +00002186 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1))) {
Chris Lattner3ac7c262003-08-13 20:16:26 +00002187 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
2188 return R;
2189
Chris Lattnerdcf756e2004-09-28 22:33:08 +00002190 Value *LHSVal, *RHSVal;
2191 ConstantInt *LHSCst, *RHSCst;
2192 Instruction::BinaryOps LHSCC, RHSCC;
2193 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
2194 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
2195 if (LHSVal == RHSVal && // Found (X setcc C1) | (X setcc C2)
2196 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
Misha Brukmanb1c93172005-04-21 23:48:37 +00002197 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
Chris Lattnerdcf756e2004-09-28 22:33:08 +00002198 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
2199 // Ensure that the larger constant is on the RHS.
2200 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
2201 SetCondInst *LHS = cast<SetCondInst>(Op0);
2202 if (cast<ConstantBool>(Cmp)->getValue()) {
2203 std::swap(LHS, RHS);
2204 std::swap(LHSCst, RHSCst);
2205 std::swap(LHSCC, RHSCC);
2206 }
2207
2208 // At this point, we know we have have two setcc instructions
2209 // comparing a value against two constants and or'ing the result
2210 // together. Because of the above check, we know that we only have
2211 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
2212 // FoldSetCCLogical check above), that the two constants are not
2213 // equal.
2214 assert(LHSCst != RHSCst && "Compares not folded above?");
2215
2216 switch (LHSCC) {
2217 default: assert(0 && "Unknown integer condition code!");
2218 case Instruction::SetEQ:
2219 switch (RHSCC) {
2220 default: assert(0 && "Unknown integer condition code!");
2221 case Instruction::SetEQ:
2222 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
2223 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
2224 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
2225 LHSVal->getName()+".off");
2226 InsertNewInstBefore(Add, I);
2227 const Type *UnsType = Add->getType()->getUnsignedVersion();
2228 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
2229 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
2230 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2231 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
2232 }
2233 break; // (X == 13 | X == 15) -> no change
2234
Chris Lattner5c219462005-04-19 06:04:18 +00002235 case Instruction::SetGT: // (X == 13 | X > 14) -> no change
2236 break;
Chris Lattnerdcf756e2004-09-28 22:33:08 +00002237 case Instruction::SetNE: // (X == 13 | X != 15) -> X != 15
2238 case Instruction::SetLT: // (X == 13 | X < 15) -> X < 15
2239 return ReplaceInstUsesWith(I, RHS);
2240 }
2241 break;
2242 case Instruction::SetNE:
2243 switch (RHSCC) {
2244 default: assert(0 && "Unknown integer condition code!");
Chris Lattnerdcf756e2004-09-28 22:33:08 +00002245 case Instruction::SetEQ: // (X != 13 | X == 15) -> X != 13
2246 case Instruction::SetGT: // (X != 13 | X > 15) -> X != 13
2247 return ReplaceInstUsesWith(I, LHS);
2248 case Instruction::SetNE: // (X != 13 | X != 15) -> true
Chris Lattner2ceb6ee2005-06-17 03:59:17 +00002249 case Instruction::SetLT: // (X != 13 | X < 15) -> true
Chris Lattnerdcf756e2004-09-28 22:33:08 +00002250 return ReplaceInstUsesWith(I, ConstantBool::True);
2251 }
2252 break;
2253 case Instruction::SetLT:
2254 switch (RHSCC) {
2255 default: assert(0 && "Unknown integer condition code!");
2256 case Instruction::SetEQ: // (X < 13 | X == 14) -> no change
2257 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00002258 case Instruction::SetGT: // (X < 13 | X > 15) -> (X-13) > 2
2259 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false, I);
Chris Lattnerdcf756e2004-09-28 22:33:08 +00002260 case Instruction::SetNE: // (X < 13 | X != 15) -> X != 15
2261 case Instruction::SetLT: // (X < 13 | X < 15) -> X < 15
2262 return ReplaceInstUsesWith(I, RHS);
2263 }
2264 break;
2265 case Instruction::SetGT:
2266 switch (RHSCC) {
2267 default: assert(0 && "Unknown integer condition code!");
2268 case Instruction::SetEQ: // (X > 13 | X == 15) -> X > 13
2269 case Instruction::SetGT: // (X > 13 | X > 15) -> X > 13
2270 return ReplaceInstUsesWith(I, LHS);
2271 case Instruction::SetNE: // (X > 13 | X != 15) -> true
2272 case Instruction::SetLT: // (X > 13 | X < 15) -> true
2273 return ReplaceInstUsesWith(I, ConstantBool::True);
2274 }
2275 }
2276 }
2277 }
Chris Lattner15212982005-09-18 03:42:07 +00002278
Chris Lattner113f4f42002-06-25 16:13:24 +00002279 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002280}
2281
Chris Lattnerc2076352004-02-16 01:20:27 +00002282// XorSelf - Implements: X ^ X --> 0
2283struct XorSelf {
2284 Value *RHS;
2285 XorSelf(Value *rhs) : RHS(rhs) {}
2286 bool shouldApply(Value *LHS) const { return LHS == RHS; }
2287 Instruction *apply(BinaryOperator &Xor) const {
2288 return &Xor;
2289 }
2290};
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002291
2292
Chris Lattner113f4f42002-06-25 16:13:24 +00002293Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00002294 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00002295 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002296
Chris Lattner81a7a232004-10-16 18:11:37 +00002297 if (isa<UndefValue>(Op1))
2298 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
2299
Chris Lattnerc2076352004-02-16 01:20:27 +00002300 // xor X, X = 0, even if X is nested in a sequence of Xor's.
2301 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
2302 assert(Result == &I && "AssociativeOpt didn't work?");
Chris Lattnere6794492002-08-12 21:17:25 +00002303 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc2076352004-02-16 01:20:27 +00002304 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002305
Chris Lattner97638592003-07-23 21:37:07 +00002306 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002307 // xor X, 0 == X
Chris Lattner97638592003-07-23 21:37:07 +00002308 if (RHS->isNullValue())
Chris Lattnere6794492002-08-12 21:17:25 +00002309 return ReplaceInstUsesWith(I, Op0);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002310
Chris Lattner97638592003-07-23 21:37:07 +00002311 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerb8d6e402002-08-20 18:24:26 +00002312 // xor (setcc A, B), true = not (setcc A, B) = setncc A, B
Chris Lattner97638592003-07-23 21:37:07 +00002313 if (SetCondInst *SCI = dyn_cast<SetCondInst>(Op0I))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002314 if (RHS == ConstantBool::True && SCI->hasOneUse())
Chris Lattnerb8d6e402002-08-20 18:24:26 +00002315 return new SetCondInst(SCI->getInverseCondition(),
2316 SCI->getOperand(0), SCI->getOperand(1));
Chris Lattnere5806662003-11-04 23:50:51 +00002317
Chris Lattner8f2f5982003-11-05 01:06:05 +00002318 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002319 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
2320 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002321 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
2322 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002323 ConstantInt::get(I.getType(), 1));
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002324 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002325 }
Chris Lattner023a4832004-06-18 06:07:51 +00002326
2327 // ~(~X & Y) --> (X | ~Y)
2328 if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
2329 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
2330 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
2331 Instruction *NotY =
Misha Brukmanb1c93172005-04-21 23:48:37 +00002332 BinaryOperator::createNot(Op0I->getOperand(1),
Chris Lattner023a4832004-06-18 06:07:51 +00002333 Op0I->getOperand(1)->getName()+".not");
2334 InsertNewInstBefore(NotY, I);
2335 return BinaryOperator::createOr(Op0NotVal, NotY);
2336 }
2337 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002338
Chris Lattner97638592003-07-23 21:37:07 +00002339 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattnere5806662003-11-04 23:50:51 +00002340 switch (Op0I->getOpcode()) {
2341 case Instruction::Add:
Chris Lattner0f68fa62003-11-04 23:37:10 +00002342 // ~(X-c) --> (-c-1)-X
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002343 if (RHS->isAllOnesValue()) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002344 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
2345 return BinaryOperator::createSub(
2346 ConstantExpr::getSub(NegOp0CI,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002347 ConstantInt::get(I.getType(), 1)),
Chris Lattner0f68fa62003-11-04 23:37:10 +00002348 Op0I->getOperand(0));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002349 }
Chris Lattnere5806662003-11-04 23:50:51 +00002350 break;
2351 case Instruction::And:
Chris Lattner97638592003-07-23 21:37:07 +00002352 // (X & C1) ^ C2 --> (X & C1) | C2 iff (C1&C2) == 0
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002353 if (ConstantExpr::getAnd(RHS, Op0CI)->isNullValue())
2354 return BinaryOperator::createOr(Op0, RHS);
Chris Lattnere5806662003-11-04 23:50:51 +00002355 break;
2356 case Instruction::Or:
Chris Lattner97638592003-07-23 21:37:07 +00002357 // (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002358 if (ConstantExpr::getAnd(RHS, Op0CI) == RHS)
Chris Lattnerc8e7e292004-06-10 02:12:35 +00002359 return BinaryOperator::createAnd(Op0, ConstantExpr::getNot(RHS));
Chris Lattnere5806662003-11-04 23:50:51 +00002360 break;
2361 default: break;
Chris Lattner97638592003-07-23 21:37:07 +00002362 }
Chris Lattnerb8d6e402002-08-20 18:24:26 +00002363 }
Chris Lattner183b3362004-04-09 19:05:30 +00002364
2365 // Try to fold constant and into select arguments.
2366 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00002367 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00002368 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002369 if (isa<PHINode>(Op0))
2370 if (Instruction *NV = FoldOpIntoPhi(I))
2371 return NV;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002372 }
2373
Chris Lattnerbb74e222003-03-10 23:06:50 +00002374 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00002375 if (X == Op1)
2376 return ReplaceInstUsesWith(I,
2377 ConstantIntegral::getAllOnesValue(I.getType()));
2378
Chris Lattnerbb74e222003-03-10 23:06:50 +00002379 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00002380 if (X == Op0)
2381 return ReplaceInstUsesWith(I,
2382 ConstantIntegral::getAllOnesValue(I.getType()));
2383
Chris Lattner1bbb7b62003-03-10 18:24:17 +00002384 if (Instruction *Op1I = dyn_cast<Instruction>(Op1))
Chris Lattnerb36d9082004-02-16 03:54:20 +00002385 if (Op1I->getOpcode() == Instruction::Or) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00002386 if (Op1I->getOperand(0) == Op0) { // B^(B|A) == (A|B)^B
2387 cast<BinaryOperator>(Op1I)->swapOperands();
2388 I.swapOperands();
2389 std::swap(Op0, Op1);
2390 } else if (Op1I->getOperand(1) == Op0) { // B^(A|B) == (A|B)^B
2391 I.swapOperands();
2392 std::swap(Op0, Op1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002393 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00002394 } else if (Op1I->getOpcode() == Instruction::Xor) {
2395 if (Op0 == Op1I->getOperand(0)) // A^(A^B) == B
2396 return ReplaceInstUsesWith(I, Op1I->getOperand(1));
2397 else if (Op0 == Op1I->getOperand(1)) // A^(B^A) == B
2398 return ReplaceInstUsesWith(I, Op1I->getOperand(0));
2399 }
Chris Lattner1bbb7b62003-03-10 18:24:17 +00002400
2401 if (Instruction *Op0I = dyn_cast<Instruction>(Op0))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002402 if (Op0I->getOpcode() == Instruction::Or && Op0I->hasOneUse()) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00002403 if (Op0I->getOperand(0) == Op1) // (B|A)^B == (A|B)^B
2404 cast<BinaryOperator>(Op0I)->swapOperands();
Chris Lattnerdcf240a2003-03-10 21:43:22 +00002405 if (Op0I->getOperand(1) == Op1) { // (A|B)^B == A & ~B
Chris Lattner396dbfe2004-06-09 05:08:07 +00002406 Value *NotB = InsertNewInstBefore(BinaryOperator::createNot(Op1,
2407 Op1->getName()+".not"), I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002408 return BinaryOperator::createAnd(Op0I->getOperand(0), NotB);
Chris Lattner1bbb7b62003-03-10 18:24:17 +00002409 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00002410 } else if (Op0I->getOpcode() == Instruction::Xor) {
2411 if (Op1 == Op0I->getOperand(0)) // (A^B)^A == B
2412 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2413 else if (Op1 == Op0I->getOperand(1)) // (B^A)^A == B
2414 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner1bbb7b62003-03-10 18:24:17 +00002415 }
2416
Chris Lattner7aa2d472004-08-01 19:42:59 +00002417 // (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattnerd4252a72004-07-30 07:50:03 +00002418 Value *A, *B; ConstantInt *C1, *C2;
2419 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
2420 match(Op1, m_And(m_Value(B), m_ConstantInt(C2))) &&
Chris Lattner7aa2d472004-08-01 19:42:59 +00002421 ConstantExpr::getAnd(C1, C2)->isNullValue())
Chris Lattnerd4252a72004-07-30 07:50:03 +00002422 return BinaryOperator::createOr(Op0, Op1);
Chris Lattner7fb29e12003-03-11 00:12:48 +00002423
Chris Lattner3ac7c262003-08-13 20:16:26 +00002424 // (setcc1 A, B) ^ (setcc2 A, B) --> (setcc3 A, B)
2425 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
2426 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
2427 return R;
2428
Chris Lattner113f4f42002-06-25 16:13:24 +00002429 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002430}
2431
Chris Lattner6862fbd2004-09-29 17:40:11 +00002432/// MulWithOverflow - Compute Result = In1*In2, returning true if the result
2433/// overflowed for this type.
2434static bool MulWithOverflow(ConstantInt *&Result, ConstantInt *In1,
2435 ConstantInt *In2) {
2436 Result = cast<ConstantInt>(ConstantExpr::getMul(In1, In2));
2437 return !In2->isNullValue() && ConstantExpr::getDiv(Result, In2) != In1;
2438}
2439
2440static bool isPositive(ConstantInt *C) {
2441 return cast<ConstantSInt>(C)->getValue() >= 0;
2442}
2443
2444/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
2445/// overflowed for this type.
2446static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
2447 ConstantInt *In2) {
2448 Result = cast<ConstantInt>(ConstantExpr::getAdd(In1, In2));
2449
2450 if (In1->getType()->isUnsigned())
2451 return cast<ConstantUInt>(Result)->getValue() <
2452 cast<ConstantUInt>(In1)->getValue();
2453 if (isPositive(In1) != isPositive(In2))
2454 return false;
2455 if (isPositive(In1))
2456 return cast<ConstantSInt>(Result)->getValue() <
2457 cast<ConstantSInt>(In1)->getValue();
2458 return cast<ConstantSInt>(Result)->getValue() >
2459 cast<ConstantSInt>(In1)->getValue();
2460}
2461
Chris Lattner0798af32005-01-13 20:14:25 +00002462/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
2463/// code necessary to compute the offset from the base pointer (without adding
2464/// in the base pointer). Return the result as a signed integer of intptr size.
2465static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
2466 TargetData &TD = IC.getTargetData();
2467 gep_type_iterator GTI = gep_type_begin(GEP);
2468 const Type *UIntPtrTy = TD.getIntPtrType();
2469 const Type *SIntPtrTy = UIntPtrTy->getSignedVersion();
2470 Value *Result = Constant::getNullValue(SIntPtrTy);
2471
2472 // Build a mask for high order bits.
2473 uint64_t PtrSizeMask = ~0ULL;
2474 PtrSizeMask >>= 64-(TD.getPointerSize()*8);
2475
Chris Lattner0798af32005-01-13 20:14:25 +00002476 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
2477 Value *Op = GEP->getOperand(i);
Chris Lattnerd35d2102005-01-13 23:26:48 +00002478 uint64_t Size = TD.getTypeSize(GTI.getIndexedType()) & PtrSizeMask;
Chris Lattner0798af32005-01-13 20:14:25 +00002479 Constant *Scale = ConstantExpr::getCast(ConstantUInt::get(UIntPtrTy, Size),
2480 SIntPtrTy);
2481 if (Constant *OpC = dyn_cast<Constant>(Op)) {
2482 if (!OpC->isNullValue()) {
Chris Lattner4cb9fa32005-01-13 20:40:58 +00002483 OpC = ConstantExpr::getCast(OpC, SIntPtrTy);
Chris Lattner0798af32005-01-13 20:14:25 +00002484 Scale = ConstantExpr::getMul(OpC, Scale);
2485 if (Constant *RC = dyn_cast<Constant>(Result))
2486 Result = ConstantExpr::getAdd(RC, Scale);
2487 else {
2488 // Emit an add instruction.
2489 Result = IC.InsertNewInstBefore(
2490 BinaryOperator::createAdd(Result, Scale,
2491 GEP->getName()+".offs"), I);
2492 }
2493 }
2494 } else {
Chris Lattner7aa41cf2005-01-14 17:17:59 +00002495 // Convert to correct type.
2496 Op = IC.InsertNewInstBefore(new CastInst(Op, SIntPtrTy,
2497 Op->getName()+".c"), I);
2498 if (Size != 1)
Chris Lattner4cb9fa32005-01-13 20:40:58 +00002499 // We'll let instcombine(mul) convert this to a shl if possible.
2500 Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
2501 GEP->getName()+".idx"), I);
Chris Lattner0798af32005-01-13 20:14:25 +00002502
2503 // Emit an add instruction.
Chris Lattner4cb9fa32005-01-13 20:40:58 +00002504 Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
Chris Lattner0798af32005-01-13 20:14:25 +00002505 GEP->getName()+".offs"), I);
2506 }
2507 }
2508 return Result;
2509}
2510
2511/// FoldGEPSetCC - Fold comparisons between a GEP instruction and something
2512/// else. At this point we know that the GEP is on the LHS of the comparison.
2513Instruction *InstCombiner::FoldGEPSetCC(User *GEPLHS, Value *RHS,
2514 Instruction::BinaryOps Cond,
2515 Instruction &I) {
2516 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattner81e84172005-01-13 22:25:21 +00002517
2518 if (CastInst *CI = dyn_cast<CastInst>(RHS))
2519 if (isa<PointerType>(CI->getOperand(0)->getType()))
2520 RHS = CI->getOperand(0);
2521
Chris Lattner0798af32005-01-13 20:14:25 +00002522 Value *PtrBase = GEPLHS->getOperand(0);
2523 if (PtrBase == RHS) {
2524 // As an optimization, we don't actually have to compute the actual value of
2525 // OFFSET if this is a seteq or setne comparison, just return whether each
2526 // index is zero or not.
Chris Lattner81e84172005-01-13 22:25:21 +00002527 if (Cond == Instruction::SetEQ || Cond == Instruction::SetNE) {
2528 Instruction *InVal = 0;
Chris Lattnercd517ff2005-01-28 19:32:01 +00002529 gep_type_iterator GTI = gep_type_begin(GEPLHS);
2530 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i, ++GTI) {
Chris Lattner81e84172005-01-13 22:25:21 +00002531 bool EmitIt = true;
2532 if (Constant *C = dyn_cast<Constant>(GEPLHS->getOperand(i))) {
2533 if (isa<UndefValue>(C)) // undef index -> undef.
2534 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2535 if (C->isNullValue())
2536 EmitIt = false;
Chris Lattnercd517ff2005-01-28 19:32:01 +00002537 else if (TD->getTypeSize(GTI.getIndexedType()) == 0) {
2538 EmitIt = false; // This is indexing into a zero sized array?
Misha Brukmanb1c93172005-04-21 23:48:37 +00002539 } else if (isa<ConstantInt>(C))
Chris Lattner81e84172005-01-13 22:25:21 +00002540 return ReplaceInstUsesWith(I, // No comparison is needed here.
2541 ConstantBool::get(Cond == Instruction::SetNE));
2542 }
2543
2544 if (EmitIt) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00002545 Instruction *Comp =
Chris Lattner81e84172005-01-13 22:25:21 +00002546 new SetCondInst(Cond, GEPLHS->getOperand(i),
2547 Constant::getNullValue(GEPLHS->getOperand(i)->getType()));
2548 if (InVal == 0)
2549 InVal = Comp;
2550 else {
2551 InVal = InsertNewInstBefore(InVal, I);
2552 InsertNewInstBefore(Comp, I);
2553 if (Cond == Instruction::SetNE) // True if any are unequal
2554 InVal = BinaryOperator::createOr(InVal, Comp);
2555 else // True if all are equal
2556 InVal = BinaryOperator::createAnd(InVal, Comp);
2557 }
2558 }
2559 }
2560
2561 if (InVal)
2562 return InVal;
2563 else
2564 ReplaceInstUsesWith(I, // No comparison is needed here, all indexes = 0
2565 ConstantBool::get(Cond == Instruction::SetEQ));
2566 }
Chris Lattner0798af32005-01-13 20:14:25 +00002567
2568 // Only lower this if the setcc is the only user of the GEP or if we expect
2569 // the result to fold to a constant!
2570 if (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) {
2571 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
2572 Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
2573 return new SetCondInst(Cond, Offset,
2574 Constant::getNullValue(Offset->getType()));
2575 }
2576 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
Chris Lattnera21bf8d2005-04-25 20:17:30 +00002577 // If the base pointers are different, but the indices are the same, just
2578 // compare the base pointer.
2579 if (PtrBase != GEPRHS->getOperand(0)) {
2580 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00002581 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattnerbd43b9d2005-04-26 14:40:41 +00002582 GEPRHS->getOperand(0)->getType();
Chris Lattnera21bf8d2005-04-25 20:17:30 +00002583 if (IndicesTheSame)
2584 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
2585 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
2586 IndicesTheSame = false;
2587 break;
2588 }
2589
2590 // If all indices are the same, just compare the base pointers.
2591 if (IndicesTheSame)
2592 return new SetCondInst(Cond, GEPLHS->getOperand(0),
2593 GEPRHS->getOperand(0));
2594
2595 // Otherwise, the base pointers are different and the indices are
2596 // different, bail out.
Chris Lattner0798af32005-01-13 20:14:25 +00002597 return 0;
Chris Lattnera21bf8d2005-04-25 20:17:30 +00002598 }
Chris Lattner0798af32005-01-13 20:14:25 +00002599
Chris Lattner81e84172005-01-13 22:25:21 +00002600 // If one of the GEPs has all zero indices, recurse.
2601 bool AllZeros = true;
2602 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
2603 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
2604 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
2605 AllZeros = false;
2606 break;
2607 }
2608 if (AllZeros)
2609 return FoldGEPSetCC(GEPRHS, GEPLHS->getOperand(0),
2610 SetCondInst::getSwappedCondition(Cond), I);
Chris Lattner4fa89822005-01-14 00:20:05 +00002611
2612 // If the other GEP has all zero indices, recurse.
Chris Lattner81e84172005-01-13 22:25:21 +00002613 AllZeros = true;
2614 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
2615 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
2616 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
2617 AllZeros = false;
2618 break;
2619 }
2620 if (AllZeros)
2621 return FoldGEPSetCC(GEPLHS, GEPRHS->getOperand(0), Cond, I);
2622
Chris Lattner4fa89822005-01-14 00:20:05 +00002623 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
2624 // If the GEPs only differ by one index, compare it.
2625 unsigned NumDifferences = 0; // Keep track of # differences.
2626 unsigned DiffOperand = 0; // The operand that differs.
2627 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
2628 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002629 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
2630 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattnerfc4429e2005-01-21 23:06:49 +00002631 // Irreconcilable differences.
Chris Lattner4fa89822005-01-14 00:20:05 +00002632 NumDifferences = 2;
2633 break;
2634 } else {
2635 if (NumDifferences++) break;
2636 DiffOperand = i;
2637 }
2638 }
2639
2640 if (NumDifferences == 0) // SAME GEP?
2641 return ReplaceInstUsesWith(I, // No comparison is needed here.
2642 ConstantBool::get(Cond == Instruction::SetEQ));
2643 else if (NumDifferences == 1) {
Chris Lattnerfc4429e2005-01-21 23:06:49 +00002644 Value *LHSV = GEPLHS->getOperand(DiffOperand);
2645 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Chris Lattner247aef82005-07-18 23:07:33 +00002646
2647 // Convert the operands to signed values to make sure to perform a
2648 // signed comparison.
2649 const Type *NewTy = LHSV->getType()->getSignedVersion();
2650 if (LHSV->getType() != NewTy)
2651 LHSV = InsertNewInstBefore(new CastInst(LHSV, NewTy,
2652 LHSV->getName()), I);
2653 if (RHSV->getType() != NewTy)
2654 RHSV = InsertNewInstBefore(new CastInst(RHSV, NewTy,
2655 RHSV->getName()), I);
2656 return new SetCondInst(Cond, LHSV, RHSV);
Chris Lattner4fa89822005-01-14 00:20:05 +00002657 }
2658 }
2659
Chris Lattner0798af32005-01-13 20:14:25 +00002660 // Only lower this if the setcc is the only user of the GEP or if we expect
2661 // the result to fold to a constant!
2662 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
2663 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
2664 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
2665 Value *L = EmitGEPOffset(GEPLHS, I, *this);
2666 Value *R = EmitGEPOffset(GEPRHS, I, *this);
2667 return new SetCondInst(Cond, L, R);
2668 }
2669 }
2670 return 0;
2671}
2672
2673
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002674Instruction *InstCombiner::visitSetCondInst(SetCondInst &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00002675 bool Changed = SimplifyCommutative(I);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002676 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2677 const Type *Ty = Op0->getType();
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002678
2679 // setcc X, X
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002680 if (Op0 == Op1)
2681 return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
Chris Lattner1fc23f32002-05-09 20:11:54 +00002682
Chris Lattner81a7a232004-10-16 18:11:37 +00002683 if (isa<UndefValue>(Op1)) // X setcc undef -> undef
2684 return ReplaceInstUsesWith(I, UndefValue::get(Type::BoolTy));
2685
Chris Lattner15ff1e12004-11-14 07:33:16 +00002686 // setcc <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
2687 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanb1c93172005-04-21 23:48:37 +00002688 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
2689 isa<ConstantPointerNull>(Op0)) &&
2690 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner15ff1e12004-11-14 07:33:16 +00002691 isa<ConstantPointerNull>(Op1)))
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002692 return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
2693
2694 // setcc's with boolean values can always be turned into bitwise operations
2695 if (Ty == Type::BoolTy) {
Chris Lattner4456da62004-08-11 00:50:51 +00002696 switch (I.getOpcode()) {
2697 default: assert(0 && "Invalid setcc instruction!");
2698 case Instruction::SetEQ: { // seteq bool %A, %B -> ~(A^B)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002699 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002700 InsertNewInstBefore(Xor, I);
Chris Lattner16930792003-11-03 04:25:02 +00002701 return BinaryOperator::createNot(Xor);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002702 }
Chris Lattner4456da62004-08-11 00:50:51 +00002703 case Instruction::SetNE:
2704 return BinaryOperator::createXor(Op0, Op1);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002705
Chris Lattner4456da62004-08-11 00:50:51 +00002706 case Instruction::SetGT:
2707 std::swap(Op0, Op1); // Change setgt -> setlt
2708 // FALL THROUGH
2709 case Instruction::SetLT: { // setlt bool A, B -> ~X & Y
2710 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
2711 InsertNewInstBefore(Not, I);
2712 return BinaryOperator::createAnd(Not, Op1);
2713 }
2714 case Instruction::SetGE:
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002715 std::swap(Op0, Op1); // Change setge -> setle
Chris Lattner4456da62004-08-11 00:50:51 +00002716 // FALL THROUGH
2717 case Instruction::SetLE: { // setle bool %A, %B -> ~A | B
2718 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
2719 InsertNewInstBefore(Not, I);
2720 return BinaryOperator::createOr(Not, Op1);
2721 }
2722 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002723 }
2724
Chris Lattner2dd01742004-06-09 04:24:29 +00002725 // See if we are doing a comparison between a constant and an instruction that
2726 // can be folded into the comparison.
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002727 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner6862fbd2004-09-29 17:40:11 +00002728 // Check to see if we are comparing against the minimum or maximum value...
2729 if (CI->isMinValue()) {
2730 if (I.getOpcode() == Instruction::SetLT) // A < MIN -> FALSE
2731 return ReplaceInstUsesWith(I, ConstantBool::False);
2732 if (I.getOpcode() == Instruction::SetGE) // A >= MIN -> TRUE
2733 return ReplaceInstUsesWith(I, ConstantBool::True);
2734 if (I.getOpcode() == Instruction::SetLE) // A <= MIN -> A == MIN
2735 return BinaryOperator::createSetEQ(Op0, Op1);
2736 if (I.getOpcode() == Instruction::SetGT) // A > MIN -> A != MIN
2737 return BinaryOperator::createSetNE(Op0, Op1);
2738
2739 } else if (CI->isMaxValue()) {
2740 if (I.getOpcode() == Instruction::SetGT) // A > MAX -> FALSE
2741 return ReplaceInstUsesWith(I, ConstantBool::False);
2742 if (I.getOpcode() == Instruction::SetLE) // A <= MAX -> TRUE
2743 return ReplaceInstUsesWith(I, ConstantBool::True);
2744 if (I.getOpcode() == Instruction::SetGE) // A >= MAX -> A == MAX
2745 return BinaryOperator::createSetEQ(Op0, Op1);
2746 if (I.getOpcode() == Instruction::SetLT) // A < MAX -> A != MAX
2747 return BinaryOperator::createSetNE(Op0, Op1);
2748
2749 // Comparing against a value really close to min or max?
2750 } else if (isMinValuePlusOne(CI)) {
2751 if (I.getOpcode() == Instruction::SetLT) // A < MIN+1 -> A == MIN
2752 return BinaryOperator::createSetEQ(Op0, SubOne(CI));
2753 if (I.getOpcode() == Instruction::SetGE) // A >= MIN-1 -> A != MIN
2754 return BinaryOperator::createSetNE(Op0, SubOne(CI));
2755
2756 } else if (isMaxValueMinusOne(CI)) {
2757 if (I.getOpcode() == Instruction::SetGT) // A > MAX-1 -> A == MAX
2758 return BinaryOperator::createSetEQ(Op0, AddOne(CI));
2759 if (I.getOpcode() == Instruction::SetLE) // A <= MAX-1 -> A != MAX
2760 return BinaryOperator::createSetNE(Op0, AddOne(CI));
2761 }
2762
2763 // If we still have a setle or setge instruction, turn it into the
2764 // appropriate setlt or setgt instruction. Since the border cases have
2765 // already been handled above, this requires little checking.
2766 //
2767 if (I.getOpcode() == Instruction::SetLE)
2768 return BinaryOperator::createSetLT(Op0, AddOne(CI));
2769 if (I.getOpcode() == Instruction::SetGE)
2770 return BinaryOperator::createSetGT(Op0, SubOne(CI));
2771
Chris Lattnere1e10e12004-05-25 06:32:08 +00002772 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002773 switch (LHSI->getOpcode()) {
2774 case Instruction::And:
2775 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
2776 LHSI->getOperand(0)->hasOneUse()) {
2777 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
2778 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
2779 // happens a LOT in code produced by the C front-end, for bitfield
2780 // access.
2781 ShiftInst *Shift = dyn_cast<ShiftInst>(LHSI->getOperand(0));
2782 ConstantUInt *ShAmt;
2783 ShAmt = Shift ? dyn_cast<ConstantUInt>(Shift->getOperand(1)) : 0;
2784 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
2785 const Type *Ty = LHSI->getType();
Misha Brukmanb1c93172005-04-21 23:48:37 +00002786
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002787 // We can fold this as long as we can't shift unknown bits
2788 // into the mask. This can only happen with signed shift
2789 // rights, as they sign-extend.
2790 if (ShAmt) {
2791 bool CanFold = Shift->getOpcode() != Instruction::Shr ||
Chris Lattner6afc02f2004-09-28 17:54:07 +00002792 Shift->getType()->isUnsigned();
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002793 if (!CanFold) {
2794 // To test for the bad case of the signed shr, see if any
2795 // of the bits shifted in could be tested after the mask.
Chris Lattnerc53cb9d2005-06-17 01:29:28 +00002796 int ShAmtVal = Ty->getPrimitiveSizeInBits()-ShAmt->getValue();
2797 if (ShAmtVal < 0) ShAmtVal = 0; // Out of range shift.
2798
2799 Constant *OShAmt = ConstantUInt::get(Type::UByteTy, ShAmtVal);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002800 Constant *ShVal =
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002801 ConstantExpr::getShl(ConstantInt::getAllOnesValue(Ty), OShAmt);
2802 if (ConstantExpr::getAnd(ShVal, AndCST)->isNullValue())
2803 CanFold = true;
2804 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002805
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002806 if (CanFold) {
Chris Lattner6afc02f2004-09-28 17:54:07 +00002807 Constant *NewCst;
2808 if (Shift->getOpcode() == Instruction::Shl)
2809 NewCst = ConstantExpr::getUShr(CI, ShAmt);
2810 else
2811 NewCst = ConstantExpr::getShl(CI, ShAmt);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002812
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002813 // Check to see if we are shifting out any of the bits being
2814 // compared.
2815 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != CI){
2816 // If we shifted bits out, the fold is not going to work out.
2817 // As a special case, check to see if this means that the
2818 // result is always true or false now.
2819 if (I.getOpcode() == Instruction::SetEQ)
2820 return ReplaceInstUsesWith(I, ConstantBool::False);
2821 if (I.getOpcode() == Instruction::SetNE)
2822 return ReplaceInstUsesWith(I, ConstantBool::True);
2823 } else {
2824 I.setOperand(1, NewCst);
Chris Lattner6afc02f2004-09-28 17:54:07 +00002825 Constant *NewAndCST;
2826 if (Shift->getOpcode() == Instruction::Shl)
2827 NewAndCST = ConstantExpr::getUShr(AndCST, ShAmt);
2828 else
2829 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
2830 LHSI->setOperand(1, NewAndCST);
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002831 LHSI->setOperand(0, Shift->getOperand(0));
2832 WorkList.push_back(Shift); // Shift is dead.
2833 AddUsesToWorkList(I);
2834 return &I;
Chris Lattner1638de42004-07-21 19:50:44 +00002835 }
2836 }
Chris Lattner35167c32004-06-09 07:59:58 +00002837 }
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002838 }
2839 break;
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002840
Chris Lattner272d5ca2004-09-28 18:22:15 +00002841 case Instruction::Shl: // (setcc (shl X, ShAmt), CI)
2842 if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
2843 switch (I.getOpcode()) {
2844 default: break;
2845 case Instruction::SetEQ:
2846 case Instruction::SetNE: {
Chris Lattner19b57f52005-06-15 20:53:31 +00002847 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
2848
2849 // Check that the shift amount is in range. If not, don't perform
2850 // undefined shifts. When the shift is visited it will be
2851 // simplified.
2852 if (ShAmt->getValue() >= TypeBits)
2853 break;
2854
Chris Lattner272d5ca2004-09-28 18:22:15 +00002855 // If we are comparing against bits always shifted out, the
2856 // comparison cannot succeed.
Misha Brukmanb1c93172005-04-21 23:48:37 +00002857 Constant *Comp =
Chris Lattner272d5ca2004-09-28 18:22:15 +00002858 ConstantExpr::getShl(ConstantExpr::getShr(CI, ShAmt), ShAmt);
2859 if (Comp != CI) {// Comparing against a bit that we know is zero.
2860 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
2861 Constant *Cst = ConstantBool::get(IsSetNE);
2862 return ReplaceInstUsesWith(I, Cst);
2863 }
2864
2865 if (LHSI->hasOneUse()) {
2866 // Otherwise strength reduce the shift into an and.
Chris Lattnerfdfe3e492005-01-08 19:42:22 +00002867 unsigned ShAmtVal = (unsigned)ShAmt->getValue();
Chris Lattner272d5ca2004-09-28 18:22:15 +00002868 uint64_t Val = (1ULL << (TypeBits-ShAmtVal))-1;
2869
2870 Constant *Mask;
2871 if (CI->getType()->isUnsigned()) {
2872 Mask = ConstantUInt::get(CI->getType(), Val);
2873 } else if (ShAmtVal != 0) {
2874 Mask = ConstantSInt::get(CI->getType(), Val);
2875 } else {
2876 Mask = ConstantInt::getAllOnesValue(CI->getType());
2877 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002878
Chris Lattner272d5ca2004-09-28 18:22:15 +00002879 Instruction *AndI =
2880 BinaryOperator::createAnd(LHSI->getOperand(0),
2881 Mask, LHSI->getName()+".mask");
2882 Value *And = InsertNewInstBefore(AndI, I);
2883 return new SetCondInst(I.getOpcode(), And,
2884 ConstantExpr::getUShr(CI, ShAmt));
2885 }
2886 }
2887 }
2888 }
2889 break;
2890
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002891 case Instruction::Shr: // (setcc (shr X, ShAmt), CI)
Chris Lattner1023b872004-09-27 16:18:50 +00002892 if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
Chris Lattner1023b872004-09-27 16:18:50 +00002893 switch (I.getOpcode()) {
2894 default: break;
2895 case Instruction::SetEQ:
2896 case Instruction::SetNE: {
Chris Lattner19b57f52005-06-15 20:53:31 +00002897
2898 // Check that the shift amount is in range. If not, don't perform
2899 // undefined shifts. When the shift is visited it will be
2900 // simplified.
Chris Lattner104002b2005-06-16 01:52:07 +00002901 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
Chris Lattner19b57f52005-06-15 20:53:31 +00002902 if (ShAmt->getValue() >= TypeBits)
2903 break;
2904
Chris Lattner1023b872004-09-27 16:18:50 +00002905 // If we are comparing against bits always shifted out, the
2906 // comparison cannot succeed.
Misha Brukmanb1c93172005-04-21 23:48:37 +00002907 Constant *Comp =
Chris Lattner1023b872004-09-27 16:18:50 +00002908 ConstantExpr::getShr(ConstantExpr::getShl(CI, ShAmt), ShAmt);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002909
Chris Lattner1023b872004-09-27 16:18:50 +00002910 if (Comp != CI) {// Comparing against a bit that we know is zero.
2911 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
2912 Constant *Cst = ConstantBool::get(IsSetNE);
2913 return ReplaceInstUsesWith(I, Cst);
2914 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002915
Chris Lattner1023b872004-09-27 16:18:50 +00002916 if (LHSI->hasOneUse() || CI->isNullValue()) {
Chris Lattnerfdfe3e492005-01-08 19:42:22 +00002917 unsigned ShAmtVal = (unsigned)ShAmt->getValue();
Chris Lattner272d5ca2004-09-28 18:22:15 +00002918
Chris Lattner1023b872004-09-27 16:18:50 +00002919 // Otherwise strength reduce the shift into an and.
2920 uint64_t Val = ~0ULL; // All ones.
2921 Val <<= ShAmtVal; // Shift over to the right spot.
2922
2923 Constant *Mask;
2924 if (CI->getType()->isUnsigned()) {
Chris Lattner2f1457f2005-04-24 17:46:05 +00002925 Val &= ~0ULL >> (64-TypeBits);
Chris Lattner1023b872004-09-27 16:18:50 +00002926 Mask = ConstantUInt::get(CI->getType(), Val);
2927 } else {
2928 Mask = ConstantSInt::get(CI->getType(), Val);
2929 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002930
Chris Lattner1023b872004-09-27 16:18:50 +00002931 Instruction *AndI =
2932 BinaryOperator::createAnd(LHSI->getOperand(0),
2933 Mask, LHSI->getName()+".mask");
2934 Value *And = InsertNewInstBefore(AndI, I);
2935 return new SetCondInst(I.getOpcode(), And,
2936 ConstantExpr::getShl(CI, ShAmt));
2937 }
2938 break;
2939 }
2940 }
2941 }
2942 break;
Chris Lattner7e794272004-09-24 15:21:34 +00002943
Chris Lattner6862fbd2004-09-29 17:40:11 +00002944 case Instruction::Div:
2945 // Fold: (div X, C1) op C2 -> range check
2946 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
2947 // Fold this div into the comparison, producing a range check.
2948 // Determine, based on the divide type, what the range is being
2949 // checked. If there is an overflow on the low or high side, remember
2950 // it, otherwise compute the range [low, hi) bounding the new value.
2951 bool LoOverflow = false, HiOverflow = 0;
2952 ConstantInt *LoBound = 0, *HiBound = 0;
2953
2954 ConstantInt *Prod;
2955 bool ProdOV = MulWithOverflow(Prod, CI, DivRHS);
2956
Chris Lattnera92af962004-10-11 19:40:04 +00002957 Instruction::BinaryOps Opcode = I.getOpcode();
2958
Chris Lattner6862fbd2004-09-29 17:40:11 +00002959 if (DivRHS->isNullValue()) { // Don't hack on divide by zeros.
2960 } else if (LHSI->getType()->isUnsigned()) { // udiv
2961 LoBound = Prod;
2962 LoOverflow = ProdOV;
2963 HiOverflow = ProdOV || AddWithOverflow(HiBound, LoBound, DivRHS);
2964 } else if (isPositive(DivRHS)) { // Divisor is > 0.
2965 if (CI->isNullValue()) { // (X / pos) op 0
2966 // Can't overflow.
2967 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
2968 HiBound = DivRHS;
2969 } else if (isPositive(CI)) { // (X / pos) op pos
2970 LoBound = Prod;
2971 LoOverflow = ProdOV;
2972 HiOverflow = ProdOV || AddWithOverflow(HiBound, Prod, DivRHS);
2973 } else { // (X / pos) op neg
2974 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
2975 LoOverflow = AddWithOverflow(LoBound, Prod,
2976 cast<ConstantInt>(DivRHSH));
2977 HiBound = Prod;
2978 HiOverflow = ProdOV;
2979 }
2980 } else { // Divisor is < 0.
2981 if (CI->isNullValue()) { // (X / neg) op 0
2982 LoBound = AddOne(DivRHS);
2983 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner73bcba52005-06-17 02:05:55 +00002984 if (HiBound == DivRHS)
2985 LoBound = 0; // - INTMIN = INTMIN
Chris Lattner6862fbd2004-09-29 17:40:11 +00002986 } else if (isPositive(CI)) { // (X / neg) op pos
2987 HiOverflow = LoOverflow = ProdOV;
2988 if (!LoOverflow)
2989 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS));
2990 HiBound = AddOne(Prod);
2991 } else { // (X / neg) op neg
2992 LoBound = Prod;
2993 LoOverflow = HiOverflow = ProdOV;
2994 HiBound = cast<ConstantInt>(ConstantExpr::getSub(Prod, DivRHS));
2995 }
Chris Lattner0b41e862004-10-08 19:15:44 +00002996
Chris Lattnera92af962004-10-11 19:40:04 +00002997 // Dividing by a negate swaps the condition.
2998 Opcode = SetCondInst::getSwappedCondition(Opcode);
Chris Lattner6862fbd2004-09-29 17:40:11 +00002999 }
3000
3001 if (LoBound) {
3002 Value *X = LHSI->getOperand(0);
Chris Lattnera92af962004-10-11 19:40:04 +00003003 switch (Opcode) {
Chris Lattner6862fbd2004-09-29 17:40:11 +00003004 default: assert(0 && "Unhandled setcc opcode!");
3005 case Instruction::SetEQ:
3006 if (LoOverflow && HiOverflow)
3007 return ReplaceInstUsesWith(I, ConstantBool::False);
3008 else if (HiOverflow)
3009 return new SetCondInst(Instruction::SetGE, X, LoBound);
3010 else if (LoOverflow)
3011 return new SetCondInst(Instruction::SetLT, X, HiBound);
3012 else
3013 return InsertRangeTest(X, LoBound, HiBound, true, I);
3014 case Instruction::SetNE:
3015 if (LoOverflow && HiOverflow)
3016 return ReplaceInstUsesWith(I, ConstantBool::True);
3017 else if (HiOverflow)
3018 return new SetCondInst(Instruction::SetLT, X, LoBound);
3019 else if (LoOverflow)
3020 return new SetCondInst(Instruction::SetGE, X, HiBound);
3021 else
3022 return InsertRangeTest(X, LoBound, HiBound, false, I);
3023 case Instruction::SetLT:
3024 if (LoOverflow)
3025 return ReplaceInstUsesWith(I, ConstantBool::False);
3026 return new SetCondInst(Instruction::SetLT, X, LoBound);
3027 case Instruction::SetGT:
3028 if (HiOverflow)
3029 return ReplaceInstUsesWith(I, ConstantBool::False);
3030 return new SetCondInst(Instruction::SetGE, X, HiBound);
3031 }
3032 }
3033 }
3034 break;
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00003035 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003036
Chris Lattnerd492a0b2003-07-23 17:02:11 +00003037 // Simplify seteq and setne instructions...
3038 if (I.getOpcode() == Instruction::SetEQ ||
3039 I.getOpcode() == Instruction::SetNE) {
3040 bool isSetNE = I.getOpcode() == Instruction::SetNE;
3041
Chris Lattnercfbce7c2003-07-23 17:26:36 +00003042 // If the first operand is (and|or|xor) with a constant, and the second
Chris Lattnerd492a0b2003-07-23 17:02:11 +00003043 // operand is a constant, simplify a bit.
Chris Lattnerc992add2003-08-13 05:33:12 +00003044 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
3045 switch (BO->getOpcode()) {
Chris Lattner23b47b62004-07-06 07:38:18 +00003046 case Instruction::Rem:
3047 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
3048 if (CI->isNullValue() && isa<ConstantSInt>(BO->getOperand(1)) &&
3049 BO->hasOneUse() &&
Chris Lattner22d00a82005-08-02 19:16:58 +00003050 cast<ConstantSInt>(BO->getOperand(1))->getValue() > 1) {
3051 int64_t V = cast<ConstantSInt>(BO->getOperand(1))->getValue();
3052 if (isPowerOf2_64(V)) {
3053 unsigned L2 = Log2_64(V);
Chris Lattner23b47b62004-07-06 07:38:18 +00003054 const Type *UTy = BO->getType()->getUnsignedVersion();
3055 Value *NewX = InsertNewInstBefore(new CastInst(BO->getOperand(0),
3056 UTy, "tmp"), I);
3057 Constant *RHSCst = ConstantUInt::get(UTy, 1ULL << L2);
3058 Value *NewRem =InsertNewInstBefore(BinaryOperator::createRem(NewX,
3059 RHSCst, BO->getName()), I);
3060 return BinaryOperator::create(I.getOpcode(), NewRem,
3061 Constant::getNullValue(UTy));
3062 }
Chris Lattner22d00a82005-08-02 19:16:58 +00003063 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003064 break;
Chris Lattner23b47b62004-07-06 07:38:18 +00003065
Chris Lattnerc992add2003-08-13 05:33:12 +00003066 case Instruction::Add:
Chris Lattner6e079362004-06-27 22:51:36 +00003067 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
3068 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerb121ae12004-09-21 21:35:23 +00003069 if (BO->hasOneUse())
3070 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
3071 ConstantExpr::getSub(CI, BOp1C));
Chris Lattner6e079362004-06-27 22:51:36 +00003072 } else if (CI->isNullValue()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00003073 // Replace ((add A, B) != 0) with (A != -B) if A or B is
3074 // efficiently invertible, or if the add has just this one use.
3075 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003076
Chris Lattnerc992add2003-08-13 05:33:12 +00003077 if (Value *NegVal = dyn_castNegVal(BOp1))
3078 return new SetCondInst(I.getOpcode(), BOp0, NegVal);
3079 else if (Value *NegVal = dyn_castNegVal(BOp0))
3080 return new SetCondInst(I.getOpcode(), NegVal, BOp1);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00003081 else if (BO->hasOneUse()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00003082 Instruction *Neg = BinaryOperator::createNeg(BOp1, BO->getName());
3083 BO->setName("");
3084 InsertNewInstBefore(Neg, I);
3085 return new SetCondInst(I.getOpcode(), BOp0, Neg);
3086 }
3087 }
3088 break;
3089 case Instruction::Xor:
3090 // For the xor case, we can xor two constants together, eliminating
3091 // the explicit xor.
3092 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
3093 return BinaryOperator::create(I.getOpcode(), BO->getOperand(0),
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003094 ConstantExpr::getXor(CI, BOC));
Chris Lattnerc992add2003-08-13 05:33:12 +00003095
3096 // FALLTHROUGH
3097 case Instruction::Sub:
3098 // Replace (([sub|xor] A, B) != 0) with (A != B)
3099 if (CI->isNullValue())
3100 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
3101 BO->getOperand(1));
3102 break;
3103
3104 case Instruction::Or:
3105 // If bits are being or'd in that are not present in the constant we
3106 // are comparing against, then the comparison could never succeed!
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003107 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Chris Lattnerc8e7e292004-06-10 02:12:35 +00003108 Constant *NotCI = ConstantExpr::getNot(CI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003109 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Chris Lattnerd492a0b2003-07-23 17:02:11 +00003110 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003111 }
Chris Lattnerc992add2003-08-13 05:33:12 +00003112 break;
3113
3114 case Instruction::And:
3115 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerd492a0b2003-07-23 17:02:11 +00003116 // If bits are being compared against that are and'd out, then the
3117 // comparison can never succeed!
Chris Lattnerc8e7e292004-06-10 02:12:35 +00003118 if (!ConstantExpr::getAnd(CI,
3119 ConstantExpr::getNot(BOC))->isNullValue())
Chris Lattnerd492a0b2003-07-23 17:02:11 +00003120 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattnerc992add2003-08-13 05:33:12 +00003121
Chris Lattner35167c32004-06-09 07:59:58 +00003122 // If we have ((X & C) == C), turn it into ((X & C) != 0).
Chris Lattneree59d4b2004-06-10 02:33:20 +00003123 if (CI == BOC && isOneBitSet(CI))
Chris Lattner35167c32004-06-09 07:59:58 +00003124 return new SetCondInst(isSetNE ? Instruction::SetEQ :
3125 Instruction::SetNE, Op0,
3126 Constant::getNullValue(CI->getType()));
Chris Lattner35167c32004-06-09 07:59:58 +00003127
Chris Lattnerc992add2003-08-13 05:33:12 +00003128 // Replace (and X, (1 << size(X)-1) != 0) with x < 0, converting X
3129 // to be a signed value as appropriate.
3130 if (isSignBit(BOC)) {
3131 Value *X = BO->getOperand(0);
3132 // If 'X' is not signed, insert a cast now...
3133 if (!BOC->getType()->isSigned()) {
Chris Lattner97bfcea2004-06-17 18:16:02 +00003134 const Type *DestTy = BOC->getType()->getSignedVersion();
Chris Lattnerbfff18a2004-09-27 19:29:18 +00003135 X = InsertCastBefore(X, DestTy, I);
Chris Lattnerc992add2003-08-13 05:33:12 +00003136 }
3137 return new SetCondInst(isSetNE ? Instruction::SetLT :
3138 Instruction::SetGE, X,
3139 Constant::getNullValue(X->getType()));
3140 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003141
Chris Lattnerbfff18a2004-09-27 19:29:18 +00003142 // ((X & ~7) == 0) --> X < 8
Chris Lattner8fc5af42004-09-23 21:46:38 +00003143 if (CI->isNullValue() && isHighOnes(BOC)) {
3144 Value *X = BO->getOperand(0);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00003145 Constant *NegX = ConstantExpr::getNeg(BOC);
Chris Lattner8fc5af42004-09-23 21:46:38 +00003146
3147 // If 'X' is signed, insert a cast now.
Chris Lattnerbfff18a2004-09-27 19:29:18 +00003148 if (NegX->getType()->isSigned()) {
3149 const Type *DestTy = NegX->getType()->getUnsignedVersion();
3150 X = InsertCastBefore(X, DestTy, I);
3151 NegX = ConstantExpr::getCast(NegX, DestTy);
Chris Lattner8fc5af42004-09-23 21:46:38 +00003152 }
3153
3154 return new SetCondInst(isSetNE ? Instruction::SetGE :
Chris Lattnerbfff18a2004-09-27 19:29:18 +00003155 Instruction::SetLT, X, NegX);
Chris Lattner8fc5af42004-09-23 21:46:38 +00003156 }
3157
Chris Lattnerd492a0b2003-07-23 17:02:11 +00003158 }
Chris Lattnerc992add2003-08-13 05:33:12 +00003159 default: break;
3160 }
3161 }
Chris Lattner2b55ea32004-02-23 07:16:20 +00003162 } else { // Not a SetEQ/SetNE
Misha Brukmanb1c93172005-04-21 23:48:37 +00003163 // If the LHS is a cast from an integral value of the same size,
Chris Lattner2b55ea32004-02-23 07:16:20 +00003164 if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
3165 Value *CastOp = Cast->getOperand(0);
3166 const Type *SrcTy = CastOp->getType();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003167 unsigned SrcTySize = SrcTy->getPrimitiveSizeInBits();
Chris Lattner2b55ea32004-02-23 07:16:20 +00003168 if (SrcTy != Cast->getType() && SrcTy->isInteger() &&
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003169 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00003170 assert((SrcTy->isSigned() ^ Cast->getType()->isSigned()) &&
Chris Lattner2b55ea32004-02-23 07:16:20 +00003171 "Source and destination signednesses should differ!");
3172 if (Cast->getType()->isSigned()) {
3173 // If this is a signed comparison, check for comparisons in the
3174 // vicinity of zero.
3175 if (I.getOpcode() == Instruction::SetLT && CI->isNullValue())
3176 // X < 0 => x > 127
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003177 return BinaryOperator::createSetGT(CastOp,
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003178 ConstantUInt::get(SrcTy, (1ULL << (SrcTySize-1))-1));
Chris Lattner2b55ea32004-02-23 07:16:20 +00003179 else if (I.getOpcode() == Instruction::SetGT &&
3180 cast<ConstantSInt>(CI)->getValue() == -1)
3181 // X > -1 => x < 128
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003182 return BinaryOperator::createSetLT(CastOp,
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003183 ConstantUInt::get(SrcTy, 1ULL << (SrcTySize-1)));
Chris Lattner2b55ea32004-02-23 07:16:20 +00003184 } else {
3185 ConstantUInt *CUI = cast<ConstantUInt>(CI);
3186 if (I.getOpcode() == Instruction::SetLT &&
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003187 CUI->getValue() == 1ULL << (SrcTySize-1))
Chris Lattner2b55ea32004-02-23 07:16:20 +00003188 // X < 128 => X > -1
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003189 return BinaryOperator::createSetGT(CastOp,
3190 ConstantSInt::get(SrcTy, -1));
Chris Lattner2b55ea32004-02-23 07:16:20 +00003191 else if (I.getOpcode() == Instruction::SetGT &&
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003192 CUI->getValue() == (1ULL << (SrcTySize-1))-1)
Chris Lattner2b55ea32004-02-23 07:16:20 +00003193 // X > 127 => X < 0
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003194 return BinaryOperator::createSetLT(CastOp,
3195 Constant::getNullValue(SrcTy));
Chris Lattner2b55ea32004-02-23 07:16:20 +00003196 }
3197 }
3198 }
Chris Lattnere967b342003-06-04 05:10:11 +00003199 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003200 }
3201
Chris Lattner77c32c32005-04-23 15:31:55 +00003202 // Handle setcc with constant RHS's that can be integer, FP or pointer.
3203 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
3204 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
3205 switch (LHSI->getOpcode()) {
Chris Lattnera816eee2005-05-01 04:42:15 +00003206 case Instruction::GetElementPtr:
3207 if (RHSC->isNullValue()) {
3208 // Transform setcc GEP P, int 0, int 0, int 0, null -> setcc P, null
3209 bool isAllZeros = true;
3210 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
3211 if (!isa<Constant>(LHSI->getOperand(i)) ||
3212 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
3213 isAllZeros = false;
3214 break;
3215 }
3216 if (isAllZeros)
3217 return new SetCondInst(I.getOpcode(), LHSI->getOperand(0),
3218 Constant::getNullValue(LHSI->getOperand(0)->getType()));
3219 }
3220 break;
3221
Chris Lattner77c32c32005-04-23 15:31:55 +00003222 case Instruction::PHI:
3223 if (Instruction *NV = FoldOpIntoPhi(I))
3224 return NV;
3225 break;
3226 case Instruction::Select:
3227 // If either operand of the select is a constant, we can fold the
3228 // comparison into the select arms, which will cause one to be
3229 // constant folded and the select turned into a bitwise or.
3230 Value *Op1 = 0, *Op2 = 0;
3231 if (LHSI->hasOneUse()) {
3232 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
3233 // Fold the known value into the constant operand.
3234 Op1 = ConstantExpr::get(I.getOpcode(), C, RHSC);
3235 // Insert a new SetCC of the other select operand.
3236 Op2 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
3237 LHSI->getOperand(2), RHSC,
3238 I.getName()), I);
3239 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
3240 // Fold the known value into the constant operand.
3241 Op2 = ConstantExpr::get(I.getOpcode(), C, RHSC);
3242 // Insert a new SetCC of the other select operand.
3243 Op1 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
3244 LHSI->getOperand(1), RHSC,
3245 I.getName()), I);
3246 }
3247 }
Jeff Cohen82639852005-04-23 21:38:35 +00003248
Chris Lattner77c32c32005-04-23 15:31:55 +00003249 if (Op1)
3250 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
3251 break;
3252 }
3253 }
3254
Chris Lattner0798af32005-01-13 20:14:25 +00003255 // If we can optimize a 'setcc GEP, P' or 'setcc P, GEP', do so now.
3256 if (User *GEP = dyn_castGetElementPtr(Op0))
3257 if (Instruction *NI = FoldGEPSetCC(GEP, Op1, I.getOpcode(), I))
3258 return NI;
3259 if (User *GEP = dyn_castGetElementPtr(Op1))
3260 if (Instruction *NI = FoldGEPSetCC(GEP, Op0,
3261 SetCondInst::getSwappedCondition(I.getOpcode()), I))
3262 return NI;
3263
Chris Lattner16930792003-11-03 04:25:02 +00003264 // Test to see if the operands of the setcc are casted versions of other
3265 // values. If the cast can be stripped off both arguments, we do so now.
Chris Lattner6444c372003-11-03 05:17:03 +00003266 if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3267 Value *CastOp0 = CI->getOperand(0);
3268 if (CastOp0->getType()->isLosslesslyConvertibleTo(CI->getType()) &&
Chris Lattner7d2a5392004-03-13 23:54:27 +00003269 (isa<Constant>(Op1) || isa<CastInst>(Op1)) &&
Chris Lattner16930792003-11-03 04:25:02 +00003270 (I.getOpcode() == Instruction::SetEQ ||
3271 I.getOpcode() == Instruction::SetNE)) {
3272 // We keep moving the cast from the left operand over to the right
3273 // operand, where it can often be eliminated completely.
Chris Lattner6444c372003-11-03 05:17:03 +00003274 Op0 = CastOp0;
Misha Brukmanb1c93172005-04-21 23:48:37 +00003275
Chris Lattner16930792003-11-03 04:25:02 +00003276 // If operand #1 is a cast instruction, see if we can eliminate it as
3277 // well.
Chris Lattner6444c372003-11-03 05:17:03 +00003278 if (CastInst *CI2 = dyn_cast<CastInst>(Op1))
3279 if (CI2->getOperand(0)->getType()->isLosslesslyConvertibleTo(
Chris Lattner16930792003-11-03 04:25:02 +00003280 Op0->getType()))
Chris Lattner6444c372003-11-03 05:17:03 +00003281 Op1 = CI2->getOperand(0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003282
Chris Lattner16930792003-11-03 04:25:02 +00003283 // If Op1 is a constant, we can fold the cast into the constant.
3284 if (Op1->getType() != Op0->getType())
3285 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
3286 Op1 = ConstantExpr::getCast(Op1C, Op0->getType());
3287 } else {
3288 // Otherwise, cast the RHS right before the setcc
3289 Op1 = new CastInst(Op1, Op0->getType(), Op1->getName());
3290 InsertNewInstBefore(cast<Instruction>(Op1), I);
3291 }
3292 return BinaryOperator::create(I.getOpcode(), Op0, Op1);
3293 }
3294
Chris Lattner6444c372003-11-03 05:17:03 +00003295 // Handle the special case of: setcc (cast bool to X), <cst>
3296 // This comes up when you have code like
3297 // int X = A < B;
3298 // if (X) ...
3299 // For generality, we handle any zero-extension of any operand comparison
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003300 // with a constant or another cast from the same type.
3301 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
3302 if (Instruction *R = visitSetCondInstWithCastAndCast(I))
3303 return R;
Chris Lattner6444c372003-11-03 05:17:03 +00003304 }
Chris Lattner113f4f42002-06-25 16:13:24 +00003305 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003306}
3307
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003308// visitSetCondInstWithCastAndCast - Handle setcond (cast x to y), (cast/cst).
3309// We only handle extending casts so far.
3310//
3311Instruction *InstCombiner::visitSetCondInstWithCastAndCast(SetCondInst &SCI) {
3312 Value *LHSCIOp = cast<CastInst>(SCI.getOperand(0))->getOperand(0);
3313 const Type *SrcTy = LHSCIOp->getType();
3314 const Type *DestTy = SCI.getOperand(0)->getType();
3315 Value *RHSCIOp;
3316
3317 if (!DestTy->isIntegral() || !SrcTy->isIntegral())
Chris Lattner03f06f12005-01-17 03:20:02 +00003318 return 0;
3319
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003320 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
3321 unsigned DestBits = DestTy->getPrimitiveSizeInBits();
3322 if (SrcBits >= DestBits) return 0; // Only handle extending cast.
3323
3324 // Is this a sign or zero extension?
3325 bool isSignSrc = SrcTy->isSigned();
3326 bool isSignDest = DestTy->isSigned();
3327
3328 if (CastInst *CI = dyn_cast<CastInst>(SCI.getOperand(1))) {
3329 // Not an extension from the same type?
3330 RHSCIOp = CI->getOperand(0);
3331 if (RHSCIOp->getType() != LHSCIOp->getType()) return 0;
3332 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(SCI.getOperand(1))) {
3333 // Compute the constant that would happen if we truncated to SrcTy then
3334 // reextended to DestTy.
3335 Constant *Res = ConstantExpr::getCast(CI, SrcTy);
3336
3337 if (ConstantExpr::getCast(Res, DestTy) == CI) {
3338 RHSCIOp = Res;
3339 } else {
3340 // If the value cannot be represented in the shorter type, we cannot emit
3341 // a simple comparison.
3342 if (SCI.getOpcode() == Instruction::SetEQ)
3343 return ReplaceInstUsesWith(SCI, ConstantBool::False);
3344 if (SCI.getOpcode() == Instruction::SetNE)
3345 return ReplaceInstUsesWith(SCI, ConstantBool::True);
3346
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003347 // Evaluate the comparison for LT.
3348 Value *Result;
3349 if (DestTy->isSigned()) {
3350 // We're performing a signed comparison.
3351 if (isSignSrc) {
3352 // Signed extend and signed comparison.
3353 if (cast<ConstantSInt>(CI)->getValue() < 0) // X < (small) --> false
3354 Result = ConstantBool::False;
3355 else
3356 Result = ConstantBool::True; // X < (large) --> true
3357 } else {
3358 // Unsigned extend and signed comparison.
3359 if (cast<ConstantSInt>(CI)->getValue() < 0)
3360 Result = ConstantBool::False;
3361 else
3362 Result = ConstantBool::True;
3363 }
3364 } else {
3365 // We're performing an unsigned comparison.
3366 if (!isSignSrc) {
3367 // Unsigned extend & compare -> always true.
3368 Result = ConstantBool::True;
3369 } else {
3370 // We're performing an unsigned comp with a sign extended value.
3371 // This is true if the input is >= 0. [aka >s -1]
3372 Constant *NegOne = ConstantIntegral::getAllOnesValue(SrcTy);
3373 Result = InsertNewInstBefore(BinaryOperator::createSetGT(LHSCIOp,
3374 NegOne, SCI.getName()), SCI);
3375 }
Reid Spencer279fa252004-11-28 21:31:15 +00003376 }
Chris Lattner03f06f12005-01-17 03:20:02 +00003377
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00003378 // Finally, return the value computed.
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003379 if (SCI.getOpcode() == Instruction::SetLT) {
3380 return ReplaceInstUsesWith(SCI, Result);
3381 } else {
3382 assert(SCI.getOpcode()==Instruction::SetGT &&"SetCC should be folded!");
3383 if (Constant *CI = dyn_cast<Constant>(Result))
3384 return ReplaceInstUsesWith(SCI, ConstantExpr::getNot(CI));
3385 else
3386 return BinaryOperator::createNot(Result);
3387 }
Chris Lattner03f06f12005-01-17 03:20:02 +00003388 }
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003389 } else {
3390 return 0;
Reid Spencer279fa252004-11-28 21:31:15 +00003391 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003392
Chris Lattner252a8452005-06-16 03:00:08 +00003393 // Okay, just insert a compare of the reduced operands now!
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003394 return BinaryOperator::create(SCI.getOpcode(), LHSCIOp, RHSCIOp);
3395}
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003396
Chris Lattnere8d6c602003-03-10 19:16:08 +00003397Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +00003398 assert(I.getOperand(1)->getType() == Type::UByteTy);
3399 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003400 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003401
3402 // shl X, 0 == X and shr X, 0 == X
3403 // shl 0, X == 0 and shr 0, X == 0
3404 if (Op1 == Constant::getNullValue(Type::UByteTy) ||
Chris Lattnere6794492002-08-12 21:17:25 +00003405 Op0 == Constant::getNullValue(Op0->getType()))
3406 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003407
Chris Lattner81a7a232004-10-16 18:11:37 +00003408 if (isa<UndefValue>(Op0)) { // undef >>s X -> undef
3409 if (!isLeftShift && I.getType()->isSigned())
Chris Lattner67f05452004-10-16 23:28:04 +00003410 return ReplaceInstUsesWith(I, Op0);
Chris Lattner81a7a232004-10-16 18:11:37 +00003411 else // undef << X -> 0 AND undef >>u X -> 0
3412 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3413 }
3414 if (isa<UndefValue>(Op1)) {
Chris Lattner18aa4d82005-07-20 18:49:28 +00003415 if (isLeftShift || I.getType()->isUnsigned())// X << undef, X >>u undef -> 0
Chris Lattner81a7a232004-10-16 18:11:37 +00003416 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3417 else
3418 return ReplaceInstUsesWith(I, Op0); // X >>s undef -> X
3419 }
3420
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003421 // shr int -1, X = -1 (for any arithmetic shift rights of ~0)
3422 if (!isLeftShift)
3423 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
3424 if (CSI->isAllOnesValue())
3425 return ReplaceInstUsesWith(I, CSI);
3426
Chris Lattner183b3362004-04-09 19:05:30 +00003427 // Try to fold constant and into select arguments.
3428 if (isa<Constant>(Op0))
3429 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner86102b82005-01-01 16:22:27 +00003430 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00003431 return R;
3432
Chris Lattnerb18dbbf2005-05-08 17:34:56 +00003433 // See if we can turn a signed shr into an unsigned shr.
3434 if (!isLeftShift && I.getType()->isSigned()) {
3435 if (MaskedValueIsZero(Op0, ConstantInt::getMinValue(I.getType()))) {
3436 Value *V = InsertCastBefore(Op0, I.getType()->getUnsignedVersion(), I);
3437 V = InsertNewInstBefore(new ShiftInst(Instruction::Shr, V, Op1,
3438 I.getName()), I);
3439 return new CastInst(V, I.getType());
3440 }
3441 }
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00003442
Chris Lattner14553932006-01-06 07:12:35 +00003443 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op1))
3444 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
3445 return Res;
3446 return 0;
3447}
3448
3449Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantUInt *Op1,
3450 ShiftInst &I) {
3451 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattnerb3309392006-01-06 07:22:22 +00003452 bool isSignedShift = Op0->getType()->isSigned();
3453 bool isUnsignedShift = !isSignedShift;
Chris Lattner14553932006-01-06 07:12:35 +00003454
3455 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
3456 // of a signed value.
3457 //
3458 unsigned TypeBits = Op0->getType()->getPrimitiveSizeInBits();
3459 if (Op1->getValue() >= TypeBits) {
Chris Lattnerb3309392006-01-06 07:22:22 +00003460 if (isUnsignedShift || isLeftShift)
Chris Lattner14553932006-01-06 07:12:35 +00003461 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
3462 else {
3463 I.setOperand(1, ConstantUInt::get(Type::UByteTy, TypeBits-1));
3464 return &I;
Chris Lattnerf5ce2542004-02-23 20:30:06 +00003465 }
Chris Lattner14553932006-01-06 07:12:35 +00003466 }
3467
3468 // ((X*C1) << C2) == (X * (C1 << C2))
3469 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
3470 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
3471 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
3472 return BinaryOperator::createMul(BO->getOperand(0),
3473 ConstantExpr::getShl(BOOp, Op1));
3474
3475 // Try to fold constant and into select arguments.
3476 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3477 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3478 return R;
3479 if (isa<PHINode>(Op0))
3480 if (Instruction *NV = FoldOpIntoPhi(I))
3481 return NV;
3482
3483 if (Op0->hasOneUse()) {
3484 // If this is a SHL of a sign-extending cast, see if we can turn the input
3485 // into a zero extending cast (a simple strength reduction).
3486 if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3487 const Type *SrcTy = CI->getOperand(0)->getType();
3488 if (isLeftShift && SrcTy->isInteger() && SrcTy->isSigned() &&
3489 SrcTy->getPrimitiveSizeInBits() <
3490 CI->getType()->getPrimitiveSizeInBits()) {
3491 // We can change it to a zero extension if we are shifting out all of
3492 // the sign extended bits. To check this, form a mask of all of the
3493 // sign extend bits, then shift them left and see if we have anything
3494 // left.
3495 Constant *Mask = ConstantIntegral::getAllOnesValue(SrcTy); // 1111
3496 Mask = ConstantExpr::getZeroExtend(Mask, CI->getType()); // 00001111
3497 Mask = ConstantExpr::getNot(Mask); // 1's in the sign bits: 11110000
3498 if (ConstantExpr::getShl(Mask, Op1)->isNullValue()) {
3499 // If the shift is nuking all of the sign bits, change this to a
3500 // zero extension cast. To do this, cast the cast input to
3501 // unsigned, then to the requested size.
3502 Value *CastOp = CI->getOperand(0);
3503 Instruction *NC =
3504 new CastInst(CastOp, CastOp->getType()->getUnsignedVersion(),
3505 CI->getName()+".uns");
3506 NC = InsertNewInstBefore(NC, I);
3507 // Finally, insert a replacement for CI.
3508 NC = new CastInst(NC, CI->getType(), CI->getName());
3509 CI->setName("");
3510 NC = InsertNewInstBefore(NC, I);
3511 WorkList.push_back(CI); // Delete CI later.
3512 I.setOperand(0, NC);
3513 return &I; // The SHL operand was modified.
Chris Lattner86102b82005-01-01 16:22:27 +00003514 }
3515 }
Chris Lattner14553932006-01-06 07:12:35 +00003516 }
3517
3518 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
3519 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
3520 Value *V1, *V2;
3521 ConstantInt *CC;
3522 switch (Op0BO->getOpcode()) {
Chris Lattner27cb9db2005-09-18 05:12:10 +00003523 default: break;
3524 case Instruction::Add:
3525 case Instruction::And:
3526 case Instruction::Or:
3527 case Instruction::Xor:
3528 // These operators commute.
3529 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner797dee72005-09-18 06:30:59 +00003530 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
3531 match(Op0BO->getOperand(1),
Chris Lattner14553932006-01-06 07:12:35 +00003532 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Chris Lattner797dee72005-09-18 06:30:59 +00003533 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00003534 Op0BO->getOperand(0), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00003535 Op0BO->getName());
3536 InsertNewInstBefore(YS, I); // (Y << C)
3537 Instruction *X = BinaryOperator::create(Op0BO->getOpcode(), YS,
3538 V1,
Chris Lattner14553932006-01-06 07:12:35 +00003539 Op0BO->getOperand(1)->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00003540 InsertNewInstBefore(X, I); // (X + (Y << C))
3541 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
Chris Lattner14553932006-01-06 07:12:35 +00003542 C2 = ConstantExpr::getShl(C2, Op1);
Chris Lattner797dee72005-09-18 06:30:59 +00003543 return BinaryOperator::createAnd(X, C2);
3544 }
Chris Lattner14553932006-01-06 07:12:35 +00003545
Chris Lattner797dee72005-09-18 06:30:59 +00003546 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
3547 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
3548 match(Op0BO->getOperand(1),
3549 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner14553932006-01-06 07:12:35 +00003550 m_ConstantInt(CC))) && V2 == Op1 &&
3551 cast<BinaryOperator>(Op0BO->getOperand(1))->getOperand(0)->hasOneUse()) {
Chris Lattner797dee72005-09-18 06:30:59 +00003552 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00003553 Op0BO->getOperand(0), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00003554 Op0BO->getName());
3555 InsertNewInstBefore(YS, I); // (Y << C)
3556 Instruction *XM =
Chris Lattner14553932006-01-06 07:12:35 +00003557 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner797dee72005-09-18 06:30:59 +00003558 V1->getName()+".mask");
3559 InsertNewInstBefore(XM, I); // X & (CC << C)
3560
3561 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
3562 }
Chris Lattner14553932006-01-06 07:12:35 +00003563
Chris Lattner797dee72005-09-18 06:30:59 +00003564 // FALL THROUGH.
Chris Lattner27cb9db2005-09-18 05:12:10 +00003565 case Instruction::Sub:
3566 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner797dee72005-09-18 06:30:59 +00003567 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
3568 match(Op0BO->getOperand(0),
Chris Lattner14553932006-01-06 07:12:35 +00003569 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Chris Lattner797dee72005-09-18 06:30:59 +00003570 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00003571 Op0BO->getOperand(1), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00003572 Op0BO->getName());
3573 InsertNewInstBefore(YS, I); // (Y << C)
3574 Instruction *X = BinaryOperator::create(Op0BO->getOpcode(), YS,
3575 V1,
Chris Lattner14553932006-01-06 07:12:35 +00003576 Op0BO->getOperand(0)->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00003577 InsertNewInstBefore(X, I); // (X + (Y << C))
3578 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
Chris Lattner14553932006-01-06 07:12:35 +00003579 C2 = ConstantExpr::getShl(C2, Op1);
Chris Lattner797dee72005-09-18 06:30:59 +00003580 return BinaryOperator::createAnd(X, C2);
3581 }
Chris Lattner14553932006-01-06 07:12:35 +00003582
Chris Lattner797dee72005-09-18 06:30:59 +00003583 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
3584 match(Op0BO->getOperand(0),
3585 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner14553932006-01-06 07:12:35 +00003586 m_ConstantInt(CC))) && V2 == Op1 &&
3587 cast<BinaryOperator>(Op0BO->getOperand(0))->getOperand(0)->hasOneUse()) {
Chris Lattner797dee72005-09-18 06:30:59 +00003588 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00003589 Op0BO->getOperand(1), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00003590 Op0BO->getName());
3591 InsertNewInstBefore(YS, I); // (Y << C)
3592 Instruction *XM =
Chris Lattner14553932006-01-06 07:12:35 +00003593 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner797dee72005-09-18 06:30:59 +00003594 V1->getName()+".mask");
3595 InsertNewInstBefore(XM, I); // X & (CC << C)
3596
3597 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
3598 }
Chris Lattner14553932006-01-06 07:12:35 +00003599
Chris Lattner27cb9db2005-09-18 05:12:10 +00003600 break;
Chris Lattner14553932006-01-06 07:12:35 +00003601 }
3602
3603
3604 // If the operand is an bitwise operator with a constant RHS, and the
3605 // shift is the only use, we can pull it out of the shift.
3606 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
3607 bool isValid = true; // Valid only for And, Or, Xor
3608 bool highBitSet = false; // Transform if high bit of constant set?
3609
3610 switch (Op0BO->getOpcode()) {
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003611 default: isValid = false; break; // Do not perform transform!
Chris Lattner44bd3922004-10-08 03:46:20 +00003612 case Instruction::Add:
3613 isValid = isLeftShift;
3614 break;
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003615 case Instruction::Or:
3616 case Instruction::Xor:
3617 highBitSet = false;
3618 break;
3619 case Instruction::And:
3620 highBitSet = true;
3621 break;
Chris Lattner14553932006-01-06 07:12:35 +00003622 }
3623
3624 // If this is a signed shift right, and the high bit is modified
3625 // by the logical operation, do not perform the transformation.
3626 // The highBitSet boolean indicates the value of the high bit of
3627 // the constant which would cause it to be modified for this
3628 // operation.
3629 //
Chris Lattnerb3309392006-01-06 07:22:22 +00003630 if (isValid && !isLeftShift && isSignedShift) {
Chris Lattner14553932006-01-06 07:12:35 +00003631 uint64_t Val = Op0C->getRawValue();
3632 isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
3633 }
3634
3635 if (isValid) {
3636 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
3637
3638 Instruction *NewShift =
3639 new ShiftInst(I.getOpcode(), Op0BO->getOperand(0), Op1,
3640 Op0BO->getName());
3641 Op0BO->setName("");
3642 InsertNewInstBefore(NewShift, I);
3643
3644 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
3645 NewRHS);
3646 }
3647 }
3648 }
3649 }
3650
3651 // If this is a shift of a shift, see if we can fold the two together.
3652 if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0))
3653 if (ConstantUInt *ShiftAmt1C =
3654 dyn_cast<ConstantUInt>(Op0SI->getOperand(1))) {
3655 unsigned ShiftAmt1 = (unsigned)ShiftAmt1C->getValue();
3656 unsigned ShiftAmt2 = (unsigned)Op1->getValue();
3657
3658 // Check for (A << c1) << c2 and (A >> c1) >> c2
3659 if (I.getOpcode() == Op0SI->getOpcode()) {
3660 unsigned Amt = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
3661 if (Op0->getType()->getPrimitiveSizeInBits() < Amt)
3662 Amt = Op0->getType()->getPrimitiveSizeInBits();
3663 return new ShiftInst(I.getOpcode(), Op0SI->getOperand(0),
3664 ConstantUInt::get(Type::UByteTy, Amt));
3665 }
3666
3667 // Check for (A << c1) >> c2 or visaversa. If we are dealing with
3668 // signed types, we can only support the (A >> c1) << c2 configuration,
3669 // because it can not turn an arbitrary bit of A into a sign bit.
Chris Lattnerb3309392006-01-06 07:22:22 +00003670 if (isUnsignedShift || isLeftShift) {
Chris Lattner14553932006-01-06 07:12:35 +00003671 // Calculate bitmask for what gets shifted off the edge...
3672 Constant *C = ConstantIntegral::getAllOnesValue(I.getType());
3673 if (isLeftShift)
3674 C = ConstantExpr::getShl(C, ShiftAmt1C);
3675 else
3676 C = ConstantExpr::getShr(C, ShiftAmt1C);
3677
3678 Instruction *Mask =
3679 BinaryOperator::createAnd(Op0SI->getOperand(0), C,
3680 Op0SI->getOperand(0)->getName()+".mask");
3681 InsertNewInstBefore(Mask, I);
3682
3683 // Figure out what flavor of shift we should use...
3684 if (ShiftAmt1 == ShiftAmt2)
3685 return ReplaceInstUsesWith(I, Mask); // (A << c) >> c === A & c2
3686 else if (ShiftAmt1 < ShiftAmt2) {
3687 return new ShiftInst(I.getOpcode(), Mask,
3688 ConstantUInt::get(Type::UByteTy, ShiftAmt2-ShiftAmt1));
3689 } else {
3690 return new ShiftInst(Op0SI->getOpcode(), Mask,
3691 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
3692 }
3693 } else {
3694 // We can handle signed (X << C1) >> C2 if it's a sign extend. In
3695 // this case, C1 == C2 and C1 is 8, 16, or 32.
3696 if (ShiftAmt1 == ShiftAmt2) {
3697 const Type *SExtType = 0;
3698 switch (ShiftAmt1) {
3699 case 8 : SExtType = Type::SByteTy; break;
3700 case 16: SExtType = Type::ShortTy; break;
3701 case 32: SExtType = Type::IntTy; break;
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003702 }
Chris Lattner14553932006-01-06 07:12:35 +00003703
3704 if (SExtType) {
3705 Instruction *NewTrunc = new CastInst(Op0SI->getOperand(0),
3706 SExtType, "sext");
3707 InsertNewInstBefore(NewTrunc, I);
3708 return new CastInst(NewTrunc, I.getType());
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003709 }
3710 }
Chris Lattner27cb9db2005-09-18 05:12:10 +00003711 }
Chris Lattner86102b82005-01-01 16:22:27 +00003712 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003713 return 0;
3714}
3715
Chris Lattner4e2dbc62004-07-20 00:59:32 +00003716enum CastType {
3717 Noop = 0,
3718 Truncate = 1,
3719 Signext = 2,
3720 Zeroext = 3
3721};
3722
3723/// getCastType - In the future, we will split the cast instruction into these
3724/// various types. Until then, we have to do the analysis here.
3725static CastType getCastType(const Type *Src, const Type *Dest) {
3726 assert(Src->isIntegral() && Dest->isIntegral() &&
3727 "Only works on integral types!");
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003728 unsigned SrcSize = Src->getPrimitiveSizeInBits();
3729 unsigned DestSize = Dest->getPrimitiveSizeInBits();
Chris Lattner4e2dbc62004-07-20 00:59:32 +00003730
3731 if (SrcSize == DestSize) return Noop;
3732 if (SrcSize > DestSize) return Truncate;
3733 if (Src->isSigned()) return Signext;
3734 return Zeroext;
3735}
3736
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003737
Chris Lattner48a44f72002-05-02 17:06:02 +00003738// isEliminableCastOfCast - Return true if it is valid to eliminate the CI
3739// instruction.
3740//
Chris Lattnerdfae8be2003-07-24 17:35:25 +00003741static inline bool isEliminableCastOfCast(const Type *SrcTy, const Type *MidTy,
Chris Lattner11ffd592004-07-20 05:21:00 +00003742 const Type *DstTy, TargetData *TD) {
Chris Lattner48a44f72002-05-02 17:06:02 +00003743
Chris Lattner650b6da2002-08-02 20:00:25 +00003744 // It is legal to eliminate the instruction if casting A->B->A if the sizes
Misha Brukmanb1c93172005-04-21 23:48:37 +00003745 // are identical and the bits don't get reinterpreted (for example
Chris Lattner1638de42004-07-21 19:50:44 +00003746 // int->float->int would not be allowed).
Misha Brukmane5838c42003-05-20 18:45:36 +00003747 if (SrcTy == DstTy && SrcTy->isLosslesslyConvertibleTo(MidTy))
Chris Lattner650b6da2002-08-02 20:00:25 +00003748 return true;
Chris Lattner48a44f72002-05-02 17:06:02 +00003749
Chris Lattner4fbad962004-07-21 04:27:24 +00003750 // If we are casting between pointer and integer types, treat pointers as
3751 // integers of the appropriate size for the code below.
3752 if (isa<PointerType>(SrcTy)) SrcTy = TD->getIntPtrType();
3753 if (isa<PointerType>(MidTy)) MidTy = TD->getIntPtrType();
3754 if (isa<PointerType>(DstTy)) DstTy = TD->getIntPtrType();
Chris Lattner11ffd592004-07-20 05:21:00 +00003755
Chris Lattner48a44f72002-05-02 17:06:02 +00003756 // Allow free casting and conversion of sizes as long as the sign doesn't
3757 // change...
Chris Lattnerb0b412e2002-09-03 01:08:28 +00003758 if (SrcTy->isIntegral() && MidTy->isIntegral() && DstTy->isIntegral()) {
Chris Lattner4e2dbc62004-07-20 00:59:32 +00003759 CastType FirstCast = getCastType(SrcTy, MidTy);
3760 CastType SecondCast = getCastType(MidTy, DstTy);
Chris Lattner650b6da2002-08-02 20:00:25 +00003761
Chris Lattner4e2dbc62004-07-20 00:59:32 +00003762 // Capture the effect of these two casts. If the result is a legal cast,
3763 // the CastType is stored here, otherwise a special code is used.
3764 static const unsigned CastResult[] = {
3765 // First cast is noop
3766 0, 1, 2, 3,
3767 // First cast is a truncate
3768 1, 1, 4, 4, // trunc->extend is not safe to eliminate
3769 // First cast is a sign ext
Chris Lattner1638de42004-07-21 19:50:44 +00003770 2, 5, 2, 4, // signext->zeroext never ok
Chris Lattner4e2dbc62004-07-20 00:59:32 +00003771 // First cast is a zero ext
Chris Lattner1638de42004-07-21 19:50:44 +00003772 3, 5, 3, 3,
Chris Lattner4e2dbc62004-07-20 00:59:32 +00003773 };
3774
3775 unsigned Result = CastResult[FirstCast*4+SecondCast];
3776 switch (Result) {
3777 default: assert(0 && "Illegal table value!");
3778 case 0:
3779 case 1:
3780 case 2:
3781 case 3:
3782 // FIXME: in the future, when LLVM has explicit sign/zeroextends and
3783 // truncates, we could eliminate more casts.
3784 return (unsigned)getCastType(SrcTy, DstTy) == Result;
3785 case 4:
3786 return false; // Not possible to eliminate this here.
3787 case 5:
Chris Lattner1638de42004-07-21 19:50:44 +00003788 // Sign or zero extend followed by truncate is always ok if the result
3789 // is a truncate or noop.
3790 CastType ResultCast = getCastType(SrcTy, DstTy);
3791 if (ResultCast == Noop || ResultCast == Truncate)
3792 return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +00003793 // Otherwise we are still growing the value, we are only safe if the
Chris Lattner1638de42004-07-21 19:50:44 +00003794 // result will match the sign/zeroextendness of the result.
3795 return ResultCast == FirstCast;
Chris Lattner3732aca2002-08-15 16:15:25 +00003796 }
Chris Lattner650b6da2002-08-02 20:00:25 +00003797 }
Chris Lattner48a44f72002-05-02 17:06:02 +00003798 return false;
3799}
3800
Chris Lattner11ffd592004-07-20 05:21:00 +00003801static bool ValueRequiresCast(const Value *V, const Type *Ty, TargetData *TD) {
Chris Lattnerdfae8be2003-07-24 17:35:25 +00003802 if (V->getType() == Ty || isa<Constant>(V)) return false;
3803 if (const CastInst *CI = dyn_cast<CastInst>(V))
Chris Lattner11ffd592004-07-20 05:21:00 +00003804 if (isEliminableCastOfCast(CI->getOperand(0)->getType(), CI->getType(), Ty,
3805 TD))
Chris Lattnerdfae8be2003-07-24 17:35:25 +00003806 return false;
3807 return true;
3808}
3809
3810/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
3811/// InsertBefore instruction. This is specialized a bit to avoid inserting
3812/// casts that are known to not do anything...
3813///
3814Value *InstCombiner::InsertOperandCastBefore(Value *V, const Type *DestTy,
3815 Instruction *InsertBefore) {
3816 if (V->getType() == DestTy) return V;
3817 if (Constant *C = dyn_cast<Constant>(V))
3818 return ConstantExpr::getCast(C, DestTy);
3819
3820 CastInst *CI = new CastInst(V, DestTy, V->getName());
3821 InsertNewInstBefore(CI, *InsertBefore);
3822 return CI;
3823}
Chris Lattner48a44f72002-05-02 17:06:02 +00003824
Chris Lattner8f663e82005-10-29 04:36:15 +00003825/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
3826/// expression. If so, decompose it, returning some value X, such that Val is
3827/// X*Scale+Offset.
3828///
3829static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
3830 unsigned &Offset) {
3831 assert(Val->getType() == Type::UIntTy && "Unexpected allocation size type!");
3832 if (ConstantUInt *CI = dyn_cast<ConstantUInt>(Val)) {
3833 Offset = CI->getValue();
3834 Scale = 1;
3835 return ConstantUInt::get(Type::UIntTy, 0);
3836 } else if (Instruction *I = dyn_cast<Instruction>(Val)) {
3837 if (I->getNumOperands() == 2) {
3838 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(I->getOperand(1))) {
3839 if (I->getOpcode() == Instruction::Shl) {
3840 // This is a value scaled by '1 << the shift amt'.
3841 Scale = 1U << CUI->getValue();
3842 Offset = 0;
3843 return I->getOperand(0);
3844 } else if (I->getOpcode() == Instruction::Mul) {
3845 // This value is scaled by 'CUI'.
3846 Scale = CUI->getValue();
3847 Offset = 0;
3848 return I->getOperand(0);
3849 } else if (I->getOpcode() == Instruction::Add) {
3850 // We have X+C. Check to see if we really have (X*C2)+C1, where C1 is
3851 // divisible by C2.
3852 unsigned SubScale;
3853 Value *SubVal = DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
3854 Offset);
3855 Offset += CUI->getValue();
3856 if (SubScale > 1 && (Offset % SubScale == 0)) {
3857 Scale = SubScale;
3858 return SubVal;
3859 }
3860 }
3861 }
3862 }
3863 }
3864
3865 // Otherwise, we can't look past this.
3866 Scale = 1;
3867 Offset = 0;
3868 return Val;
3869}
3870
3871
Chris Lattner216be912005-10-24 06:03:58 +00003872/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
3873/// try to eliminate the cast by moving the type information into the alloc.
3874Instruction *InstCombiner::PromoteCastOfAllocation(CastInst &CI,
3875 AllocationInst &AI) {
3876 const PointerType *PTy = dyn_cast<PointerType>(CI.getType());
Chris Lattnerbb171802005-10-27 05:53:56 +00003877 if (!PTy) return 0; // Not casting the allocation to a pointer type.
Chris Lattner216be912005-10-24 06:03:58 +00003878
Chris Lattnerac87beb2005-10-24 06:22:12 +00003879 // Remove any uses of AI that are dead.
3880 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
3881 std::vector<Instruction*> DeadUsers;
3882 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
3883 Instruction *User = cast<Instruction>(*UI++);
3884 if (isInstructionTriviallyDead(User)) {
3885 while (UI != E && *UI == User)
3886 ++UI; // If this instruction uses AI more than once, don't break UI.
3887
3888 // Add operands to the worklist.
3889 AddUsesToWorkList(*User);
3890 ++NumDeadInst;
3891 DEBUG(std::cerr << "IC: DCE: " << *User);
3892
3893 User->eraseFromParent();
3894 removeFromWorkList(User);
3895 }
3896 }
3897
Chris Lattner216be912005-10-24 06:03:58 +00003898 // Get the type really allocated and the type casted to.
3899 const Type *AllocElTy = AI.getAllocatedType();
3900 const Type *CastElTy = PTy->getElementType();
3901 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner355ecc02005-10-24 06:26:18 +00003902
3903 unsigned AllocElTyAlign = TD->getTypeSize(AllocElTy);
3904 unsigned CastElTyAlign = TD->getTypeSize(CastElTy);
3905 if (CastElTyAlign < AllocElTyAlign) return 0;
3906
Chris Lattner46705b22005-10-24 06:35:18 +00003907 // If the allocation has multiple uses, only promote it if we are strictly
3908 // increasing the alignment of the resultant allocation. If we keep it the
3909 // same, we open the door to infinite loops of various kinds.
3910 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
3911
Chris Lattner216be912005-10-24 06:03:58 +00003912 uint64_t AllocElTySize = TD->getTypeSize(AllocElTy);
3913 uint64_t CastElTySize = TD->getTypeSize(CastElTy);
Chris Lattnerbb171802005-10-27 05:53:56 +00003914 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner355ecc02005-10-24 06:26:18 +00003915
Chris Lattner8270c332005-10-29 03:19:53 +00003916 // See if we can satisfy the modulus by pulling a scale out of the array
3917 // size argument.
Chris Lattner8f663e82005-10-29 04:36:15 +00003918 unsigned ArraySizeScale, ArrayOffset;
3919 Value *NumElements = // See if the array size is a decomposable linear expr.
3920 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
3921
Chris Lattner8270c332005-10-29 03:19:53 +00003922 // If we can now satisfy the modulus, by using a non-1 scale, we really can
3923 // do the xform.
Chris Lattner8f663e82005-10-29 04:36:15 +00003924 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
3925 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattnerb3ecf962005-10-27 06:12:00 +00003926
Chris Lattner8270c332005-10-29 03:19:53 +00003927 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
3928 Value *Amt = 0;
3929 if (Scale == 1) {
3930 Amt = NumElements;
3931 } else {
3932 Amt = ConstantUInt::get(Type::UIntTy, Scale);
3933 if (ConstantUInt *CI = dyn_cast<ConstantUInt>(NumElements))
3934 Amt = ConstantExpr::getMul(CI, cast<ConstantUInt>(Amt));
3935 else if (Scale != 1) {
3936 Instruction *Tmp = BinaryOperator::createMul(Amt, NumElements, "tmp");
3937 Amt = InsertNewInstBefore(Tmp, AI);
Chris Lattnerb3ecf962005-10-27 06:12:00 +00003938 }
Chris Lattnerbb171802005-10-27 05:53:56 +00003939 }
3940
Chris Lattner8f663e82005-10-29 04:36:15 +00003941 if (unsigned Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
3942 Value *Off = ConstantUInt::get(Type::UIntTy, Offset);
3943 Instruction *Tmp = BinaryOperator::createAdd(Amt, Off, "tmp");
3944 Amt = InsertNewInstBefore(Tmp, AI);
3945 }
3946
Chris Lattner216be912005-10-24 06:03:58 +00003947 std::string Name = AI.getName(); AI.setName("");
3948 AllocationInst *New;
3949 if (isa<MallocInst>(AI))
Nate Begeman848622f2005-11-05 09:21:28 +00003950 New = new MallocInst(CastElTy, Amt, AI.getAlignment(), Name);
Chris Lattner216be912005-10-24 06:03:58 +00003951 else
Nate Begeman848622f2005-11-05 09:21:28 +00003952 New = new AllocaInst(CastElTy, Amt, AI.getAlignment(), Name);
Chris Lattner216be912005-10-24 06:03:58 +00003953 InsertNewInstBefore(New, AI);
Chris Lattner46705b22005-10-24 06:35:18 +00003954
3955 // If the allocation has multiple uses, insert a cast and change all things
3956 // that used it to use the new cast. This will also hack on CI, but it will
3957 // die soon.
3958 if (!AI.hasOneUse()) {
3959 AddUsesToWorkList(AI);
3960 CastInst *NewCast = new CastInst(New, AI.getType(), "tmpcast");
3961 InsertNewInstBefore(NewCast, AI);
3962 AI.replaceAllUsesWith(NewCast);
3963 }
Chris Lattner216be912005-10-24 06:03:58 +00003964 return ReplaceInstUsesWith(CI, New);
3965}
3966
3967
Chris Lattner48a44f72002-05-02 17:06:02 +00003968// CastInst simplification
Chris Lattner260ab202002-04-18 17:39:14 +00003969//
Chris Lattner113f4f42002-06-25 16:13:24 +00003970Instruction *InstCombiner::visitCastInst(CastInst &CI) {
Chris Lattner55d4bda2003-06-23 21:59:52 +00003971 Value *Src = CI.getOperand(0);
3972
Chris Lattner48a44f72002-05-02 17:06:02 +00003973 // If the user is casting a value to the same type, eliminate this cast
3974 // instruction...
Chris Lattner55d4bda2003-06-23 21:59:52 +00003975 if (CI.getType() == Src->getType())
3976 return ReplaceInstUsesWith(CI, Src);
Chris Lattner48a44f72002-05-02 17:06:02 +00003977
Chris Lattner81a7a232004-10-16 18:11:37 +00003978 if (isa<UndefValue>(Src)) // cast undef -> undef
3979 return ReplaceInstUsesWith(CI, UndefValue::get(CI.getType()));
3980
Chris Lattner48a44f72002-05-02 17:06:02 +00003981 // If casting the result of another cast instruction, try to eliminate this
3982 // one!
3983 //
Chris Lattner86102b82005-01-01 16:22:27 +00003984 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
3985 Value *A = CSrc->getOperand(0);
3986 if (isEliminableCastOfCast(A->getType(), CSrc->getType(),
3987 CI.getType(), TD)) {
Chris Lattner48a44f72002-05-02 17:06:02 +00003988 // This instruction now refers directly to the cast's src operand. This
3989 // has a good chance of making CSrc dead.
Chris Lattner113f4f42002-06-25 16:13:24 +00003990 CI.setOperand(0, CSrc->getOperand(0));
3991 return &CI;
Chris Lattner48a44f72002-05-02 17:06:02 +00003992 }
3993
Chris Lattner650b6da2002-08-02 20:00:25 +00003994 // If this is an A->B->A cast, and we are dealing with integral types, try
3995 // to convert this into a logical 'and' instruction.
3996 //
Misha Brukmanb1c93172005-04-21 23:48:37 +00003997 if (A->getType()->isInteger() &&
Chris Lattnerb0b412e2002-09-03 01:08:28 +00003998 CI.getType()->isInteger() && CSrc->getType()->isInteger() &&
Chris Lattner86102b82005-01-01 16:22:27 +00003999 CSrc->getType()->isUnsigned() && // B->A cast must zero extend
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004000 CSrc->getType()->getPrimitiveSizeInBits() <
4001 CI.getType()->getPrimitiveSizeInBits()&&
4002 A->getType()->getPrimitiveSizeInBits() ==
4003 CI.getType()->getPrimitiveSizeInBits()) {
Chris Lattner650b6da2002-08-02 20:00:25 +00004004 assert(CSrc->getType() != Type::ULongTy &&
4005 "Cannot have type bigger than ulong!");
Chris Lattner2f1457f2005-04-24 17:46:05 +00004006 uint64_t AndValue = ~0ULL>>(64-CSrc->getType()->getPrimitiveSizeInBits());
Chris Lattner86102b82005-01-01 16:22:27 +00004007 Constant *AndOp = ConstantUInt::get(A->getType()->getUnsignedVersion(),
4008 AndValue);
4009 AndOp = ConstantExpr::getCast(AndOp, A->getType());
4010 Instruction *And = BinaryOperator::createAnd(CSrc->getOperand(0), AndOp);
4011 if (And->getType() != CI.getType()) {
4012 And->setName(CSrc->getName()+".mask");
4013 InsertNewInstBefore(And, CI);
4014 And = new CastInst(And, CI.getType());
4015 }
4016 return And;
Chris Lattner650b6da2002-08-02 20:00:25 +00004017 }
4018 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004019
Chris Lattner03841652004-05-25 04:29:21 +00004020 // If this is a cast to bool, turn it into the appropriate setne instruction.
4021 if (CI.getType() == Type::BoolTy)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004022 return BinaryOperator::createSetNE(CI.getOperand(0),
Chris Lattner03841652004-05-25 04:29:21 +00004023 Constant::getNullValue(CI.getOperand(0)->getType()));
4024
Chris Lattnerd0d51602003-06-21 23:12:02 +00004025 // If casting the result of a getelementptr instruction with no offset, turn
4026 // this into a cast of the original pointer!
4027 //
Chris Lattner55d4bda2003-06-23 21:59:52 +00004028 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattnerd0d51602003-06-21 23:12:02 +00004029 bool AllZeroOperands = true;
4030 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
4031 if (!isa<Constant>(GEP->getOperand(i)) ||
4032 !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
4033 AllZeroOperands = false;
4034 break;
4035 }
4036 if (AllZeroOperands) {
4037 CI.setOperand(0, GEP->getOperand(0));
4038 return &CI;
4039 }
4040 }
4041
Chris Lattnerf4ad1652003-11-02 05:57:39 +00004042 // If we are casting a malloc or alloca to a pointer to a type of the same
4043 // size, rewrite the allocation instruction to allocate the "right" type.
4044 //
4045 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
Chris Lattner216be912005-10-24 06:03:58 +00004046 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
4047 return V;
Chris Lattnerf4ad1652003-11-02 05:57:39 +00004048
Chris Lattner86102b82005-01-01 16:22:27 +00004049 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
4050 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
4051 return NV;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00004052 if (isa<PHINode>(Src))
4053 if (Instruction *NV = FoldOpIntoPhi(CI))
4054 return NV;
4055
Chris Lattnerdfae8be2003-07-24 17:35:25 +00004056 // If the source value is an instruction with only this use, we can attempt to
4057 // propagate the cast into the instruction. Also, only handle integral types
4058 // for now.
4059 if (Instruction *SrcI = dyn_cast<Instruction>(Src))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00004060 if (SrcI->hasOneUse() && Src->getType()->isIntegral() &&
Chris Lattnerdfae8be2003-07-24 17:35:25 +00004061 CI.getType()->isInteger()) { // Don't mess with casts to bool here
4062 const Type *DestTy = CI.getType();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004063 unsigned SrcBitSize = Src->getType()->getPrimitiveSizeInBits();
4064 unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
Chris Lattnerdfae8be2003-07-24 17:35:25 +00004065
4066 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
4067 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
4068
4069 switch (SrcI->getOpcode()) {
4070 case Instruction::Add:
4071 case Instruction::Mul:
4072 case Instruction::And:
4073 case Instruction::Or:
4074 case Instruction::Xor:
4075 // If we are discarding information, or just changing the sign, rewrite.
4076 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
4077 // Don't insert two casts if they cannot be eliminated. We allow two
4078 // casts to be inserted if the sizes are the same. This could only be
4079 // converting signedness, which is a noop.
Chris Lattner11ffd592004-07-20 05:21:00 +00004080 if (DestBitSize == SrcBitSize || !ValueRequiresCast(Op1, DestTy,TD) ||
4081 !ValueRequiresCast(Op0, DestTy, TD)) {
Chris Lattnerdfae8be2003-07-24 17:35:25 +00004082 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
4083 Value *Op1c = InsertOperandCastBefore(Op1, DestTy, SrcI);
4084 return BinaryOperator::create(cast<BinaryOperator>(SrcI)
4085 ->getOpcode(), Op0c, Op1c);
4086 }
4087 }
Chris Lattner72086162005-05-06 02:07:39 +00004088
4089 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
4090 if (SrcBitSize == 1 && SrcI->getOpcode() == Instruction::Xor &&
4091 Op1 == ConstantBool::True &&
4092 (!Op0->hasOneUse() || !isa<SetCondInst>(Op0))) {
4093 Value *New = InsertOperandCastBefore(Op0, DestTy, &CI);
4094 return BinaryOperator::createXor(New,
4095 ConstantInt::get(CI.getType(), 1));
4096 }
Chris Lattnerdfae8be2003-07-24 17:35:25 +00004097 break;
4098 case Instruction::Shl:
4099 // Allow changing the sign of the source operand. Do not allow changing
4100 // the size of the shift, UNLESS the shift amount is a constant. We
4101 // mush not change variable sized shifts to a smaller size, because it
4102 // is undefined to shift more bits out than exist in the value.
4103 if (DestBitSize == SrcBitSize ||
4104 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
4105 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
4106 return new ShiftInst(Instruction::Shl, Op0c, Op1);
4107 }
4108 break;
Chris Lattner87380412005-05-06 04:18:52 +00004109 case Instruction::Shr:
4110 // If this is a signed shr, and if all bits shifted in are about to be
4111 // truncated off, turn it into an unsigned shr to allow greater
4112 // simplifications.
4113 if (DestBitSize < SrcBitSize && Src->getType()->isSigned() &&
4114 isa<ConstantInt>(Op1)) {
4115 unsigned ShiftAmt = cast<ConstantUInt>(Op1)->getValue();
4116 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
4117 // Convert to unsigned.
4118 Value *N1 = InsertOperandCastBefore(Op0,
4119 Op0->getType()->getUnsignedVersion(), &CI);
4120 // Insert the new shift, which is now unsigned.
4121 N1 = InsertNewInstBefore(new ShiftInst(Instruction::Shr, N1,
4122 Op1, Src->getName()), CI);
4123 return new CastInst(N1, CI.getType());
4124 }
4125 }
4126 break;
4127
Chris Lattner809dfac2005-05-04 19:10:26 +00004128 case Instruction::SetNE:
Chris Lattner809dfac2005-05-04 19:10:26 +00004129 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner4c2d3782005-05-06 01:53:19 +00004130 if (Op1C->getRawValue() == 0) {
4131 // If the input only has the low bit set, simplify directly.
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00004132 Constant *Not1 =
Chris Lattner809dfac2005-05-04 19:10:26 +00004133 ConstantExpr::getNot(ConstantInt::get(Op0->getType(), 1));
Chris Lattner4c2d3782005-05-06 01:53:19 +00004134 // cast (X != 0) to int --> X if X&~1 == 0
Chris Lattner809dfac2005-05-04 19:10:26 +00004135 if (MaskedValueIsZero(Op0, cast<ConstantIntegral>(Not1))) {
4136 if (CI.getType() == Op0->getType())
4137 return ReplaceInstUsesWith(CI, Op0);
4138 else
4139 return new CastInst(Op0, CI.getType());
4140 }
Chris Lattner4c2d3782005-05-06 01:53:19 +00004141
4142 // If the input is an and with a single bit, shift then simplify.
4143 ConstantInt *AndRHS;
4144 if (match(Op0, m_And(m_Value(), m_ConstantInt(AndRHS))))
4145 if (AndRHS->getRawValue() &&
4146 (AndRHS->getRawValue() & (AndRHS->getRawValue()-1)) == 0) {
Chris Lattner22d00a82005-08-02 19:16:58 +00004147 unsigned ShiftAmt = Log2_64(AndRHS->getRawValue());
Chris Lattner4c2d3782005-05-06 01:53:19 +00004148 // Perform an unsigned shr by shiftamt. Convert input to
4149 // unsigned if it is signed.
4150 Value *In = Op0;
4151 if (In->getType()->isSigned())
4152 In = InsertNewInstBefore(new CastInst(In,
4153 In->getType()->getUnsignedVersion(), In->getName()),CI);
4154 // Insert the shift to put the result in the low bit.
4155 In = InsertNewInstBefore(new ShiftInst(Instruction::Shr, In,
4156 ConstantInt::get(Type::UByteTy, ShiftAmt),
4157 In->getName()+".lobit"), CI);
Chris Lattner4c2d3782005-05-06 01:53:19 +00004158 if (CI.getType() == In->getType())
4159 return ReplaceInstUsesWith(CI, In);
4160 else
4161 return new CastInst(In, CI.getType());
4162 }
4163 }
4164 }
4165 break;
4166 case Instruction::SetEQ:
4167 // We if we are just checking for a seteq of a single bit and casting it
4168 // to an integer. If so, shift the bit to the appropriate place then
4169 // cast to integer to avoid the comparison.
4170 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
4171 // Is Op1C a power of two or zero?
4172 if ((Op1C->getRawValue() & Op1C->getRawValue()-1) == 0) {
4173 // cast (X == 1) to int -> X iff X has only the low bit set.
4174 if (Op1C->getRawValue() == 1) {
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00004175 Constant *Not1 =
Chris Lattner4c2d3782005-05-06 01:53:19 +00004176 ConstantExpr::getNot(ConstantInt::get(Op0->getType(), 1));
4177 if (MaskedValueIsZero(Op0, cast<ConstantIntegral>(Not1))) {
4178 if (CI.getType() == Op0->getType())
4179 return ReplaceInstUsesWith(CI, Op0);
4180 else
4181 return new CastInst(Op0, CI.getType());
4182 }
4183 }
Chris Lattner809dfac2005-05-04 19:10:26 +00004184 }
4185 }
4186 break;
Chris Lattnerdfae8be2003-07-24 17:35:25 +00004187 }
4188 }
Chris Lattnerbb171802005-10-27 05:53:56 +00004189
Chris Lattner260ab202002-04-18 17:39:14 +00004190 return 0;
Chris Lattnerca081252001-12-14 16:52:21 +00004191}
4192
Chris Lattner56e4d3d2004-04-09 23:46:01 +00004193/// GetSelectFoldableOperands - We want to turn code that looks like this:
4194/// %C = or %A, %B
4195/// %D = select %cond, %C, %A
4196/// into:
4197/// %C = select %cond, %B, 0
4198/// %D = or %A, %C
4199///
4200/// Assuming that the specified instruction is an operand to the select, return
4201/// a bitmask indicating which operands of this instruction are foldable if they
4202/// equal the other incoming value of the select.
4203///
4204static unsigned GetSelectFoldableOperands(Instruction *I) {
4205 switch (I->getOpcode()) {
4206 case Instruction::Add:
4207 case Instruction::Mul:
4208 case Instruction::And:
4209 case Instruction::Or:
4210 case Instruction::Xor:
4211 return 3; // Can fold through either operand.
4212 case Instruction::Sub: // Can only fold on the amount subtracted.
4213 case Instruction::Shl: // Can only fold on the shift amount.
4214 case Instruction::Shr:
Misha Brukmanb1c93172005-04-21 23:48:37 +00004215 return 1;
Chris Lattner56e4d3d2004-04-09 23:46:01 +00004216 default:
4217 return 0; // Cannot fold
4218 }
4219}
4220
4221/// GetSelectFoldableConstant - For the same transformation as the previous
4222/// function, return the identity constant that goes into the select.
4223static Constant *GetSelectFoldableConstant(Instruction *I) {
4224 switch (I->getOpcode()) {
4225 default: assert(0 && "This cannot happen!"); abort();
4226 case Instruction::Add:
4227 case Instruction::Sub:
4228 case Instruction::Or:
4229 case Instruction::Xor:
4230 return Constant::getNullValue(I->getType());
4231 case Instruction::Shl:
4232 case Instruction::Shr:
4233 return Constant::getNullValue(Type::UByteTy);
4234 case Instruction::And:
4235 return ConstantInt::getAllOnesValue(I->getType());
4236 case Instruction::Mul:
4237 return ConstantInt::get(I->getType(), 1);
4238 }
4239}
4240
Chris Lattner411336f2005-01-19 21:50:18 +00004241/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
4242/// have the same opcode and only one use each. Try to simplify this.
4243Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
4244 Instruction *FI) {
4245 if (TI->getNumOperands() == 1) {
4246 // If this is a non-volatile load or a cast from the same type,
4247 // merge.
4248 if (TI->getOpcode() == Instruction::Cast) {
4249 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
4250 return 0;
4251 } else {
4252 return 0; // unknown unary op.
4253 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004254
Chris Lattner411336f2005-01-19 21:50:18 +00004255 // Fold this by inserting a select from the input values.
4256 SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
4257 FI->getOperand(0), SI.getName()+".v");
4258 InsertNewInstBefore(NewSI, SI);
4259 return new CastInst(NewSI, TI->getType());
4260 }
4261
4262 // Only handle binary operators here.
4263 if (!isa<ShiftInst>(TI) && !isa<BinaryOperator>(TI))
4264 return 0;
4265
4266 // Figure out if the operations have any operands in common.
4267 Value *MatchOp, *OtherOpT, *OtherOpF;
4268 bool MatchIsOpZero;
4269 if (TI->getOperand(0) == FI->getOperand(0)) {
4270 MatchOp = TI->getOperand(0);
4271 OtherOpT = TI->getOperand(1);
4272 OtherOpF = FI->getOperand(1);
4273 MatchIsOpZero = true;
4274 } else if (TI->getOperand(1) == FI->getOperand(1)) {
4275 MatchOp = TI->getOperand(1);
4276 OtherOpT = TI->getOperand(0);
4277 OtherOpF = FI->getOperand(0);
4278 MatchIsOpZero = false;
4279 } else if (!TI->isCommutative()) {
4280 return 0;
4281 } else if (TI->getOperand(0) == FI->getOperand(1)) {
4282 MatchOp = TI->getOperand(0);
4283 OtherOpT = TI->getOperand(1);
4284 OtherOpF = FI->getOperand(0);
4285 MatchIsOpZero = true;
4286 } else if (TI->getOperand(1) == FI->getOperand(0)) {
4287 MatchOp = TI->getOperand(1);
4288 OtherOpT = TI->getOperand(0);
4289 OtherOpF = FI->getOperand(1);
4290 MatchIsOpZero = true;
4291 } else {
4292 return 0;
4293 }
4294
4295 // If we reach here, they do have operations in common.
4296 SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
4297 OtherOpF, SI.getName()+".v");
4298 InsertNewInstBefore(NewSI, SI);
4299
4300 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
4301 if (MatchIsOpZero)
4302 return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
4303 else
4304 return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
4305 } else {
4306 if (MatchIsOpZero)
4307 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), MatchOp, NewSI);
4308 else
4309 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), NewSI, MatchOp);
4310 }
4311}
4312
Chris Lattnerb909e8b2004-03-12 05:52:32 +00004313Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattner533bc492004-03-30 19:37:13 +00004314 Value *CondVal = SI.getCondition();
4315 Value *TrueVal = SI.getTrueValue();
4316 Value *FalseVal = SI.getFalseValue();
4317
4318 // select true, X, Y -> X
4319 // select false, X, Y -> Y
4320 if (ConstantBool *C = dyn_cast<ConstantBool>(CondVal))
Chris Lattnerb909e8b2004-03-12 05:52:32 +00004321 if (C == ConstantBool::True)
Chris Lattner533bc492004-03-30 19:37:13 +00004322 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattnerb909e8b2004-03-12 05:52:32 +00004323 else {
4324 assert(C == ConstantBool::False);
Chris Lattner533bc492004-03-30 19:37:13 +00004325 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattnerb909e8b2004-03-12 05:52:32 +00004326 }
Chris Lattner533bc492004-03-30 19:37:13 +00004327
4328 // select C, X, X -> X
4329 if (TrueVal == FalseVal)
4330 return ReplaceInstUsesWith(SI, TrueVal);
4331
Chris Lattner81a7a232004-10-16 18:11:37 +00004332 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
4333 return ReplaceInstUsesWith(SI, FalseVal);
4334 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
4335 return ReplaceInstUsesWith(SI, TrueVal);
4336 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
4337 if (isa<Constant>(TrueVal))
4338 return ReplaceInstUsesWith(SI, TrueVal);
4339 else
4340 return ReplaceInstUsesWith(SI, FalseVal);
4341 }
4342
Chris Lattner1c631e82004-04-08 04:43:23 +00004343 if (SI.getType() == Type::BoolTy)
4344 if (ConstantBool *C = dyn_cast<ConstantBool>(TrueVal)) {
4345 if (C == ConstantBool::True) {
4346 // Change: A = select B, true, C --> A = or B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004347 return BinaryOperator::createOr(CondVal, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00004348 } else {
4349 // Change: A = select B, false, C --> A = and !B, C
4350 Value *NotCond =
4351 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
4352 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004353 return BinaryOperator::createAnd(NotCond, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00004354 }
4355 } else if (ConstantBool *C = dyn_cast<ConstantBool>(FalseVal)) {
4356 if (C == ConstantBool::False) {
4357 // Change: A = select B, C, false --> A = and B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004358 return BinaryOperator::createAnd(CondVal, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00004359 } else {
4360 // Change: A = select B, C, true --> A = or !B, C
4361 Value *NotCond =
4362 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
4363 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004364 return BinaryOperator::createOr(NotCond, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00004365 }
4366 }
4367
Chris Lattner183b3362004-04-09 19:05:30 +00004368 // Selecting between two integer constants?
4369 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
4370 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
4371 // select C, 1, 0 -> cast C to int
4372 if (FalseValC->isNullValue() && TrueValC->getRawValue() == 1) {
4373 return new CastInst(CondVal, SI.getType());
4374 } else if (TrueValC->isNullValue() && FalseValC->getRawValue() == 1) {
4375 // select C, 0, 1 -> cast !C to int
4376 Value *NotCond =
4377 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
Chris Lattnercf7baf32004-04-09 18:19:44 +00004378 "not."+CondVal->getName()), SI);
Chris Lattner183b3362004-04-09 19:05:30 +00004379 return new CastInst(NotCond, SI.getType());
Chris Lattnercf7baf32004-04-09 18:19:44 +00004380 }
Chris Lattner35167c32004-06-09 07:59:58 +00004381
4382 // If one of the constants is zero (we know they can't both be) and we
4383 // have a setcc instruction with zero, and we have an 'and' with the
4384 // non-constant value, eliminate this whole mess. This corresponds to
4385 // cases like this: ((X & 27) ? 27 : 0)
4386 if (TrueValC->isNullValue() || FalseValC->isNullValue())
4387 if (Instruction *IC = dyn_cast<Instruction>(SI.getCondition()))
4388 if ((IC->getOpcode() == Instruction::SetEQ ||
4389 IC->getOpcode() == Instruction::SetNE) &&
4390 isa<ConstantInt>(IC->getOperand(1)) &&
4391 cast<Constant>(IC->getOperand(1))->isNullValue())
4392 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
4393 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00004394 isa<ConstantInt>(ICA->getOperand(1)) &&
4395 (ICA->getOperand(1) == TrueValC ||
4396 ICA->getOperand(1) == FalseValC) &&
Chris Lattner35167c32004-06-09 07:59:58 +00004397 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
4398 // Okay, now we know that everything is set up, we just don't
4399 // know whether we have a setne or seteq and whether the true or
4400 // false val is the zero.
4401 bool ShouldNotVal = !TrueValC->isNullValue();
4402 ShouldNotVal ^= IC->getOpcode() == Instruction::SetNE;
4403 Value *V = ICA;
4404 if (ShouldNotVal)
4405 V = InsertNewInstBefore(BinaryOperator::create(
4406 Instruction::Xor, V, ICA->getOperand(1)), SI);
4407 return ReplaceInstUsesWith(SI, V);
4408 }
Chris Lattner533bc492004-03-30 19:37:13 +00004409 }
Chris Lattner623fba12004-04-10 22:21:27 +00004410
4411 // See if we are selecting two values based on a comparison of the two values.
4412 if (SetCondInst *SCI = dyn_cast<SetCondInst>(CondVal)) {
4413 if (SCI->getOperand(0) == TrueVal && SCI->getOperand(1) == FalseVal) {
4414 // Transform (X == Y) ? X : Y -> Y
4415 if (SCI->getOpcode() == Instruction::SetEQ)
4416 return ReplaceInstUsesWith(SI, FalseVal);
4417 // Transform (X != Y) ? X : Y -> X
4418 if (SCI->getOpcode() == Instruction::SetNE)
4419 return ReplaceInstUsesWith(SI, TrueVal);
4420 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
4421
4422 } else if (SCI->getOperand(0) == FalseVal && SCI->getOperand(1) == TrueVal){
4423 // Transform (X == Y) ? Y : X -> X
4424 if (SCI->getOpcode() == Instruction::SetEQ)
Chris Lattner24cf0202004-04-11 01:39:19 +00004425 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattner623fba12004-04-10 22:21:27 +00004426 // Transform (X != Y) ? Y : X -> Y
4427 if (SCI->getOpcode() == Instruction::SetNE)
Chris Lattner24cf0202004-04-11 01:39:19 +00004428 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattner623fba12004-04-10 22:21:27 +00004429 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
4430 }
4431 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004432
Chris Lattnera04c9042005-01-13 22:52:24 +00004433 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
4434 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
4435 if (TI->hasOneUse() && FI->hasOneUse()) {
4436 bool isInverse = false;
4437 Instruction *AddOp = 0, *SubOp = 0;
4438
Chris Lattner411336f2005-01-19 21:50:18 +00004439 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
4440 if (TI->getOpcode() == FI->getOpcode())
4441 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
4442 return IV;
4443
4444 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
4445 // even legal for FP.
Chris Lattnera04c9042005-01-13 22:52:24 +00004446 if (TI->getOpcode() == Instruction::Sub &&
4447 FI->getOpcode() == Instruction::Add) {
4448 AddOp = FI; SubOp = TI;
4449 } else if (FI->getOpcode() == Instruction::Sub &&
4450 TI->getOpcode() == Instruction::Add) {
4451 AddOp = TI; SubOp = FI;
4452 }
4453
4454 if (AddOp) {
4455 Value *OtherAddOp = 0;
4456 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
4457 OtherAddOp = AddOp->getOperand(1);
4458 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
4459 OtherAddOp = AddOp->getOperand(0);
4460 }
4461
4462 if (OtherAddOp) {
4463 // So at this point we know we have:
4464 // select C, (add X, Y), (sub X, ?)
4465 // We can do the transform profitably if either 'Y' = '?' or '?' is
4466 // a constant.
4467 if (SubOp->getOperand(1) == AddOp ||
4468 isa<Constant>(SubOp->getOperand(1))) {
4469 Value *NegVal;
4470 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
4471 NegVal = ConstantExpr::getNeg(C);
4472 } else {
4473 NegVal = InsertNewInstBefore(
4474 BinaryOperator::createNeg(SubOp->getOperand(1)), SI);
4475 }
4476
Chris Lattner51726c42005-01-14 17:35:12 +00004477 Value *NewTrueOp = OtherAddOp;
Chris Lattnera04c9042005-01-13 22:52:24 +00004478 Value *NewFalseOp = NegVal;
4479 if (AddOp != TI)
4480 std::swap(NewTrueOp, NewFalseOp);
4481 Instruction *NewSel =
4482 new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
Misha Brukmanb1c93172005-04-21 23:48:37 +00004483
Chris Lattnera04c9042005-01-13 22:52:24 +00004484 NewSel = InsertNewInstBefore(NewSel, SI);
Chris Lattner51726c42005-01-14 17:35:12 +00004485 return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
Chris Lattnera04c9042005-01-13 22:52:24 +00004486 }
4487 }
4488 }
4489 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004490
Chris Lattner56e4d3d2004-04-09 23:46:01 +00004491 // See if we can fold the select into one of our operands.
4492 if (SI.getType()->isInteger()) {
4493 // See the comment above GetSelectFoldableOperands for a description of the
4494 // transformation we are doing here.
4495 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
4496 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
4497 !isa<Constant>(FalseVal))
4498 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
4499 unsigned OpToFold = 0;
4500 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
4501 OpToFold = 1;
4502 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
4503 OpToFold = 2;
4504 }
4505
4506 if (OpToFold) {
4507 Constant *C = GetSelectFoldableConstant(TVI);
4508 std::string Name = TVI->getName(); TVI->setName("");
4509 Instruction *NewSel =
4510 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C,
4511 Name);
4512 InsertNewInstBefore(NewSel, SI);
4513 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
4514 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
4515 else if (ShiftInst *SI = dyn_cast<ShiftInst>(TVI))
4516 return new ShiftInst(SI->getOpcode(), FalseVal, NewSel);
4517 else {
4518 assert(0 && "Unknown instruction!!");
4519 }
4520 }
4521 }
Chris Lattner6862fbd2004-09-29 17:40:11 +00004522
Chris Lattner56e4d3d2004-04-09 23:46:01 +00004523 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
4524 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
4525 !isa<Constant>(TrueVal))
4526 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
4527 unsigned OpToFold = 0;
4528 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
4529 OpToFold = 1;
4530 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
4531 OpToFold = 2;
4532 }
4533
4534 if (OpToFold) {
4535 Constant *C = GetSelectFoldableConstant(FVI);
4536 std::string Name = FVI->getName(); FVI->setName("");
4537 Instruction *NewSel =
4538 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold),
4539 Name);
4540 InsertNewInstBefore(NewSel, SI);
4541 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
4542 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
4543 else if (ShiftInst *SI = dyn_cast<ShiftInst>(FVI))
4544 return new ShiftInst(SI->getOpcode(), TrueVal, NewSel);
4545 else {
4546 assert(0 && "Unknown instruction!!");
4547 }
4548 }
4549 }
4550 }
Chris Lattnerd6f636a2005-04-24 07:30:14 +00004551
4552 if (BinaryOperator::isNot(CondVal)) {
4553 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
4554 SI.setOperand(1, FalseVal);
4555 SI.setOperand(2, TrueVal);
4556 return &SI;
4557 }
4558
Chris Lattnerb909e8b2004-03-12 05:52:32 +00004559 return 0;
4560}
4561
4562
Chris Lattner970c33a2003-06-19 17:00:31 +00004563// CallInst simplification
4564//
4565Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattner51ea1272004-02-28 05:22:00 +00004566 // Intrinsics cannot occur in an invoke, so handle them here instead of in
4567 // visitCallSite.
Chris Lattner00648e12004-10-12 04:52:52 +00004568 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(&CI)) {
4569 bool Changed = false;
4570
4571 // memmove/cpy/set of zero bytes is a noop.
4572 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
4573 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
4574
4575 // FIXME: Increase alignment here.
Misha Brukmanb1c93172005-04-21 23:48:37 +00004576
Chris Lattner00648e12004-10-12 04:52:52 +00004577 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
4578 if (CI->getRawValue() == 1) {
4579 // Replace the instruction with just byte operations. We would
4580 // transform other cases to loads/stores, but we don't know if
4581 // alignment is sufficient.
4582 }
Chris Lattner51ea1272004-02-28 05:22:00 +00004583 }
4584
Chris Lattner00648e12004-10-12 04:52:52 +00004585 // If we have a memmove and the source operation is a constant global,
4586 // then the source and dest pointers can't alias, so we can change this
4587 // into a call to memcpy.
4588 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI))
4589 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
4590 if (GVSrc->isConstant()) {
4591 Module *M = CI.getParent()->getParent()->getParent();
4592 Function *MemCpy = M->getOrInsertFunction("llvm.memcpy",
4593 CI.getCalledFunction()->getFunctionType());
4594 CI.setOperand(0, MemCpy);
4595 Changed = true;
4596 }
4597
4598 if (Changed) return &CI;
Chris Lattner95307542004-11-18 21:41:39 +00004599 } else if (DbgStopPointInst *SPI = dyn_cast<DbgStopPointInst>(&CI)) {
4600 // If this stoppoint is at the same source location as the previous
4601 // stoppoint in the chain, it is not needed.
4602 if (DbgStopPointInst *PrevSPI =
4603 dyn_cast<DbgStopPointInst>(SPI->getChain()))
4604 if (SPI->getLineNo() == PrevSPI->getLineNo() &&
4605 SPI->getColNo() == PrevSPI->getColNo()) {
4606 SPI->replaceAllUsesWith(PrevSPI);
4607 return EraseInstFromFunction(CI);
4608 }
Chris Lattner00648e12004-10-12 04:52:52 +00004609 }
4610
Chris Lattneraec3d942003-10-07 22:32:43 +00004611 return visitCallSite(&CI);
Chris Lattner970c33a2003-06-19 17:00:31 +00004612}
4613
4614// InvokeInst simplification
4615//
4616Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattneraec3d942003-10-07 22:32:43 +00004617 return visitCallSite(&II);
Chris Lattner970c33a2003-06-19 17:00:31 +00004618}
4619
Chris Lattneraec3d942003-10-07 22:32:43 +00004620// visitCallSite - Improvements for call and invoke instructions.
4621//
4622Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner75b4d1d2003-10-07 22:54:13 +00004623 bool Changed = false;
4624
4625 // If the callee is a constexpr cast of a function, attempt to move the cast
4626 // to the arguments of the call/invoke.
Chris Lattneraec3d942003-10-07 22:32:43 +00004627 if (transformConstExprCastCall(CS)) return 0;
4628
Chris Lattner75b4d1d2003-10-07 22:54:13 +00004629 Value *Callee = CS.getCalledValue();
Chris Lattner81a7a232004-10-16 18:11:37 +00004630
Chris Lattner61d9d812005-05-13 07:09:09 +00004631 if (Function *CalleeF = dyn_cast<Function>(Callee))
4632 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
4633 Instruction *OldCall = CS.getInstruction();
4634 // If the call and callee calling conventions don't match, this call must
4635 // be unreachable, as the call is undefined.
4636 new StoreInst(ConstantBool::True,
4637 UndefValue::get(PointerType::get(Type::BoolTy)), OldCall);
4638 if (!OldCall->use_empty())
4639 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
4640 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
4641 return EraseInstFromFunction(*OldCall);
4642 return 0;
4643 }
4644
Chris Lattner8ba9ec92004-10-18 02:59:09 +00004645 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
4646 // This instruction is not reachable, just remove it. We insert a store to
4647 // undef so that we know that this code is not reachable, despite the fact
4648 // that we can't modify the CFG here.
4649 new StoreInst(ConstantBool::True,
4650 UndefValue::get(PointerType::get(Type::BoolTy)),
4651 CS.getInstruction());
4652
4653 if (!CS.getInstruction()->use_empty())
4654 CS.getInstruction()->
4655 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
4656
4657 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
4658 // Don't break the CFG, insert a dummy cond branch.
4659 new BranchInst(II->getNormalDest(), II->getUnwindDest(),
4660 ConstantBool::True, II);
Chris Lattner81a7a232004-10-16 18:11:37 +00004661 }
Chris Lattner8ba9ec92004-10-18 02:59:09 +00004662 return EraseInstFromFunction(*CS.getInstruction());
4663 }
Chris Lattner81a7a232004-10-16 18:11:37 +00004664
Chris Lattner75b4d1d2003-10-07 22:54:13 +00004665 const PointerType *PTy = cast<PointerType>(Callee->getType());
4666 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
4667 if (FTy->isVarArg()) {
4668 // See if we can optimize any arguments passed through the varargs area of
4669 // the call.
4670 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
4671 E = CS.arg_end(); I != E; ++I)
4672 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
4673 // If this cast does not effect the value passed through the varargs
4674 // area, we can eliminate the use of the cast.
4675 Value *Op = CI->getOperand(0);
4676 if (CI->getType()->isLosslesslyConvertibleTo(Op->getType())) {
4677 *I = Op;
4678 Changed = true;
4679 }
4680 }
4681 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004682
Chris Lattner75b4d1d2003-10-07 22:54:13 +00004683 return Changed ? CS.getInstruction() : 0;
Chris Lattneraec3d942003-10-07 22:32:43 +00004684}
4685
Chris Lattner970c33a2003-06-19 17:00:31 +00004686// transformConstExprCastCall - If the callee is a constexpr cast of a function,
4687// attempt to move the cast to the arguments of the call/invoke.
4688//
4689bool InstCombiner::transformConstExprCastCall(CallSite CS) {
4690 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
4691 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Chris Lattnerf3edc492004-07-18 18:59:44 +00004692 if (CE->getOpcode() != Instruction::Cast || !isa<Function>(CE->getOperand(0)))
Chris Lattner970c33a2003-06-19 17:00:31 +00004693 return false;
Reid Spencer87436872004-07-18 00:38:32 +00004694 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner970c33a2003-06-19 17:00:31 +00004695 Instruction *Caller = CS.getInstruction();
4696
4697 // Okay, this is a cast from a function to a different type. Unless doing so
4698 // would cause a type conversion of one of our arguments, change this call to
4699 // be a direct call with arguments casted to the appropriate types.
4700 //
4701 const FunctionType *FT = Callee->getFunctionType();
4702 const Type *OldRetTy = Caller->getType();
4703
Chris Lattner1f7942f2004-01-14 06:06:08 +00004704 // Check to see if we are changing the return type...
4705 if (OldRetTy != FT->getReturnType()) {
4706 if (Callee->isExternal() &&
4707 !OldRetTy->isLosslesslyConvertibleTo(FT->getReturnType()) &&
4708 !Caller->use_empty())
4709 return false; // Cannot transform this return value...
4710
4711 // If the callsite is an invoke instruction, and the return value is used by
4712 // a PHI node in a successor, we cannot change the return type of the call
4713 // because there is no place to put the cast instruction (without breaking
4714 // the critical edge). Bail out in this case.
4715 if (!Caller->use_empty())
4716 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
4717 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
4718 UI != E; ++UI)
4719 if (PHINode *PN = dyn_cast<PHINode>(*UI))
4720 if (PN->getParent() == II->getNormalDest() ||
Chris Lattnerfae8ab32004-02-08 21:44:31 +00004721 PN->getParent() == II->getUnwindDest())
Chris Lattner1f7942f2004-01-14 06:06:08 +00004722 return false;
4723 }
Chris Lattner970c33a2003-06-19 17:00:31 +00004724
4725 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
4726 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004727
Chris Lattner970c33a2003-06-19 17:00:31 +00004728 CallSite::arg_iterator AI = CS.arg_begin();
4729 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
4730 const Type *ParamTy = FT->getParamType(i);
4731 bool isConvertible = (*AI)->getType()->isLosslesslyConvertibleTo(ParamTy);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004732 if (Callee->isExternal() && !isConvertible) return false;
Chris Lattner970c33a2003-06-19 17:00:31 +00004733 }
4734
4735 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
4736 Callee->isExternal())
4737 return false; // Do not delete arguments unless we have a function body...
4738
4739 // Okay, we decided that this is a safe thing to do: go ahead and start
4740 // inserting cast instructions as necessary...
4741 std::vector<Value*> Args;
4742 Args.reserve(NumActualArgs);
4743
4744 AI = CS.arg_begin();
4745 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
4746 const Type *ParamTy = FT->getParamType(i);
4747 if ((*AI)->getType() == ParamTy) {
4748 Args.push_back(*AI);
4749 } else {
Chris Lattner1c631e82004-04-08 04:43:23 +00004750 Args.push_back(InsertNewInstBefore(new CastInst(*AI, ParamTy, "tmp"),
4751 *Caller));
Chris Lattner970c33a2003-06-19 17:00:31 +00004752 }
4753 }
4754
4755 // If the function takes more arguments than the call was taking, add them
4756 // now...
4757 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
4758 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
4759
4760 // If we are removing arguments to the function, emit an obnoxious warning...
4761 if (FT->getNumParams() < NumActualArgs)
4762 if (!FT->isVarArg()) {
4763 std::cerr << "WARNING: While resolving call to function '"
4764 << Callee->getName() << "' arguments were dropped!\n";
4765 } else {
4766 // Add all of the arguments in their promoted form to the arg list...
4767 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
4768 const Type *PTy = getPromotedType((*AI)->getType());
4769 if (PTy != (*AI)->getType()) {
4770 // Must promote to pass through va_arg area!
4771 Instruction *Cast = new CastInst(*AI, PTy, "tmp");
4772 InsertNewInstBefore(Cast, *Caller);
4773 Args.push_back(Cast);
4774 } else {
4775 Args.push_back(*AI);
4776 }
4777 }
4778 }
4779
4780 if (FT->getReturnType() == Type::VoidTy)
4781 Caller->setName(""); // Void type should not have a name...
4782
4783 Instruction *NC;
4784 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Chris Lattnerfae8ab32004-02-08 21:44:31 +00004785 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
Chris Lattner970c33a2003-06-19 17:00:31 +00004786 Args, Caller->getName(), Caller);
Chris Lattner05c703e2005-05-14 12:25:32 +00004787 cast<InvokeInst>(II)->setCallingConv(II->getCallingConv());
Chris Lattner970c33a2003-06-19 17:00:31 +00004788 } else {
4789 NC = new CallInst(Callee, Args, Caller->getName(), Caller);
Chris Lattner6aacb0f2005-05-06 06:48:21 +00004790 if (cast<CallInst>(Caller)->isTailCall())
4791 cast<CallInst>(NC)->setTailCall();
Chris Lattner05c703e2005-05-14 12:25:32 +00004792 cast<CallInst>(NC)->setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Chris Lattner970c33a2003-06-19 17:00:31 +00004793 }
4794
4795 // Insert a cast of the return type as necessary...
4796 Value *NV = NC;
4797 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
4798 if (NV->getType() != Type::VoidTy) {
4799 NV = NC = new CastInst(NC, Caller->getType(), "tmp");
Chris Lattner686767f2003-10-30 00:46:41 +00004800
4801 // If this is an invoke instruction, we should insert it after the first
4802 // non-phi, instruction in the normal successor block.
4803 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
4804 BasicBlock::iterator I = II->getNormalDest()->begin();
4805 while (isa<PHINode>(I)) ++I;
4806 InsertNewInstBefore(NC, *I);
4807 } else {
4808 // Otherwise, it's a call, just insert cast right after the call instr
4809 InsertNewInstBefore(NC, *Caller);
4810 }
Chris Lattner51ea1272004-02-28 05:22:00 +00004811 AddUsersToWorkList(*Caller);
Chris Lattner970c33a2003-06-19 17:00:31 +00004812 } else {
Chris Lattnere29d6342004-10-17 21:22:38 +00004813 NV = UndefValue::get(Caller->getType());
Chris Lattner970c33a2003-06-19 17:00:31 +00004814 }
4815 }
4816
4817 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
4818 Caller->replaceAllUsesWith(NV);
4819 Caller->getParent()->getInstList().erase(Caller);
4820 removeFromWorkList(Caller);
4821 return true;
4822}
4823
4824
Chris Lattner7515cab2004-11-14 19:13:23 +00004825// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
4826// operator and they all are only used by the PHI, PHI together their
4827// inputs, and do the operation once, to the result of the PHI.
4828Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
4829 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
4830
4831 // Scan the instruction, looking for input operations that can be folded away.
4832 // If all input operands to the phi are the same instruction (e.g. a cast from
4833 // the same type or "+42") we can pull the operation through the PHI, reducing
4834 // code size and simplifying code.
4835 Constant *ConstantOp = 0;
4836 const Type *CastSrcTy = 0;
4837 if (isa<CastInst>(FirstInst)) {
4838 CastSrcTy = FirstInst->getOperand(0)->getType();
4839 } else if (isa<BinaryOperator>(FirstInst) || isa<ShiftInst>(FirstInst)) {
4840 // Can fold binop or shift if the RHS is a constant.
4841 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
4842 if (ConstantOp == 0) return 0;
4843 } else {
4844 return 0; // Cannot fold this operation.
4845 }
4846
4847 // Check to see if all arguments are the same operation.
4848 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
4849 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
4850 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
4851 if (!I->hasOneUse() || I->getOpcode() != FirstInst->getOpcode())
4852 return 0;
4853 if (CastSrcTy) {
4854 if (I->getOperand(0)->getType() != CastSrcTy)
4855 return 0; // Cast operation must match.
4856 } else if (I->getOperand(1) != ConstantOp) {
4857 return 0;
4858 }
4859 }
4860
4861 // Okay, they are all the same operation. Create a new PHI node of the
4862 // correct type, and PHI together all of the LHS's of the instructions.
4863 PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
4864 PN.getName()+".in");
Chris Lattnerd8e20182005-01-29 00:39:08 +00004865 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattner46dd5a62004-11-14 19:29:34 +00004866
4867 Value *InVal = FirstInst->getOperand(0);
4868 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattner7515cab2004-11-14 19:13:23 +00004869
4870 // Add all operands to the new PHI.
Chris Lattner46dd5a62004-11-14 19:29:34 +00004871 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
4872 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
4873 if (NewInVal != InVal)
4874 InVal = 0;
4875 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
4876 }
4877
4878 Value *PhiVal;
4879 if (InVal) {
4880 // The new PHI unions all of the same values together. This is really
4881 // common, so we handle it intelligently here for compile-time speed.
4882 PhiVal = InVal;
4883 delete NewPN;
4884 } else {
4885 InsertNewInstBefore(NewPN, PN);
4886 PhiVal = NewPN;
4887 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004888
Chris Lattner7515cab2004-11-14 19:13:23 +00004889 // Insert and return the new operation.
4890 if (isa<CastInst>(FirstInst))
Chris Lattner46dd5a62004-11-14 19:29:34 +00004891 return new CastInst(PhiVal, PN.getType());
Chris Lattner7515cab2004-11-14 19:13:23 +00004892 else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattner46dd5a62004-11-14 19:29:34 +00004893 return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattner7515cab2004-11-14 19:13:23 +00004894 else
4895 return new ShiftInst(cast<ShiftInst>(FirstInst)->getOpcode(),
Chris Lattner46dd5a62004-11-14 19:29:34 +00004896 PhiVal, ConstantOp);
Chris Lattner7515cab2004-11-14 19:13:23 +00004897}
Chris Lattner48a44f72002-05-02 17:06:02 +00004898
Chris Lattner71536432005-01-17 05:10:15 +00004899/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
4900/// that is dead.
4901static bool DeadPHICycle(PHINode *PN, std::set<PHINode*> &PotentiallyDeadPHIs) {
4902 if (PN->use_empty()) return true;
4903 if (!PN->hasOneUse()) return false;
4904
4905 // Remember this node, and if we find the cycle, return.
4906 if (!PotentiallyDeadPHIs.insert(PN).second)
4907 return true;
4908
4909 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
4910 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004911
Chris Lattner71536432005-01-17 05:10:15 +00004912 return false;
4913}
4914
Chris Lattnerbbbdd852002-05-06 18:06:38 +00004915// PHINode simplification
4916//
Chris Lattner113f4f42002-06-25 16:13:24 +00004917Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Chris Lattner9f9c2602005-08-05 01:04:30 +00004918 if (Value *V = PN.hasConstantValue())
4919 return ReplaceInstUsesWith(PN, V);
Chris Lattner4db2d222004-02-16 05:07:08 +00004920
4921 // If the only user of this instruction is a cast instruction, and all of the
4922 // incoming values are constants, change this PHI to merge together the casted
4923 // constants.
4924 if (PN.hasOneUse())
4925 if (CastInst *CI = dyn_cast<CastInst>(PN.use_back()))
4926 if (CI->getType() != PN.getType()) { // noop casts will be folded
4927 bool AllConstant = true;
4928 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
4929 if (!isa<Constant>(PN.getIncomingValue(i))) {
4930 AllConstant = false;
4931 break;
4932 }
4933 if (AllConstant) {
4934 // Make a new PHI with all casted values.
4935 PHINode *New = new PHINode(CI->getType(), PN.getName(), &PN);
4936 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
4937 Constant *OldArg = cast<Constant>(PN.getIncomingValue(i));
4938 New->addIncoming(ConstantExpr::getCast(OldArg, New->getType()),
4939 PN.getIncomingBlock(i));
4940 }
4941
4942 // Update the cast instruction.
4943 CI->setOperand(0, New);
4944 WorkList.push_back(CI); // revisit the cast instruction to fold.
4945 WorkList.push_back(New); // Make sure to revisit the new Phi
4946 return &PN; // PN is now dead!
4947 }
4948 }
Chris Lattner7515cab2004-11-14 19:13:23 +00004949
4950 // If all PHI operands are the same operation, pull them through the PHI,
4951 // reducing code size.
4952 if (isa<Instruction>(PN.getIncomingValue(0)) &&
4953 PN.getIncomingValue(0)->hasOneUse())
4954 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
4955 return Result;
4956
Chris Lattner71536432005-01-17 05:10:15 +00004957 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
4958 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
4959 // PHI)... break the cycle.
4960 if (PN.hasOneUse())
4961 if (PHINode *PU = dyn_cast<PHINode>(PN.use_back())) {
4962 std::set<PHINode*> PotentiallyDeadPHIs;
4963 PotentiallyDeadPHIs.insert(&PN);
4964 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
4965 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
4966 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004967
Chris Lattner91daeb52003-12-19 05:58:40 +00004968 return 0;
Chris Lattnerbbbdd852002-05-06 18:06:38 +00004969}
4970
Chris Lattner69193f92004-04-05 01:30:19 +00004971static Value *InsertSignExtendToPtrTy(Value *V, const Type *DTy,
4972 Instruction *InsertPoint,
4973 InstCombiner *IC) {
4974 unsigned PS = IC->getTargetData().getPointerSize();
4975 const Type *VTy = V->getType();
Chris Lattner69193f92004-04-05 01:30:19 +00004976 if (!VTy->isSigned() && VTy->getPrimitiveSize() < PS)
4977 // We must insert a cast to ensure we sign-extend.
4978 V = IC->InsertNewInstBefore(new CastInst(V, VTy->getSignedVersion(),
4979 V->getName()), *InsertPoint);
4980 return IC->InsertNewInstBefore(new CastInst(V, DTy, V->getName()),
4981 *InsertPoint);
4982}
4983
Chris Lattner48a44f72002-05-02 17:06:02 +00004984
Chris Lattner113f4f42002-06-25 16:13:24 +00004985Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner5f667a62004-05-07 22:09:22 +00004986 Value *PtrOp = GEP.getOperand(0);
Chris Lattner471bd762003-05-22 19:07:21 +00004987 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
Chris Lattner113f4f42002-06-25 16:13:24 +00004988 // If so, eliminate the noop.
Chris Lattner8d0bacb2004-02-22 05:25:17 +00004989 if (GEP.getNumOperands() == 1)
Chris Lattner5f667a62004-05-07 22:09:22 +00004990 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner8d0bacb2004-02-22 05:25:17 +00004991
Chris Lattner81a7a232004-10-16 18:11:37 +00004992 if (isa<UndefValue>(GEP.getOperand(0)))
4993 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
4994
Chris Lattner8d0bacb2004-02-22 05:25:17 +00004995 bool HasZeroPointerIndex = false;
4996 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
4997 HasZeroPointerIndex = C->isNullValue();
4998
4999 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner5f667a62004-05-07 22:09:22 +00005000 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner48a44f72002-05-02 17:06:02 +00005001
Chris Lattner69193f92004-04-05 01:30:19 +00005002 // Eliminate unneeded casts for indices.
5003 bool MadeChange = false;
Chris Lattner2b2412d2004-04-07 18:38:20 +00005004 gep_type_iterator GTI = gep_type_begin(GEP);
5005 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI)
5006 if (isa<SequentialType>(*GTI)) {
5007 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
5008 Value *Src = CI->getOperand(0);
5009 const Type *SrcTy = Src->getType();
5010 const Type *DestTy = CI->getType();
5011 if (Src->getType()->isInteger()) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005012 if (SrcTy->getPrimitiveSizeInBits() ==
5013 DestTy->getPrimitiveSizeInBits()) {
Chris Lattner2b2412d2004-04-07 18:38:20 +00005014 // We can always eliminate a cast from ulong or long to the other.
5015 // We can always eliminate a cast from uint to int or the other on
5016 // 32-bit pointer platforms.
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005017 if (DestTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()){
Chris Lattner2b2412d2004-04-07 18:38:20 +00005018 MadeChange = true;
5019 GEP.setOperand(i, Src);
5020 }
5021 } else if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
5022 SrcTy->getPrimitiveSize() == 4) {
5023 // We can always eliminate a cast from int to [u]long. We can
5024 // eliminate a cast from uint to [u]long iff the target is a 32-bit
5025 // pointer target.
Misha Brukmanb1c93172005-04-21 23:48:37 +00005026 if (SrcTy->isSigned() ||
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005027 SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
Chris Lattner2b2412d2004-04-07 18:38:20 +00005028 MadeChange = true;
5029 GEP.setOperand(i, Src);
5030 }
Chris Lattner69193f92004-04-05 01:30:19 +00005031 }
5032 }
5033 }
Chris Lattner2b2412d2004-04-07 18:38:20 +00005034 // If we are using a wider index than needed for this platform, shrink it
5035 // to what we need. If the incoming value needs a cast instruction,
5036 // insert it. This explicit cast can make subsequent optimizations more
5037 // obvious.
5038 Value *Op = GEP.getOperand(i);
5039 if (Op->getType()->getPrimitiveSize() > TD->getPointerSize())
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00005040 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner44d0b952004-07-20 01:48:15 +00005041 GEP.setOperand(i, ConstantExpr::getCast(C,
5042 TD->getIntPtrType()->getSignedVersion()));
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00005043 MadeChange = true;
5044 } else {
Chris Lattner2b2412d2004-04-07 18:38:20 +00005045 Op = InsertNewInstBefore(new CastInst(Op, TD->getIntPtrType(),
5046 Op->getName()), GEP);
5047 GEP.setOperand(i, Op);
5048 MadeChange = true;
5049 }
Chris Lattner44d0b952004-07-20 01:48:15 +00005050
5051 // If this is a constant idx, make sure to canonicalize it to be a signed
5052 // operand, otherwise CSE and other optimizations are pessimized.
5053 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op)) {
5054 GEP.setOperand(i, ConstantExpr::getCast(CUI,
5055 CUI->getType()->getSignedVersion()));
5056 MadeChange = true;
5057 }
Chris Lattner69193f92004-04-05 01:30:19 +00005058 }
5059 if (MadeChange) return &GEP;
5060
Chris Lattnerae7a0d32002-08-02 19:29:35 +00005061 // Combine Indices - If the source pointer to this getelementptr instruction
5062 // is a getelementptr instruction, combine the indices of the two
5063 // getelementptr instructions into a single instruction.
5064 //
Chris Lattner57c67b02004-03-25 22:59:29 +00005065 std::vector<Value*> SrcGEPOperands;
Chris Lattner0798af32005-01-13 20:14:25 +00005066 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattner57c67b02004-03-25 22:59:29 +00005067 SrcGEPOperands.assign(Src->op_begin(), Src->op_end());
Chris Lattner57c67b02004-03-25 22:59:29 +00005068
5069 if (!SrcGEPOperands.empty()) {
Chris Lattner5f667a62004-05-07 22:09:22 +00005070 // Note that if our source is a gep chain itself that we wait for that
5071 // chain to be resolved before we perform this transformation. This
5072 // avoids us creating a TON of code in some cases.
5073 //
5074 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
5075 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
5076 return 0; // Wait until our source is folded to completion.
5077
Chris Lattnerae7a0d32002-08-02 19:29:35 +00005078 std::vector<Value *> Indices;
Chris Lattner5f667a62004-05-07 22:09:22 +00005079
5080 // Find out whether the last index in the source GEP is a sequential idx.
5081 bool EndsWithSequential = false;
5082 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
5083 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattner8ec5f882004-05-08 22:41:42 +00005084 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00005085
Chris Lattnerae7a0d32002-08-02 19:29:35 +00005086 // Can we combine the two pointer arithmetics offsets?
Chris Lattner5f667a62004-05-07 22:09:22 +00005087 if (EndsWithSequential) {
Chris Lattner235af562003-03-05 22:33:14 +00005088 // Replace: gep (gep %P, long B), long A, ...
5089 // With: T = long A+B; gep %P, T, ...
5090 //
Chris Lattner5f667a62004-05-07 22:09:22 +00005091 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner69193f92004-04-05 01:30:19 +00005092 if (SO1 == Constant::getNullValue(SO1->getType())) {
5093 Sum = GO1;
5094 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
5095 Sum = SO1;
5096 } else {
5097 // If they aren't the same type, convert both to an integer of the
5098 // target's pointer size.
5099 if (SO1->getType() != GO1->getType()) {
5100 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
5101 SO1 = ConstantExpr::getCast(SO1C, GO1->getType());
5102 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
5103 GO1 = ConstantExpr::getCast(GO1C, SO1->getType());
5104 } else {
5105 unsigned PS = TD->getPointerSize();
Chris Lattner69193f92004-04-05 01:30:19 +00005106 if (SO1->getType()->getPrimitiveSize() == PS) {
5107 // Convert GO1 to SO1's type.
5108 GO1 = InsertSignExtendToPtrTy(GO1, SO1->getType(), &GEP, this);
5109
5110 } else if (GO1->getType()->getPrimitiveSize() == PS) {
5111 // Convert SO1 to GO1's type.
5112 SO1 = InsertSignExtendToPtrTy(SO1, GO1->getType(), &GEP, this);
5113 } else {
5114 const Type *PT = TD->getIntPtrType();
5115 SO1 = InsertSignExtendToPtrTy(SO1, PT, &GEP, this);
5116 GO1 = InsertSignExtendToPtrTy(GO1, PT, &GEP, this);
5117 }
5118 }
5119 }
Chris Lattner5f667a62004-05-07 22:09:22 +00005120 if (isa<Constant>(SO1) && isa<Constant>(GO1))
5121 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
5122 else {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00005123 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
5124 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner5f667a62004-05-07 22:09:22 +00005125 }
Chris Lattner69193f92004-04-05 01:30:19 +00005126 }
Chris Lattner5f667a62004-05-07 22:09:22 +00005127
5128 // Recycle the GEP we already have if possible.
5129 if (SrcGEPOperands.size() == 2) {
5130 GEP.setOperand(0, SrcGEPOperands[0]);
5131 GEP.setOperand(1, Sum);
5132 return &GEP;
5133 } else {
5134 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
5135 SrcGEPOperands.end()-1);
5136 Indices.push_back(Sum);
5137 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
5138 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00005139 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner69193f92004-04-05 01:30:19 +00005140 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00005141 SrcGEPOperands.size() != 1) {
Chris Lattnerae7a0d32002-08-02 19:29:35 +00005142 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattner57c67b02004-03-25 22:59:29 +00005143 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
5144 SrcGEPOperands.end());
Chris Lattnerae7a0d32002-08-02 19:29:35 +00005145 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
5146 }
5147
5148 if (!Indices.empty())
Chris Lattner57c67b02004-03-25 22:59:29 +00005149 return new GetElementPtrInst(SrcGEPOperands[0], Indices, GEP.getName());
Chris Lattnerc59af1d2002-08-17 22:21:59 +00005150
Chris Lattner5f667a62004-05-07 22:09:22 +00005151 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattnerc59af1d2002-08-17 22:21:59 +00005152 // GEP of global variable. If all of the indices for this GEP are
5153 // constants, we can promote this to a constexpr instead of an instruction.
5154
5155 // Scan for nonconstants...
5156 std::vector<Constant*> Indices;
5157 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
5158 for (; I != E && isa<Constant>(*I); ++I)
5159 Indices.push_back(cast<Constant>(*I));
5160
5161 if (I == E) { // If they are all constants...
Chris Lattnerf3edc492004-07-18 18:59:44 +00005162 Constant *CE = ConstantExpr::getGetElementPtr(GV, Indices);
Chris Lattnerc59af1d2002-08-17 22:21:59 +00005163
5164 // Replace all uses of the GEP with the new constexpr...
5165 return ReplaceInstUsesWith(GEP, CE);
5166 }
Chris Lattner567b81f2005-09-13 00:40:14 +00005167 } else if (Value *X = isCast(PtrOp)) { // Is the operand a cast?
5168 if (!isa<PointerType>(X->getType())) {
5169 // Not interesting. Source pointer must be a cast from pointer.
5170 } else if (HasZeroPointerIndex) {
5171 // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
5172 // into : GEP [10 x ubyte]* X, long 0, ...
5173 //
5174 // This occurs when the program declares an array extern like "int X[];"
5175 //
5176 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
5177 const PointerType *XTy = cast<PointerType>(X->getType());
5178 if (const ArrayType *XATy =
5179 dyn_cast<ArrayType>(XTy->getElementType()))
5180 if (const ArrayType *CATy =
5181 dyn_cast<ArrayType>(CPTy->getElementType()))
5182 if (CATy->getElementType() == XATy->getElementType()) {
5183 // At this point, we know that the cast source type is a pointer
5184 // to an array of the same type as the destination pointer
5185 // array. Because the array type is never stepped over (there
5186 // is a leading zero) we can fold the cast into this GEP.
5187 GEP.setOperand(0, X);
5188 return &GEP;
5189 }
5190 } else if (GEP.getNumOperands() == 2) {
5191 // Transform things like:
Chris Lattner2a893292005-09-13 18:36:04 +00005192 // %t = getelementptr ubyte* cast ([2 x int]* %str to uint*), uint %V
5193 // into: %t1 = getelementptr [2 x int*]* %str, int 0, uint %V; cast
Chris Lattner567b81f2005-09-13 00:40:14 +00005194 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
5195 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
5196 if (isa<ArrayType>(SrcElTy) &&
5197 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
5198 TD->getTypeSize(ResElTy)) {
5199 Value *V = InsertNewInstBefore(
5200 new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
5201 GEP.getOperand(1), GEP.getName()), GEP);
5202 return new CastInst(V, GEP.getType());
Chris Lattner8d0bacb2004-02-22 05:25:17 +00005203 }
Chris Lattner2a893292005-09-13 18:36:04 +00005204
5205 // Transform things like:
5206 // getelementptr sbyte* cast ([100 x double]* X to sbyte*), int %tmp
5207 // (where tmp = 8*tmp2) into:
5208 // getelementptr [100 x double]* %arr, int 0, int %tmp.2
5209
5210 if (isa<ArrayType>(SrcElTy) &&
5211 (ResElTy == Type::SByteTy || ResElTy == Type::UByteTy)) {
5212 uint64_t ArrayEltSize =
5213 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType());
5214
5215 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
5216 // allow either a mul, shift, or constant here.
5217 Value *NewIdx = 0;
5218 ConstantInt *Scale = 0;
5219 if (ArrayEltSize == 1) {
5220 NewIdx = GEP.getOperand(1);
5221 Scale = ConstantInt::get(NewIdx->getType(), 1);
5222 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Chris Lattnera393e4d2005-09-14 17:32:56 +00005223 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner2a893292005-09-13 18:36:04 +00005224 Scale = CI;
5225 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
5226 if (Inst->getOpcode() == Instruction::Shl &&
5227 isa<ConstantInt>(Inst->getOperand(1))) {
5228 unsigned ShAmt =cast<ConstantUInt>(Inst->getOperand(1))->getValue();
5229 if (Inst->getType()->isSigned())
5230 Scale = ConstantSInt::get(Inst->getType(), 1ULL << ShAmt);
5231 else
5232 Scale = ConstantUInt::get(Inst->getType(), 1ULL << ShAmt);
5233 NewIdx = Inst->getOperand(0);
5234 } else if (Inst->getOpcode() == Instruction::Mul &&
5235 isa<ConstantInt>(Inst->getOperand(1))) {
5236 Scale = cast<ConstantInt>(Inst->getOperand(1));
5237 NewIdx = Inst->getOperand(0);
5238 }
5239 }
5240
5241 // If the index will be to exactly the right offset with the scale taken
5242 // out, perform the transformation.
5243 if (Scale && Scale->getRawValue() % ArrayEltSize == 0) {
5244 if (ConstantSInt *C = dyn_cast<ConstantSInt>(Scale))
5245 Scale = ConstantSInt::get(C->getType(),
Chris Lattnera393e4d2005-09-14 17:32:56 +00005246 (int64_t)C->getRawValue() /
5247 (int64_t)ArrayEltSize);
Chris Lattner2a893292005-09-13 18:36:04 +00005248 else
5249 Scale = ConstantUInt::get(Scale->getType(),
5250 Scale->getRawValue() / ArrayEltSize);
5251 if (Scale->getRawValue() != 1) {
5252 Constant *C = ConstantExpr::getCast(Scale, NewIdx->getType());
5253 Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
5254 NewIdx = InsertNewInstBefore(Sc, GEP);
5255 }
5256
5257 // Insert the new GEP instruction.
5258 Instruction *Idx =
5259 new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
5260 NewIdx, GEP.getName());
5261 Idx = InsertNewInstBefore(Idx, GEP);
5262 return new CastInst(Idx, GEP.getType());
5263 }
5264 }
Chris Lattner8d0bacb2004-02-22 05:25:17 +00005265 }
Chris Lattnerca081252001-12-14 16:52:21 +00005266 }
5267
Chris Lattnerca081252001-12-14 16:52:21 +00005268 return 0;
5269}
5270
Chris Lattner1085bdf2002-11-04 16:18:53 +00005271Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
5272 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
5273 if (AI.isArrayAllocation()) // Check C != 1
5274 if (const ConstantUInt *C = dyn_cast<ConstantUInt>(AI.getArraySize())) {
5275 const Type *NewTy = ArrayType::get(AI.getAllocatedType(), C->getValue());
Chris Lattnera2620ac2002-11-09 00:49:43 +00005276 AllocationInst *New = 0;
Chris Lattner1085bdf2002-11-04 16:18:53 +00005277
5278 // Create and insert the replacement instruction...
5279 if (isa<MallocInst>(AI))
Nate Begeman848622f2005-11-05 09:21:28 +00005280 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00005281 else {
5282 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Nate Begeman848622f2005-11-05 09:21:28 +00005283 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00005284 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00005285
5286 InsertNewInstBefore(New, AI);
Misha Brukmanb1c93172005-04-21 23:48:37 +00005287
Chris Lattner1085bdf2002-11-04 16:18:53 +00005288 // Scan to the end of the allocation instructions, to skip over a block of
5289 // allocas if possible...
5290 //
5291 BasicBlock::iterator It = New;
5292 while (isa<AllocationInst>(*It)) ++It;
5293
5294 // Now that I is pointing to the first non-allocation-inst in the block,
5295 // insert our getelementptr instruction...
5296 //
Chris Lattner809dfac2005-05-04 19:10:26 +00005297 Value *NullIdx = Constant::getNullValue(Type::IntTy);
5298 Value *V = new GetElementPtrInst(New, NullIdx, NullIdx,
5299 New->getName()+".sub", It);
Chris Lattner1085bdf2002-11-04 16:18:53 +00005300
5301 // Now make everything use the getelementptr instead of the original
5302 // allocation.
Chris Lattnerabb77c92004-03-19 06:08:10 +00005303 return ReplaceInstUsesWith(AI, V);
Chris Lattner81a7a232004-10-16 18:11:37 +00005304 } else if (isa<UndefValue>(AI.getArraySize())) {
5305 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner1085bdf2002-11-04 16:18:53 +00005306 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00005307
5308 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
5309 // Note that we only do this for alloca's, because malloc should allocate and
5310 // return a unique pointer, even for a zero byte allocation.
Misha Brukmanb1c93172005-04-21 23:48:37 +00005311 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
Chris Lattner49df6ce2004-07-02 22:55:47 +00005312 TD->getTypeSize(AI.getAllocatedType()) == 0)
Chris Lattnerabb77c92004-03-19 06:08:10 +00005313 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
5314
Chris Lattner1085bdf2002-11-04 16:18:53 +00005315 return 0;
5316}
5317
Chris Lattner8427bff2003-12-07 01:24:23 +00005318Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
5319 Value *Op = FI.getOperand(0);
5320
5321 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
5322 if (CastInst *CI = dyn_cast<CastInst>(Op))
5323 if (isa<PointerType>(CI->getOperand(0)->getType())) {
5324 FI.setOperand(0, CI->getOperand(0));
5325 return &FI;
5326 }
5327
Chris Lattner8ba9ec92004-10-18 02:59:09 +00005328 // free undef -> unreachable.
5329 if (isa<UndefValue>(Op)) {
5330 // Insert a new store to null because we cannot modify the CFG here.
5331 new StoreInst(ConstantBool::True,
5332 UndefValue::get(PointerType::get(Type::BoolTy)), &FI);
5333 return EraseInstFromFunction(FI);
5334 }
5335
Chris Lattnerf3a36602004-02-28 04:57:37 +00005336 // If we have 'free null' delete the instruction. This can happen in stl code
5337 // when lots of inlining happens.
Chris Lattner8ba9ec92004-10-18 02:59:09 +00005338 if (isa<ConstantPointerNull>(Op))
Chris Lattner51ea1272004-02-28 05:22:00 +00005339 return EraseInstFromFunction(FI);
Chris Lattnerf3a36602004-02-28 04:57:37 +00005340
Chris Lattner8427bff2003-12-07 01:24:23 +00005341 return 0;
5342}
5343
5344
Chris Lattner72684fe2005-01-31 05:51:45 +00005345/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Chris Lattner35e24772004-07-13 01:49:43 +00005346static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
5347 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00005348 Value *CastOp = CI->getOperand(0);
Chris Lattner35e24772004-07-13 01:49:43 +00005349
5350 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00005351 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Chris Lattner35e24772004-07-13 01:49:43 +00005352 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00005353
5354 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
5355 // If the source is an array, the code below will not succeed. Check to
5356 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
5357 // constants.
5358 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
5359 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
5360 if (ASrcTy->getNumElements() != 0) {
5361 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
5362 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
5363 SrcTy = cast<PointerType>(CastOp->getType());
5364 SrcPTy = SrcTy->getElementType();
5365 }
5366
5367 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
Chris Lattnerecfa9b52005-03-29 06:37:47 +00005368 // Do not allow turning this into a load of an integer, which is then
5369 // casted to a pointer, this pessimizes pointer analysis a lot.
5370 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00005371 IC.getTargetData().getTypeSize(SrcPTy) ==
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00005372 IC.getTargetData().getTypeSize(DestPTy)) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00005373
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00005374 // Okay, we are casting from one integer or pointer type to another of
5375 // the same size. Instead of casting the pointer before the load, cast
5376 // the result of the loaded value.
5377 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
5378 CI->getName(),
5379 LI.isVolatile()),LI);
5380 // Now cast the result of the load.
5381 return new CastInst(NewLoad, LI.getType());
5382 }
Chris Lattner35e24772004-07-13 01:49:43 +00005383 }
5384 }
5385 return 0;
5386}
5387
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00005388/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattnere6f13092004-09-19 19:18:10 +00005389/// from this value cannot trap. If it is not obviously safe to load from the
5390/// specified pointer, we do a quick local scan of the basic block containing
5391/// ScanFrom, to determine if the address is already accessed.
5392static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
5393 // If it is an alloca or global variable, it is always safe to load from.
5394 if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
5395
5396 // Otherwise, be a little bit agressive by scanning the local block where we
5397 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00005398 // from/to. If so, the previous load or store would have already trapped,
5399 // so there is no harm doing an extra load (also, CSE will later eliminate
5400 // the load entirely).
Chris Lattnere6f13092004-09-19 19:18:10 +00005401 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
5402
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00005403 while (BBI != E) {
Chris Lattnere6f13092004-09-19 19:18:10 +00005404 --BBI;
5405
5406 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
5407 if (LI->getOperand(0) == V) return true;
5408 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
5409 if (SI->getOperand(1) == V) return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +00005410
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00005411 }
Chris Lattnere6f13092004-09-19 19:18:10 +00005412 return false;
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00005413}
5414
Chris Lattner0f1d8a32003-06-26 05:06:25 +00005415Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
5416 Value *Op = LI.getOperand(0);
Chris Lattner7e8af382004-01-12 04:13:56 +00005417
Chris Lattnera9d84e32005-05-01 04:24:53 +00005418 // load (cast X) --> cast (load X) iff safe
5419 if (CastInst *CI = dyn_cast<CastInst>(Op))
5420 if (Instruction *Res = InstCombineLoadCast(*this, LI))
5421 return Res;
5422
5423 // None of the following transforms are legal for volatile loads.
5424 if (LI.isVolatile()) return 0;
Chris Lattnerb990f7d2005-09-12 22:00:15 +00005425
Chris Lattnerb990f7d2005-09-12 22:00:15 +00005426 if (&LI.getParent()->front() != &LI) {
5427 BasicBlock::iterator BBI = &LI; --BBI;
Chris Lattnere0bfdf12005-09-12 22:21:03 +00005428 // If the instruction immediately before this is a store to the same
5429 // address, do a simple form of store->load forwarding.
Chris Lattnerb990f7d2005-09-12 22:00:15 +00005430 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
5431 if (SI->getOperand(1) == LI.getOperand(0))
5432 return ReplaceInstUsesWith(LI, SI->getOperand(0));
Chris Lattnere0bfdf12005-09-12 22:21:03 +00005433 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
5434 if (LIB->getOperand(0) == LI.getOperand(0))
5435 return ReplaceInstUsesWith(LI, LIB);
Chris Lattnerb990f7d2005-09-12 22:00:15 +00005436 }
Chris Lattnera9d84e32005-05-01 04:24:53 +00005437
5438 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op))
5439 if (isa<ConstantPointerNull>(GEPI->getOperand(0)) ||
5440 isa<UndefValue>(GEPI->getOperand(0))) {
5441 // Insert a new store to null instruction before the load to indicate
5442 // that this code is not reachable. We do this instead of inserting
5443 // an unreachable instruction directly because we cannot modify the
5444 // CFG.
5445 new StoreInst(UndefValue::get(LI.getType()),
5446 Constant::getNullValue(Op->getType()), &LI);
5447 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
5448 }
5449
Chris Lattner81a7a232004-10-16 18:11:37 +00005450 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattnera9d84e32005-05-01 04:24:53 +00005451 // load null/undef -> undef
5452 if ((C->isNullValue() || isa<UndefValue>(C))) {
Chris Lattner8ba9ec92004-10-18 02:59:09 +00005453 // Insert a new store to null instruction before the load to indicate that
5454 // this code is not reachable. We do this instead of inserting an
5455 // unreachable instruction directly because we cannot modify the CFG.
Chris Lattnera9d84e32005-05-01 04:24:53 +00005456 new StoreInst(UndefValue::get(LI.getType()),
5457 Constant::getNullValue(Op->getType()), &LI);
Chris Lattner81a7a232004-10-16 18:11:37 +00005458 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner8ba9ec92004-10-18 02:59:09 +00005459 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00005460
Chris Lattner81a7a232004-10-16 18:11:37 +00005461 // Instcombine load (constant global) into the value loaded.
5462 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
5463 if (GV->isConstant() && !GV->isExternal())
5464 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanb1c93172005-04-21 23:48:37 +00005465
Chris Lattner81a7a232004-10-16 18:11:37 +00005466 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
5467 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
5468 if (CE->getOpcode() == Instruction::GetElementPtr) {
5469 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
5470 if (GV->isConstant() && !GV->isExternal())
Chris Lattner0b011ec2005-09-26 05:28:06 +00005471 if (Constant *V =
5472 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
Chris Lattner81a7a232004-10-16 18:11:37 +00005473 return ReplaceInstUsesWith(LI, V);
Chris Lattnera9d84e32005-05-01 04:24:53 +00005474 if (CE->getOperand(0)->isNullValue()) {
5475 // Insert a new store to null instruction before the load to indicate
5476 // that this code is not reachable. We do this instead of inserting
5477 // an unreachable instruction directly because we cannot modify the
5478 // CFG.
5479 new StoreInst(UndefValue::get(LI.getType()),
5480 Constant::getNullValue(Op->getType()), &LI);
5481 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
5482 }
5483
Chris Lattner81a7a232004-10-16 18:11:37 +00005484 } else if (CE->getOpcode() == Instruction::Cast) {
5485 if (Instruction *Res = InstCombineLoadCast(*this, LI))
5486 return Res;
5487 }
5488 }
Chris Lattnere228ee52004-04-08 20:39:49 +00005489
Chris Lattnera9d84e32005-05-01 04:24:53 +00005490 if (Op->hasOneUse()) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00005491 // Change select and PHI nodes to select values instead of addresses: this
5492 // helps alias analysis out a lot, allows many others simplifications, and
5493 // exposes redundancy in the code.
5494 //
5495 // Note that we cannot do the transformation unless we know that the
5496 // introduced loads cannot trap! Something like this is valid as long as
5497 // the condition is always false: load (select bool %C, int* null, int* %G),
5498 // but it would not be valid if we transformed it to load from null
5499 // unconditionally.
5500 //
5501 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
5502 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattnere6f13092004-09-19 19:18:10 +00005503 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
5504 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00005505 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner42618552004-09-20 10:15:10 +00005506 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00005507 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner42618552004-09-20 10:15:10 +00005508 SI->getOperand(2)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00005509 return new SelectInst(SI->getCondition(), V1, V2);
5510 }
5511
Chris Lattnerbdcf41a2004-09-23 15:46:00 +00005512 // load (select (cond, null, P)) -> load P
5513 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
5514 if (C->isNullValue()) {
5515 LI.setOperand(0, SI->getOperand(2));
5516 return &LI;
5517 }
5518
5519 // load (select (cond, P, null)) -> load P
5520 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
5521 if (C->isNullValue()) {
5522 LI.setOperand(0, SI->getOperand(1));
5523 return &LI;
5524 }
5525
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00005526 } else if (PHINode *PN = dyn_cast<PHINode>(Op)) {
5527 // load (phi (&V1, &V2, &V3)) --> phi(load &V1, load &V2, load &V3)
Chris Lattner42618552004-09-20 10:15:10 +00005528 bool Safe = PN->getParent() == LI.getParent();
5529
5530 // Scan all of the instructions between the PHI and the load to make
5531 // sure there are no instructions that might possibly alter the value
5532 // loaded from the PHI.
5533 if (Safe) {
5534 BasicBlock::iterator I = &LI;
5535 for (--I; !isa<PHINode>(I); --I)
5536 if (isa<StoreInst>(I) || isa<CallInst>(I)) {
5537 Safe = false;
5538 break;
5539 }
5540 }
5541
5542 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e && Safe; ++i)
Chris Lattnere6f13092004-09-19 19:18:10 +00005543 if (!isSafeToLoadUnconditionally(PN->getIncomingValue(i),
Chris Lattner42618552004-09-20 10:15:10 +00005544 PN->getIncomingBlock(i)->getTerminator()))
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00005545 Safe = false;
Chris Lattner42618552004-09-20 10:15:10 +00005546
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00005547 if (Safe) {
5548 // Create the PHI.
5549 PHINode *NewPN = new PHINode(LI.getType(), PN->getName());
5550 InsertNewInstBefore(NewPN, *PN);
5551 std::map<BasicBlock*,Value*> LoadMap; // Don't insert duplicate loads
5552
5553 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
5554 BasicBlock *BB = PN->getIncomingBlock(i);
5555 Value *&TheLoad = LoadMap[BB];
5556 if (TheLoad == 0) {
5557 Value *InVal = PN->getIncomingValue(i);
5558 TheLoad = InsertNewInstBefore(new LoadInst(InVal,
5559 InVal->getName()+".val"),
5560 *BB->getTerminator());
5561 }
5562 NewPN->addIncoming(TheLoad, BB);
5563 }
5564 return ReplaceInstUsesWith(LI, NewPN);
5565 }
5566 }
5567 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00005568 return 0;
5569}
5570
Chris Lattner72684fe2005-01-31 05:51:45 +00005571/// InstCombineStoreToCast - Fold 'store V, (cast P)' -> store (cast V), P'
5572/// when possible.
5573static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
5574 User *CI = cast<User>(SI.getOperand(1));
5575 Value *CastOp = CI->getOperand(0);
5576
5577 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
5578 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
5579 const Type *SrcPTy = SrcTy->getElementType();
5580
5581 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
5582 // If the source is an array, the code below will not succeed. Check to
5583 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
5584 // constants.
5585 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
5586 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
5587 if (ASrcTy->getNumElements() != 0) {
5588 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
5589 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
5590 SrcTy = cast<PointerType>(CastOp->getType());
5591 SrcPTy = SrcTy->getElementType();
5592 }
5593
5594 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00005595 IC.getTargetData().getTypeSize(SrcPTy) ==
Chris Lattner72684fe2005-01-31 05:51:45 +00005596 IC.getTargetData().getTypeSize(DestPTy)) {
5597
5598 // Okay, we are casting from one integer or pointer type to another of
5599 // the same size. Instead of casting the pointer before the store, cast
5600 // the value to be stored.
5601 Value *NewCast;
5602 if (Constant *C = dyn_cast<Constant>(SI.getOperand(0)))
5603 NewCast = ConstantExpr::getCast(C, SrcPTy);
5604 else
5605 NewCast = IC.InsertNewInstBefore(new CastInst(SI.getOperand(0),
5606 SrcPTy,
5607 SI.getOperand(0)->getName()+".c"), SI);
5608
5609 return new StoreInst(NewCast, CastOp);
5610 }
5611 }
5612 }
5613 return 0;
5614}
5615
Chris Lattner31f486c2005-01-31 05:36:43 +00005616Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
5617 Value *Val = SI.getOperand(0);
5618 Value *Ptr = SI.getOperand(1);
5619
5620 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
5621 removeFromWorkList(&SI);
5622 SI.eraseFromParent();
5623 ++NumCombined;
5624 return 0;
5625 }
5626
5627 if (SI.isVolatile()) return 0; // Don't hack volatile loads.
5628
5629 // store X, null -> turns into 'unreachable' in SimplifyCFG
5630 if (isa<ConstantPointerNull>(Ptr)) {
5631 if (!isa<UndefValue>(Val)) {
5632 SI.setOperand(0, UndefValue::get(Val->getType()));
5633 if (Instruction *U = dyn_cast<Instruction>(Val))
5634 WorkList.push_back(U); // Dropped a use.
5635 ++NumCombined;
5636 }
5637 return 0; // Do not modify these!
5638 }
5639
5640 // store undef, Ptr -> noop
5641 if (isa<UndefValue>(Val)) {
5642 removeFromWorkList(&SI);
5643 SI.eraseFromParent();
5644 ++NumCombined;
5645 return 0;
5646 }
5647
Chris Lattner72684fe2005-01-31 05:51:45 +00005648 // If the pointer destination is a cast, see if we can fold the cast into the
5649 // source instead.
5650 if (CastInst *CI = dyn_cast<CastInst>(Ptr))
5651 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
5652 return Res;
5653 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
5654 if (CE->getOpcode() == Instruction::Cast)
5655 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
5656 return Res;
5657
Chris Lattner219175c2005-09-12 23:23:25 +00005658
5659 // If this store is the last instruction in the basic block, and if the block
5660 // ends with an unconditional branch, try to move it to the successor block.
5661 BasicBlock::iterator BBI = &SI; ++BBI;
5662 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
5663 if (BI->isUnconditional()) {
5664 // Check to see if the successor block has exactly two incoming edges. If
5665 // so, see if the other predecessor contains a store to the same location.
5666 // if so, insert a PHI node (if needed) and move the stores down.
5667 BasicBlock *Dest = BI->getSuccessor(0);
5668
5669 pred_iterator PI = pred_begin(Dest);
5670 BasicBlock *Other = 0;
5671 if (*PI != BI->getParent())
5672 Other = *PI;
5673 ++PI;
5674 if (PI != pred_end(Dest)) {
5675 if (*PI != BI->getParent())
5676 if (Other)
5677 Other = 0;
5678 else
5679 Other = *PI;
5680 if (++PI != pred_end(Dest))
5681 Other = 0;
5682 }
5683 if (Other) { // If only one other pred...
5684 BBI = Other->getTerminator();
5685 // Make sure this other block ends in an unconditional branch and that
5686 // there is an instruction before the branch.
5687 if (isa<BranchInst>(BBI) && cast<BranchInst>(BBI)->isUnconditional() &&
5688 BBI != Other->begin()) {
5689 --BBI;
5690 StoreInst *OtherStore = dyn_cast<StoreInst>(BBI);
5691
5692 // If this instruction is a store to the same location.
5693 if (OtherStore && OtherStore->getOperand(1) == SI.getOperand(1)) {
5694 // Okay, we know we can perform this transformation. Insert a PHI
5695 // node now if we need it.
5696 Value *MergedVal = OtherStore->getOperand(0);
5697 if (MergedVal != SI.getOperand(0)) {
5698 PHINode *PN = new PHINode(MergedVal->getType(), "storemerge");
5699 PN->reserveOperandSpace(2);
5700 PN->addIncoming(SI.getOperand(0), SI.getParent());
5701 PN->addIncoming(OtherStore->getOperand(0), Other);
5702 MergedVal = InsertNewInstBefore(PN, Dest->front());
5703 }
5704
5705 // Advance to a place where it is safe to insert the new store and
5706 // insert it.
5707 BBI = Dest->begin();
5708 while (isa<PHINode>(BBI)) ++BBI;
5709 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
5710 OtherStore->isVolatile()), *BBI);
5711
5712 // Nuke the old stores.
5713 removeFromWorkList(&SI);
5714 removeFromWorkList(OtherStore);
5715 SI.eraseFromParent();
5716 OtherStore->eraseFromParent();
5717 ++NumCombined;
5718 return 0;
5719 }
5720 }
5721 }
5722 }
5723
Chris Lattner31f486c2005-01-31 05:36:43 +00005724 return 0;
5725}
5726
5727
Chris Lattner9eef8a72003-06-04 04:46:00 +00005728Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
5729 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4fdd96c2005-06-18 17:37:34 +00005730 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00005731 BasicBlock *TrueDest;
5732 BasicBlock *FalseDest;
5733 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
5734 !isa<Constant>(X)) {
5735 // Swap Destinations and condition...
5736 BI.setCondition(X);
5737 BI.setSuccessor(0, FalseDest);
5738 BI.setSuccessor(1, TrueDest);
5739 return &BI;
5740 }
5741
5742 // Cannonicalize setne -> seteq
5743 Instruction::BinaryOps Op; Value *Y;
5744 if (match(&BI, m_Br(m_SetCond(Op, m_Value(X), m_Value(Y)),
5745 TrueDest, FalseDest)))
5746 if ((Op == Instruction::SetNE || Op == Instruction::SetLE ||
5747 Op == Instruction::SetGE) && BI.getCondition()->hasOneUse()) {
5748 SetCondInst *I = cast<SetCondInst>(BI.getCondition());
5749 std::string Name = I->getName(); I->setName("");
5750 Instruction::BinaryOps NewOpcode = SetCondInst::getInverseCondition(Op);
5751 Value *NewSCC = BinaryOperator::create(NewOpcode, X, Y, Name, I);
Chris Lattnere967b342003-06-04 05:10:11 +00005752 // Swap Destinations and condition...
Chris Lattnerd4252a72004-07-30 07:50:03 +00005753 BI.setCondition(NewSCC);
Chris Lattnere967b342003-06-04 05:10:11 +00005754 BI.setSuccessor(0, FalseDest);
5755 BI.setSuccessor(1, TrueDest);
Chris Lattnerd4252a72004-07-30 07:50:03 +00005756 removeFromWorkList(I);
5757 I->getParent()->getInstList().erase(I);
5758 WorkList.push_back(cast<Instruction>(NewSCC));
Chris Lattnere967b342003-06-04 05:10:11 +00005759 return &BI;
5760 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00005761
Chris Lattner9eef8a72003-06-04 04:46:00 +00005762 return 0;
5763}
Chris Lattner1085bdf2002-11-04 16:18:53 +00005764
Chris Lattner4c9c20a2004-07-03 00:26:11 +00005765Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
5766 Value *Cond = SI.getCondition();
5767 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
5768 if (I->getOpcode() == Instruction::Add)
5769 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
5770 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
5771 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattner81a7a232004-10-16 18:11:37 +00005772 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner4c9c20a2004-07-03 00:26:11 +00005773 AddRHS));
5774 SI.setOperand(0, I->getOperand(0));
5775 WorkList.push_back(I);
5776 return &SI;
5777 }
5778 }
5779 return 0;
5780}
5781
Chris Lattner99f48c62002-09-02 04:59:56 +00005782void InstCombiner::removeFromWorkList(Instruction *I) {
5783 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
5784 WorkList.end());
5785}
5786
Chris Lattner39c98bb2004-12-08 23:43:58 +00005787
5788/// TryToSinkInstruction - Try to move the specified instruction from its
5789/// current block into the beginning of DestBlock, which can only happen if it's
5790/// safe to move the instruction past all of the instructions between it and the
5791/// end of its block.
5792static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
5793 assert(I->hasOneUse() && "Invariants didn't hold!");
5794
Chris Lattnerc4f67e62005-10-27 17:13:11 +00005795 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
5796 if (isa<PHINode>(I) || I->mayWriteToMemory()) return false;
Misha Brukmanb1c93172005-04-21 23:48:37 +00005797
Chris Lattner39c98bb2004-12-08 23:43:58 +00005798 // Do not sink alloca instructions out of the entry block.
5799 if (isa<AllocaInst>(I) && I->getParent() == &DestBlock->getParent()->front())
5800 return false;
5801
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00005802 // We can only sink load instructions if there is nothing between the load and
5803 // the end of block that could change the value.
5804 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00005805 for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
5806 Scan != E; ++Scan)
5807 if (Scan->mayWriteToMemory())
5808 return false;
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00005809 }
Chris Lattner39c98bb2004-12-08 23:43:58 +00005810
5811 BasicBlock::iterator InsertPos = DestBlock->begin();
5812 while (isa<PHINode>(InsertPos)) ++InsertPos;
5813
Chris Lattner9f269e42005-08-08 19:11:57 +00005814 I->moveBefore(InsertPos);
Chris Lattner39c98bb2004-12-08 23:43:58 +00005815 ++NumSunkInst;
5816 return true;
5817}
5818
Chris Lattner113f4f42002-06-25 16:13:24 +00005819bool InstCombiner::runOnFunction(Function &F) {
Chris Lattner260ab202002-04-18 17:39:14 +00005820 bool Changed = false;
Chris Lattnerf4ad1652003-11-02 05:57:39 +00005821 TD = &getAnalysis<TargetData>();
Chris Lattnerca081252001-12-14 16:52:21 +00005822
Chris Lattner4ed40f72005-07-07 20:40:38 +00005823 {
5824 // Populate the worklist with the reachable instructions.
5825 std::set<BasicBlock*> Visited;
5826 for (df_ext_iterator<BasicBlock*> BB = df_ext_begin(&F.front(), Visited),
5827 E = df_ext_end(&F.front(), Visited); BB != E; ++BB)
5828 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
5829 WorkList.push_back(I);
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00005830
Chris Lattner4ed40f72005-07-07 20:40:38 +00005831 // Do a quick scan over the function. If we find any blocks that are
5832 // unreachable, remove any instructions inside of them. This prevents
5833 // the instcombine code from having to deal with some bad special cases.
5834 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
5835 if (!Visited.count(BB)) {
5836 Instruction *Term = BB->getTerminator();
5837 while (Term != BB->begin()) { // Remove instrs bottom-up
5838 BasicBlock::iterator I = Term; --I;
Chris Lattner2d3a7a62004-04-27 15:13:33 +00005839
Chris Lattner4ed40f72005-07-07 20:40:38 +00005840 DEBUG(std::cerr << "IC: DCE: " << *I);
5841 ++NumDeadInst;
5842
5843 if (!I->use_empty())
5844 I->replaceAllUsesWith(UndefValue::get(I->getType()));
5845 I->eraseFromParent();
5846 }
5847 }
5848 }
Chris Lattnerca081252001-12-14 16:52:21 +00005849
5850 while (!WorkList.empty()) {
5851 Instruction *I = WorkList.back(); // Get an instruction from the worklist
5852 WorkList.pop_back();
5853
Misha Brukman632df282002-10-29 23:06:16 +00005854 // Check to see if we can DCE or ConstantPropagate the instruction...
Chris Lattner99f48c62002-09-02 04:59:56 +00005855 // Check to see if we can DIE the instruction...
5856 if (isInstructionTriviallyDead(I)) {
5857 // Add operands to the worklist...
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00005858 if (I->getNumOperands() < 4)
Chris Lattner51ea1272004-02-28 05:22:00 +00005859 AddUsesToWorkList(*I);
Chris Lattner99f48c62002-09-02 04:59:56 +00005860 ++NumDeadInst;
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00005861
Chris Lattnercd517ff2005-01-28 19:32:01 +00005862 DEBUG(std::cerr << "IC: DCE: " << *I);
5863
5864 I->eraseFromParent();
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00005865 removeFromWorkList(I);
5866 continue;
5867 }
Chris Lattner99f48c62002-09-02 04:59:56 +00005868
Misha Brukman632df282002-10-29 23:06:16 +00005869 // Instruction isn't dead, see if we can constant propagate it...
Chris Lattner99f48c62002-09-02 04:59:56 +00005870 if (Constant *C = ConstantFoldInstruction(I)) {
Alkis Evlogimenosa1291a02004-12-08 23:10:30 +00005871 Value* Ptr = I->getOperand(0);
Chris Lattner6580e092004-10-16 19:44:59 +00005872 if (isa<GetElementPtrInst>(I) &&
Alkis Evlogimenosa1291a02004-12-08 23:10:30 +00005873 cast<Constant>(Ptr)->isNullValue() &&
5874 !isa<ConstantPointerNull>(C) &&
5875 cast<PointerType>(Ptr->getType())->getElementType()->isSized()) {
Chris Lattner6580e092004-10-16 19:44:59 +00005876 // If this is a constant expr gep that is effectively computing an
5877 // "offsetof", fold it into 'cast int X to T*' instead of 'gep 0, 0, 12'
5878 bool isFoldableGEP = true;
5879 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i)
5880 if (!isa<ConstantInt>(I->getOperand(i)))
5881 isFoldableGEP = false;
5882 if (isFoldableGEP) {
Alkis Evlogimenosa1291a02004-12-08 23:10:30 +00005883 uint64_t Offset = TD->getIndexedOffset(Ptr->getType(),
Chris Lattner6580e092004-10-16 19:44:59 +00005884 std::vector<Value*>(I->op_begin()+1, I->op_end()));
5885 C = ConstantUInt::get(Type::ULongTy, Offset);
Chris Lattner684c5c62004-10-16 19:46:33 +00005886 C = ConstantExpr::getCast(C, TD->getIntPtrType());
Chris Lattner6580e092004-10-16 19:44:59 +00005887 C = ConstantExpr::getCast(C, I->getType());
5888 }
5889 }
5890
Chris Lattnercd517ff2005-01-28 19:32:01 +00005891 DEBUG(std::cerr << "IC: ConstFold to: " << *C << " from: " << *I);
5892
Chris Lattner99f48c62002-09-02 04:59:56 +00005893 // Add operands to the worklist...
Chris Lattner51ea1272004-02-28 05:22:00 +00005894 AddUsesToWorkList(*I);
Chris Lattnerc6509f42002-12-05 22:41:53 +00005895 ReplaceInstUsesWith(*I, C);
5896
Chris Lattner99f48c62002-09-02 04:59:56 +00005897 ++NumConstProp;
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00005898 I->getParent()->getInstList().erase(I);
Chris Lattner800aaaf2003-10-07 15:17:02 +00005899 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00005900 continue;
Chris Lattner99f48c62002-09-02 04:59:56 +00005901 }
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00005902
Chris Lattner39c98bb2004-12-08 23:43:58 +00005903 // See if we can trivially sink this instruction to a successor basic block.
5904 if (I->hasOneUse()) {
5905 BasicBlock *BB = I->getParent();
5906 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
5907 if (UserParent != BB) {
5908 bool UserIsSuccessor = false;
5909 // See if the user is one of our successors.
5910 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
5911 if (*SI == UserParent) {
5912 UserIsSuccessor = true;
5913 break;
5914 }
5915
5916 // If the user is one of our immediate successors, and if that successor
5917 // only has us as a predecessors (we'd have to split the critical edge
5918 // otherwise), we can keep going.
5919 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
5920 next(pred_begin(UserParent)) == pred_end(UserParent))
5921 // Okay, the CFG is simple enough, try to sink this instruction.
5922 Changed |= TryToSinkInstruction(I, UserParent);
5923 }
5924 }
5925
Chris Lattnerca081252001-12-14 16:52:21 +00005926 // Now that we have an instruction, try combining it to simplify it...
Chris Lattnerae7a0d32002-08-02 19:29:35 +00005927 if (Instruction *Result = visit(*I)) {
Chris Lattner0b18c1d2002-05-10 15:38:35 +00005928 ++NumCombined;
Chris Lattner260ab202002-04-18 17:39:14 +00005929 // Should we replace the old instruction with a new one?
Chris Lattner053c0932002-05-14 15:24:07 +00005930 if (Result != I) {
Chris Lattner7d2a5392004-03-13 23:54:27 +00005931 DEBUG(std::cerr << "IC: Old = " << *I
5932 << " New = " << *Result);
5933
Chris Lattner396dbfe2004-06-09 05:08:07 +00005934 // Everything uses the new instruction now.
5935 I->replaceAllUsesWith(Result);
5936
5937 // Push the new instruction and any users onto the worklist.
5938 WorkList.push_back(Result);
5939 AddUsersToWorkList(*Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00005940
5941 // Move the name to the new instruction first...
5942 std::string OldName = I->getName(); I->setName("");
Chris Lattner950fc782003-10-07 22:58:41 +00005943 Result->setName(OldName);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00005944
5945 // Insert the new instruction into the basic block...
5946 BasicBlock *InstParent = I->getParent();
Chris Lattner7515cab2004-11-14 19:13:23 +00005947 BasicBlock::iterator InsertPos = I;
5948
5949 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
5950 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
5951 ++InsertPos;
5952
5953 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00005954
Chris Lattner63d75af2004-05-01 23:27:23 +00005955 // Make sure that we reprocess all operands now that we reduced their
5956 // use counts.
Chris Lattnerb643a9e2004-05-01 23:19:52 +00005957 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
5958 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
5959 WorkList.push_back(OpI);
5960
Chris Lattner396dbfe2004-06-09 05:08:07 +00005961 // Instructions can end up on the worklist more than once. Make sure
5962 // we do not process an instruction that has been deleted.
5963 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00005964
5965 // Erase the old instruction.
5966 InstParent->getInstList().erase(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00005967 } else {
Chris Lattner7d2a5392004-03-13 23:54:27 +00005968 DEBUG(std::cerr << "IC: MOD = " << *I);
5969
Chris Lattnerae7a0d32002-08-02 19:29:35 +00005970 // If the instruction was modified, it's possible that it is now dead.
5971 // if so, remove it.
Chris Lattner63d75af2004-05-01 23:27:23 +00005972 if (isInstructionTriviallyDead(I)) {
5973 // Make sure we process all operands now that we are reducing their
5974 // use counts.
5975 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
5976 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
5977 WorkList.push_back(OpI);
Misha Brukmanb1c93172005-04-21 23:48:37 +00005978
Chris Lattner63d75af2004-05-01 23:27:23 +00005979 // Instructions may end up in the worklist more than once. Erase all
5980 // occurrances of this instruction.
Chris Lattner99f48c62002-09-02 04:59:56 +00005981 removeFromWorkList(I);
Chris Lattner31f486c2005-01-31 05:36:43 +00005982 I->eraseFromParent();
Chris Lattner396dbfe2004-06-09 05:08:07 +00005983 } else {
5984 WorkList.push_back(Result);
5985 AddUsersToWorkList(*Result);
Chris Lattnerae7a0d32002-08-02 19:29:35 +00005986 }
Chris Lattner053c0932002-05-14 15:24:07 +00005987 }
Chris Lattner260ab202002-04-18 17:39:14 +00005988 Changed = true;
Chris Lattnerca081252001-12-14 16:52:21 +00005989 }
5990 }
5991
Chris Lattner260ab202002-04-18 17:39:14 +00005992 return Changed;
Chris Lattner04805fa2002-02-26 21:46:54 +00005993}
5994
Brian Gaeke38b79e82004-07-27 17:43:21 +00005995FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattner260ab202002-04-18 17:39:14 +00005996 return new InstCombiner();
Chris Lattner04805fa2002-02-26 21:46:54 +00005997}
Brian Gaeke960707c2003-11-11 22:41:34 +00005998