blob: b326220499d109e0de2060664bb0cb754920f790 [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
Chris Lattner330628a2006-01-06 17:59:59 +0000724 ConstantInt *XorRHS = 0;
725 Value *XorLHS = 0;
Chris Lattner0b3557f2005-09-24 23:43:33 +0000726 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 Lattner330628a2006-01-06 17:59:59 +0000824 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +0000825 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 {
Chris Lattner330628a2006-01-06 17:59:59 +00001775 Value *X = 0; ConstantInt *C1 = 0;
Chris Lattner38a1b002005-10-26 17:18:16 +00001776 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 Lattner330628a2006-01-06 17:59:59 +00002079 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00002080 // (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 Lattner330628a2006-01-06 17:59:59 +00002106 Value *A = 0, *B = 0;
2107 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattner4294cec2005-05-07 23:49:08 +00002108
2109 if (match(Op0, m_And(m_Value(A), m_Value(B))))
2110 if (A == Op1 || B == Op1) // (A & ?) | A --> A
2111 return ReplaceInstUsesWith(I, Op1);
2112 if (match(Op1, m_And(m_Value(A), m_Value(B))))
2113 if (A == Op0 || B == Op0) // A | (A & ?) --> A
2114 return ReplaceInstUsesWith(I, Op0);
2115
Chris Lattnerb62f5082005-05-09 04:58:36 +00002116 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
2117 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
2118 MaskedValueIsZero(Op1, C1)) {
2119 Instruction *NOr = BinaryOperator::createOr(A, Op1, Op0->getName());
2120 Op0->setName("");
2121 return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
2122 }
2123
2124 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
2125 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
2126 MaskedValueIsZero(Op0, C1)) {
2127 Instruction *NOr = BinaryOperator::createOr(A, Op0, Op1->getName());
2128 Op0->setName("");
2129 return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
2130 }
2131
Chris Lattner15212982005-09-18 03:42:07 +00002132 // (A & C1)|(B & C2)
Chris Lattnerd4252a72004-07-30 07:50:03 +00002133 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattner15212982005-09-18 03:42:07 +00002134 match(Op1, m_And(m_Value(B), m_ConstantInt(C2)))) {
2135
2136 if (A == B) // (A & C1)|(A & C2) == A & (C1|C2)
2137 return BinaryOperator::createAnd(A, ConstantExpr::getOr(C1, C2));
2138
2139
Chris Lattner01f56c62005-09-18 06:02:59 +00002140 // If we have: ((V + N) & C1) | (V & C2)
2141 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
2142 // replace with V+N.
2143 if (C1 == ConstantExpr::getNot(C2)) {
Chris Lattner330628a2006-01-06 17:59:59 +00002144 Value *V1 = 0, *V2 = 0;
Chris Lattner01f56c62005-09-18 06:02:59 +00002145 if ((C2->getRawValue() & (C2->getRawValue()+1)) == 0 && // C2 == 0+1+
2146 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
2147 // Add commutes, try both ways.
2148 if (V1 == B && MaskedValueIsZero(V2, C2))
2149 return ReplaceInstUsesWith(I, A);
2150 if (V2 == B && MaskedValueIsZero(V1, C2))
2151 return ReplaceInstUsesWith(I, A);
2152 }
2153 // Or commutes, try both ways.
2154 if ((C1->getRawValue() & (C1->getRawValue()+1)) == 0 &&
2155 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
2156 // Add commutes, try both ways.
2157 if (V1 == A && MaskedValueIsZero(V2, C1))
2158 return ReplaceInstUsesWith(I, B);
2159 if (V2 == A && MaskedValueIsZero(V1, C1))
2160 return ReplaceInstUsesWith(I, B);
Chris Lattner15212982005-09-18 03:42:07 +00002161 }
2162 }
2163 }
Chris Lattner812aab72003-08-12 19:11:07 +00002164
Chris Lattnerd4252a72004-07-30 07:50:03 +00002165 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
2166 if (A == Op1) // ~A | A == -1
Misha Brukmanb1c93172005-04-21 23:48:37 +00002167 return ReplaceInstUsesWith(I,
Chris Lattnerd4252a72004-07-30 07:50:03 +00002168 ConstantIntegral::getAllOnesValue(I.getType()));
2169 } else {
2170 A = 0;
2171 }
Chris Lattner4294cec2005-05-07 23:49:08 +00002172 // Note, A is still live here!
Chris Lattnerd4252a72004-07-30 07:50:03 +00002173 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
2174 if (Op0 == B)
Misha Brukmanb1c93172005-04-21 23:48:37 +00002175 return ReplaceInstUsesWith(I,
Chris Lattnerd4252a72004-07-30 07:50:03 +00002176 ConstantIntegral::getAllOnesValue(I.getType()));
Chris Lattner3e327a42003-03-10 23:13:59 +00002177
Misha Brukman9c003d82004-07-30 12:50:08 +00002178 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattnerd4252a72004-07-30 07:50:03 +00002179 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
2180 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
2181 I.getName()+".demorgan"), I);
2182 return BinaryOperator::createNot(And);
2183 }
Chris Lattner3e327a42003-03-10 23:13:59 +00002184 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00002185
Chris Lattner3ac7c262003-08-13 20:16:26 +00002186 // (setcc1 A, B) | (setcc2 A, B) --> (setcc3 A, B)
Chris Lattnerdcf756e2004-09-28 22:33:08 +00002187 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1))) {
Chris Lattner3ac7c262003-08-13 20:16:26 +00002188 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
2189 return R;
2190
Chris Lattnerdcf756e2004-09-28 22:33:08 +00002191 Value *LHSVal, *RHSVal;
2192 ConstantInt *LHSCst, *RHSCst;
2193 Instruction::BinaryOps LHSCC, RHSCC;
2194 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
2195 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
2196 if (LHSVal == RHSVal && // Found (X setcc C1) | (X setcc C2)
2197 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
Misha Brukmanb1c93172005-04-21 23:48:37 +00002198 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
Chris Lattnerdcf756e2004-09-28 22:33:08 +00002199 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
2200 // Ensure that the larger constant is on the RHS.
2201 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
2202 SetCondInst *LHS = cast<SetCondInst>(Op0);
2203 if (cast<ConstantBool>(Cmp)->getValue()) {
2204 std::swap(LHS, RHS);
2205 std::swap(LHSCst, RHSCst);
2206 std::swap(LHSCC, RHSCC);
2207 }
2208
2209 // At this point, we know we have have two setcc instructions
2210 // comparing a value against two constants and or'ing the result
2211 // together. Because of the above check, we know that we only have
2212 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
2213 // FoldSetCCLogical check above), that the two constants are not
2214 // equal.
2215 assert(LHSCst != RHSCst && "Compares not folded above?");
2216
2217 switch (LHSCC) {
2218 default: assert(0 && "Unknown integer condition code!");
2219 case Instruction::SetEQ:
2220 switch (RHSCC) {
2221 default: assert(0 && "Unknown integer condition code!");
2222 case Instruction::SetEQ:
2223 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
2224 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
2225 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
2226 LHSVal->getName()+".off");
2227 InsertNewInstBefore(Add, I);
2228 const Type *UnsType = Add->getType()->getUnsignedVersion();
2229 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
2230 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
2231 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2232 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
2233 }
2234 break; // (X == 13 | X == 15) -> no change
2235
Chris Lattner5c219462005-04-19 06:04:18 +00002236 case Instruction::SetGT: // (X == 13 | X > 14) -> no change
2237 break;
Chris Lattnerdcf756e2004-09-28 22:33:08 +00002238 case Instruction::SetNE: // (X == 13 | X != 15) -> X != 15
2239 case Instruction::SetLT: // (X == 13 | X < 15) -> X < 15
2240 return ReplaceInstUsesWith(I, RHS);
2241 }
2242 break;
2243 case Instruction::SetNE:
2244 switch (RHSCC) {
2245 default: assert(0 && "Unknown integer condition code!");
Chris Lattnerdcf756e2004-09-28 22:33:08 +00002246 case Instruction::SetEQ: // (X != 13 | X == 15) -> X != 13
2247 case Instruction::SetGT: // (X != 13 | X > 15) -> X != 13
2248 return ReplaceInstUsesWith(I, LHS);
2249 case Instruction::SetNE: // (X != 13 | X != 15) -> true
Chris Lattner2ceb6ee2005-06-17 03:59:17 +00002250 case Instruction::SetLT: // (X != 13 | X < 15) -> true
Chris Lattnerdcf756e2004-09-28 22:33:08 +00002251 return ReplaceInstUsesWith(I, ConstantBool::True);
2252 }
2253 break;
2254 case Instruction::SetLT:
2255 switch (RHSCC) {
2256 default: assert(0 && "Unknown integer condition code!");
2257 case Instruction::SetEQ: // (X < 13 | X == 14) -> no change
2258 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00002259 case Instruction::SetGT: // (X < 13 | X > 15) -> (X-13) > 2
2260 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false, I);
Chris Lattnerdcf756e2004-09-28 22:33:08 +00002261 case Instruction::SetNE: // (X < 13 | X != 15) -> X != 15
2262 case Instruction::SetLT: // (X < 13 | X < 15) -> X < 15
2263 return ReplaceInstUsesWith(I, RHS);
2264 }
2265 break;
2266 case Instruction::SetGT:
2267 switch (RHSCC) {
2268 default: assert(0 && "Unknown integer condition code!");
2269 case Instruction::SetEQ: // (X > 13 | X == 15) -> X > 13
2270 case Instruction::SetGT: // (X > 13 | X > 15) -> X > 13
2271 return ReplaceInstUsesWith(I, LHS);
2272 case Instruction::SetNE: // (X > 13 | X != 15) -> true
2273 case Instruction::SetLT: // (X > 13 | X < 15) -> true
2274 return ReplaceInstUsesWith(I, ConstantBool::True);
2275 }
2276 }
2277 }
2278 }
Chris Lattner15212982005-09-18 03:42:07 +00002279
Chris Lattner113f4f42002-06-25 16:13:24 +00002280 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002281}
2282
Chris Lattnerc2076352004-02-16 01:20:27 +00002283// XorSelf - Implements: X ^ X --> 0
2284struct XorSelf {
2285 Value *RHS;
2286 XorSelf(Value *rhs) : RHS(rhs) {}
2287 bool shouldApply(Value *LHS) const { return LHS == RHS; }
2288 Instruction *apply(BinaryOperator &Xor) const {
2289 return &Xor;
2290 }
2291};
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002292
2293
Chris Lattner113f4f42002-06-25 16:13:24 +00002294Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00002295 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00002296 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002297
Chris Lattner81a7a232004-10-16 18:11:37 +00002298 if (isa<UndefValue>(Op1))
2299 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
2300
Chris Lattnerc2076352004-02-16 01:20:27 +00002301 // xor X, X = 0, even if X is nested in a sequence of Xor's.
2302 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
2303 assert(Result == &I && "AssociativeOpt didn't work?");
Chris Lattnere6794492002-08-12 21:17:25 +00002304 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc2076352004-02-16 01:20:27 +00002305 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002306
Chris Lattner97638592003-07-23 21:37:07 +00002307 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002308 // xor X, 0 == X
Chris Lattner97638592003-07-23 21:37:07 +00002309 if (RHS->isNullValue())
Chris Lattnere6794492002-08-12 21:17:25 +00002310 return ReplaceInstUsesWith(I, Op0);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002311
Chris Lattner97638592003-07-23 21:37:07 +00002312 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerb8d6e402002-08-20 18:24:26 +00002313 // xor (setcc A, B), true = not (setcc A, B) = setncc A, B
Chris Lattner97638592003-07-23 21:37:07 +00002314 if (SetCondInst *SCI = dyn_cast<SetCondInst>(Op0I))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002315 if (RHS == ConstantBool::True && SCI->hasOneUse())
Chris Lattnerb8d6e402002-08-20 18:24:26 +00002316 return new SetCondInst(SCI->getInverseCondition(),
2317 SCI->getOperand(0), SCI->getOperand(1));
Chris Lattnere5806662003-11-04 23:50:51 +00002318
Chris Lattner8f2f5982003-11-05 01:06:05 +00002319 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002320 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
2321 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002322 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
2323 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002324 ConstantInt::get(I.getType(), 1));
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002325 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002326 }
Chris Lattner023a4832004-06-18 06:07:51 +00002327
2328 // ~(~X & Y) --> (X | ~Y)
2329 if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
2330 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
2331 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
2332 Instruction *NotY =
Misha Brukmanb1c93172005-04-21 23:48:37 +00002333 BinaryOperator::createNot(Op0I->getOperand(1),
Chris Lattner023a4832004-06-18 06:07:51 +00002334 Op0I->getOperand(1)->getName()+".not");
2335 InsertNewInstBefore(NotY, I);
2336 return BinaryOperator::createOr(Op0NotVal, NotY);
2337 }
2338 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002339
Chris Lattner97638592003-07-23 21:37:07 +00002340 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattnere5806662003-11-04 23:50:51 +00002341 switch (Op0I->getOpcode()) {
2342 case Instruction::Add:
Chris Lattner0f68fa62003-11-04 23:37:10 +00002343 // ~(X-c) --> (-c-1)-X
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002344 if (RHS->isAllOnesValue()) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002345 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
2346 return BinaryOperator::createSub(
2347 ConstantExpr::getSub(NegOp0CI,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002348 ConstantInt::get(I.getType(), 1)),
Chris Lattner0f68fa62003-11-04 23:37:10 +00002349 Op0I->getOperand(0));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002350 }
Chris Lattnere5806662003-11-04 23:50:51 +00002351 break;
2352 case Instruction::And:
Chris Lattner97638592003-07-23 21:37:07 +00002353 // (X & C1) ^ C2 --> (X & C1) | C2 iff (C1&C2) == 0
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002354 if (ConstantExpr::getAnd(RHS, Op0CI)->isNullValue())
2355 return BinaryOperator::createOr(Op0, RHS);
Chris Lattnere5806662003-11-04 23:50:51 +00002356 break;
2357 case Instruction::Or:
Chris Lattner97638592003-07-23 21:37:07 +00002358 // (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002359 if (ConstantExpr::getAnd(RHS, Op0CI) == RHS)
Chris Lattnerc8e7e292004-06-10 02:12:35 +00002360 return BinaryOperator::createAnd(Op0, ConstantExpr::getNot(RHS));
Chris Lattnere5806662003-11-04 23:50:51 +00002361 break;
2362 default: break;
Chris Lattner97638592003-07-23 21:37:07 +00002363 }
Chris Lattnerb8d6e402002-08-20 18:24:26 +00002364 }
Chris Lattner183b3362004-04-09 19:05:30 +00002365
2366 // Try to fold constant and into select arguments.
2367 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00002368 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00002369 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002370 if (isa<PHINode>(Op0))
2371 if (Instruction *NV = FoldOpIntoPhi(I))
2372 return NV;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002373 }
2374
Chris Lattnerbb74e222003-03-10 23:06:50 +00002375 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00002376 if (X == Op1)
2377 return ReplaceInstUsesWith(I,
2378 ConstantIntegral::getAllOnesValue(I.getType()));
2379
Chris Lattnerbb74e222003-03-10 23:06:50 +00002380 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00002381 if (X == Op0)
2382 return ReplaceInstUsesWith(I,
2383 ConstantIntegral::getAllOnesValue(I.getType()));
2384
Chris Lattner1bbb7b62003-03-10 18:24:17 +00002385 if (Instruction *Op1I = dyn_cast<Instruction>(Op1))
Chris Lattnerb36d9082004-02-16 03:54:20 +00002386 if (Op1I->getOpcode() == Instruction::Or) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00002387 if (Op1I->getOperand(0) == Op0) { // B^(B|A) == (A|B)^B
2388 cast<BinaryOperator>(Op1I)->swapOperands();
2389 I.swapOperands();
2390 std::swap(Op0, Op1);
2391 } else if (Op1I->getOperand(1) == Op0) { // B^(A|B) == (A|B)^B
2392 I.swapOperands();
2393 std::swap(Op0, Op1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002394 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00002395 } else if (Op1I->getOpcode() == Instruction::Xor) {
2396 if (Op0 == Op1I->getOperand(0)) // A^(A^B) == B
2397 return ReplaceInstUsesWith(I, Op1I->getOperand(1));
2398 else if (Op0 == Op1I->getOperand(1)) // A^(B^A) == B
2399 return ReplaceInstUsesWith(I, Op1I->getOperand(0));
2400 }
Chris Lattner1bbb7b62003-03-10 18:24:17 +00002401
2402 if (Instruction *Op0I = dyn_cast<Instruction>(Op0))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002403 if (Op0I->getOpcode() == Instruction::Or && Op0I->hasOneUse()) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00002404 if (Op0I->getOperand(0) == Op1) // (B|A)^B == (A|B)^B
2405 cast<BinaryOperator>(Op0I)->swapOperands();
Chris Lattnerdcf240a2003-03-10 21:43:22 +00002406 if (Op0I->getOperand(1) == Op1) { // (A|B)^B == A & ~B
Chris Lattner396dbfe2004-06-09 05:08:07 +00002407 Value *NotB = InsertNewInstBefore(BinaryOperator::createNot(Op1,
2408 Op1->getName()+".not"), I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002409 return BinaryOperator::createAnd(Op0I->getOperand(0), NotB);
Chris Lattner1bbb7b62003-03-10 18:24:17 +00002410 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00002411 } else if (Op0I->getOpcode() == Instruction::Xor) {
2412 if (Op1 == Op0I->getOperand(0)) // (A^B)^A == B
2413 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2414 else if (Op1 == Op0I->getOperand(1)) // (B^A)^A == B
2415 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner1bbb7b62003-03-10 18:24:17 +00002416 }
2417
Chris Lattner7aa2d472004-08-01 19:42:59 +00002418 // (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattner330628a2006-01-06 17:59:59 +00002419 ConstantInt *C1 = 0, *C2 = 0;
2420 if (match(Op0, m_And(m_Value(), m_ConstantInt(C1))) &&
2421 match(Op1, m_And(m_Value(), m_ConstantInt(C2))) &&
Chris Lattner7aa2d472004-08-01 19:42:59 +00002422 ConstantExpr::getAnd(C1, C2)->isNullValue())
Chris Lattnerd4252a72004-07-30 07:50:03 +00002423 return BinaryOperator::createOr(Op0, Op1);
Chris Lattner7fb29e12003-03-11 00:12:48 +00002424
Chris Lattner3ac7c262003-08-13 20:16:26 +00002425 // (setcc1 A, B) ^ (setcc2 A, B) --> (setcc3 A, B)
2426 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
2427 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
2428 return R;
2429
Chris Lattner113f4f42002-06-25 16:13:24 +00002430 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002431}
2432
Chris Lattner6862fbd2004-09-29 17:40:11 +00002433/// MulWithOverflow - Compute Result = In1*In2, returning true if the result
2434/// overflowed for this type.
2435static bool MulWithOverflow(ConstantInt *&Result, ConstantInt *In1,
2436 ConstantInt *In2) {
2437 Result = cast<ConstantInt>(ConstantExpr::getMul(In1, In2));
2438 return !In2->isNullValue() && ConstantExpr::getDiv(Result, In2) != In1;
2439}
2440
2441static bool isPositive(ConstantInt *C) {
2442 return cast<ConstantSInt>(C)->getValue() >= 0;
2443}
2444
2445/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
2446/// overflowed for this type.
2447static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
2448 ConstantInt *In2) {
2449 Result = cast<ConstantInt>(ConstantExpr::getAdd(In1, In2));
2450
2451 if (In1->getType()->isUnsigned())
2452 return cast<ConstantUInt>(Result)->getValue() <
2453 cast<ConstantUInt>(In1)->getValue();
2454 if (isPositive(In1) != isPositive(In2))
2455 return false;
2456 if (isPositive(In1))
2457 return cast<ConstantSInt>(Result)->getValue() <
2458 cast<ConstantSInt>(In1)->getValue();
2459 return cast<ConstantSInt>(Result)->getValue() >
2460 cast<ConstantSInt>(In1)->getValue();
2461}
2462
Chris Lattner0798af32005-01-13 20:14:25 +00002463/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
2464/// code necessary to compute the offset from the base pointer (without adding
2465/// in the base pointer). Return the result as a signed integer of intptr size.
2466static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
2467 TargetData &TD = IC.getTargetData();
2468 gep_type_iterator GTI = gep_type_begin(GEP);
2469 const Type *UIntPtrTy = TD.getIntPtrType();
2470 const Type *SIntPtrTy = UIntPtrTy->getSignedVersion();
2471 Value *Result = Constant::getNullValue(SIntPtrTy);
2472
2473 // Build a mask for high order bits.
2474 uint64_t PtrSizeMask = ~0ULL;
2475 PtrSizeMask >>= 64-(TD.getPointerSize()*8);
2476
Chris Lattner0798af32005-01-13 20:14:25 +00002477 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
2478 Value *Op = GEP->getOperand(i);
Chris Lattnerd35d2102005-01-13 23:26:48 +00002479 uint64_t Size = TD.getTypeSize(GTI.getIndexedType()) & PtrSizeMask;
Chris Lattner0798af32005-01-13 20:14:25 +00002480 Constant *Scale = ConstantExpr::getCast(ConstantUInt::get(UIntPtrTy, Size),
2481 SIntPtrTy);
2482 if (Constant *OpC = dyn_cast<Constant>(Op)) {
2483 if (!OpC->isNullValue()) {
Chris Lattner4cb9fa32005-01-13 20:40:58 +00002484 OpC = ConstantExpr::getCast(OpC, SIntPtrTy);
Chris Lattner0798af32005-01-13 20:14:25 +00002485 Scale = ConstantExpr::getMul(OpC, Scale);
2486 if (Constant *RC = dyn_cast<Constant>(Result))
2487 Result = ConstantExpr::getAdd(RC, Scale);
2488 else {
2489 // Emit an add instruction.
2490 Result = IC.InsertNewInstBefore(
2491 BinaryOperator::createAdd(Result, Scale,
2492 GEP->getName()+".offs"), I);
2493 }
2494 }
2495 } else {
Chris Lattner7aa41cf2005-01-14 17:17:59 +00002496 // Convert to correct type.
2497 Op = IC.InsertNewInstBefore(new CastInst(Op, SIntPtrTy,
2498 Op->getName()+".c"), I);
2499 if (Size != 1)
Chris Lattner4cb9fa32005-01-13 20:40:58 +00002500 // We'll let instcombine(mul) convert this to a shl if possible.
2501 Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
2502 GEP->getName()+".idx"), I);
Chris Lattner0798af32005-01-13 20:14:25 +00002503
2504 // Emit an add instruction.
Chris Lattner4cb9fa32005-01-13 20:40:58 +00002505 Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
Chris Lattner0798af32005-01-13 20:14:25 +00002506 GEP->getName()+".offs"), I);
2507 }
2508 }
2509 return Result;
2510}
2511
2512/// FoldGEPSetCC - Fold comparisons between a GEP instruction and something
2513/// else. At this point we know that the GEP is on the LHS of the comparison.
2514Instruction *InstCombiner::FoldGEPSetCC(User *GEPLHS, Value *RHS,
2515 Instruction::BinaryOps Cond,
2516 Instruction &I) {
2517 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattner81e84172005-01-13 22:25:21 +00002518
2519 if (CastInst *CI = dyn_cast<CastInst>(RHS))
2520 if (isa<PointerType>(CI->getOperand(0)->getType()))
2521 RHS = CI->getOperand(0);
2522
Chris Lattner0798af32005-01-13 20:14:25 +00002523 Value *PtrBase = GEPLHS->getOperand(0);
2524 if (PtrBase == RHS) {
2525 // As an optimization, we don't actually have to compute the actual value of
2526 // OFFSET if this is a seteq or setne comparison, just return whether each
2527 // index is zero or not.
Chris Lattner81e84172005-01-13 22:25:21 +00002528 if (Cond == Instruction::SetEQ || Cond == Instruction::SetNE) {
2529 Instruction *InVal = 0;
Chris Lattnercd517ff2005-01-28 19:32:01 +00002530 gep_type_iterator GTI = gep_type_begin(GEPLHS);
2531 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i, ++GTI) {
Chris Lattner81e84172005-01-13 22:25:21 +00002532 bool EmitIt = true;
2533 if (Constant *C = dyn_cast<Constant>(GEPLHS->getOperand(i))) {
2534 if (isa<UndefValue>(C)) // undef index -> undef.
2535 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2536 if (C->isNullValue())
2537 EmitIt = false;
Chris Lattnercd517ff2005-01-28 19:32:01 +00002538 else if (TD->getTypeSize(GTI.getIndexedType()) == 0) {
2539 EmitIt = false; // This is indexing into a zero sized array?
Misha Brukmanb1c93172005-04-21 23:48:37 +00002540 } else if (isa<ConstantInt>(C))
Chris Lattner81e84172005-01-13 22:25:21 +00002541 return ReplaceInstUsesWith(I, // No comparison is needed here.
2542 ConstantBool::get(Cond == Instruction::SetNE));
2543 }
2544
2545 if (EmitIt) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00002546 Instruction *Comp =
Chris Lattner81e84172005-01-13 22:25:21 +00002547 new SetCondInst(Cond, GEPLHS->getOperand(i),
2548 Constant::getNullValue(GEPLHS->getOperand(i)->getType()));
2549 if (InVal == 0)
2550 InVal = Comp;
2551 else {
2552 InVal = InsertNewInstBefore(InVal, I);
2553 InsertNewInstBefore(Comp, I);
2554 if (Cond == Instruction::SetNE) // True if any are unequal
2555 InVal = BinaryOperator::createOr(InVal, Comp);
2556 else // True if all are equal
2557 InVal = BinaryOperator::createAnd(InVal, Comp);
2558 }
2559 }
2560 }
2561
2562 if (InVal)
2563 return InVal;
2564 else
2565 ReplaceInstUsesWith(I, // No comparison is needed here, all indexes = 0
2566 ConstantBool::get(Cond == Instruction::SetEQ));
2567 }
Chris Lattner0798af32005-01-13 20:14:25 +00002568
2569 // Only lower this if the setcc is the only user of the GEP or if we expect
2570 // the result to fold to a constant!
2571 if (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) {
2572 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
2573 Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
2574 return new SetCondInst(Cond, Offset,
2575 Constant::getNullValue(Offset->getType()));
2576 }
2577 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
Chris Lattnera21bf8d2005-04-25 20:17:30 +00002578 // If the base pointers are different, but the indices are the same, just
2579 // compare the base pointer.
2580 if (PtrBase != GEPRHS->getOperand(0)) {
2581 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00002582 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattnerbd43b9d2005-04-26 14:40:41 +00002583 GEPRHS->getOperand(0)->getType();
Chris Lattnera21bf8d2005-04-25 20:17:30 +00002584 if (IndicesTheSame)
2585 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
2586 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
2587 IndicesTheSame = false;
2588 break;
2589 }
2590
2591 // If all indices are the same, just compare the base pointers.
2592 if (IndicesTheSame)
2593 return new SetCondInst(Cond, GEPLHS->getOperand(0),
2594 GEPRHS->getOperand(0));
2595
2596 // Otherwise, the base pointers are different and the indices are
2597 // different, bail out.
Chris Lattner0798af32005-01-13 20:14:25 +00002598 return 0;
Chris Lattnera21bf8d2005-04-25 20:17:30 +00002599 }
Chris Lattner0798af32005-01-13 20:14:25 +00002600
Chris Lattner81e84172005-01-13 22:25:21 +00002601 // If one of the GEPs has all zero indices, recurse.
2602 bool AllZeros = true;
2603 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
2604 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
2605 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
2606 AllZeros = false;
2607 break;
2608 }
2609 if (AllZeros)
2610 return FoldGEPSetCC(GEPRHS, GEPLHS->getOperand(0),
2611 SetCondInst::getSwappedCondition(Cond), I);
Chris Lattner4fa89822005-01-14 00:20:05 +00002612
2613 // If the other GEP has all zero indices, recurse.
Chris Lattner81e84172005-01-13 22:25:21 +00002614 AllZeros = true;
2615 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
2616 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
2617 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
2618 AllZeros = false;
2619 break;
2620 }
2621 if (AllZeros)
2622 return FoldGEPSetCC(GEPLHS, GEPRHS->getOperand(0), Cond, I);
2623
Chris Lattner4fa89822005-01-14 00:20:05 +00002624 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
2625 // If the GEPs only differ by one index, compare it.
2626 unsigned NumDifferences = 0; // Keep track of # differences.
2627 unsigned DiffOperand = 0; // The operand that differs.
2628 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
2629 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002630 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
2631 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattnerfc4429e2005-01-21 23:06:49 +00002632 // Irreconcilable differences.
Chris Lattner4fa89822005-01-14 00:20:05 +00002633 NumDifferences = 2;
2634 break;
2635 } else {
2636 if (NumDifferences++) break;
2637 DiffOperand = i;
2638 }
2639 }
2640
2641 if (NumDifferences == 0) // SAME GEP?
2642 return ReplaceInstUsesWith(I, // No comparison is needed here.
2643 ConstantBool::get(Cond == Instruction::SetEQ));
2644 else if (NumDifferences == 1) {
Chris Lattnerfc4429e2005-01-21 23:06:49 +00002645 Value *LHSV = GEPLHS->getOperand(DiffOperand);
2646 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Chris Lattner247aef82005-07-18 23:07:33 +00002647
2648 // Convert the operands to signed values to make sure to perform a
2649 // signed comparison.
2650 const Type *NewTy = LHSV->getType()->getSignedVersion();
2651 if (LHSV->getType() != NewTy)
2652 LHSV = InsertNewInstBefore(new CastInst(LHSV, NewTy,
2653 LHSV->getName()), I);
2654 if (RHSV->getType() != NewTy)
2655 RHSV = InsertNewInstBefore(new CastInst(RHSV, NewTy,
2656 RHSV->getName()), I);
2657 return new SetCondInst(Cond, LHSV, RHSV);
Chris Lattner4fa89822005-01-14 00:20:05 +00002658 }
2659 }
2660
Chris Lattner0798af32005-01-13 20:14:25 +00002661 // Only lower this if the setcc is the only user of the GEP or if we expect
2662 // the result to fold to a constant!
2663 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
2664 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
2665 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
2666 Value *L = EmitGEPOffset(GEPLHS, I, *this);
2667 Value *R = EmitGEPOffset(GEPRHS, I, *this);
2668 return new SetCondInst(Cond, L, R);
2669 }
2670 }
2671 return 0;
2672}
2673
2674
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002675Instruction *InstCombiner::visitSetCondInst(SetCondInst &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00002676 bool Changed = SimplifyCommutative(I);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002677 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2678 const Type *Ty = Op0->getType();
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002679
2680 // setcc X, X
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002681 if (Op0 == Op1)
2682 return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
Chris Lattner1fc23f32002-05-09 20:11:54 +00002683
Chris Lattner81a7a232004-10-16 18:11:37 +00002684 if (isa<UndefValue>(Op1)) // X setcc undef -> undef
2685 return ReplaceInstUsesWith(I, UndefValue::get(Type::BoolTy));
2686
Chris Lattner15ff1e12004-11-14 07:33:16 +00002687 // setcc <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
2688 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanb1c93172005-04-21 23:48:37 +00002689 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
2690 isa<ConstantPointerNull>(Op0)) &&
2691 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner15ff1e12004-11-14 07:33:16 +00002692 isa<ConstantPointerNull>(Op1)))
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002693 return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
2694
2695 // setcc's with boolean values can always be turned into bitwise operations
2696 if (Ty == Type::BoolTy) {
Chris Lattner4456da62004-08-11 00:50:51 +00002697 switch (I.getOpcode()) {
2698 default: assert(0 && "Invalid setcc instruction!");
2699 case Instruction::SetEQ: { // seteq bool %A, %B -> ~(A^B)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002700 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002701 InsertNewInstBefore(Xor, I);
Chris Lattner16930792003-11-03 04:25:02 +00002702 return BinaryOperator::createNot(Xor);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002703 }
Chris Lattner4456da62004-08-11 00:50:51 +00002704 case Instruction::SetNE:
2705 return BinaryOperator::createXor(Op0, Op1);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002706
Chris Lattner4456da62004-08-11 00:50:51 +00002707 case Instruction::SetGT:
2708 std::swap(Op0, Op1); // Change setgt -> setlt
2709 // FALL THROUGH
2710 case Instruction::SetLT: { // setlt bool A, B -> ~X & Y
2711 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
2712 InsertNewInstBefore(Not, I);
2713 return BinaryOperator::createAnd(Not, Op1);
2714 }
2715 case Instruction::SetGE:
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002716 std::swap(Op0, Op1); // Change setge -> setle
Chris Lattner4456da62004-08-11 00:50:51 +00002717 // FALL THROUGH
2718 case Instruction::SetLE: { // setle bool %A, %B -> ~A | B
2719 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
2720 InsertNewInstBefore(Not, I);
2721 return BinaryOperator::createOr(Not, Op1);
2722 }
2723 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002724 }
2725
Chris Lattner2dd01742004-06-09 04:24:29 +00002726 // See if we are doing a comparison between a constant and an instruction that
2727 // can be folded into the comparison.
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002728 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner6862fbd2004-09-29 17:40:11 +00002729 // Check to see if we are comparing against the minimum or maximum value...
2730 if (CI->isMinValue()) {
2731 if (I.getOpcode() == Instruction::SetLT) // A < MIN -> FALSE
2732 return ReplaceInstUsesWith(I, ConstantBool::False);
2733 if (I.getOpcode() == Instruction::SetGE) // A >= MIN -> TRUE
2734 return ReplaceInstUsesWith(I, ConstantBool::True);
2735 if (I.getOpcode() == Instruction::SetLE) // A <= MIN -> A == MIN
2736 return BinaryOperator::createSetEQ(Op0, Op1);
2737 if (I.getOpcode() == Instruction::SetGT) // A > MIN -> A != MIN
2738 return BinaryOperator::createSetNE(Op0, Op1);
2739
2740 } else if (CI->isMaxValue()) {
2741 if (I.getOpcode() == Instruction::SetGT) // A > MAX -> FALSE
2742 return ReplaceInstUsesWith(I, ConstantBool::False);
2743 if (I.getOpcode() == Instruction::SetLE) // A <= MAX -> TRUE
2744 return ReplaceInstUsesWith(I, ConstantBool::True);
2745 if (I.getOpcode() == Instruction::SetGE) // A >= MAX -> A == MAX
2746 return BinaryOperator::createSetEQ(Op0, Op1);
2747 if (I.getOpcode() == Instruction::SetLT) // A < MAX -> A != MAX
2748 return BinaryOperator::createSetNE(Op0, Op1);
2749
2750 // Comparing against a value really close to min or max?
2751 } else if (isMinValuePlusOne(CI)) {
2752 if (I.getOpcode() == Instruction::SetLT) // A < MIN+1 -> A == MIN
2753 return BinaryOperator::createSetEQ(Op0, SubOne(CI));
2754 if (I.getOpcode() == Instruction::SetGE) // A >= MIN-1 -> A != MIN
2755 return BinaryOperator::createSetNE(Op0, SubOne(CI));
2756
2757 } else if (isMaxValueMinusOne(CI)) {
2758 if (I.getOpcode() == Instruction::SetGT) // A > MAX-1 -> A == MAX
2759 return BinaryOperator::createSetEQ(Op0, AddOne(CI));
2760 if (I.getOpcode() == Instruction::SetLE) // A <= MAX-1 -> A != MAX
2761 return BinaryOperator::createSetNE(Op0, AddOne(CI));
2762 }
2763
2764 // If we still have a setle or setge instruction, turn it into the
2765 // appropriate setlt or setgt instruction. Since the border cases have
2766 // already been handled above, this requires little checking.
2767 //
2768 if (I.getOpcode() == Instruction::SetLE)
2769 return BinaryOperator::createSetLT(Op0, AddOne(CI));
2770 if (I.getOpcode() == Instruction::SetGE)
2771 return BinaryOperator::createSetGT(Op0, SubOne(CI));
2772
Chris Lattnere1e10e12004-05-25 06:32:08 +00002773 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002774 switch (LHSI->getOpcode()) {
2775 case Instruction::And:
2776 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
2777 LHSI->getOperand(0)->hasOneUse()) {
2778 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
2779 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
2780 // happens a LOT in code produced by the C front-end, for bitfield
2781 // access.
2782 ShiftInst *Shift = dyn_cast<ShiftInst>(LHSI->getOperand(0));
2783 ConstantUInt *ShAmt;
2784 ShAmt = Shift ? dyn_cast<ConstantUInt>(Shift->getOperand(1)) : 0;
2785 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
2786 const Type *Ty = LHSI->getType();
Misha Brukmanb1c93172005-04-21 23:48:37 +00002787
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002788 // We can fold this as long as we can't shift unknown bits
2789 // into the mask. This can only happen with signed shift
2790 // rights, as they sign-extend.
2791 if (ShAmt) {
2792 bool CanFold = Shift->getOpcode() != Instruction::Shr ||
Chris Lattner6afc02f2004-09-28 17:54:07 +00002793 Shift->getType()->isUnsigned();
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002794 if (!CanFold) {
2795 // To test for the bad case of the signed shr, see if any
2796 // of the bits shifted in could be tested after the mask.
Chris Lattnerc53cb9d2005-06-17 01:29:28 +00002797 int ShAmtVal = Ty->getPrimitiveSizeInBits()-ShAmt->getValue();
2798 if (ShAmtVal < 0) ShAmtVal = 0; // Out of range shift.
2799
2800 Constant *OShAmt = ConstantUInt::get(Type::UByteTy, ShAmtVal);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002801 Constant *ShVal =
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002802 ConstantExpr::getShl(ConstantInt::getAllOnesValue(Ty), OShAmt);
2803 if (ConstantExpr::getAnd(ShVal, AndCST)->isNullValue())
2804 CanFold = true;
2805 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002806
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002807 if (CanFold) {
Chris Lattner6afc02f2004-09-28 17:54:07 +00002808 Constant *NewCst;
2809 if (Shift->getOpcode() == Instruction::Shl)
2810 NewCst = ConstantExpr::getUShr(CI, ShAmt);
2811 else
2812 NewCst = ConstantExpr::getShl(CI, ShAmt);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002813
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002814 // Check to see if we are shifting out any of the bits being
2815 // compared.
2816 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != CI){
2817 // If we shifted bits out, the fold is not going to work out.
2818 // As a special case, check to see if this means that the
2819 // result is always true or false now.
2820 if (I.getOpcode() == Instruction::SetEQ)
2821 return ReplaceInstUsesWith(I, ConstantBool::False);
2822 if (I.getOpcode() == Instruction::SetNE)
2823 return ReplaceInstUsesWith(I, ConstantBool::True);
2824 } else {
2825 I.setOperand(1, NewCst);
Chris Lattner6afc02f2004-09-28 17:54:07 +00002826 Constant *NewAndCST;
2827 if (Shift->getOpcode() == Instruction::Shl)
2828 NewAndCST = ConstantExpr::getUShr(AndCST, ShAmt);
2829 else
2830 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
2831 LHSI->setOperand(1, NewAndCST);
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002832 LHSI->setOperand(0, Shift->getOperand(0));
2833 WorkList.push_back(Shift); // Shift is dead.
2834 AddUsesToWorkList(I);
2835 return &I;
Chris Lattner1638de42004-07-21 19:50:44 +00002836 }
2837 }
Chris Lattner35167c32004-06-09 07:59:58 +00002838 }
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002839 }
2840 break;
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002841
Chris Lattner272d5ca2004-09-28 18:22:15 +00002842 case Instruction::Shl: // (setcc (shl X, ShAmt), CI)
2843 if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
2844 switch (I.getOpcode()) {
2845 default: break;
2846 case Instruction::SetEQ:
2847 case Instruction::SetNE: {
Chris Lattner19b57f52005-06-15 20:53:31 +00002848 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
2849
2850 // Check that the shift amount is in range. If not, don't perform
2851 // undefined shifts. When the shift is visited it will be
2852 // simplified.
2853 if (ShAmt->getValue() >= TypeBits)
2854 break;
2855
Chris Lattner272d5ca2004-09-28 18:22:15 +00002856 // If we are comparing against bits always shifted out, the
2857 // comparison cannot succeed.
Misha Brukmanb1c93172005-04-21 23:48:37 +00002858 Constant *Comp =
Chris Lattner272d5ca2004-09-28 18:22:15 +00002859 ConstantExpr::getShl(ConstantExpr::getShr(CI, ShAmt), ShAmt);
2860 if (Comp != CI) {// Comparing against a bit that we know is zero.
2861 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
2862 Constant *Cst = ConstantBool::get(IsSetNE);
2863 return ReplaceInstUsesWith(I, Cst);
2864 }
2865
2866 if (LHSI->hasOneUse()) {
2867 // Otherwise strength reduce the shift into an and.
Chris Lattnerfdfe3e492005-01-08 19:42:22 +00002868 unsigned ShAmtVal = (unsigned)ShAmt->getValue();
Chris Lattner272d5ca2004-09-28 18:22:15 +00002869 uint64_t Val = (1ULL << (TypeBits-ShAmtVal))-1;
2870
2871 Constant *Mask;
2872 if (CI->getType()->isUnsigned()) {
2873 Mask = ConstantUInt::get(CI->getType(), Val);
2874 } else if (ShAmtVal != 0) {
2875 Mask = ConstantSInt::get(CI->getType(), Val);
2876 } else {
2877 Mask = ConstantInt::getAllOnesValue(CI->getType());
2878 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002879
Chris Lattner272d5ca2004-09-28 18:22:15 +00002880 Instruction *AndI =
2881 BinaryOperator::createAnd(LHSI->getOperand(0),
2882 Mask, LHSI->getName()+".mask");
2883 Value *And = InsertNewInstBefore(AndI, I);
2884 return new SetCondInst(I.getOpcode(), And,
2885 ConstantExpr::getUShr(CI, ShAmt));
2886 }
2887 }
2888 }
2889 }
2890 break;
2891
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002892 case Instruction::Shr: // (setcc (shr X, ShAmt), CI)
Chris Lattner1023b872004-09-27 16:18:50 +00002893 if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
Chris Lattner1023b872004-09-27 16:18:50 +00002894 switch (I.getOpcode()) {
2895 default: break;
2896 case Instruction::SetEQ:
2897 case Instruction::SetNE: {
Chris Lattner19b57f52005-06-15 20:53:31 +00002898
2899 // Check that the shift amount is in range. If not, don't perform
2900 // undefined shifts. When the shift is visited it will be
2901 // simplified.
Chris Lattner104002b2005-06-16 01:52:07 +00002902 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
Chris Lattner19b57f52005-06-15 20:53:31 +00002903 if (ShAmt->getValue() >= TypeBits)
2904 break;
2905
Chris Lattner1023b872004-09-27 16:18:50 +00002906 // If we are comparing against bits always shifted out, the
2907 // comparison cannot succeed.
Misha Brukmanb1c93172005-04-21 23:48:37 +00002908 Constant *Comp =
Chris Lattner1023b872004-09-27 16:18:50 +00002909 ConstantExpr::getShr(ConstantExpr::getShl(CI, ShAmt), ShAmt);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002910
Chris Lattner1023b872004-09-27 16:18:50 +00002911 if (Comp != CI) {// Comparing against a bit that we know is zero.
2912 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
2913 Constant *Cst = ConstantBool::get(IsSetNE);
2914 return ReplaceInstUsesWith(I, Cst);
2915 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002916
Chris Lattner1023b872004-09-27 16:18:50 +00002917 if (LHSI->hasOneUse() || CI->isNullValue()) {
Chris Lattnerfdfe3e492005-01-08 19:42:22 +00002918 unsigned ShAmtVal = (unsigned)ShAmt->getValue();
Chris Lattner272d5ca2004-09-28 18:22:15 +00002919
Chris Lattner1023b872004-09-27 16:18:50 +00002920 // Otherwise strength reduce the shift into an and.
2921 uint64_t Val = ~0ULL; // All ones.
2922 Val <<= ShAmtVal; // Shift over to the right spot.
2923
2924 Constant *Mask;
2925 if (CI->getType()->isUnsigned()) {
Chris Lattner2f1457f2005-04-24 17:46:05 +00002926 Val &= ~0ULL >> (64-TypeBits);
Chris Lattner1023b872004-09-27 16:18:50 +00002927 Mask = ConstantUInt::get(CI->getType(), Val);
2928 } else {
2929 Mask = ConstantSInt::get(CI->getType(), Val);
2930 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002931
Chris Lattner1023b872004-09-27 16:18:50 +00002932 Instruction *AndI =
2933 BinaryOperator::createAnd(LHSI->getOperand(0),
2934 Mask, LHSI->getName()+".mask");
2935 Value *And = InsertNewInstBefore(AndI, I);
2936 return new SetCondInst(I.getOpcode(), And,
2937 ConstantExpr::getShl(CI, ShAmt));
2938 }
2939 break;
2940 }
2941 }
2942 }
2943 break;
Chris Lattner7e794272004-09-24 15:21:34 +00002944
Chris Lattner6862fbd2004-09-29 17:40:11 +00002945 case Instruction::Div:
2946 // Fold: (div X, C1) op C2 -> range check
2947 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
2948 // Fold this div into the comparison, producing a range check.
2949 // Determine, based on the divide type, what the range is being
2950 // checked. If there is an overflow on the low or high side, remember
2951 // it, otherwise compute the range [low, hi) bounding the new value.
2952 bool LoOverflow = false, HiOverflow = 0;
2953 ConstantInt *LoBound = 0, *HiBound = 0;
2954
2955 ConstantInt *Prod;
2956 bool ProdOV = MulWithOverflow(Prod, CI, DivRHS);
2957
Chris Lattnera92af962004-10-11 19:40:04 +00002958 Instruction::BinaryOps Opcode = I.getOpcode();
2959
Chris Lattner6862fbd2004-09-29 17:40:11 +00002960 if (DivRHS->isNullValue()) { // Don't hack on divide by zeros.
2961 } else if (LHSI->getType()->isUnsigned()) { // udiv
2962 LoBound = Prod;
2963 LoOverflow = ProdOV;
2964 HiOverflow = ProdOV || AddWithOverflow(HiBound, LoBound, DivRHS);
2965 } else if (isPositive(DivRHS)) { // Divisor is > 0.
2966 if (CI->isNullValue()) { // (X / pos) op 0
2967 // Can't overflow.
2968 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
2969 HiBound = DivRHS;
2970 } else if (isPositive(CI)) { // (X / pos) op pos
2971 LoBound = Prod;
2972 LoOverflow = ProdOV;
2973 HiOverflow = ProdOV || AddWithOverflow(HiBound, Prod, DivRHS);
2974 } else { // (X / pos) op neg
2975 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
2976 LoOverflow = AddWithOverflow(LoBound, Prod,
2977 cast<ConstantInt>(DivRHSH));
2978 HiBound = Prod;
2979 HiOverflow = ProdOV;
2980 }
2981 } else { // Divisor is < 0.
2982 if (CI->isNullValue()) { // (X / neg) op 0
2983 LoBound = AddOne(DivRHS);
2984 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner73bcba52005-06-17 02:05:55 +00002985 if (HiBound == DivRHS)
2986 LoBound = 0; // - INTMIN = INTMIN
Chris Lattner6862fbd2004-09-29 17:40:11 +00002987 } else if (isPositive(CI)) { // (X / neg) op pos
2988 HiOverflow = LoOverflow = ProdOV;
2989 if (!LoOverflow)
2990 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS));
2991 HiBound = AddOne(Prod);
2992 } else { // (X / neg) op neg
2993 LoBound = Prod;
2994 LoOverflow = HiOverflow = ProdOV;
2995 HiBound = cast<ConstantInt>(ConstantExpr::getSub(Prod, DivRHS));
2996 }
Chris Lattner0b41e862004-10-08 19:15:44 +00002997
Chris Lattnera92af962004-10-11 19:40:04 +00002998 // Dividing by a negate swaps the condition.
2999 Opcode = SetCondInst::getSwappedCondition(Opcode);
Chris Lattner6862fbd2004-09-29 17:40:11 +00003000 }
3001
3002 if (LoBound) {
3003 Value *X = LHSI->getOperand(0);
Chris Lattnera92af962004-10-11 19:40:04 +00003004 switch (Opcode) {
Chris Lattner6862fbd2004-09-29 17:40:11 +00003005 default: assert(0 && "Unhandled setcc opcode!");
3006 case Instruction::SetEQ:
3007 if (LoOverflow && HiOverflow)
3008 return ReplaceInstUsesWith(I, ConstantBool::False);
3009 else if (HiOverflow)
3010 return new SetCondInst(Instruction::SetGE, X, LoBound);
3011 else if (LoOverflow)
3012 return new SetCondInst(Instruction::SetLT, X, HiBound);
3013 else
3014 return InsertRangeTest(X, LoBound, HiBound, true, I);
3015 case Instruction::SetNE:
3016 if (LoOverflow && HiOverflow)
3017 return ReplaceInstUsesWith(I, ConstantBool::True);
3018 else if (HiOverflow)
3019 return new SetCondInst(Instruction::SetLT, X, LoBound);
3020 else if (LoOverflow)
3021 return new SetCondInst(Instruction::SetGE, X, HiBound);
3022 else
3023 return InsertRangeTest(X, LoBound, HiBound, false, I);
3024 case Instruction::SetLT:
3025 if (LoOverflow)
3026 return ReplaceInstUsesWith(I, ConstantBool::False);
3027 return new SetCondInst(Instruction::SetLT, X, LoBound);
3028 case Instruction::SetGT:
3029 if (HiOverflow)
3030 return ReplaceInstUsesWith(I, ConstantBool::False);
3031 return new SetCondInst(Instruction::SetGE, X, HiBound);
3032 }
3033 }
3034 }
3035 break;
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00003036 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003037
Chris Lattnerd492a0b2003-07-23 17:02:11 +00003038 // Simplify seteq and setne instructions...
3039 if (I.getOpcode() == Instruction::SetEQ ||
3040 I.getOpcode() == Instruction::SetNE) {
3041 bool isSetNE = I.getOpcode() == Instruction::SetNE;
3042
Chris Lattnercfbce7c2003-07-23 17:26:36 +00003043 // If the first operand is (and|or|xor) with a constant, and the second
Chris Lattnerd492a0b2003-07-23 17:02:11 +00003044 // operand is a constant, simplify a bit.
Chris Lattnerc992add2003-08-13 05:33:12 +00003045 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
3046 switch (BO->getOpcode()) {
Chris Lattner23b47b62004-07-06 07:38:18 +00003047 case Instruction::Rem:
3048 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
3049 if (CI->isNullValue() && isa<ConstantSInt>(BO->getOperand(1)) &&
3050 BO->hasOneUse() &&
Chris Lattner22d00a82005-08-02 19:16:58 +00003051 cast<ConstantSInt>(BO->getOperand(1))->getValue() > 1) {
3052 int64_t V = cast<ConstantSInt>(BO->getOperand(1))->getValue();
3053 if (isPowerOf2_64(V)) {
3054 unsigned L2 = Log2_64(V);
Chris Lattner23b47b62004-07-06 07:38:18 +00003055 const Type *UTy = BO->getType()->getUnsignedVersion();
3056 Value *NewX = InsertNewInstBefore(new CastInst(BO->getOperand(0),
3057 UTy, "tmp"), I);
3058 Constant *RHSCst = ConstantUInt::get(UTy, 1ULL << L2);
3059 Value *NewRem =InsertNewInstBefore(BinaryOperator::createRem(NewX,
3060 RHSCst, BO->getName()), I);
3061 return BinaryOperator::create(I.getOpcode(), NewRem,
3062 Constant::getNullValue(UTy));
3063 }
Chris Lattner22d00a82005-08-02 19:16:58 +00003064 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003065 break;
Chris Lattner23b47b62004-07-06 07:38:18 +00003066
Chris Lattnerc992add2003-08-13 05:33:12 +00003067 case Instruction::Add:
Chris Lattner6e079362004-06-27 22:51:36 +00003068 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
3069 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerb121ae12004-09-21 21:35:23 +00003070 if (BO->hasOneUse())
3071 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
3072 ConstantExpr::getSub(CI, BOp1C));
Chris Lattner6e079362004-06-27 22:51:36 +00003073 } else if (CI->isNullValue()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00003074 // Replace ((add A, B) != 0) with (A != -B) if A or B is
3075 // efficiently invertible, or if the add has just this one use.
3076 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003077
Chris Lattnerc992add2003-08-13 05:33:12 +00003078 if (Value *NegVal = dyn_castNegVal(BOp1))
3079 return new SetCondInst(I.getOpcode(), BOp0, NegVal);
3080 else if (Value *NegVal = dyn_castNegVal(BOp0))
3081 return new SetCondInst(I.getOpcode(), NegVal, BOp1);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00003082 else if (BO->hasOneUse()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00003083 Instruction *Neg = BinaryOperator::createNeg(BOp1, BO->getName());
3084 BO->setName("");
3085 InsertNewInstBefore(Neg, I);
3086 return new SetCondInst(I.getOpcode(), BOp0, Neg);
3087 }
3088 }
3089 break;
3090 case Instruction::Xor:
3091 // For the xor case, we can xor two constants together, eliminating
3092 // the explicit xor.
3093 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
3094 return BinaryOperator::create(I.getOpcode(), BO->getOperand(0),
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003095 ConstantExpr::getXor(CI, BOC));
Chris Lattnerc992add2003-08-13 05:33:12 +00003096
3097 // FALLTHROUGH
3098 case Instruction::Sub:
3099 // Replace (([sub|xor] A, B) != 0) with (A != B)
3100 if (CI->isNullValue())
3101 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
3102 BO->getOperand(1));
3103 break;
3104
3105 case Instruction::Or:
3106 // If bits are being or'd in that are not present in the constant we
3107 // are comparing against, then the comparison could never succeed!
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003108 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Chris Lattnerc8e7e292004-06-10 02:12:35 +00003109 Constant *NotCI = ConstantExpr::getNot(CI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003110 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Chris Lattnerd492a0b2003-07-23 17:02:11 +00003111 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003112 }
Chris Lattnerc992add2003-08-13 05:33:12 +00003113 break;
3114
3115 case Instruction::And:
3116 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerd492a0b2003-07-23 17:02:11 +00003117 // If bits are being compared against that are and'd out, then the
3118 // comparison can never succeed!
Chris Lattnerc8e7e292004-06-10 02:12:35 +00003119 if (!ConstantExpr::getAnd(CI,
3120 ConstantExpr::getNot(BOC))->isNullValue())
Chris Lattnerd492a0b2003-07-23 17:02:11 +00003121 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattnerc992add2003-08-13 05:33:12 +00003122
Chris Lattner35167c32004-06-09 07:59:58 +00003123 // If we have ((X & C) == C), turn it into ((X & C) != 0).
Chris Lattneree59d4b2004-06-10 02:33:20 +00003124 if (CI == BOC && isOneBitSet(CI))
Chris Lattner35167c32004-06-09 07:59:58 +00003125 return new SetCondInst(isSetNE ? Instruction::SetEQ :
3126 Instruction::SetNE, Op0,
3127 Constant::getNullValue(CI->getType()));
Chris Lattner35167c32004-06-09 07:59:58 +00003128
Chris Lattnerc992add2003-08-13 05:33:12 +00003129 // Replace (and X, (1 << size(X)-1) != 0) with x < 0, converting X
3130 // to be a signed value as appropriate.
3131 if (isSignBit(BOC)) {
3132 Value *X = BO->getOperand(0);
3133 // If 'X' is not signed, insert a cast now...
3134 if (!BOC->getType()->isSigned()) {
Chris Lattner97bfcea2004-06-17 18:16:02 +00003135 const Type *DestTy = BOC->getType()->getSignedVersion();
Chris Lattnerbfff18a2004-09-27 19:29:18 +00003136 X = InsertCastBefore(X, DestTy, I);
Chris Lattnerc992add2003-08-13 05:33:12 +00003137 }
3138 return new SetCondInst(isSetNE ? Instruction::SetLT :
3139 Instruction::SetGE, X,
3140 Constant::getNullValue(X->getType()));
3141 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003142
Chris Lattnerbfff18a2004-09-27 19:29:18 +00003143 // ((X & ~7) == 0) --> X < 8
Chris Lattner8fc5af42004-09-23 21:46:38 +00003144 if (CI->isNullValue() && isHighOnes(BOC)) {
3145 Value *X = BO->getOperand(0);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00003146 Constant *NegX = ConstantExpr::getNeg(BOC);
Chris Lattner8fc5af42004-09-23 21:46:38 +00003147
3148 // If 'X' is signed, insert a cast now.
Chris Lattnerbfff18a2004-09-27 19:29:18 +00003149 if (NegX->getType()->isSigned()) {
3150 const Type *DestTy = NegX->getType()->getUnsignedVersion();
3151 X = InsertCastBefore(X, DestTy, I);
3152 NegX = ConstantExpr::getCast(NegX, DestTy);
Chris Lattner8fc5af42004-09-23 21:46:38 +00003153 }
3154
3155 return new SetCondInst(isSetNE ? Instruction::SetGE :
Chris Lattnerbfff18a2004-09-27 19:29:18 +00003156 Instruction::SetLT, X, NegX);
Chris Lattner8fc5af42004-09-23 21:46:38 +00003157 }
3158
Chris Lattnerd492a0b2003-07-23 17:02:11 +00003159 }
Chris Lattnerc992add2003-08-13 05:33:12 +00003160 default: break;
3161 }
3162 }
Chris Lattner2b55ea32004-02-23 07:16:20 +00003163 } else { // Not a SetEQ/SetNE
Misha Brukmanb1c93172005-04-21 23:48:37 +00003164 // If the LHS is a cast from an integral value of the same size,
Chris Lattner2b55ea32004-02-23 07:16:20 +00003165 if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
3166 Value *CastOp = Cast->getOperand(0);
3167 const Type *SrcTy = CastOp->getType();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003168 unsigned SrcTySize = SrcTy->getPrimitiveSizeInBits();
Chris Lattner2b55ea32004-02-23 07:16:20 +00003169 if (SrcTy != Cast->getType() && SrcTy->isInteger() &&
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003170 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00003171 assert((SrcTy->isSigned() ^ Cast->getType()->isSigned()) &&
Chris Lattner2b55ea32004-02-23 07:16:20 +00003172 "Source and destination signednesses should differ!");
3173 if (Cast->getType()->isSigned()) {
3174 // If this is a signed comparison, check for comparisons in the
3175 // vicinity of zero.
3176 if (I.getOpcode() == Instruction::SetLT && CI->isNullValue())
3177 // X < 0 => x > 127
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003178 return BinaryOperator::createSetGT(CastOp,
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003179 ConstantUInt::get(SrcTy, (1ULL << (SrcTySize-1))-1));
Chris Lattner2b55ea32004-02-23 07:16:20 +00003180 else if (I.getOpcode() == Instruction::SetGT &&
3181 cast<ConstantSInt>(CI)->getValue() == -1)
3182 // X > -1 => x < 128
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003183 return BinaryOperator::createSetLT(CastOp,
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003184 ConstantUInt::get(SrcTy, 1ULL << (SrcTySize-1)));
Chris Lattner2b55ea32004-02-23 07:16:20 +00003185 } else {
3186 ConstantUInt *CUI = cast<ConstantUInt>(CI);
3187 if (I.getOpcode() == Instruction::SetLT &&
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003188 CUI->getValue() == 1ULL << (SrcTySize-1))
Chris Lattner2b55ea32004-02-23 07:16:20 +00003189 // X < 128 => X > -1
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003190 return BinaryOperator::createSetGT(CastOp,
3191 ConstantSInt::get(SrcTy, -1));
Chris Lattner2b55ea32004-02-23 07:16:20 +00003192 else if (I.getOpcode() == Instruction::SetGT &&
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003193 CUI->getValue() == (1ULL << (SrcTySize-1))-1)
Chris Lattner2b55ea32004-02-23 07:16:20 +00003194 // X > 127 => X < 0
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003195 return BinaryOperator::createSetLT(CastOp,
3196 Constant::getNullValue(SrcTy));
Chris Lattner2b55ea32004-02-23 07:16:20 +00003197 }
3198 }
3199 }
Chris Lattnere967b342003-06-04 05:10:11 +00003200 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003201 }
3202
Chris Lattner77c32c32005-04-23 15:31:55 +00003203 // Handle setcc with constant RHS's that can be integer, FP or pointer.
3204 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
3205 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
3206 switch (LHSI->getOpcode()) {
Chris Lattnera816eee2005-05-01 04:42:15 +00003207 case Instruction::GetElementPtr:
3208 if (RHSC->isNullValue()) {
3209 // Transform setcc GEP P, int 0, int 0, int 0, null -> setcc P, null
3210 bool isAllZeros = true;
3211 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
3212 if (!isa<Constant>(LHSI->getOperand(i)) ||
3213 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
3214 isAllZeros = false;
3215 break;
3216 }
3217 if (isAllZeros)
3218 return new SetCondInst(I.getOpcode(), LHSI->getOperand(0),
3219 Constant::getNullValue(LHSI->getOperand(0)->getType()));
3220 }
3221 break;
3222
Chris Lattner77c32c32005-04-23 15:31:55 +00003223 case Instruction::PHI:
3224 if (Instruction *NV = FoldOpIntoPhi(I))
3225 return NV;
3226 break;
3227 case Instruction::Select:
3228 // If either operand of the select is a constant, we can fold the
3229 // comparison into the select arms, which will cause one to be
3230 // constant folded and the select turned into a bitwise or.
3231 Value *Op1 = 0, *Op2 = 0;
3232 if (LHSI->hasOneUse()) {
3233 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
3234 // Fold the known value into the constant operand.
3235 Op1 = ConstantExpr::get(I.getOpcode(), C, RHSC);
3236 // Insert a new SetCC of the other select operand.
3237 Op2 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
3238 LHSI->getOperand(2), RHSC,
3239 I.getName()), I);
3240 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
3241 // Fold the known value into the constant operand.
3242 Op2 = ConstantExpr::get(I.getOpcode(), C, RHSC);
3243 // Insert a new SetCC of the other select operand.
3244 Op1 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
3245 LHSI->getOperand(1), RHSC,
3246 I.getName()), I);
3247 }
3248 }
Jeff Cohen82639852005-04-23 21:38:35 +00003249
Chris Lattner77c32c32005-04-23 15:31:55 +00003250 if (Op1)
3251 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
3252 break;
3253 }
3254 }
3255
Chris Lattner0798af32005-01-13 20:14:25 +00003256 // If we can optimize a 'setcc GEP, P' or 'setcc P, GEP', do so now.
3257 if (User *GEP = dyn_castGetElementPtr(Op0))
3258 if (Instruction *NI = FoldGEPSetCC(GEP, Op1, I.getOpcode(), I))
3259 return NI;
3260 if (User *GEP = dyn_castGetElementPtr(Op1))
3261 if (Instruction *NI = FoldGEPSetCC(GEP, Op0,
3262 SetCondInst::getSwappedCondition(I.getOpcode()), I))
3263 return NI;
3264
Chris Lattner16930792003-11-03 04:25:02 +00003265 // Test to see if the operands of the setcc are casted versions of other
3266 // values. If the cast can be stripped off both arguments, we do so now.
Chris Lattner6444c372003-11-03 05:17:03 +00003267 if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3268 Value *CastOp0 = CI->getOperand(0);
3269 if (CastOp0->getType()->isLosslesslyConvertibleTo(CI->getType()) &&
Chris Lattner7d2a5392004-03-13 23:54:27 +00003270 (isa<Constant>(Op1) || isa<CastInst>(Op1)) &&
Chris Lattner16930792003-11-03 04:25:02 +00003271 (I.getOpcode() == Instruction::SetEQ ||
3272 I.getOpcode() == Instruction::SetNE)) {
3273 // We keep moving the cast from the left operand over to the right
3274 // operand, where it can often be eliminated completely.
Chris Lattner6444c372003-11-03 05:17:03 +00003275 Op0 = CastOp0;
Misha Brukmanb1c93172005-04-21 23:48:37 +00003276
Chris Lattner16930792003-11-03 04:25:02 +00003277 // If operand #1 is a cast instruction, see if we can eliminate it as
3278 // well.
Chris Lattner6444c372003-11-03 05:17:03 +00003279 if (CastInst *CI2 = dyn_cast<CastInst>(Op1))
3280 if (CI2->getOperand(0)->getType()->isLosslesslyConvertibleTo(
Chris Lattner16930792003-11-03 04:25:02 +00003281 Op0->getType()))
Chris Lattner6444c372003-11-03 05:17:03 +00003282 Op1 = CI2->getOperand(0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003283
Chris Lattner16930792003-11-03 04:25:02 +00003284 // If Op1 is a constant, we can fold the cast into the constant.
3285 if (Op1->getType() != Op0->getType())
3286 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
3287 Op1 = ConstantExpr::getCast(Op1C, Op0->getType());
3288 } else {
3289 // Otherwise, cast the RHS right before the setcc
3290 Op1 = new CastInst(Op1, Op0->getType(), Op1->getName());
3291 InsertNewInstBefore(cast<Instruction>(Op1), I);
3292 }
3293 return BinaryOperator::create(I.getOpcode(), Op0, Op1);
3294 }
3295
Chris Lattner6444c372003-11-03 05:17:03 +00003296 // Handle the special case of: setcc (cast bool to X), <cst>
3297 // This comes up when you have code like
3298 // int X = A < B;
3299 // if (X) ...
3300 // For generality, we handle any zero-extension of any operand comparison
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003301 // with a constant or another cast from the same type.
3302 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
3303 if (Instruction *R = visitSetCondInstWithCastAndCast(I))
3304 return R;
Chris Lattner6444c372003-11-03 05:17:03 +00003305 }
Chris Lattner113f4f42002-06-25 16:13:24 +00003306 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003307}
3308
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003309// visitSetCondInstWithCastAndCast - Handle setcond (cast x to y), (cast/cst).
3310// We only handle extending casts so far.
3311//
3312Instruction *InstCombiner::visitSetCondInstWithCastAndCast(SetCondInst &SCI) {
3313 Value *LHSCIOp = cast<CastInst>(SCI.getOperand(0))->getOperand(0);
3314 const Type *SrcTy = LHSCIOp->getType();
3315 const Type *DestTy = SCI.getOperand(0)->getType();
3316 Value *RHSCIOp;
3317
3318 if (!DestTy->isIntegral() || !SrcTy->isIntegral())
Chris Lattner03f06f12005-01-17 03:20:02 +00003319 return 0;
3320
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003321 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
3322 unsigned DestBits = DestTy->getPrimitiveSizeInBits();
3323 if (SrcBits >= DestBits) return 0; // Only handle extending cast.
3324
3325 // Is this a sign or zero extension?
3326 bool isSignSrc = SrcTy->isSigned();
3327 bool isSignDest = DestTy->isSigned();
3328
3329 if (CastInst *CI = dyn_cast<CastInst>(SCI.getOperand(1))) {
3330 // Not an extension from the same type?
3331 RHSCIOp = CI->getOperand(0);
3332 if (RHSCIOp->getType() != LHSCIOp->getType()) return 0;
3333 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(SCI.getOperand(1))) {
3334 // Compute the constant that would happen if we truncated to SrcTy then
3335 // reextended to DestTy.
3336 Constant *Res = ConstantExpr::getCast(CI, SrcTy);
3337
3338 if (ConstantExpr::getCast(Res, DestTy) == CI) {
3339 RHSCIOp = Res;
3340 } else {
3341 // If the value cannot be represented in the shorter type, we cannot emit
3342 // a simple comparison.
3343 if (SCI.getOpcode() == Instruction::SetEQ)
3344 return ReplaceInstUsesWith(SCI, ConstantBool::False);
3345 if (SCI.getOpcode() == Instruction::SetNE)
3346 return ReplaceInstUsesWith(SCI, ConstantBool::True);
3347
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003348 // Evaluate the comparison for LT.
3349 Value *Result;
3350 if (DestTy->isSigned()) {
3351 // We're performing a signed comparison.
3352 if (isSignSrc) {
3353 // Signed extend and signed comparison.
3354 if (cast<ConstantSInt>(CI)->getValue() < 0) // X < (small) --> false
3355 Result = ConstantBool::False;
3356 else
3357 Result = ConstantBool::True; // X < (large) --> true
3358 } else {
3359 // Unsigned extend and signed comparison.
3360 if (cast<ConstantSInt>(CI)->getValue() < 0)
3361 Result = ConstantBool::False;
3362 else
3363 Result = ConstantBool::True;
3364 }
3365 } else {
3366 // We're performing an unsigned comparison.
3367 if (!isSignSrc) {
3368 // Unsigned extend & compare -> always true.
3369 Result = ConstantBool::True;
3370 } else {
3371 // We're performing an unsigned comp with a sign extended value.
3372 // This is true if the input is >= 0. [aka >s -1]
3373 Constant *NegOne = ConstantIntegral::getAllOnesValue(SrcTy);
3374 Result = InsertNewInstBefore(BinaryOperator::createSetGT(LHSCIOp,
3375 NegOne, SCI.getName()), SCI);
3376 }
Reid Spencer279fa252004-11-28 21:31:15 +00003377 }
Chris Lattner03f06f12005-01-17 03:20:02 +00003378
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00003379 // Finally, return the value computed.
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003380 if (SCI.getOpcode() == Instruction::SetLT) {
3381 return ReplaceInstUsesWith(SCI, Result);
3382 } else {
3383 assert(SCI.getOpcode()==Instruction::SetGT &&"SetCC should be folded!");
3384 if (Constant *CI = dyn_cast<Constant>(Result))
3385 return ReplaceInstUsesWith(SCI, ConstantExpr::getNot(CI));
3386 else
3387 return BinaryOperator::createNot(Result);
3388 }
Chris Lattner03f06f12005-01-17 03:20:02 +00003389 }
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003390 } else {
3391 return 0;
Reid Spencer279fa252004-11-28 21:31:15 +00003392 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003393
Chris Lattner252a8452005-06-16 03:00:08 +00003394 // Okay, just insert a compare of the reduced operands now!
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003395 return BinaryOperator::create(SCI.getOpcode(), LHSCIOp, RHSCIOp);
3396}
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003397
Chris Lattnere8d6c602003-03-10 19:16:08 +00003398Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +00003399 assert(I.getOperand(1)->getType() == Type::UByteTy);
3400 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003401 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003402
3403 // shl X, 0 == X and shr X, 0 == X
3404 // shl 0, X == 0 and shr 0, X == 0
3405 if (Op1 == Constant::getNullValue(Type::UByteTy) ||
Chris Lattnere6794492002-08-12 21:17:25 +00003406 Op0 == Constant::getNullValue(Op0->getType()))
3407 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003408
Chris Lattner81a7a232004-10-16 18:11:37 +00003409 if (isa<UndefValue>(Op0)) { // undef >>s X -> undef
3410 if (!isLeftShift && I.getType()->isSigned())
Chris Lattner67f05452004-10-16 23:28:04 +00003411 return ReplaceInstUsesWith(I, Op0);
Chris Lattner81a7a232004-10-16 18:11:37 +00003412 else // undef << X -> 0 AND undef >>u X -> 0
3413 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3414 }
3415 if (isa<UndefValue>(Op1)) {
Chris Lattner18aa4d82005-07-20 18:49:28 +00003416 if (isLeftShift || I.getType()->isUnsigned())// X << undef, X >>u undef -> 0
Chris Lattner81a7a232004-10-16 18:11:37 +00003417 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3418 else
3419 return ReplaceInstUsesWith(I, Op0); // X >>s undef -> X
3420 }
3421
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003422 // shr int -1, X = -1 (for any arithmetic shift rights of ~0)
3423 if (!isLeftShift)
3424 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
3425 if (CSI->isAllOnesValue())
3426 return ReplaceInstUsesWith(I, CSI);
3427
Chris Lattner183b3362004-04-09 19:05:30 +00003428 // Try to fold constant and into select arguments.
3429 if (isa<Constant>(Op0))
3430 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner86102b82005-01-01 16:22:27 +00003431 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00003432 return R;
3433
Chris Lattnerb18dbbf2005-05-08 17:34:56 +00003434 // See if we can turn a signed shr into an unsigned shr.
3435 if (!isLeftShift && I.getType()->isSigned()) {
3436 if (MaskedValueIsZero(Op0, ConstantInt::getMinValue(I.getType()))) {
3437 Value *V = InsertCastBefore(Op0, I.getType()->getUnsignedVersion(), I);
3438 V = InsertNewInstBefore(new ShiftInst(Instruction::Shr, V, Op1,
3439 I.getName()), I);
3440 return new CastInst(V, I.getType());
3441 }
3442 }
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00003443
Chris Lattner14553932006-01-06 07:12:35 +00003444 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op1))
3445 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
3446 return Res;
3447 return 0;
3448}
3449
3450Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantUInt *Op1,
3451 ShiftInst &I) {
3452 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattnerb3309392006-01-06 07:22:22 +00003453 bool isSignedShift = Op0->getType()->isSigned();
3454 bool isUnsignedShift = !isSignedShift;
Chris Lattner14553932006-01-06 07:12:35 +00003455
3456 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
3457 // of a signed value.
3458 //
3459 unsigned TypeBits = Op0->getType()->getPrimitiveSizeInBits();
3460 if (Op1->getValue() >= TypeBits) {
Chris Lattnerb3309392006-01-06 07:22:22 +00003461 if (isUnsignedShift || isLeftShift)
Chris Lattner14553932006-01-06 07:12:35 +00003462 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
3463 else {
3464 I.setOperand(1, ConstantUInt::get(Type::UByteTy, TypeBits-1));
3465 return &I;
Chris Lattnerf5ce2542004-02-23 20:30:06 +00003466 }
Chris Lattner14553932006-01-06 07:12:35 +00003467 }
3468
3469 // ((X*C1) << C2) == (X * (C1 << C2))
3470 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
3471 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
3472 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
3473 return BinaryOperator::createMul(BO->getOperand(0),
3474 ConstantExpr::getShl(BOOp, Op1));
3475
3476 // Try to fold constant and into select arguments.
3477 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3478 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3479 return R;
3480 if (isa<PHINode>(Op0))
3481 if (Instruction *NV = FoldOpIntoPhi(I))
3482 return NV;
3483
3484 if (Op0->hasOneUse()) {
3485 // If this is a SHL of a sign-extending cast, see if we can turn the input
3486 // into a zero extending cast (a simple strength reduction).
3487 if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3488 const Type *SrcTy = CI->getOperand(0)->getType();
3489 if (isLeftShift && SrcTy->isInteger() && SrcTy->isSigned() &&
3490 SrcTy->getPrimitiveSizeInBits() <
3491 CI->getType()->getPrimitiveSizeInBits()) {
3492 // We can change it to a zero extension if we are shifting out all of
3493 // the sign extended bits. To check this, form a mask of all of the
3494 // sign extend bits, then shift them left and see if we have anything
3495 // left.
3496 Constant *Mask = ConstantIntegral::getAllOnesValue(SrcTy); // 1111
3497 Mask = ConstantExpr::getZeroExtend(Mask, CI->getType()); // 00001111
3498 Mask = ConstantExpr::getNot(Mask); // 1's in the sign bits: 11110000
3499 if (ConstantExpr::getShl(Mask, Op1)->isNullValue()) {
3500 // If the shift is nuking all of the sign bits, change this to a
3501 // zero extension cast. To do this, cast the cast input to
3502 // unsigned, then to the requested size.
3503 Value *CastOp = CI->getOperand(0);
3504 Instruction *NC =
3505 new CastInst(CastOp, CastOp->getType()->getUnsignedVersion(),
3506 CI->getName()+".uns");
3507 NC = InsertNewInstBefore(NC, I);
3508 // Finally, insert a replacement for CI.
3509 NC = new CastInst(NC, CI->getType(), CI->getName());
3510 CI->setName("");
3511 NC = InsertNewInstBefore(NC, I);
3512 WorkList.push_back(CI); // Delete CI later.
3513 I.setOperand(0, NC);
3514 return &I; // The SHL operand was modified.
Chris Lattner86102b82005-01-01 16:22:27 +00003515 }
3516 }
Chris Lattner14553932006-01-06 07:12:35 +00003517 }
3518
3519 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
3520 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
3521 Value *V1, *V2;
3522 ConstantInt *CC;
3523 switch (Op0BO->getOpcode()) {
Chris Lattner27cb9db2005-09-18 05:12:10 +00003524 default: break;
3525 case Instruction::Add:
3526 case Instruction::And:
3527 case Instruction::Or:
3528 case Instruction::Xor:
3529 // These operators commute.
3530 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner797dee72005-09-18 06:30:59 +00003531 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
3532 match(Op0BO->getOperand(1),
Chris Lattner14553932006-01-06 07:12:35 +00003533 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Chris Lattner797dee72005-09-18 06:30:59 +00003534 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00003535 Op0BO->getOperand(0), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00003536 Op0BO->getName());
3537 InsertNewInstBefore(YS, I); // (Y << C)
3538 Instruction *X = BinaryOperator::create(Op0BO->getOpcode(), YS,
3539 V1,
Chris Lattner14553932006-01-06 07:12:35 +00003540 Op0BO->getOperand(1)->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00003541 InsertNewInstBefore(X, I); // (X + (Y << C))
3542 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
Chris Lattner14553932006-01-06 07:12:35 +00003543 C2 = ConstantExpr::getShl(C2, Op1);
Chris Lattner797dee72005-09-18 06:30:59 +00003544 return BinaryOperator::createAnd(X, C2);
3545 }
Chris Lattner14553932006-01-06 07:12:35 +00003546
Chris Lattner797dee72005-09-18 06:30:59 +00003547 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
3548 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
3549 match(Op0BO->getOperand(1),
3550 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner14553932006-01-06 07:12:35 +00003551 m_ConstantInt(CC))) && V2 == Op1 &&
3552 cast<BinaryOperator>(Op0BO->getOperand(1))->getOperand(0)->hasOneUse()) {
Chris Lattner797dee72005-09-18 06:30:59 +00003553 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00003554 Op0BO->getOperand(0), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00003555 Op0BO->getName());
3556 InsertNewInstBefore(YS, I); // (Y << C)
3557 Instruction *XM =
Chris Lattner14553932006-01-06 07:12:35 +00003558 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner797dee72005-09-18 06:30:59 +00003559 V1->getName()+".mask");
3560 InsertNewInstBefore(XM, I); // X & (CC << C)
3561
3562 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
3563 }
Chris Lattner14553932006-01-06 07:12:35 +00003564
Chris Lattner797dee72005-09-18 06:30:59 +00003565 // FALL THROUGH.
Chris Lattner27cb9db2005-09-18 05:12:10 +00003566 case Instruction::Sub:
3567 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner797dee72005-09-18 06:30:59 +00003568 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
3569 match(Op0BO->getOperand(0),
Chris Lattner14553932006-01-06 07:12:35 +00003570 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Chris Lattner797dee72005-09-18 06:30:59 +00003571 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00003572 Op0BO->getOperand(1), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00003573 Op0BO->getName());
3574 InsertNewInstBefore(YS, I); // (Y << C)
3575 Instruction *X = BinaryOperator::create(Op0BO->getOpcode(), YS,
3576 V1,
Chris Lattner14553932006-01-06 07:12:35 +00003577 Op0BO->getOperand(0)->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00003578 InsertNewInstBefore(X, I); // (X + (Y << C))
3579 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
Chris Lattner14553932006-01-06 07:12:35 +00003580 C2 = ConstantExpr::getShl(C2, Op1);
Chris Lattner797dee72005-09-18 06:30:59 +00003581 return BinaryOperator::createAnd(X, C2);
3582 }
Chris Lattner14553932006-01-06 07:12:35 +00003583
Chris Lattner797dee72005-09-18 06:30:59 +00003584 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
3585 match(Op0BO->getOperand(0),
3586 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner14553932006-01-06 07:12:35 +00003587 m_ConstantInt(CC))) && V2 == Op1 &&
3588 cast<BinaryOperator>(Op0BO->getOperand(0))->getOperand(0)->hasOneUse()) {
Chris Lattner797dee72005-09-18 06:30:59 +00003589 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00003590 Op0BO->getOperand(1), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00003591 Op0BO->getName());
3592 InsertNewInstBefore(YS, I); // (Y << C)
3593 Instruction *XM =
Chris Lattner14553932006-01-06 07:12:35 +00003594 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner797dee72005-09-18 06:30:59 +00003595 V1->getName()+".mask");
3596 InsertNewInstBefore(XM, I); // X & (CC << C)
3597
3598 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
3599 }
Chris Lattner14553932006-01-06 07:12:35 +00003600
Chris Lattner27cb9db2005-09-18 05:12:10 +00003601 break;
Chris Lattner14553932006-01-06 07:12:35 +00003602 }
3603
3604
3605 // If the operand is an bitwise operator with a constant RHS, and the
3606 // shift is the only use, we can pull it out of the shift.
3607 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
3608 bool isValid = true; // Valid only for And, Or, Xor
3609 bool highBitSet = false; // Transform if high bit of constant set?
3610
3611 switch (Op0BO->getOpcode()) {
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003612 default: isValid = false; break; // Do not perform transform!
Chris Lattner44bd3922004-10-08 03:46:20 +00003613 case Instruction::Add:
3614 isValid = isLeftShift;
3615 break;
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003616 case Instruction::Or:
3617 case Instruction::Xor:
3618 highBitSet = false;
3619 break;
3620 case Instruction::And:
3621 highBitSet = true;
3622 break;
Chris Lattner14553932006-01-06 07:12:35 +00003623 }
3624
3625 // If this is a signed shift right, and the high bit is modified
3626 // by the logical operation, do not perform the transformation.
3627 // The highBitSet boolean indicates the value of the high bit of
3628 // the constant which would cause it to be modified for this
3629 // operation.
3630 //
Chris Lattnerb3309392006-01-06 07:22:22 +00003631 if (isValid && !isLeftShift && isSignedShift) {
Chris Lattner14553932006-01-06 07:12:35 +00003632 uint64_t Val = Op0C->getRawValue();
3633 isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
3634 }
3635
3636 if (isValid) {
3637 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
3638
3639 Instruction *NewShift =
3640 new ShiftInst(I.getOpcode(), Op0BO->getOperand(0), Op1,
3641 Op0BO->getName());
3642 Op0BO->setName("");
3643 InsertNewInstBefore(NewShift, I);
3644
3645 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
3646 NewRHS);
3647 }
3648 }
3649 }
3650 }
3651
Chris Lattnereb372a02006-01-06 07:52:12 +00003652 // Find out if this is a shift of a shift by a constant.
3653 ShiftInst *ShiftOp = 0;
Chris Lattner14553932006-01-06 07:12:35 +00003654 if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0))
Chris Lattnereb372a02006-01-06 07:52:12 +00003655 ShiftOp = Op0SI;
3656 else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3657 // If this is a noop-integer case of a shift instruction, use the shift.
3658 if (CI->getOperand(0)->getType()->isInteger() &&
3659 CI->getOperand(0)->getType()->getPrimitiveSizeInBits() ==
3660 CI->getType()->getPrimitiveSizeInBits() &&
3661 isa<ShiftInst>(CI->getOperand(0))) {
3662 ShiftOp = cast<ShiftInst>(CI->getOperand(0));
3663 }
3664 }
3665
3666 if (ShiftOp && isa<ConstantUInt>(ShiftOp->getOperand(1))) {
3667 // Find the operands and properties of the input shift. Note that the
3668 // signedness of the input shift may differ from the current shift if there
3669 // is a noop cast between the two.
3670 bool isShiftOfLeftShift = ShiftOp->getOpcode() == Instruction::Shl;
3671 bool isShiftOfSignedShift = ShiftOp->getType()->isSigned();
Chris Lattner9cbfbc22006-01-07 01:32:28 +00003672 bool isShiftOfUnsignedShift = !isShiftOfSignedShift;
Chris Lattnereb372a02006-01-06 07:52:12 +00003673
3674 ConstantUInt *ShiftAmt1C = cast<ConstantUInt>(ShiftOp->getOperand(1));
3675
3676 unsigned ShiftAmt1 = (unsigned)ShiftAmt1C->getValue();
3677 unsigned ShiftAmt2 = (unsigned)Op1->getValue();
3678
3679 // Check for (A << c1) << c2 and (A >> c1) >> c2.
3680 if (isLeftShift == isShiftOfLeftShift) {
3681 // Do not fold these shifts if the first one is signed and the second one
3682 // is unsigned and this is a right shift. Further, don't do any folding
3683 // on them.
3684 if (isShiftOfSignedShift && isUnsignedShift && !isLeftShift)
3685 return 0;
Chris Lattner14553932006-01-06 07:12:35 +00003686
Chris Lattnereb372a02006-01-06 07:52:12 +00003687 unsigned Amt = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
3688 if (Amt > Op0->getType()->getPrimitiveSizeInBits())
3689 Amt = Op0->getType()->getPrimitiveSizeInBits();
Chris Lattner14553932006-01-06 07:12:35 +00003690
Chris Lattnereb372a02006-01-06 07:52:12 +00003691 Value *Op = ShiftOp->getOperand(0);
3692 if (isShiftOfSignedShift != isSignedShift)
3693 Op = InsertNewInstBefore(new CastInst(Op, I.getType(), "tmp"), I);
3694 return new ShiftInst(I.getOpcode(), Op,
3695 ConstantUInt::get(Type::UByteTy, Amt));
3696 }
3697
3698 // Check for (A << c1) >> c2 or (A >> c1) << c2. If we are dealing with
3699 // signed types, we can only support the (A >> c1) << c2 configuration,
3700 // because it can not turn an arbitrary bit of A into a sign bit.
3701 if (isUnsignedShift || isLeftShift) {
3702 // Calculate bitmask for what gets shifted off the edge.
3703 Constant *C = ConstantIntegral::getAllOnesValue(I.getType());
3704 if (isLeftShift)
3705 C = ConstantExpr::getShl(C, ShiftAmt1C);
3706 else
Chris Lattner9cbfbc22006-01-07 01:32:28 +00003707 C = ConstantExpr::getUShr(C, ShiftAmt1C);
Chris Lattnereb372a02006-01-06 07:52:12 +00003708
3709 Value *Op = ShiftOp->getOperand(0);
3710 if (isShiftOfSignedShift != isSignedShift)
3711 Op = InsertNewInstBefore(new CastInst(Op, I.getType(),Op->getName()),I);
3712
3713 Instruction *Mask =
3714 BinaryOperator::createAnd(Op, C, Op->getName()+".mask");
3715 InsertNewInstBefore(Mask, I);
3716
3717 // Figure out what flavor of shift we should use...
Chris Lattner9cbfbc22006-01-07 01:32:28 +00003718 if (ShiftAmt1 == ShiftAmt2) {
Chris Lattnereb372a02006-01-06 07:52:12 +00003719 return ReplaceInstUsesWith(I, Mask); // (A << c) >> c === A & c2
Chris Lattner9cbfbc22006-01-07 01:32:28 +00003720 } else if (ShiftAmt1 < ShiftAmt2) {
Chris Lattnereb372a02006-01-06 07:52:12 +00003721 return new ShiftInst(I.getOpcode(), Mask,
3722 ConstantUInt::get(Type::UByteTy, ShiftAmt2-ShiftAmt1));
Chris Lattner9cbfbc22006-01-07 01:32:28 +00003723 } else if (isShiftOfUnsignedShift || isShiftOfLeftShift) {
3724 if (isShiftOfUnsignedShift && !isShiftOfLeftShift && isSignedShift) {
3725 // Make sure to emit an unsigned shift right, not a signed one.
3726 Mask = InsertNewInstBefore(new CastInst(Mask,
3727 Mask->getType()->getUnsignedVersion(),
3728 Op->getName()), I);
3729 Mask = new ShiftInst(Instruction::Shr, Mask,
Chris Lattnereb372a02006-01-06 07:52:12 +00003730 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
Chris Lattner9cbfbc22006-01-07 01:32:28 +00003731 InsertNewInstBefore(Mask, I);
3732 return new CastInst(Mask, I.getType());
3733 } else {
3734 return new ShiftInst(ShiftOp->getOpcode(), Mask,
3735 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
3736 }
3737 } else {
3738 // (X >>s C1) << C2 where C1 > C2 === (X >>s (C1-C2)) & mask
3739 Op = InsertNewInstBefore(new CastInst(Mask,
3740 I.getType()->getSignedVersion(),
3741 Mask->getName()), I);
3742 Instruction *Shift =
3743 new ShiftInst(ShiftOp->getOpcode(), Op,
3744 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
3745 InsertNewInstBefore(Shift, I);
3746
3747 C = ConstantIntegral::getAllOnesValue(Shift->getType());
3748 C = ConstantExpr::getShl(C, Op1);
3749 Mask = BinaryOperator::createAnd(Shift, C, Op->getName()+".mask");
3750 InsertNewInstBefore(Mask, I);
3751 return new CastInst(Mask, I.getType());
Chris Lattnereb372a02006-01-06 07:52:12 +00003752 }
3753 } else {
Chris Lattner9cbfbc22006-01-07 01:32:28 +00003754 // We can handle signed (X << C1) >>s C2 if it's a sign extend. In
Chris Lattnereb372a02006-01-06 07:52:12 +00003755 // this case, C1 == C2 and C1 is 8, 16, or 32.
3756 if (ShiftAmt1 == ShiftAmt2) {
3757 const Type *SExtType = 0;
3758 switch (ShiftAmt1) {
3759 case 8 : SExtType = Type::SByteTy; break;
3760 case 16: SExtType = Type::ShortTy; break;
3761 case 32: SExtType = Type::IntTy; break;
3762 }
3763
3764 if (SExtType) {
3765 Instruction *NewTrunc = new CastInst(ShiftOp->getOperand(0),
3766 SExtType, "sext");
3767 InsertNewInstBefore(NewTrunc, I);
3768 return new CastInst(NewTrunc, I.getType());
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003769 }
Chris Lattner27cb9db2005-09-18 05:12:10 +00003770 }
Chris Lattner86102b82005-01-01 16:22:27 +00003771 }
Chris Lattnereb372a02006-01-06 07:52:12 +00003772 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003773 return 0;
3774}
3775
Chris Lattner4e2dbc62004-07-20 00:59:32 +00003776enum CastType {
3777 Noop = 0,
3778 Truncate = 1,
3779 Signext = 2,
3780 Zeroext = 3
3781};
3782
3783/// getCastType - In the future, we will split the cast instruction into these
3784/// various types. Until then, we have to do the analysis here.
3785static CastType getCastType(const Type *Src, const Type *Dest) {
3786 assert(Src->isIntegral() && Dest->isIntegral() &&
3787 "Only works on integral types!");
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003788 unsigned SrcSize = Src->getPrimitiveSizeInBits();
3789 unsigned DestSize = Dest->getPrimitiveSizeInBits();
Chris Lattner4e2dbc62004-07-20 00:59:32 +00003790
3791 if (SrcSize == DestSize) return Noop;
3792 if (SrcSize > DestSize) return Truncate;
3793 if (Src->isSigned()) return Signext;
3794 return Zeroext;
3795}
3796
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003797
Chris Lattner48a44f72002-05-02 17:06:02 +00003798// isEliminableCastOfCast - Return true if it is valid to eliminate the CI
3799// instruction.
3800//
Chris Lattnerdfae8be2003-07-24 17:35:25 +00003801static inline bool isEliminableCastOfCast(const Type *SrcTy, const Type *MidTy,
Chris Lattner11ffd592004-07-20 05:21:00 +00003802 const Type *DstTy, TargetData *TD) {
Chris Lattner48a44f72002-05-02 17:06:02 +00003803
Chris Lattner650b6da2002-08-02 20:00:25 +00003804 // It is legal to eliminate the instruction if casting A->B->A if the sizes
Misha Brukmanb1c93172005-04-21 23:48:37 +00003805 // are identical and the bits don't get reinterpreted (for example
Chris Lattner1638de42004-07-21 19:50:44 +00003806 // int->float->int would not be allowed).
Misha Brukmane5838c42003-05-20 18:45:36 +00003807 if (SrcTy == DstTy && SrcTy->isLosslesslyConvertibleTo(MidTy))
Chris Lattner650b6da2002-08-02 20:00:25 +00003808 return true;
Chris Lattner48a44f72002-05-02 17:06:02 +00003809
Chris Lattner4fbad962004-07-21 04:27:24 +00003810 // If we are casting between pointer and integer types, treat pointers as
3811 // integers of the appropriate size for the code below.
3812 if (isa<PointerType>(SrcTy)) SrcTy = TD->getIntPtrType();
3813 if (isa<PointerType>(MidTy)) MidTy = TD->getIntPtrType();
3814 if (isa<PointerType>(DstTy)) DstTy = TD->getIntPtrType();
Chris Lattner11ffd592004-07-20 05:21:00 +00003815
Chris Lattner48a44f72002-05-02 17:06:02 +00003816 // Allow free casting and conversion of sizes as long as the sign doesn't
3817 // change...
Chris Lattnerb0b412e2002-09-03 01:08:28 +00003818 if (SrcTy->isIntegral() && MidTy->isIntegral() && DstTy->isIntegral()) {
Chris Lattner4e2dbc62004-07-20 00:59:32 +00003819 CastType FirstCast = getCastType(SrcTy, MidTy);
3820 CastType SecondCast = getCastType(MidTy, DstTy);
Chris Lattner650b6da2002-08-02 20:00:25 +00003821
Chris Lattner4e2dbc62004-07-20 00:59:32 +00003822 // Capture the effect of these two casts. If the result is a legal cast,
3823 // the CastType is stored here, otherwise a special code is used.
3824 static const unsigned CastResult[] = {
3825 // First cast is noop
3826 0, 1, 2, 3,
3827 // First cast is a truncate
3828 1, 1, 4, 4, // trunc->extend is not safe to eliminate
3829 // First cast is a sign ext
Chris Lattner1638de42004-07-21 19:50:44 +00003830 2, 5, 2, 4, // signext->zeroext never ok
Chris Lattner4e2dbc62004-07-20 00:59:32 +00003831 // First cast is a zero ext
Chris Lattner1638de42004-07-21 19:50:44 +00003832 3, 5, 3, 3,
Chris Lattner4e2dbc62004-07-20 00:59:32 +00003833 };
3834
3835 unsigned Result = CastResult[FirstCast*4+SecondCast];
3836 switch (Result) {
3837 default: assert(0 && "Illegal table value!");
3838 case 0:
3839 case 1:
3840 case 2:
3841 case 3:
3842 // FIXME: in the future, when LLVM has explicit sign/zeroextends and
3843 // truncates, we could eliminate more casts.
3844 return (unsigned)getCastType(SrcTy, DstTy) == Result;
3845 case 4:
3846 return false; // Not possible to eliminate this here.
3847 case 5:
Chris Lattner1638de42004-07-21 19:50:44 +00003848 // Sign or zero extend followed by truncate is always ok if the result
3849 // is a truncate or noop.
3850 CastType ResultCast = getCastType(SrcTy, DstTy);
3851 if (ResultCast == Noop || ResultCast == Truncate)
3852 return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +00003853 // Otherwise we are still growing the value, we are only safe if the
Chris Lattner1638de42004-07-21 19:50:44 +00003854 // result will match the sign/zeroextendness of the result.
3855 return ResultCast == FirstCast;
Chris Lattner3732aca2002-08-15 16:15:25 +00003856 }
Chris Lattner650b6da2002-08-02 20:00:25 +00003857 }
Chris Lattner48a44f72002-05-02 17:06:02 +00003858 return false;
3859}
3860
Chris Lattner11ffd592004-07-20 05:21:00 +00003861static bool ValueRequiresCast(const Value *V, const Type *Ty, TargetData *TD) {
Chris Lattnerdfae8be2003-07-24 17:35:25 +00003862 if (V->getType() == Ty || isa<Constant>(V)) return false;
3863 if (const CastInst *CI = dyn_cast<CastInst>(V))
Chris Lattner11ffd592004-07-20 05:21:00 +00003864 if (isEliminableCastOfCast(CI->getOperand(0)->getType(), CI->getType(), Ty,
3865 TD))
Chris Lattnerdfae8be2003-07-24 17:35:25 +00003866 return false;
3867 return true;
3868}
3869
3870/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
3871/// InsertBefore instruction. This is specialized a bit to avoid inserting
3872/// casts that are known to not do anything...
3873///
3874Value *InstCombiner::InsertOperandCastBefore(Value *V, const Type *DestTy,
3875 Instruction *InsertBefore) {
3876 if (V->getType() == DestTy) return V;
3877 if (Constant *C = dyn_cast<Constant>(V))
3878 return ConstantExpr::getCast(C, DestTy);
3879
3880 CastInst *CI = new CastInst(V, DestTy, V->getName());
3881 InsertNewInstBefore(CI, *InsertBefore);
3882 return CI;
3883}
Chris Lattner48a44f72002-05-02 17:06:02 +00003884
Chris Lattner8f663e82005-10-29 04:36:15 +00003885/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
3886/// expression. If so, decompose it, returning some value X, such that Val is
3887/// X*Scale+Offset.
3888///
3889static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
3890 unsigned &Offset) {
3891 assert(Val->getType() == Type::UIntTy && "Unexpected allocation size type!");
3892 if (ConstantUInt *CI = dyn_cast<ConstantUInt>(Val)) {
3893 Offset = CI->getValue();
3894 Scale = 1;
3895 return ConstantUInt::get(Type::UIntTy, 0);
3896 } else if (Instruction *I = dyn_cast<Instruction>(Val)) {
3897 if (I->getNumOperands() == 2) {
3898 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(I->getOperand(1))) {
3899 if (I->getOpcode() == Instruction::Shl) {
3900 // This is a value scaled by '1 << the shift amt'.
3901 Scale = 1U << CUI->getValue();
3902 Offset = 0;
3903 return I->getOperand(0);
3904 } else if (I->getOpcode() == Instruction::Mul) {
3905 // This value is scaled by 'CUI'.
3906 Scale = CUI->getValue();
3907 Offset = 0;
3908 return I->getOperand(0);
3909 } else if (I->getOpcode() == Instruction::Add) {
3910 // We have X+C. Check to see if we really have (X*C2)+C1, where C1 is
3911 // divisible by C2.
3912 unsigned SubScale;
3913 Value *SubVal = DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
3914 Offset);
3915 Offset += CUI->getValue();
3916 if (SubScale > 1 && (Offset % SubScale == 0)) {
3917 Scale = SubScale;
3918 return SubVal;
3919 }
3920 }
3921 }
3922 }
3923 }
3924
3925 // Otherwise, we can't look past this.
3926 Scale = 1;
3927 Offset = 0;
3928 return Val;
3929}
3930
3931
Chris Lattner216be912005-10-24 06:03:58 +00003932/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
3933/// try to eliminate the cast by moving the type information into the alloc.
3934Instruction *InstCombiner::PromoteCastOfAllocation(CastInst &CI,
3935 AllocationInst &AI) {
3936 const PointerType *PTy = dyn_cast<PointerType>(CI.getType());
Chris Lattnerbb171802005-10-27 05:53:56 +00003937 if (!PTy) return 0; // Not casting the allocation to a pointer type.
Chris Lattner216be912005-10-24 06:03:58 +00003938
Chris Lattnerac87beb2005-10-24 06:22:12 +00003939 // Remove any uses of AI that are dead.
3940 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
3941 std::vector<Instruction*> DeadUsers;
3942 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
3943 Instruction *User = cast<Instruction>(*UI++);
3944 if (isInstructionTriviallyDead(User)) {
3945 while (UI != E && *UI == User)
3946 ++UI; // If this instruction uses AI more than once, don't break UI.
3947
3948 // Add operands to the worklist.
3949 AddUsesToWorkList(*User);
3950 ++NumDeadInst;
3951 DEBUG(std::cerr << "IC: DCE: " << *User);
3952
3953 User->eraseFromParent();
3954 removeFromWorkList(User);
3955 }
3956 }
3957
Chris Lattner216be912005-10-24 06:03:58 +00003958 // Get the type really allocated and the type casted to.
3959 const Type *AllocElTy = AI.getAllocatedType();
3960 const Type *CastElTy = PTy->getElementType();
3961 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner355ecc02005-10-24 06:26:18 +00003962
3963 unsigned AllocElTyAlign = TD->getTypeSize(AllocElTy);
3964 unsigned CastElTyAlign = TD->getTypeSize(CastElTy);
3965 if (CastElTyAlign < AllocElTyAlign) return 0;
3966
Chris Lattner46705b22005-10-24 06:35:18 +00003967 // If the allocation has multiple uses, only promote it if we are strictly
3968 // increasing the alignment of the resultant allocation. If we keep it the
3969 // same, we open the door to infinite loops of various kinds.
3970 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
3971
Chris Lattner216be912005-10-24 06:03:58 +00003972 uint64_t AllocElTySize = TD->getTypeSize(AllocElTy);
3973 uint64_t CastElTySize = TD->getTypeSize(CastElTy);
Chris Lattnerbb171802005-10-27 05:53:56 +00003974 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner355ecc02005-10-24 06:26:18 +00003975
Chris Lattner8270c332005-10-29 03:19:53 +00003976 // See if we can satisfy the modulus by pulling a scale out of the array
3977 // size argument.
Chris Lattner8f663e82005-10-29 04:36:15 +00003978 unsigned ArraySizeScale, ArrayOffset;
3979 Value *NumElements = // See if the array size is a decomposable linear expr.
3980 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
3981
Chris Lattner8270c332005-10-29 03:19:53 +00003982 // If we can now satisfy the modulus, by using a non-1 scale, we really can
3983 // do the xform.
Chris Lattner8f663e82005-10-29 04:36:15 +00003984 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
3985 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattnerb3ecf962005-10-27 06:12:00 +00003986
Chris Lattner8270c332005-10-29 03:19:53 +00003987 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
3988 Value *Amt = 0;
3989 if (Scale == 1) {
3990 Amt = NumElements;
3991 } else {
3992 Amt = ConstantUInt::get(Type::UIntTy, Scale);
3993 if (ConstantUInt *CI = dyn_cast<ConstantUInt>(NumElements))
3994 Amt = ConstantExpr::getMul(CI, cast<ConstantUInt>(Amt));
3995 else if (Scale != 1) {
3996 Instruction *Tmp = BinaryOperator::createMul(Amt, NumElements, "tmp");
3997 Amt = InsertNewInstBefore(Tmp, AI);
Chris Lattnerb3ecf962005-10-27 06:12:00 +00003998 }
Chris Lattnerbb171802005-10-27 05:53:56 +00003999 }
4000
Chris Lattner8f663e82005-10-29 04:36:15 +00004001 if (unsigned Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
4002 Value *Off = ConstantUInt::get(Type::UIntTy, Offset);
4003 Instruction *Tmp = BinaryOperator::createAdd(Amt, Off, "tmp");
4004 Amt = InsertNewInstBefore(Tmp, AI);
4005 }
4006
Chris Lattner216be912005-10-24 06:03:58 +00004007 std::string Name = AI.getName(); AI.setName("");
4008 AllocationInst *New;
4009 if (isa<MallocInst>(AI))
Nate Begeman848622f2005-11-05 09:21:28 +00004010 New = new MallocInst(CastElTy, Amt, AI.getAlignment(), Name);
Chris Lattner216be912005-10-24 06:03:58 +00004011 else
Nate Begeman848622f2005-11-05 09:21:28 +00004012 New = new AllocaInst(CastElTy, Amt, AI.getAlignment(), Name);
Chris Lattner216be912005-10-24 06:03:58 +00004013 InsertNewInstBefore(New, AI);
Chris Lattner46705b22005-10-24 06:35:18 +00004014
4015 // If the allocation has multiple uses, insert a cast and change all things
4016 // that used it to use the new cast. This will also hack on CI, but it will
4017 // die soon.
4018 if (!AI.hasOneUse()) {
4019 AddUsesToWorkList(AI);
4020 CastInst *NewCast = new CastInst(New, AI.getType(), "tmpcast");
4021 InsertNewInstBefore(NewCast, AI);
4022 AI.replaceAllUsesWith(NewCast);
4023 }
Chris Lattner216be912005-10-24 06:03:58 +00004024 return ReplaceInstUsesWith(CI, New);
4025}
4026
4027
Chris Lattner48a44f72002-05-02 17:06:02 +00004028// CastInst simplification
Chris Lattner260ab202002-04-18 17:39:14 +00004029//
Chris Lattner113f4f42002-06-25 16:13:24 +00004030Instruction *InstCombiner::visitCastInst(CastInst &CI) {
Chris Lattner55d4bda2003-06-23 21:59:52 +00004031 Value *Src = CI.getOperand(0);
4032
Chris Lattner48a44f72002-05-02 17:06:02 +00004033 // If the user is casting a value to the same type, eliminate this cast
4034 // instruction...
Chris Lattner55d4bda2003-06-23 21:59:52 +00004035 if (CI.getType() == Src->getType())
4036 return ReplaceInstUsesWith(CI, Src);
Chris Lattner48a44f72002-05-02 17:06:02 +00004037
Chris Lattner81a7a232004-10-16 18:11:37 +00004038 if (isa<UndefValue>(Src)) // cast undef -> undef
4039 return ReplaceInstUsesWith(CI, UndefValue::get(CI.getType()));
4040
Chris Lattner48a44f72002-05-02 17:06:02 +00004041 // If casting the result of another cast instruction, try to eliminate this
4042 // one!
4043 //
Chris Lattner86102b82005-01-01 16:22:27 +00004044 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
4045 Value *A = CSrc->getOperand(0);
4046 if (isEliminableCastOfCast(A->getType(), CSrc->getType(),
4047 CI.getType(), TD)) {
Chris Lattner48a44f72002-05-02 17:06:02 +00004048 // This instruction now refers directly to the cast's src operand. This
4049 // has a good chance of making CSrc dead.
Chris Lattner113f4f42002-06-25 16:13:24 +00004050 CI.setOperand(0, CSrc->getOperand(0));
4051 return &CI;
Chris Lattner48a44f72002-05-02 17:06:02 +00004052 }
4053
Chris Lattner650b6da2002-08-02 20:00:25 +00004054 // If this is an A->B->A cast, and we are dealing with integral types, try
4055 // to convert this into a logical 'and' instruction.
4056 //
Misha Brukmanb1c93172005-04-21 23:48:37 +00004057 if (A->getType()->isInteger() &&
Chris Lattnerb0b412e2002-09-03 01:08:28 +00004058 CI.getType()->isInteger() && CSrc->getType()->isInteger() &&
Chris Lattner86102b82005-01-01 16:22:27 +00004059 CSrc->getType()->isUnsigned() && // B->A cast must zero extend
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004060 CSrc->getType()->getPrimitiveSizeInBits() <
4061 CI.getType()->getPrimitiveSizeInBits()&&
4062 A->getType()->getPrimitiveSizeInBits() ==
4063 CI.getType()->getPrimitiveSizeInBits()) {
Chris Lattner650b6da2002-08-02 20:00:25 +00004064 assert(CSrc->getType() != Type::ULongTy &&
4065 "Cannot have type bigger than ulong!");
Chris Lattner2f1457f2005-04-24 17:46:05 +00004066 uint64_t AndValue = ~0ULL>>(64-CSrc->getType()->getPrimitiveSizeInBits());
Chris Lattner86102b82005-01-01 16:22:27 +00004067 Constant *AndOp = ConstantUInt::get(A->getType()->getUnsignedVersion(),
4068 AndValue);
4069 AndOp = ConstantExpr::getCast(AndOp, A->getType());
4070 Instruction *And = BinaryOperator::createAnd(CSrc->getOperand(0), AndOp);
4071 if (And->getType() != CI.getType()) {
4072 And->setName(CSrc->getName()+".mask");
4073 InsertNewInstBefore(And, CI);
4074 And = new CastInst(And, CI.getType());
4075 }
4076 return And;
Chris Lattner650b6da2002-08-02 20:00:25 +00004077 }
4078 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004079
Chris Lattner03841652004-05-25 04:29:21 +00004080 // If this is a cast to bool, turn it into the appropriate setne instruction.
4081 if (CI.getType() == Type::BoolTy)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004082 return BinaryOperator::createSetNE(CI.getOperand(0),
Chris Lattner03841652004-05-25 04:29:21 +00004083 Constant::getNullValue(CI.getOperand(0)->getType()));
4084
Chris Lattnerd0d51602003-06-21 23:12:02 +00004085 // If casting the result of a getelementptr instruction with no offset, turn
4086 // this into a cast of the original pointer!
4087 //
Chris Lattner55d4bda2003-06-23 21:59:52 +00004088 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattnerd0d51602003-06-21 23:12:02 +00004089 bool AllZeroOperands = true;
4090 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
4091 if (!isa<Constant>(GEP->getOperand(i)) ||
4092 !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
4093 AllZeroOperands = false;
4094 break;
4095 }
4096 if (AllZeroOperands) {
4097 CI.setOperand(0, GEP->getOperand(0));
4098 return &CI;
4099 }
4100 }
4101
Chris Lattnerf4ad1652003-11-02 05:57:39 +00004102 // If we are casting a malloc or alloca to a pointer to a type of the same
4103 // size, rewrite the allocation instruction to allocate the "right" type.
4104 //
4105 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
Chris Lattner216be912005-10-24 06:03:58 +00004106 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
4107 return V;
Chris Lattnerf4ad1652003-11-02 05:57:39 +00004108
Chris Lattner86102b82005-01-01 16:22:27 +00004109 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
4110 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
4111 return NV;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00004112 if (isa<PHINode>(Src))
4113 if (Instruction *NV = FoldOpIntoPhi(CI))
4114 return NV;
4115
Chris Lattnerdfae8be2003-07-24 17:35:25 +00004116 // If the source value is an instruction with only this use, we can attempt to
4117 // propagate the cast into the instruction. Also, only handle integral types
4118 // for now.
4119 if (Instruction *SrcI = dyn_cast<Instruction>(Src))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00004120 if (SrcI->hasOneUse() && Src->getType()->isIntegral() &&
Chris Lattnerdfae8be2003-07-24 17:35:25 +00004121 CI.getType()->isInteger()) { // Don't mess with casts to bool here
4122 const Type *DestTy = CI.getType();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004123 unsigned SrcBitSize = Src->getType()->getPrimitiveSizeInBits();
4124 unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
Chris Lattnerdfae8be2003-07-24 17:35:25 +00004125
4126 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
4127 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
4128
4129 switch (SrcI->getOpcode()) {
4130 case Instruction::Add:
4131 case Instruction::Mul:
4132 case Instruction::And:
4133 case Instruction::Or:
4134 case Instruction::Xor:
4135 // If we are discarding information, or just changing the sign, rewrite.
4136 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
4137 // Don't insert two casts if they cannot be eliminated. We allow two
4138 // casts to be inserted if the sizes are the same. This could only be
4139 // converting signedness, which is a noop.
Chris Lattner11ffd592004-07-20 05:21:00 +00004140 if (DestBitSize == SrcBitSize || !ValueRequiresCast(Op1, DestTy,TD) ||
4141 !ValueRequiresCast(Op0, DestTy, TD)) {
Chris Lattnerdfae8be2003-07-24 17:35:25 +00004142 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
4143 Value *Op1c = InsertOperandCastBefore(Op1, DestTy, SrcI);
4144 return BinaryOperator::create(cast<BinaryOperator>(SrcI)
4145 ->getOpcode(), Op0c, Op1c);
4146 }
4147 }
Chris Lattner72086162005-05-06 02:07:39 +00004148
4149 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
4150 if (SrcBitSize == 1 && SrcI->getOpcode() == Instruction::Xor &&
4151 Op1 == ConstantBool::True &&
4152 (!Op0->hasOneUse() || !isa<SetCondInst>(Op0))) {
4153 Value *New = InsertOperandCastBefore(Op0, DestTy, &CI);
4154 return BinaryOperator::createXor(New,
4155 ConstantInt::get(CI.getType(), 1));
4156 }
Chris Lattnerdfae8be2003-07-24 17:35:25 +00004157 break;
4158 case Instruction::Shl:
4159 // Allow changing the sign of the source operand. Do not allow changing
4160 // the size of the shift, UNLESS the shift amount is a constant. We
4161 // mush not change variable sized shifts to a smaller size, because it
4162 // is undefined to shift more bits out than exist in the value.
4163 if (DestBitSize == SrcBitSize ||
4164 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
4165 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
4166 return new ShiftInst(Instruction::Shl, Op0c, Op1);
4167 }
4168 break;
Chris Lattner87380412005-05-06 04:18:52 +00004169 case Instruction::Shr:
4170 // If this is a signed shr, and if all bits shifted in are about to be
4171 // truncated off, turn it into an unsigned shr to allow greater
4172 // simplifications.
4173 if (DestBitSize < SrcBitSize && Src->getType()->isSigned() &&
4174 isa<ConstantInt>(Op1)) {
4175 unsigned ShiftAmt = cast<ConstantUInt>(Op1)->getValue();
4176 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
4177 // Convert to unsigned.
4178 Value *N1 = InsertOperandCastBefore(Op0,
4179 Op0->getType()->getUnsignedVersion(), &CI);
4180 // Insert the new shift, which is now unsigned.
4181 N1 = InsertNewInstBefore(new ShiftInst(Instruction::Shr, N1,
4182 Op1, Src->getName()), CI);
4183 return new CastInst(N1, CI.getType());
4184 }
4185 }
4186 break;
4187
Chris Lattner809dfac2005-05-04 19:10:26 +00004188 case Instruction::SetNE:
Chris Lattner809dfac2005-05-04 19:10:26 +00004189 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner4c2d3782005-05-06 01:53:19 +00004190 if (Op1C->getRawValue() == 0) {
4191 // If the input only has the low bit set, simplify directly.
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00004192 Constant *Not1 =
Chris Lattner809dfac2005-05-04 19:10:26 +00004193 ConstantExpr::getNot(ConstantInt::get(Op0->getType(), 1));
Chris Lattner4c2d3782005-05-06 01:53:19 +00004194 // cast (X != 0) to int --> X if X&~1 == 0
Chris Lattner809dfac2005-05-04 19:10:26 +00004195 if (MaskedValueIsZero(Op0, cast<ConstantIntegral>(Not1))) {
4196 if (CI.getType() == Op0->getType())
4197 return ReplaceInstUsesWith(CI, Op0);
4198 else
4199 return new CastInst(Op0, CI.getType());
4200 }
Chris Lattner4c2d3782005-05-06 01:53:19 +00004201
4202 // If the input is an and with a single bit, shift then simplify.
4203 ConstantInt *AndRHS;
4204 if (match(Op0, m_And(m_Value(), m_ConstantInt(AndRHS))))
4205 if (AndRHS->getRawValue() &&
4206 (AndRHS->getRawValue() & (AndRHS->getRawValue()-1)) == 0) {
Chris Lattner22d00a82005-08-02 19:16:58 +00004207 unsigned ShiftAmt = Log2_64(AndRHS->getRawValue());
Chris Lattner4c2d3782005-05-06 01:53:19 +00004208 // Perform an unsigned shr by shiftamt. Convert input to
4209 // unsigned if it is signed.
4210 Value *In = Op0;
4211 if (In->getType()->isSigned())
4212 In = InsertNewInstBefore(new CastInst(In,
4213 In->getType()->getUnsignedVersion(), In->getName()),CI);
4214 // Insert the shift to put the result in the low bit.
4215 In = InsertNewInstBefore(new ShiftInst(Instruction::Shr, In,
4216 ConstantInt::get(Type::UByteTy, ShiftAmt),
4217 In->getName()+".lobit"), CI);
Chris Lattner4c2d3782005-05-06 01:53:19 +00004218 if (CI.getType() == In->getType())
4219 return ReplaceInstUsesWith(CI, In);
4220 else
4221 return new CastInst(In, CI.getType());
4222 }
4223 }
4224 }
4225 break;
4226 case Instruction::SetEQ:
4227 // We if we are just checking for a seteq of a single bit and casting it
4228 // to an integer. If so, shift the bit to the appropriate place then
4229 // cast to integer to avoid the comparison.
4230 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
4231 // Is Op1C a power of two or zero?
4232 if ((Op1C->getRawValue() & Op1C->getRawValue()-1) == 0) {
4233 // cast (X == 1) to int -> X iff X has only the low bit set.
4234 if (Op1C->getRawValue() == 1) {
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00004235 Constant *Not1 =
Chris Lattner4c2d3782005-05-06 01:53:19 +00004236 ConstantExpr::getNot(ConstantInt::get(Op0->getType(), 1));
4237 if (MaskedValueIsZero(Op0, cast<ConstantIntegral>(Not1))) {
4238 if (CI.getType() == Op0->getType())
4239 return ReplaceInstUsesWith(CI, Op0);
4240 else
4241 return new CastInst(Op0, CI.getType());
4242 }
4243 }
Chris Lattner809dfac2005-05-04 19:10:26 +00004244 }
4245 }
4246 break;
Chris Lattnerdfae8be2003-07-24 17:35:25 +00004247 }
4248 }
Chris Lattnerbb171802005-10-27 05:53:56 +00004249
Chris Lattner260ab202002-04-18 17:39:14 +00004250 return 0;
Chris Lattnerca081252001-12-14 16:52:21 +00004251}
4252
Chris Lattner56e4d3d2004-04-09 23:46:01 +00004253/// GetSelectFoldableOperands - We want to turn code that looks like this:
4254/// %C = or %A, %B
4255/// %D = select %cond, %C, %A
4256/// into:
4257/// %C = select %cond, %B, 0
4258/// %D = or %A, %C
4259///
4260/// Assuming that the specified instruction is an operand to the select, return
4261/// a bitmask indicating which operands of this instruction are foldable if they
4262/// equal the other incoming value of the select.
4263///
4264static unsigned GetSelectFoldableOperands(Instruction *I) {
4265 switch (I->getOpcode()) {
4266 case Instruction::Add:
4267 case Instruction::Mul:
4268 case Instruction::And:
4269 case Instruction::Or:
4270 case Instruction::Xor:
4271 return 3; // Can fold through either operand.
4272 case Instruction::Sub: // Can only fold on the amount subtracted.
4273 case Instruction::Shl: // Can only fold on the shift amount.
4274 case Instruction::Shr:
Misha Brukmanb1c93172005-04-21 23:48:37 +00004275 return 1;
Chris Lattner56e4d3d2004-04-09 23:46:01 +00004276 default:
4277 return 0; // Cannot fold
4278 }
4279}
4280
4281/// GetSelectFoldableConstant - For the same transformation as the previous
4282/// function, return the identity constant that goes into the select.
4283static Constant *GetSelectFoldableConstant(Instruction *I) {
4284 switch (I->getOpcode()) {
4285 default: assert(0 && "This cannot happen!"); abort();
4286 case Instruction::Add:
4287 case Instruction::Sub:
4288 case Instruction::Or:
4289 case Instruction::Xor:
4290 return Constant::getNullValue(I->getType());
4291 case Instruction::Shl:
4292 case Instruction::Shr:
4293 return Constant::getNullValue(Type::UByteTy);
4294 case Instruction::And:
4295 return ConstantInt::getAllOnesValue(I->getType());
4296 case Instruction::Mul:
4297 return ConstantInt::get(I->getType(), 1);
4298 }
4299}
4300
Chris Lattner411336f2005-01-19 21:50:18 +00004301/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
4302/// have the same opcode and only one use each. Try to simplify this.
4303Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
4304 Instruction *FI) {
4305 if (TI->getNumOperands() == 1) {
4306 // If this is a non-volatile load or a cast from the same type,
4307 // merge.
4308 if (TI->getOpcode() == Instruction::Cast) {
4309 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
4310 return 0;
4311 } else {
4312 return 0; // unknown unary op.
4313 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004314
Chris Lattner411336f2005-01-19 21:50:18 +00004315 // Fold this by inserting a select from the input values.
4316 SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
4317 FI->getOperand(0), SI.getName()+".v");
4318 InsertNewInstBefore(NewSI, SI);
4319 return new CastInst(NewSI, TI->getType());
4320 }
4321
4322 // Only handle binary operators here.
4323 if (!isa<ShiftInst>(TI) && !isa<BinaryOperator>(TI))
4324 return 0;
4325
4326 // Figure out if the operations have any operands in common.
4327 Value *MatchOp, *OtherOpT, *OtherOpF;
4328 bool MatchIsOpZero;
4329 if (TI->getOperand(0) == FI->getOperand(0)) {
4330 MatchOp = TI->getOperand(0);
4331 OtherOpT = TI->getOperand(1);
4332 OtherOpF = FI->getOperand(1);
4333 MatchIsOpZero = true;
4334 } else if (TI->getOperand(1) == FI->getOperand(1)) {
4335 MatchOp = TI->getOperand(1);
4336 OtherOpT = TI->getOperand(0);
4337 OtherOpF = FI->getOperand(0);
4338 MatchIsOpZero = false;
4339 } else if (!TI->isCommutative()) {
4340 return 0;
4341 } else if (TI->getOperand(0) == FI->getOperand(1)) {
4342 MatchOp = TI->getOperand(0);
4343 OtherOpT = TI->getOperand(1);
4344 OtherOpF = FI->getOperand(0);
4345 MatchIsOpZero = true;
4346 } else if (TI->getOperand(1) == FI->getOperand(0)) {
4347 MatchOp = TI->getOperand(1);
4348 OtherOpT = TI->getOperand(0);
4349 OtherOpF = FI->getOperand(1);
4350 MatchIsOpZero = true;
4351 } else {
4352 return 0;
4353 }
4354
4355 // If we reach here, they do have operations in common.
4356 SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
4357 OtherOpF, SI.getName()+".v");
4358 InsertNewInstBefore(NewSI, SI);
4359
4360 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
4361 if (MatchIsOpZero)
4362 return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
4363 else
4364 return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
4365 } else {
4366 if (MatchIsOpZero)
4367 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), MatchOp, NewSI);
4368 else
4369 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), NewSI, MatchOp);
4370 }
4371}
4372
Chris Lattnerb909e8b2004-03-12 05:52:32 +00004373Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattner533bc492004-03-30 19:37:13 +00004374 Value *CondVal = SI.getCondition();
4375 Value *TrueVal = SI.getTrueValue();
4376 Value *FalseVal = SI.getFalseValue();
4377
4378 // select true, X, Y -> X
4379 // select false, X, Y -> Y
4380 if (ConstantBool *C = dyn_cast<ConstantBool>(CondVal))
Chris Lattnerb909e8b2004-03-12 05:52:32 +00004381 if (C == ConstantBool::True)
Chris Lattner533bc492004-03-30 19:37:13 +00004382 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattnerb909e8b2004-03-12 05:52:32 +00004383 else {
4384 assert(C == ConstantBool::False);
Chris Lattner533bc492004-03-30 19:37:13 +00004385 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattnerb909e8b2004-03-12 05:52:32 +00004386 }
Chris Lattner533bc492004-03-30 19:37:13 +00004387
4388 // select C, X, X -> X
4389 if (TrueVal == FalseVal)
4390 return ReplaceInstUsesWith(SI, TrueVal);
4391
Chris Lattner81a7a232004-10-16 18:11:37 +00004392 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
4393 return ReplaceInstUsesWith(SI, FalseVal);
4394 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
4395 return ReplaceInstUsesWith(SI, TrueVal);
4396 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
4397 if (isa<Constant>(TrueVal))
4398 return ReplaceInstUsesWith(SI, TrueVal);
4399 else
4400 return ReplaceInstUsesWith(SI, FalseVal);
4401 }
4402
Chris Lattner1c631e82004-04-08 04:43:23 +00004403 if (SI.getType() == Type::BoolTy)
4404 if (ConstantBool *C = dyn_cast<ConstantBool>(TrueVal)) {
4405 if (C == ConstantBool::True) {
4406 // Change: A = select B, true, C --> A = or B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004407 return BinaryOperator::createOr(CondVal, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00004408 } else {
4409 // Change: A = select B, false, C --> A = and !B, C
4410 Value *NotCond =
4411 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
4412 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004413 return BinaryOperator::createAnd(NotCond, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00004414 }
4415 } else if (ConstantBool *C = dyn_cast<ConstantBool>(FalseVal)) {
4416 if (C == ConstantBool::False) {
4417 // Change: A = select B, C, false --> A = and B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004418 return BinaryOperator::createAnd(CondVal, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00004419 } else {
4420 // Change: A = select B, C, true --> A = or !B, C
4421 Value *NotCond =
4422 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
4423 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004424 return BinaryOperator::createOr(NotCond, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00004425 }
4426 }
4427
Chris Lattner183b3362004-04-09 19:05:30 +00004428 // Selecting between two integer constants?
4429 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
4430 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
4431 // select C, 1, 0 -> cast C to int
4432 if (FalseValC->isNullValue() && TrueValC->getRawValue() == 1) {
4433 return new CastInst(CondVal, SI.getType());
4434 } else if (TrueValC->isNullValue() && FalseValC->getRawValue() == 1) {
4435 // select C, 0, 1 -> cast !C to int
4436 Value *NotCond =
4437 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
Chris Lattnercf7baf32004-04-09 18:19:44 +00004438 "not."+CondVal->getName()), SI);
Chris Lattner183b3362004-04-09 19:05:30 +00004439 return new CastInst(NotCond, SI.getType());
Chris Lattnercf7baf32004-04-09 18:19:44 +00004440 }
Chris Lattner35167c32004-06-09 07:59:58 +00004441
4442 // If one of the constants is zero (we know they can't both be) and we
4443 // have a setcc instruction with zero, and we have an 'and' with the
4444 // non-constant value, eliminate this whole mess. This corresponds to
4445 // cases like this: ((X & 27) ? 27 : 0)
4446 if (TrueValC->isNullValue() || FalseValC->isNullValue())
4447 if (Instruction *IC = dyn_cast<Instruction>(SI.getCondition()))
4448 if ((IC->getOpcode() == Instruction::SetEQ ||
4449 IC->getOpcode() == Instruction::SetNE) &&
4450 isa<ConstantInt>(IC->getOperand(1)) &&
4451 cast<Constant>(IC->getOperand(1))->isNullValue())
4452 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
4453 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00004454 isa<ConstantInt>(ICA->getOperand(1)) &&
4455 (ICA->getOperand(1) == TrueValC ||
4456 ICA->getOperand(1) == FalseValC) &&
Chris Lattner35167c32004-06-09 07:59:58 +00004457 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
4458 // Okay, now we know that everything is set up, we just don't
4459 // know whether we have a setne or seteq and whether the true or
4460 // false val is the zero.
4461 bool ShouldNotVal = !TrueValC->isNullValue();
4462 ShouldNotVal ^= IC->getOpcode() == Instruction::SetNE;
4463 Value *V = ICA;
4464 if (ShouldNotVal)
4465 V = InsertNewInstBefore(BinaryOperator::create(
4466 Instruction::Xor, V, ICA->getOperand(1)), SI);
4467 return ReplaceInstUsesWith(SI, V);
4468 }
Chris Lattner533bc492004-03-30 19:37:13 +00004469 }
Chris Lattner623fba12004-04-10 22:21:27 +00004470
4471 // See if we are selecting two values based on a comparison of the two values.
4472 if (SetCondInst *SCI = dyn_cast<SetCondInst>(CondVal)) {
4473 if (SCI->getOperand(0) == TrueVal && SCI->getOperand(1) == FalseVal) {
4474 // Transform (X == Y) ? X : Y -> Y
4475 if (SCI->getOpcode() == Instruction::SetEQ)
4476 return ReplaceInstUsesWith(SI, FalseVal);
4477 // Transform (X != Y) ? X : Y -> X
4478 if (SCI->getOpcode() == Instruction::SetNE)
4479 return ReplaceInstUsesWith(SI, TrueVal);
4480 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
4481
4482 } else if (SCI->getOperand(0) == FalseVal && SCI->getOperand(1) == TrueVal){
4483 // Transform (X == Y) ? Y : X -> X
4484 if (SCI->getOpcode() == Instruction::SetEQ)
Chris Lattner24cf0202004-04-11 01:39:19 +00004485 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattner623fba12004-04-10 22:21:27 +00004486 // Transform (X != Y) ? Y : X -> Y
4487 if (SCI->getOpcode() == Instruction::SetNE)
Chris Lattner24cf0202004-04-11 01:39:19 +00004488 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattner623fba12004-04-10 22:21:27 +00004489 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
4490 }
4491 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004492
Chris Lattnera04c9042005-01-13 22:52:24 +00004493 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
4494 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
4495 if (TI->hasOneUse() && FI->hasOneUse()) {
4496 bool isInverse = false;
4497 Instruction *AddOp = 0, *SubOp = 0;
4498
Chris Lattner411336f2005-01-19 21:50:18 +00004499 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
4500 if (TI->getOpcode() == FI->getOpcode())
4501 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
4502 return IV;
4503
4504 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
4505 // even legal for FP.
Chris Lattnera04c9042005-01-13 22:52:24 +00004506 if (TI->getOpcode() == Instruction::Sub &&
4507 FI->getOpcode() == Instruction::Add) {
4508 AddOp = FI; SubOp = TI;
4509 } else if (FI->getOpcode() == Instruction::Sub &&
4510 TI->getOpcode() == Instruction::Add) {
4511 AddOp = TI; SubOp = FI;
4512 }
4513
4514 if (AddOp) {
4515 Value *OtherAddOp = 0;
4516 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
4517 OtherAddOp = AddOp->getOperand(1);
4518 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
4519 OtherAddOp = AddOp->getOperand(0);
4520 }
4521
4522 if (OtherAddOp) {
4523 // So at this point we know we have:
4524 // select C, (add X, Y), (sub X, ?)
4525 // We can do the transform profitably if either 'Y' = '?' or '?' is
4526 // a constant.
4527 if (SubOp->getOperand(1) == AddOp ||
4528 isa<Constant>(SubOp->getOperand(1))) {
4529 Value *NegVal;
4530 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
4531 NegVal = ConstantExpr::getNeg(C);
4532 } else {
4533 NegVal = InsertNewInstBefore(
4534 BinaryOperator::createNeg(SubOp->getOperand(1)), SI);
4535 }
4536
Chris Lattner51726c42005-01-14 17:35:12 +00004537 Value *NewTrueOp = OtherAddOp;
Chris Lattnera04c9042005-01-13 22:52:24 +00004538 Value *NewFalseOp = NegVal;
4539 if (AddOp != TI)
4540 std::swap(NewTrueOp, NewFalseOp);
4541 Instruction *NewSel =
4542 new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
Misha Brukmanb1c93172005-04-21 23:48:37 +00004543
Chris Lattnera04c9042005-01-13 22:52:24 +00004544 NewSel = InsertNewInstBefore(NewSel, SI);
Chris Lattner51726c42005-01-14 17:35:12 +00004545 return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
Chris Lattnera04c9042005-01-13 22:52:24 +00004546 }
4547 }
4548 }
4549 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004550
Chris Lattner56e4d3d2004-04-09 23:46:01 +00004551 // See if we can fold the select into one of our operands.
4552 if (SI.getType()->isInteger()) {
4553 // See the comment above GetSelectFoldableOperands for a description of the
4554 // transformation we are doing here.
4555 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
4556 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
4557 !isa<Constant>(FalseVal))
4558 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
4559 unsigned OpToFold = 0;
4560 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
4561 OpToFold = 1;
4562 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
4563 OpToFold = 2;
4564 }
4565
4566 if (OpToFold) {
4567 Constant *C = GetSelectFoldableConstant(TVI);
4568 std::string Name = TVI->getName(); TVI->setName("");
4569 Instruction *NewSel =
4570 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C,
4571 Name);
4572 InsertNewInstBefore(NewSel, SI);
4573 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
4574 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
4575 else if (ShiftInst *SI = dyn_cast<ShiftInst>(TVI))
4576 return new ShiftInst(SI->getOpcode(), FalseVal, NewSel);
4577 else {
4578 assert(0 && "Unknown instruction!!");
4579 }
4580 }
4581 }
Chris Lattner6862fbd2004-09-29 17:40:11 +00004582
Chris Lattner56e4d3d2004-04-09 23:46:01 +00004583 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
4584 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
4585 !isa<Constant>(TrueVal))
4586 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
4587 unsigned OpToFold = 0;
4588 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
4589 OpToFold = 1;
4590 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
4591 OpToFold = 2;
4592 }
4593
4594 if (OpToFold) {
4595 Constant *C = GetSelectFoldableConstant(FVI);
4596 std::string Name = FVI->getName(); FVI->setName("");
4597 Instruction *NewSel =
4598 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold),
4599 Name);
4600 InsertNewInstBefore(NewSel, SI);
4601 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
4602 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
4603 else if (ShiftInst *SI = dyn_cast<ShiftInst>(FVI))
4604 return new ShiftInst(SI->getOpcode(), TrueVal, NewSel);
4605 else {
4606 assert(0 && "Unknown instruction!!");
4607 }
4608 }
4609 }
4610 }
Chris Lattnerd6f636a2005-04-24 07:30:14 +00004611
4612 if (BinaryOperator::isNot(CondVal)) {
4613 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
4614 SI.setOperand(1, FalseVal);
4615 SI.setOperand(2, TrueVal);
4616 return &SI;
4617 }
4618
Chris Lattnerb909e8b2004-03-12 05:52:32 +00004619 return 0;
4620}
4621
4622
Chris Lattnerc66b2232006-01-13 20:11:04 +00004623/// visitCallInst - CallInst simplification. This mostly only handles folding
4624/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
4625/// the heavy lifting.
4626///
Chris Lattner970c33a2003-06-19 17:00:31 +00004627Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattnerc66b2232006-01-13 20:11:04 +00004628 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
4629 if (!II) return visitCallSite(&CI);
4630
Chris Lattner51ea1272004-02-28 05:22:00 +00004631 // Intrinsics cannot occur in an invoke, so handle them here instead of in
4632 // visitCallSite.
Chris Lattnerc66b2232006-01-13 20:11:04 +00004633 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner00648e12004-10-12 04:52:52 +00004634 bool Changed = false;
4635
4636 // memmove/cpy/set of zero bytes is a noop.
4637 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
4638 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
4639
4640 // FIXME: Increase alignment here.
Misha Brukmanb1c93172005-04-21 23:48:37 +00004641
Chris Lattner00648e12004-10-12 04:52:52 +00004642 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
4643 if (CI->getRawValue() == 1) {
4644 // Replace the instruction with just byte operations. We would
4645 // transform other cases to loads/stores, but we don't know if
4646 // alignment is sufficient.
4647 }
Chris Lattner51ea1272004-02-28 05:22:00 +00004648 }
4649
Chris Lattner00648e12004-10-12 04:52:52 +00004650 // If we have a memmove and the source operation is a constant global,
4651 // then the source and dest pointers can't alias, so we can change this
4652 // into a call to memcpy.
Chris Lattnerc66b2232006-01-13 20:11:04 +00004653 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(II))
Chris Lattner00648e12004-10-12 04:52:52 +00004654 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
4655 if (GVSrc->isConstant()) {
4656 Module *M = CI.getParent()->getParent()->getParent();
4657 Function *MemCpy = M->getOrInsertFunction("llvm.memcpy",
4658 CI.getCalledFunction()->getFunctionType());
4659 CI.setOperand(0, MemCpy);
4660 Changed = true;
4661 }
4662
Chris Lattnerc66b2232006-01-13 20:11:04 +00004663 if (Changed) return II;
4664 } else if (DbgStopPointInst *SPI = dyn_cast<DbgStopPointInst>(II)) {
Chris Lattner95307542004-11-18 21:41:39 +00004665 // If this stoppoint is at the same source location as the previous
4666 // stoppoint in the chain, it is not needed.
4667 if (DbgStopPointInst *PrevSPI =
4668 dyn_cast<DbgStopPointInst>(SPI->getChain()))
4669 if (SPI->getLineNo() == PrevSPI->getLineNo() &&
4670 SPI->getColNo() == PrevSPI->getColNo()) {
4671 SPI->replaceAllUsesWith(PrevSPI);
4672 return EraseInstFromFunction(CI);
4673 }
Chris Lattner00648e12004-10-12 04:52:52 +00004674 }
4675
Chris Lattnerc66b2232006-01-13 20:11:04 +00004676 return visitCallSite(II);
Chris Lattner970c33a2003-06-19 17:00:31 +00004677}
4678
4679// InvokeInst simplification
4680//
4681Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattneraec3d942003-10-07 22:32:43 +00004682 return visitCallSite(&II);
Chris Lattner970c33a2003-06-19 17:00:31 +00004683}
4684
Chris Lattneraec3d942003-10-07 22:32:43 +00004685// visitCallSite - Improvements for call and invoke instructions.
4686//
4687Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner75b4d1d2003-10-07 22:54:13 +00004688 bool Changed = false;
4689
4690 // If the callee is a constexpr cast of a function, attempt to move the cast
4691 // to the arguments of the call/invoke.
Chris Lattneraec3d942003-10-07 22:32:43 +00004692 if (transformConstExprCastCall(CS)) return 0;
4693
Chris Lattner75b4d1d2003-10-07 22:54:13 +00004694 Value *Callee = CS.getCalledValue();
Chris Lattner81a7a232004-10-16 18:11:37 +00004695
Chris Lattner61d9d812005-05-13 07:09:09 +00004696 if (Function *CalleeF = dyn_cast<Function>(Callee))
4697 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
4698 Instruction *OldCall = CS.getInstruction();
4699 // If the call and callee calling conventions don't match, this call must
4700 // be unreachable, as the call is undefined.
4701 new StoreInst(ConstantBool::True,
4702 UndefValue::get(PointerType::get(Type::BoolTy)), OldCall);
4703 if (!OldCall->use_empty())
4704 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
4705 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
4706 return EraseInstFromFunction(*OldCall);
4707 return 0;
4708 }
4709
Chris Lattner8ba9ec92004-10-18 02:59:09 +00004710 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
4711 // This instruction is not reachable, just remove it. We insert a store to
4712 // undef so that we know that this code is not reachable, despite the fact
4713 // that we can't modify the CFG here.
4714 new StoreInst(ConstantBool::True,
4715 UndefValue::get(PointerType::get(Type::BoolTy)),
4716 CS.getInstruction());
4717
4718 if (!CS.getInstruction()->use_empty())
4719 CS.getInstruction()->
4720 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
4721
4722 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
4723 // Don't break the CFG, insert a dummy cond branch.
4724 new BranchInst(II->getNormalDest(), II->getUnwindDest(),
4725 ConstantBool::True, II);
Chris Lattner81a7a232004-10-16 18:11:37 +00004726 }
Chris Lattner8ba9ec92004-10-18 02:59:09 +00004727 return EraseInstFromFunction(*CS.getInstruction());
4728 }
Chris Lattner81a7a232004-10-16 18:11:37 +00004729
Chris Lattner75b4d1d2003-10-07 22:54:13 +00004730 const PointerType *PTy = cast<PointerType>(Callee->getType());
4731 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
4732 if (FTy->isVarArg()) {
4733 // See if we can optimize any arguments passed through the varargs area of
4734 // the call.
4735 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
4736 E = CS.arg_end(); I != E; ++I)
4737 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
4738 // If this cast does not effect the value passed through the varargs
4739 // area, we can eliminate the use of the cast.
4740 Value *Op = CI->getOperand(0);
4741 if (CI->getType()->isLosslesslyConvertibleTo(Op->getType())) {
4742 *I = Op;
4743 Changed = true;
4744 }
4745 }
4746 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004747
Chris Lattner75b4d1d2003-10-07 22:54:13 +00004748 return Changed ? CS.getInstruction() : 0;
Chris Lattneraec3d942003-10-07 22:32:43 +00004749}
4750
Chris Lattner970c33a2003-06-19 17:00:31 +00004751// transformConstExprCastCall - If the callee is a constexpr cast of a function,
4752// attempt to move the cast to the arguments of the call/invoke.
4753//
4754bool InstCombiner::transformConstExprCastCall(CallSite CS) {
4755 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
4756 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Chris Lattnerf3edc492004-07-18 18:59:44 +00004757 if (CE->getOpcode() != Instruction::Cast || !isa<Function>(CE->getOperand(0)))
Chris Lattner970c33a2003-06-19 17:00:31 +00004758 return false;
Reid Spencer87436872004-07-18 00:38:32 +00004759 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner970c33a2003-06-19 17:00:31 +00004760 Instruction *Caller = CS.getInstruction();
4761
4762 // Okay, this is a cast from a function to a different type. Unless doing so
4763 // would cause a type conversion of one of our arguments, change this call to
4764 // be a direct call with arguments casted to the appropriate types.
4765 //
4766 const FunctionType *FT = Callee->getFunctionType();
4767 const Type *OldRetTy = Caller->getType();
4768
Chris Lattner1f7942f2004-01-14 06:06:08 +00004769 // Check to see if we are changing the return type...
4770 if (OldRetTy != FT->getReturnType()) {
4771 if (Callee->isExternal() &&
4772 !OldRetTy->isLosslesslyConvertibleTo(FT->getReturnType()) &&
4773 !Caller->use_empty())
4774 return false; // Cannot transform this return value...
4775
4776 // If the callsite is an invoke instruction, and the return value is used by
4777 // a PHI node in a successor, we cannot change the return type of the call
4778 // because there is no place to put the cast instruction (without breaking
4779 // the critical edge). Bail out in this case.
4780 if (!Caller->use_empty())
4781 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
4782 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
4783 UI != E; ++UI)
4784 if (PHINode *PN = dyn_cast<PHINode>(*UI))
4785 if (PN->getParent() == II->getNormalDest() ||
Chris Lattnerfae8ab32004-02-08 21:44:31 +00004786 PN->getParent() == II->getUnwindDest())
Chris Lattner1f7942f2004-01-14 06:06:08 +00004787 return false;
4788 }
Chris Lattner970c33a2003-06-19 17:00:31 +00004789
4790 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
4791 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004792
Chris Lattner970c33a2003-06-19 17:00:31 +00004793 CallSite::arg_iterator AI = CS.arg_begin();
4794 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
4795 const Type *ParamTy = FT->getParamType(i);
4796 bool isConvertible = (*AI)->getType()->isLosslesslyConvertibleTo(ParamTy);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004797 if (Callee->isExternal() && !isConvertible) return false;
Chris Lattner970c33a2003-06-19 17:00:31 +00004798 }
4799
4800 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
4801 Callee->isExternal())
4802 return false; // Do not delete arguments unless we have a function body...
4803
4804 // Okay, we decided that this is a safe thing to do: go ahead and start
4805 // inserting cast instructions as necessary...
4806 std::vector<Value*> Args;
4807 Args.reserve(NumActualArgs);
4808
4809 AI = CS.arg_begin();
4810 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
4811 const Type *ParamTy = FT->getParamType(i);
4812 if ((*AI)->getType() == ParamTy) {
4813 Args.push_back(*AI);
4814 } else {
Chris Lattner1c631e82004-04-08 04:43:23 +00004815 Args.push_back(InsertNewInstBefore(new CastInst(*AI, ParamTy, "tmp"),
4816 *Caller));
Chris Lattner970c33a2003-06-19 17:00:31 +00004817 }
4818 }
4819
4820 // If the function takes more arguments than the call was taking, add them
4821 // now...
4822 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
4823 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
4824
4825 // If we are removing arguments to the function, emit an obnoxious warning...
4826 if (FT->getNumParams() < NumActualArgs)
4827 if (!FT->isVarArg()) {
4828 std::cerr << "WARNING: While resolving call to function '"
4829 << Callee->getName() << "' arguments were dropped!\n";
4830 } else {
4831 // Add all of the arguments in their promoted form to the arg list...
4832 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
4833 const Type *PTy = getPromotedType((*AI)->getType());
4834 if (PTy != (*AI)->getType()) {
4835 // Must promote to pass through va_arg area!
4836 Instruction *Cast = new CastInst(*AI, PTy, "tmp");
4837 InsertNewInstBefore(Cast, *Caller);
4838 Args.push_back(Cast);
4839 } else {
4840 Args.push_back(*AI);
4841 }
4842 }
4843 }
4844
4845 if (FT->getReturnType() == Type::VoidTy)
4846 Caller->setName(""); // Void type should not have a name...
4847
4848 Instruction *NC;
4849 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Chris Lattnerfae8ab32004-02-08 21:44:31 +00004850 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
Chris Lattner970c33a2003-06-19 17:00:31 +00004851 Args, Caller->getName(), Caller);
Chris Lattner05c703e2005-05-14 12:25:32 +00004852 cast<InvokeInst>(II)->setCallingConv(II->getCallingConv());
Chris Lattner970c33a2003-06-19 17:00:31 +00004853 } else {
4854 NC = new CallInst(Callee, Args, Caller->getName(), Caller);
Chris Lattner6aacb0f2005-05-06 06:48:21 +00004855 if (cast<CallInst>(Caller)->isTailCall())
4856 cast<CallInst>(NC)->setTailCall();
Chris Lattner05c703e2005-05-14 12:25:32 +00004857 cast<CallInst>(NC)->setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Chris Lattner970c33a2003-06-19 17:00:31 +00004858 }
4859
4860 // Insert a cast of the return type as necessary...
4861 Value *NV = NC;
4862 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
4863 if (NV->getType() != Type::VoidTy) {
4864 NV = NC = new CastInst(NC, Caller->getType(), "tmp");
Chris Lattner686767f2003-10-30 00:46:41 +00004865
4866 // If this is an invoke instruction, we should insert it after the first
4867 // non-phi, instruction in the normal successor block.
4868 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
4869 BasicBlock::iterator I = II->getNormalDest()->begin();
4870 while (isa<PHINode>(I)) ++I;
4871 InsertNewInstBefore(NC, *I);
4872 } else {
4873 // Otherwise, it's a call, just insert cast right after the call instr
4874 InsertNewInstBefore(NC, *Caller);
4875 }
Chris Lattner51ea1272004-02-28 05:22:00 +00004876 AddUsersToWorkList(*Caller);
Chris Lattner970c33a2003-06-19 17:00:31 +00004877 } else {
Chris Lattnere29d6342004-10-17 21:22:38 +00004878 NV = UndefValue::get(Caller->getType());
Chris Lattner970c33a2003-06-19 17:00:31 +00004879 }
4880 }
4881
4882 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
4883 Caller->replaceAllUsesWith(NV);
4884 Caller->getParent()->getInstList().erase(Caller);
4885 removeFromWorkList(Caller);
4886 return true;
4887}
4888
4889
Chris Lattner7515cab2004-11-14 19:13:23 +00004890// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
4891// operator and they all are only used by the PHI, PHI together their
4892// inputs, and do the operation once, to the result of the PHI.
4893Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
4894 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
4895
4896 // Scan the instruction, looking for input operations that can be folded away.
4897 // If all input operands to the phi are the same instruction (e.g. a cast from
4898 // the same type or "+42") we can pull the operation through the PHI, reducing
4899 // code size and simplifying code.
4900 Constant *ConstantOp = 0;
4901 const Type *CastSrcTy = 0;
4902 if (isa<CastInst>(FirstInst)) {
4903 CastSrcTy = FirstInst->getOperand(0)->getType();
4904 } else if (isa<BinaryOperator>(FirstInst) || isa<ShiftInst>(FirstInst)) {
4905 // Can fold binop or shift if the RHS is a constant.
4906 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
4907 if (ConstantOp == 0) return 0;
4908 } else {
4909 return 0; // Cannot fold this operation.
4910 }
4911
4912 // Check to see if all arguments are the same operation.
4913 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
4914 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
4915 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
4916 if (!I->hasOneUse() || I->getOpcode() != FirstInst->getOpcode())
4917 return 0;
4918 if (CastSrcTy) {
4919 if (I->getOperand(0)->getType() != CastSrcTy)
4920 return 0; // Cast operation must match.
4921 } else if (I->getOperand(1) != ConstantOp) {
4922 return 0;
4923 }
4924 }
4925
4926 // Okay, they are all the same operation. Create a new PHI node of the
4927 // correct type, and PHI together all of the LHS's of the instructions.
4928 PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
4929 PN.getName()+".in");
Chris Lattnerd8e20182005-01-29 00:39:08 +00004930 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattner46dd5a62004-11-14 19:29:34 +00004931
4932 Value *InVal = FirstInst->getOperand(0);
4933 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattner7515cab2004-11-14 19:13:23 +00004934
4935 // Add all operands to the new PHI.
Chris Lattner46dd5a62004-11-14 19:29:34 +00004936 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
4937 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
4938 if (NewInVal != InVal)
4939 InVal = 0;
4940 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
4941 }
4942
4943 Value *PhiVal;
4944 if (InVal) {
4945 // The new PHI unions all of the same values together. This is really
4946 // common, so we handle it intelligently here for compile-time speed.
4947 PhiVal = InVal;
4948 delete NewPN;
4949 } else {
4950 InsertNewInstBefore(NewPN, PN);
4951 PhiVal = NewPN;
4952 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004953
Chris Lattner7515cab2004-11-14 19:13:23 +00004954 // Insert and return the new operation.
4955 if (isa<CastInst>(FirstInst))
Chris Lattner46dd5a62004-11-14 19:29:34 +00004956 return new CastInst(PhiVal, PN.getType());
Chris Lattner7515cab2004-11-14 19:13:23 +00004957 else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattner46dd5a62004-11-14 19:29:34 +00004958 return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattner7515cab2004-11-14 19:13:23 +00004959 else
4960 return new ShiftInst(cast<ShiftInst>(FirstInst)->getOpcode(),
Chris Lattner46dd5a62004-11-14 19:29:34 +00004961 PhiVal, ConstantOp);
Chris Lattner7515cab2004-11-14 19:13:23 +00004962}
Chris Lattner48a44f72002-05-02 17:06:02 +00004963
Chris Lattner71536432005-01-17 05:10:15 +00004964/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
4965/// that is dead.
4966static bool DeadPHICycle(PHINode *PN, std::set<PHINode*> &PotentiallyDeadPHIs) {
4967 if (PN->use_empty()) return true;
4968 if (!PN->hasOneUse()) return false;
4969
4970 // Remember this node, and if we find the cycle, return.
4971 if (!PotentiallyDeadPHIs.insert(PN).second)
4972 return true;
4973
4974 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
4975 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004976
Chris Lattner71536432005-01-17 05:10:15 +00004977 return false;
4978}
4979
Chris Lattnerbbbdd852002-05-06 18:06:38 +00004980// PHINode simplification
4981//
Chris Lattner113f4f42002-06-25 16:13:24 +00004982Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Chris Lattner9f9c2602005-08-05 01:04:30 +00004983 if (Value *V = PN.hasConstantValue())
4984 return ReplaceInstUsesWith(PN, V);
Chris Lattner4db2d222004-02-16 05:07:08 +00004985
4986 // If the only user of this instruction is a cast instruction, and all of the
4987 // incoming values are constants, change this PHI to merge together the casted
4988 // constants.
4989 if (PN.hasOneUse())
4990 if (CastInst *CI = dyn_cast<CastInst>(PN.use_back()))
4991 if (CI->getType() != PN.getType()) { // noop casts will be folded
4992 bool AllConstant = true;
4993 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
4994 if (!isa<Constant>(PN.getIncomingValue(i))) {
4995 AllConstant = false;
4996 break;
4997 }
4998 if (AllConstant) {
4999 // Make a new PHI with all casted values.
5000 PHINode *New = new PHINode(CI->getType(), PN.getName(), &PN);
5001 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
5002 Constant *OldArg = cast<Constant>(PN.getIncomingValue(i));
5003 New->addIncoming(ConstantExpr::getCast(OldArg, New->getType()),
5004 PN.getIncomingBlock(i));
5005 }
5006
5007 // Update the cast instruction.
5008 CI->setOperand(0, New);
5009 WorkList.push_back(CI); // revisit the cast instruction to fold.
5010 WorkList.push_back(New); // Make sure to revisit the new Phi
5011 return &PN; // PN is now dead!
5012 }
5013 }
Chris Lattner7515cab2004-11-14 19:13:23 +00005014
5015 // If all PHI operands are the same operation, pull them through the PHI,
5016 // reducing code size.
5017 if (isa<Instruction>(PN.getIncomingValue(0)) &&
5018 PN.getIncomingValue(0)->hasOneUse())
5019 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
5020 return Result;
5021
Chris Lattner71536432005-01-17 05:10:15 +00005022 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
5023 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
5024 // PHI)... break the cycle.
5025 if (PN.hasOneUse())
5026 if (PHINode *PU = dyn_cast<PHINode>(PN.use_back())) {
5027 std::set<PHINode*> PotentiallyDeadPHIs;
5028 PotentiallyDeadPHIs.insert(&PN);
5029 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
5030 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
5031 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00005032
Chris Lattner91daeb52003-12-19 05:58:40 +00005033 return 0;
Chris Lattnerbbbdd852002-05-06 18:06:38 +00005034}
5035
Chris Lattner69193f92004-04-05 01:30:19 +00005036static Value *InsertSignExtendToPtrTy(Value *V, const Type *DTy,
5037 Instruction *InsertPoint,
5038 InstCombiner *IC) {
5039 unsigned PS = IC->getTargetData().getPointerSize();
5040 const Type *VTy = V->getType();
Chris Lattner69193f92004-04-05 01:30:19 +00005041 if (!VTy->isSigned() && VTy->getPrimitiveSize() < PS)
5042 // We must insert a cast to ensure we sign-extend.
5043 V = IC->InsertNewInstBefore(new CastInst(V, VTy->getSignedVersion(),
5044 V->getName()), *InsertPoint);
5045 return IC->InsertNewInstBefore(new CastInst(V, DTy, V->getName()),
5046 *InsertPoint);
5047}
5048
Chris Lattner48a44f72002-05-02 17:06:02 +00005049
Chris Lattner113f4f42002-06-25 16:13:24 +00005050Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner5f667a62004-05-07 22:09:22 +00005051 Value *PtrOp = GEP.getOperand(0);
Chris Lattner471bd762003-05-22 19:07:21 +00005052 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
Chris Lattner113f4f42002-06-25 16:13:24 +00005053 // If so, eliminate the noop.
Chris Lattner8d0bacb2004-02-22 05:25:17 +00005054 if (GEP.getNumOperands() == 1)
Chris Lattner5f667a62004-05-07 22:09:22 +00005055 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner8d0bacb2004-02-22 05:25:17 +00005056
Chris Lattner81a7a232004-10-16 18:11:37 +00005057 if (isa<UndefValue>(GEP.getOperand(0)))
5058 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
5059
Chris Lattner8d0bacb2004-02-22 05:25:17 +00005060 bool HasZeroPointerIndex = false;
5061 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
5062 HasZeroPointerIndex = C->isNullValue();
5063
5064 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner5f667a62004-05-07 22:09:22 +00005065 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner48a44f72002-05-02 17:06:02 +00005066
Chris Lattner69193f92004-04-05 01:30:19 +00005067 // Eliminate unneeded casts for indices.
5068 bool MadeChange = false;
Chris Lattner2b2412d2004-04-07 18:38:20 +00005069 gep_type_iterator GTI = gep_type_begin(GEP);
5070 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI)
5071 if (isa<SequentialType>(*GTI)) {
5072 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
5073 Value *Src = CI->getOperand(0);
5074 const Type *SrcTy = Src->getType();
5075 const Type *DestTy = CI->getType();
5076 if (Src->getType()->isInteger()) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005077 if (SrcTy->getPrimitiveSizeInBits() ==
5078 DestTy->getPrimitiveSizeInBits()) {
Chris Lattner2b2412d2004-04-07 18:38:20 +00005079 // We can always eliminate a cast from ulong or long to the other.
5080 // We can always eliminate a cast from uint to int or the other on
5081 // 32-bit pointer platforms.
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005082 if (DestTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()){
Chris Lattner2b2412d2004-04-07 18:38:20 +00005083 MadeChange = true;
5084 GEP.setOperand(i, Src);
5085 }
5086 } else if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
5087 SrcTy->getPrimitiveSize() == 4) {
5088 // We can always eliminate a cast from int to [u]long. We can
5089 // eliminate a cast from uint to [u]long iff the target is a 32-bit
5090 // pointer target.
Misha Brukmanb1c93172005-04-21 23:48:37 +00005091 if (SrcTy->isSigned() ||
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005092 SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
Chris Lattner2b2412d2004-04-07 18:38:20 +00005093 MadeChange = true;
5094 GEP.setOperand(i, Src);
5095 }
Chris Lattner69193f92004-04-05 01:30:19 +00005096 }
5097 }
5098 }
Chris Lattner2b2412d2004-04-07 18:38:20 +00005099 // If we are using a wider index than needed for this platform, shrink it
5100 // to what we need. If the incoming value needs a cast instruction,
5101 // insert it. This explicit cast can make subsequent optimizations more
5102 // obvious.
5103 Value *Op = GEP.getOperand(i);
5104 if (Op->getType()->getPrimitiveSize() > TD->getPointerSize())
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00005105 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner44d0b952004-07-20 01:48:15 +00005106 GEP.setOperand(i, ConstantExpr::getCast(C,
5107 TD->getIntPtrType()->getSignedVersion()));
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00005108 MadeChange = true;
5109 } else {
Chris Lattner2b2412d2004-04-07 18:38:20 +00005110 Op = InsertNewInstBefore(new CastInst(Op, TD->getIntPtrType(),
5111 Op->getName()), GEP);
5112 GEP.setOperand(i, Op);
5113 MadeChange = true;
5114 }
Chris Lattner44d0b952004-07-20 01:48:15 +00005115
5116 // If this is a constant idx, make sure to canonicalize it to be a signed
5117 // operand, otherwise CSE and other optimizations are pessimized.
5118 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op)) {
5119 GEP.setOperand(i, ConstantExpr::getCast(CUI,
5120 CUI->getType()->getSignedVersion()));
5121 MadeChange = true;
5122 }
Chris Lattner69193f92004-04-05 01:30:19 +00005123 }
5124 if (MadeChange) return &GEP;
5125
Chris Lattnerae7a0d32002-08-02 19:29:35 +00005126 // Combine Indices - If the source pointer to this getelementptr instruction
5127 // is a getelementptr instruction, combine the indices of the two
5128 // getelementptr instructions into a single instruction.
5129 //
Chris Lattner57c67b02004-03-25 22:59:29 +00005130 std::vector<Value*> SrcGEPOperands;
Chris Lattner0798af32005-01-13 20:14:25 +00005131 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattner57c67b02004-03-25 22:59:29 +00005132 SrcGEPOperands.assign(Src->op_begin(), Src->op_end());
Chris Lattner57c67b02004-03-25 22:59:29 +00005133
5134 if (!SrcGEPOperands.empty()) {
Chris Lattner5f667a62004-05-07 22:09:22 +00005135 // Note that if our source is a gep chain itself that we wait for that
5136 // chain to be resolved before we perform this transformation. This
5137 // avoids us creating a TON of code in some cases.
5138 //
5139 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
5140 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
5141 return 0; // Wait until our source is folded to completion.
5142
Chris Lattnerae7a0d32002-08-02 19:29:35 +00005143 std::vector<Value *> Indices;
Chris Lattner5f667a62004-05-07 22:09:22 +00005144
5145 // Find out whether the last index in the source GEP is a sequential idx.
5146 bool EndsWithSequential = false;
5147 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
5148 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattner8ec5f882004-05-08 22:41:42 +00005149 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00005150
Chris Lattnerae7a0d32002-08-02 19:29:35 +00005151 // Can we combine the two pointer arithmetics offsets?
Chris Lattner5f667a62004-05-07 22:09:22 +00005152 if (EndsWithSequential) {
Chris Lattner235af562003-03-05 22:33:14 +00005153 // Replace: gep (gep %P, long B), long A, ...
5154 // With: T = long A+B; gep %P, T, ...
5155 //
Chris Lattner5f667a62004-05-07 22:09:22 +00005156 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner69193f92004-04-05 01:30:19 +00005157 if (SO1 == Constant::getNullValue(SO1->getType())) {
5158 Sum = GO1;
5159 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
5160 Sum = SO1;
5161 } else {
5162 // If they aren't the same type, convert both to an integer of the
5163 // target's pointer size.
5164 if (SO1->getType() != GO1->getType()) {
5165 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
5166 SO1 = ConstantExpr::getCast(SO1C, GO1->getType());
5167 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
5168 GO1 = ConstantExpr::getCast(GO1C, SO1->getType());
5169 } else {
5170 unsigned PS = TD->getPointerSize();
Chris Lattner69193f92004-04-05 01:30:19 +00005171 if (SO1->getType()->getPrimitiveSize() == PS) {
5172 // Convert GO1 to SO1's type.
5173 GO1 = InsertSignExtendToPtrTy(GO1, SO1->getType(), &GEP, this);
5174
5175 } else if (GO1->getType()->getPrimitiveSize() == PS) {
5176 // Convert SO1 to GO1's type.
5177 SO1 = InsertSignExtendToPtrTy(SO1, GO1->getType(), &GEP, this);
5178 } else {
5179 const Type *PT = TD->getIntPtrType();
5180 SO1 = InsertSignExtendToPtrTy(SO1, PT, &GEP, this);
5181 GO1 = InsertSignExtendToPtrTy(GO1, PT, &GEP, this);
5182 }
5183 }
5184 }
Chris Lattner5f667a62004-05-07 22:09:22 +00005185 if (isa<Constant>(SO1) && isa<Constant>(GO1))
5186 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
5187 else {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00005188 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
5189 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner5f667a62004-05-07 22:09:22 +00005190 }
Chris Lattner69193f92004-04-05 01:30:19 +00005191 }
Chris Lattner5f667a62004-05-07 22:09:22 +00005192
5193 // Recycle the GEP we already have if possible.
5194 if (SrcGEPOperands.size() == 2) {
5195 GEP.setOperand(0, SrcGEPOperands[0]);
5196 GEP.setOperand(1, Sum);
5197 return &GEP;
5198 } else {
5199 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
5200 SrcGEPOperands.end()-1);
5201 Indices.push_back(Sum);
5202 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
5203 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00005204 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner69193f92004-04-05 01:30:19 +00005205 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00005206 SrcGEPOperands.size() != 1) {
Chris Lattnerae7a0d32002-08-02 19:29:35 +00005207 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattner57c67b02004-03-25 22:59:29 +00005208 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
5209 SrcGEPOperands.end());
Chris Lattnerae7a0d32002-08-02 19:29:35 +00005210 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
5211 }
5212
5213 if (!Indices.empty())
Chris Lattner57c67b02004-03-25 22:59:29 +00005214 return new GetElementPtrInst(SrcGEPOperands[0], Indices, GEP.getName());
Chris Lattnerc59af1d2002-08-17 22:21:59 +00005215
Chris Lattner5f667a62004-05-07 22:09:22 +00005216 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattnerc59af1d2002-08-17 22:21:59 +00005217 // GEP of global variable. If all of the indices for this GEP are
5218 // constants, we can promote this to a constexpr instead of an instruction.
5219
5220 // Scan for nonconstants...
5221 std::vector<Constant*> Indices;
5222 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
5223 for (; I != E && isa<Constant>(*I); ++I)
5224 Indices.push_back(cast<Constant>(*I));
5225
5226 if (I == E) { // If they are all constants...
Chris Lattnerf3edc492004-07-18 18:59:44 +00005227 Constant *CE = ConstantExpr::getGetElementPtr(GV, Indices);
Chris Lattnerc59af1d2002-08-17 22:21:59 +00005228
5229 // Replace all uses of the GEP with the new constexpr...
5230 return ReplaceInstUsesWith(GEP, CE);
5231 }
Chris Lattner567b81f2005-09-13 00:40:14 +00005232 } else if (Value *X = isCast(PtrOp)) { // Is the operand a cast?
5233 if (!isa<PointerType>(X->getType())) {
5234 // Not interesting. Source pointer must be a cast from pointer.
5235 } else if (HasZeroPointerIndex) {
5236 // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
5237 // into : GEP [10 x ubyte]* X, long 0, ...
5238 //
5239 // This occurs when the program declares an array extern like "int X[];"
5240 //
5241 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
5242 const PointerType *XTy = cast<PointerType>(X->getType());
5243 if (const ArrayType *XATy =
5244 dyn_cast<ArrayType>(XTy->getElementType()))
5245 if (const ArrayType *CATy =
5246 dyn_cast<ArrayType>(CPTy->getElementType()))
5247 if (CATy->getElementType() == XATy->getElementType()) {
5248 // At this point, we know that the cast source type is a pointer
5249 // to an array of the same type as the destination pointer
5250 // array. Because the array type is never stepped over (there
5251 // is a leading zero) we can fold the cast into this GEP.
5252 GEP.setOperand(0, X);
5253 return &GEP;
5254 }
5255 } else if (GEP.getNumOperands() == 2) {
5256 // Transform things like:
Chris Lattner2a893292005-09-13 18:36:04 +00005257 // %t = getelementptr ubyte* cast ([2 x int]* %str to uint*), uint %V
5258 // into: %t1 = getelementptr [2 x int*]* %str, int 0, uint %V; cast
Chris Lattner567b81f2005-09-13 00:40:14 +00005259 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
5260 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
5261 if (isa<ArrayType>(SrcElTy) &&
5262 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
5263 TD->getTypeSize(ResElTy)) {
5264 Value *V = InsertNewInstBefore(
5265 new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
5266 GEP.getOperand(1), GEP.getName()), GEP);
5267 return new CastInst(V, GEP.getType());
Chris Lattner8d0bacb2004-02-22 05:25:17 +00005268 }
Chris Lattner2a893292005-09-13 18:36:04 +00005269
5270 // Transform things like:
5271 // getelementptr sbyte* cast ([100 x double]* X to sbyte*), int %tmp
5272 // (where tmp = 8*tmp2) into:
5273 // getelementptr [100 x double]* %arr, int 0, int %tmp.2
5274
5275 if (isa<ArrayType>(SrcElTy) &&
5276 (ResElTy == Type::SByteTy || ResElTy == Type::UByteTy)) {
5277 uint64_t ArrayEltSize =
5278 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType());
5279
5280 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
5281 // allow either a mul, shift, or constant here.
5282 Value *NewIdx = 0;
5283 ConstantInt *Scale = 0;
5284 if (ArrayEltSize == 1) {
5285 NewIdx = GEP.getOperand(1);
5286 Scale = ConstantInt::get(NewIdx->getType(), 1);
5287 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Chris Lattnera393e4d2005-09-14 17:32:56 +00005288 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner2a893292005-09-13 18:36:04 +00005289 Scale = CI;
5290 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
5291 if (Inst->getOpcode() == Instruction::Shl &&
5292 isa<ConstantInt>(Inst->getOperand(1))) {
5293 unsigned ShAmt =cast<ConstantUInt>(Inst->getOperand(1))->getValue();
5294 if (Inst->getType()->isSigned())
5295 Scale = ConstantSInt::get(Inst->getType(), 1ULL << ShAmt);
5296 else
5297 Scale = ConstantUInt::get(Inst->getType(), 1ULL << ShAmt);
5298 NewIdx = Inst->getOperand(0);
5299 } else if (Inst->getOpcode() == Instruction::Mul &&
5300 isa<ConstantInt>(Inst->getOperand(1))) {
5301 Scale = cast<ConstantInt>(Inst->getOperand(1));
5302 NewIdx = Inst->getOperand(0);
5303 }
5304 }
5305
5306 // If the index will be to exactly the right offset with the scale taken
5307 // out, perform the transformation.
5308 if (Scale && Scale->getRawValue() % ArrayEltSize == 0) {
5309 if (ConstantSInt *C = dyn_cast<ConstantSInt>(Scale))
5310 Scale = ConstantSInt::get(C->getType(),
Chris Lattnera393e4d2005-09-14 17:32:56 +00005311 (int64_t)C->getRawValue() /
5312 (int64_t)ArrayEltSize);
Chris Lattner2a893292005-09-13 18:36:04 +00005313 else
5314 Scale = ConstantUInt::get(Scale->getType(),
5315 Scale->getRawValue() / ArrayEltSize);
5316 if (Scale->getRawValue() != 1) {
5317 Constant *C = ConstantExpr::getCast(Scale, NewIdx->getType());
5318 Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
5319 NewIdx = InsertNewInstBefore(Sc, GEP);
5320 }
5321
5322 // Insert the new GEP instruction.
5323 Instruction *Idx =
5324 new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
5325 NewIdx, GEP.getName());
5326 Idx = InsertNewInstBefore(Idx, GEP);
5327 return new CastInst(Idx, GEP.getType());
5328 }
5329 }
Chris Lattner8d0bacb2004-02-22 05:25:17 +00005330 }
Chris Lattnerca081252001-12-14 16:52:21 +00005331 }
5332
Chris Lattnerca081252001-12-14 16:52:21 +00005333 return 0;
5334}
5335
Chris Lattner1085bdf2002-11-04 16:18:53 +00005336Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
5337 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
5338 if (AI.isArrayAllocation()) // Check C != 1
5339 if (const ConstantUInt *C = dyn_cast<ConstantUInt>(AI.getArraySize())) {
5340 const Type *NewTy = ArrayType::get(AI.getAllocatedType(), C->getValue());
Chris Lattnera2620ac2002-11-09 00:49:43 +00005341 AllocationInst *New = 0;
Chris Lattner1085bdf2002-11-04 16:18:53 +00005342
5343 // Create and insert the replacement instruction...
5344 if (isa<MallocInst>(AI))
Nate Begeman848622f2005-11-05 09:21:28 +00005345 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00005346 else {
5347 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Nate Begeman848622f2005-11-05 09:21:28 +00005348 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00005349 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00005350
5351 InsertNewInstBefore(New, AI);
Misha Brukmanb1c93172005-04-21 23:48:37 +00005352
Chris Lattner1085bdf2002-11-04 16:18:53 +00005353 // Scan to the end of the allocation instructions, to skip over a block of
5354 // allocas if possible...
5355 //
5356 BasicBlock::iterator It = New;
5357 while (isa<AllocationInst>(*It)) ++It;
5358
5359 // Now that I is pointing to the first non-allocation-inst in the block,
5360 // insert our getelementptr instruction...
5361 //
Chris Lattner809dfac2005-05-04 19:10:26 +00005362 Value *NullIdx = Constant::getNullValue(Type::IntTy);
5363 Value *V = new GetElementPtrInst(New, NullIdx, NullIdx,
5364 New->getName()+".sub", It);
Chris Lattner1085bdf2002-11-04 16:18:53 +00005365
5366 // Now make everything use the getelementptr instead of the original
5367 // allocation.
Chris Lattnerabb77c92004-03-19 06:08:10 +00005368 return ReplaceInstUsesWith(AI, V);
Chris Lattner81a7a232004-10-16 18:11:37 +00005369 } else if (isa<UndefValue>(AI.getArraySize())) {
5370 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner1085bdf2002-11-04 16:18:53 +00005371 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00005372
5373 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
5374 // Note that we only do this for alloca's, because malloc should allocate and
5375 // return a unique pointer, even for a zero byte allocation.
Misha Brukmanb1c93172005-04-21 23:48:37 +00005376 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
Chris Lattner49df6ce2004-07-02 22:55:47 +00005377 TD->getTypeSize(AI.getAllocatedType()) == 0)
Chris Lattnerabb77c92004-03-19 06:08:10 +00005378 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
5379
Chris Lattner1085bdf2002-11-04 16:18:53 +00005380 return 0;
5381}
5382
Chris Lattner8427bff2003-12-07 01:24:23 +00005383Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
5384 Value *Op = FI.getOperand(0);
5385
5386 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
5387 if (CastInst *CI = dyn_cast<CastInst>(Op))
5388 if (isa<PointerType>(CI->getOperand(0)->getType())) {
5389 FI.setOperand(0, CI->getOperand(0));
5390 return &FI;
5391 }
5392
Chris Lattner8ba9ec92004-10-18 02:59:09 +00005393 // free undef -> unreachable.
5394 if (isa<UndefValue>(Op)) {
5395 // Insert a new store to null because we cannot modify the CFG here.
5396 new StoreInst(ConstantBool::True,
5397 UndefValue::get(PointerType::get(Type::BoolTy)), &FI);
5398 return EraseInstFromFunction(FI);
5399 }
5400
Chris Lattnerf3a36602004-02-28 04:57:37 +00005401 // If we have 'free null' delete the instruction. This can happen in stl code
5402 // when lots of inlining happens.
Chris Lattner8ba9ec92004-10-18 02:59:09 +00005403 if (isa<ConstantPointerNull>(Op))
Chris Lattner51ea1272004-02-28 05:22:00 +00005404 return EraseInstFromFunction(FI);
Chris Lattnerf3a36602004-02-28 04:57:37 +00005405
Chris Lattner8427bff2003-12-07 01:24:23 +00005406 return 0;
5407}
5408
5409
Chris Lattner72684fe2005-01-31 05:51:45 +00005410/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Chris Lattner35e24772004-07-13 01:49:43 +00005411static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
5412 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00005413 Value *CastOp = CI->getOperand(0);
Chris Lattner35e24772004-07-13 01:49:43 +00005414
5415 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00005416 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Chris Lattner35e24772004-07-13 01:49:43 +00005417 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00005418
5419 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
5420 // If the source is an array, the code below will not succeed. Check to
5421 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
5422 // constants.
5423 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
5424 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
5425 if (ASrcTy->getNumElements() != 0) {
5426 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
5427 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
5428 SrcTy = cast<PointerType>(CastOp->getType());
5429 SrcPTy = SrcTy->getElementType();
5430 }
5431
5432 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
Chris Lattnerecfa9b52005-03-29 06:37:47 +00005433 // Do not allow turning this into a load of an integer, which is then
5434 // casted to a pointer, this pessimizes pointer analysis a lot.
5435 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00005436 IC.getTargetData().getTypeSize(SrcPTy) ==
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00005437 IC.getTargetData().getTypeSize(DestPTy)) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00005438
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00005439 // Okay, we are casting from one integer or pointer type to another of
5440 // the same size. Instead of casting the pointer before the load, cast
5441 // the result of the loaded value.
5442 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
5443 CI->getName(),
5444 LI.isVolatile()),LI);
5445 // Now cast the result of the load.
5446 return new CastInst(NewLoad, LI.getType());
5447 }
Chris Lattner35e24772004-07-13 01:49:43 +00005448 }
5449 }
5450 return 0;
5451}
5452
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00005453/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattnere6f13092004-09-19 19:18:10 +00005454/// from this value cannot trap. If it is not obviously safe to load from the
5455/// specified pointer, we do a quick local scan of the basic block containing
5456/// ScanFrom, to determine if the address is already accessed.
5457static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
5458 // If it is an alloca or global variable, it is always safe to load from.
5459 if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
5460
5461 // Otherwise, be a little bit agressive by scanning the local block where we
5462 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00005463 // from/to. If so, the previous load or store would have already trapped,
5464 // so there is no harm doing an extra load (also, CSE will later eliminate
5465 // the load entirely).
Chris Lattnere6f13092004-09-19 19:18:10 +00005466 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
5467
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00005468 while (BBI != E) {
Chris Lattnere6f13092004-09-19 19:18:10 +00005469 --BBI;
5470
5471 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
5472 if (LI->getOperand(0) == V) return true;
5473 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
5474 if (SI->getOperand(1) == V) return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +00005475
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00005476 }
Chris Lattnere6f13092004-09-19 19:18:10 +00005477 return false;
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00005478}
5479
Chris Lattner0f1d8a32003-06-26 05:06:25 +00005480Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
5481 Value *Op = LI.getOperand(0);
Chris Lattner7e8af382004-01-12 04:13:56 +00005482
Chris Lattnera9d84e32005-05-01 04:24:53 +00005483 // load (cast X) --> cast (load X) iff safe
5484 if (CastInst *CI = dyn_cast<CastInst>(Op))
5485 if (Instruction *Res = InstCombineLoadCast(*this, LI))
5486 return Res;
5487
5488 // None of the following transforms are legal for volatile loads.
5489 if (LI.isVolatile()) return 0;
Chris Lattnerb990f7d2005-09-12 22:00:15 +00005490
Chris Lattnerb990f7d2005-09-12 22:00:15 +00005491 if (&LI.getParent()->front() != &LI) {
5492 BasicBlock::iterator BBI = &LI; --BBI;
Chris Lattnere0bfdf12005-09-12 22:21:03 +00005493 // If the instruction immediately before this is a store to the same
5494 // address, do a simple form of store->load forwarding.
Chris Lattnerb990f7d2005-09-12 22:00:15 +00005495 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
5496 if (SI->getOperand(1) == LI.getOperand(0))
5497 return ReplaceInstUsesWith(LI, SI->getOperand(0));
Chris Lattnere0bfdf12005-09-12 22:21:03 +00005498 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
5499 if (LIB->getOperand(0) == LI.getOperand(0))
5500 return ReplaceInstUsesWith(LI, LIB);
Chris Lattnerb990f7d2005-09-12 22:00:15 +00005501 }
Chris Lattnera9d84e32005-05-01 04:24:53 +00005502
5503 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op))
5504 if (isa<ConstantPointerNull>(GEPI->getOperand(0)) ||
5505 isa<UndefValue>(GEPI->getOperand(0))) {
5506 // Insert a new store to null instruction before the load to indicate
5507 // that this code is not reachable. We do this instead of inserting
5508 // an unreachable instruction directly because we cannot modify the
5509 // CFG.
5510 new StoreInst(UndefValue::get(LI.getType()),
5511 Constant::getNullValue(Op->getType()), &LI);
5512 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
5513 }
5514
Chris Lattner81a7a232004-10-16 18:11:37 +00005515 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattnera9d84e32005-05-01 04:24:53 +00005516 // load null/undef -> undef
5517 if ((C->isNullValue() || isa<UndefValue>(C))) {
Chris Lattner8ba9ec92004-10-18 02:59:09 +00005518 // Insert a new store to null instruction before the load to indicate that
5519 // this code is not reachable. We do this instead of inserting an
5520 // unreachable instruction directly because we cannot modify the CFG.
Chris Lattnera9d84e32005-05-01 04:24:53 +00005521 new StoreInst(UndefValue::get(LI.getType()),
5522 Constant::getNullValue(Op->getType()), &LI);
Chris Lattner81a7a232004-10-16 18:11:37 +00005523 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner8ba9ec92004-10-18 02:59:09 +00005524 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00005525
Chris Lattner81a7a232004-10-16 18:11:37 +00005526 // Instcombine load (constant global) into the value loaded.
5527 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
5528 if (GV->isConstant() && !GV->isExternal())
5529 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanb1c93172005-04-21 23:48:37 +00005530
Chris Lattner81a7a232004-10-16 18:11:37 +00005531 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
5532 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
5533 if (CE->getOpcode() == Instruction::GetElementPtr) {
5534 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
5535 if (GV->isConstant() && !GV->isExternal())
Chris Lattner0b011ec2005-09-26 05:28:06 +00005536 if (Constant *V =
5537 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
Chris Lattner81a7a232004-10-16 18:11:37 +00005538 return ReplaceInstUsesWith(LI, V);
Chris Lattnera9d84e32005-05-01 04:24:53 +00005539 if (CE->getOperand(0)->isNullValue()) {
5540 // Insert a new store to null instruction before the load to indicate
5541 // that this code is not reachable. We do this instead of inserting
5542 // an unreachable instruction directly because we cannot modify the
5543 // CFG.
5544 new StoreInst(UndefValue::get(LI.getType()),
5545 Constant::getNullValue(Op->getType()), &LI);
5546 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
5547 }
5548
Chris Lattner81a7a232004-10-16 18:11:37 +00005549 } else if (CE->getOpcode() == Instruction::Cast) {
5550 if (Instruction *Res = InstCombineLoadCast(*this, LI))
5551 return Res;
5552 }
5553 }
Chris Lattnere228ee52004-04-08 20:39:49 +00005554
Chris Lattnera9d84e32005-05-01 04:24:53 +00005555 if (Op->hasOneUse()) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00005556 // Change select and PHI nodes to select values instead of addresses: this
5557 // helps alias analysis out a lot, allows many others simplifications, and
5558 // exposes redundancy in the code.
5559 //
5560 // Note that we cannot do the transformation unless we know that the
5561 // introduced loads cannot trap! Something like this is valid as long as
5562 // the condition is always false: load (select bool %C, int* null, int* %G),
5563 // but it would not be valid if we transformed it to load from null
5564 // unconditionally.
5565 //
5566 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
5567 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattnere6f13092004-09-19 19:18:10 +00005568 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
5569 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00005570 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner42618552004-09-20 10:15:10 +00005571 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00005572 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner42618552004-09-20 10:15:10 +00005573 SI->getOperand(2)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00005574 return new SelectInst(SI->getCondition(), V1, V2);
5575 }
5576
Chris Lattnerbdcf41a2004-09-23 15:46:00 +00005577 // load (select (cond, null, P)) -> load P
5578 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
5579 if (C->isNullValue()) {
5580 LI.setOperand(0, SI->getOperand(2));
5581 return &LI;
5582 }
5583
5584 // load (select (cond, P, null)) -> load P
5585 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
5586 if (C->isNullValue()) {
5587 LI.setOperand(0, SI->getOperand(1));
5588 return &LI;
5589 }
5590
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00005591 } else if (PHINode *PN = dyn_cast<PHINode>(Op)) {
5592 // load (phi (&V1, &V2, &V3)) --> phi(load &V1, load &V2, load &V3)
Chris Lattner42618552004-09-20 10:15:10 +00005593 bool Safe = PN->getParent() == LI.getParent();
5594
5595 // Scan all of the instructions between the PHI and the load to make
5596 // sure there are no instructions that might possibly alter the value
5597 // loaded from the PHI.
5598 if (Safe) {
5599 BasicBlock::iterator I = &LI;
5600 for (--I; !isa<PHINode>(I); --I)
5601 if (isa<StoreInst>(I) || isa<CallInst>(I)) {
5602 Safe = false;
5603 break;
5604 }
5605 }
5606
5607 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e && Safe; ++i)
Chris Lattnere6f13092004-09-19 19:18:10 +00005608 if (!isSafeToLoadUnconditionally(PN->getIncomingValue(i),
Chris Lattner42618552004-09-20 10:15:10 +00005609 PN->getIncomingBlock(i)->getTerminator()))
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00005610 Safe = false;
Chris Lattner42618552004-09-20 10:15:10 +00005611
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00005612 if (Safe) {
5613 // Create the PHI.
5614 PHINode *NewPN = new PHINode(LI.getType(), PN->getName());
5615 InsertNewInstBefore(NewPN, *PN);
5616 std::map<BasicBlock*,Value*> LoadMap; // Don't insert duplicate loads
5617
5618 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
5619 BasicBlock *BB = PN->getIncomingBlock(i);
5620 Value *&TheLoad = LoadMap[BB];
5621 if (TheLoad == 0) {
5622 Value *InVal = PN->getIncomingValue(i);
5623 TheLoad = InsertNewInstBefore(new LoadInst(InVal,
5624 InVal->getName()+".val"),
5625 *BB->getTerminator());
5626 }
5627 NewPN->addIncoming(TheLoad, BB);
5628 }
5629 return ReplaceInstUsesWith(LI, NewPN);
5630 }
5631 }
5632 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00005633 return 0;
5634}
5635
Chris Lattner72684fe2005-01-31 05:51:45 +00005636/// InstCombineStoreToCast - Fold 'store V, (cast P)' -> store (cast V), P'
5637/// when possible.
5638static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
5639 User *CI = cast<User>(SI.getOperand(1));
5640 Value *CastOp = CI->getOperand(0);
5641
5642 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
5643 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
5644 const Type *SrcPTy = SrcTy->getElementType();
5645
5646 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
5647 // If the source is an array, the code below will not succeed. Check to
5648 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
5649 // constants.
5650 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
5651 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
5652 if (ASrcTy->getNumElements() != 0) {
5653 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
5654 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
5655 SrcTy = cast<PointerType>(CastOp->getType());
5656 SrcPTy = SrcTy->getElementType();
5657 }
5658
5659 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00005660 IC.getTargetData().getTypeSize(SrcPTy) ==
Chris Lattner72684fe2005-01-31 05:51:45 +00005661 IC.getTargetData().getTypeSize(DestPTy)) {
5662
5663 // Okay, we are casting from one integer or pointer type to another of
5664 // the same size. Instead of casting the pointer before the store, cast
5665 // the value to be stored.
5666 Value *NewCast;
5667 if (Constant *C = dyn_cast<Constant>(SI.getOperand(0)))
5668 NewCast = ConstantExpr::getCast(C, SrcPTy);
5669 else
5670 NewCast = IC.InsertNewInstBefore(new CastInst(SI.getOperand(0),
5671 SrcPTy,
5672 SI.getOperand(0)->getName()+".c"), SI);
5673
5674 return new StoreInst(NewCast, CastOp);
5675 }
5676 }
5677 }
5678 return 0;
5679}
5680
Chris Lattner31f486c2005-01-31 05:36:43 +00005681Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
5682 Value *Val = SI.getOperand(0);
5683 Value *Ptr = SI.getOperand(1);
5684
5685 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
5686 removeFromWorkList(&SI);
5687 SI.eraseFromParent();
5688 ++NumCombined;
5689 return 0;
5690 }
5691
5692 if (SI.isVolatile()) return 0; // Don't hack volatile loads.
5693
5694 // store X, null -> turns into 'unreachable' in SimplifyCFG
5695 if (isa<ConstantPointerNull>(Ptr)) {
5696 if (!isa<UndefValue>(Val)) {
5697 SI.setOperand(0, UndefValue::get(Val->getType()));
5698 if (Instruction *U = dyn_cast<Instruction>(Val))
5699 WorkList.push_back(U); // Dropped a use.
5700 ++NumCombined;
5701 }
5702 return 0; // Do not modify these!
5703 }
5704
5705 // store undef, Ptr -> noop
5706 if (isa<UndefValue>(Val)) {
5707 removeFromWorkList(&SI);
5708 SI.eraseFromParent();
5709 ++NumCombined;
5710 return 0;
5711 }
5712
Chris Lattner72684fe2005-01-31 05:51:45 +00005713 // If the pointer destination is a cast, see if we can fold the cast into the
5714 // source instead.
5715 if (CastInst *CI = dyn_cast<CastInst>(Ptr))
5716 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
5717 return Res;
5718 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
5719 if (CE->getOpcode() == Instruction::Cast)
5720 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
5721 return Res;
5722
Chris Lattner219175c2005-09-12 23:23:25 +00005723
5724 // If this store is the last instruction in the basic block, and if the block
5725 // ends with an unconditional branch, try to move it to the successor block.
5726 BasicBlock::iterator BBI = &SI; ++BBI;
5727 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
5728 if (BI->isUnconditional()) {
5729 // Check to see if the successor block has exactly two incoming edges. If
5730 // so, see if the other predecessor contains a store to the same location.
5731 // if so, insert a PHI node (if needed) and move the stores down.
5732 BasicBlock *Dest = BI->getSuccessor(0);
5733
5734 pred_iterator PI = pred_begin(Dest);
5735 BasicBlock *Other = 0;
5736 if (*PI != BI->getParent())
5737 Other = *PI;
5738 ++PI;
5739 if (PI != pred_end(Dest)) {
5740 if (*PI != BI->getParent())
5741 if (Other)
5742 Other = 0;
5743 else
5744 Other = *PI;
5745 if (++PI != pred_end(Dest))
5746 Other = 0;
5747 }
5748 if (Other) { // If only one other pred...
5749 BBI = Other->getTerminator();
5750 // Make sure this other block ends in an unconditional branch and that
5751 // there is an instruction before the branch.
5752 if (isa<BranchInst>(BBI) && cast<BranchInst>(BBI)->isUnconditional() &&
5753 BBI != Other->begin()) {
5754 --BBI;
5755 StoreInst *OtherStore = dyn_cast<StoreInst>(BBI);
5756
5757 // If this instruction is a store to the same location.
5758 if (OtherStore && OtherStore->getOperand(1) == SI.getOperand(1)) {
5759 // Okay, we know we can perform this transformation. Insert a PHI
5760 // node now if we need it.
5761 Value *MergedVal = OtherStore->getOperand(0);
5762 if (MergedVal != SI.getOperand(0)) {
5763 PHINode *PN = new PHINode(MergedVal->getType(), "storemerge");
5764 PN->reserveOperandSpace(2);
5765 PN->addIncoming(SI.getOperand(0), SI.getParent());
5766 PN->addIncoming(OtherStore->getOperand(0), Other);
5767 MergedVal = InsertNewInstBefore(PN, Dest->front());
5768 }
5769
5770 // Advance to a place where it is safe to insert the new store and
5771 // insert it.
5772 BBI = Dest->begin();
5773 while (isa<PHINode>(BBI)) ++BBI;
5774 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
5775 OtherStore->isVolatile()), *BBI);
5776
5777 // Nuke the old stores.
5778 removeFromWorkList(&SI);
5779 removeFromWorkList(OtherStore);
5780 SI.eraseFromParent();
5781 OtherStore->eraseFromParent();
5782 ++NumCombined;
5783 return 0;
5784 }
5785 }
5786 }
5787 }
5788
Chris Lattner31f486c2005-01-31 05:36:43 +00005789 return 0;
5790}
5791
5792
Chris Lattner9eef8a72003-06-04 04:46:00 +00005793Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
5794 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4fdd96c2005-06-18 17:37:34 +00005795 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00005796 BasicBlock *TrueDest;
5797 BasicBlock *FalseDest;
5798 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
5799 !isa<Constant>(X)) {
5800 // Swap Destinations and condition...
5801 BI.setCondition(X);
5802 BI.setSuccessor(0, FalseDest);
5803 BI.setSuccessor(1, TrueDest);
5804 return &BI;
5805 }
5806
5807 // Cannonicalize setne -> seteq
5808 Instruction::BinaryOps Op; Value *Y;
5809 if (match(&BI, m_Br(m_SetCond(Op, m_Value(X), m_Value(Y)),
5810 TrueDest, FalseDest)))
5811 if ((Op == Instruction::SetNE || Op == Instruction::SetLE ||
5812 Op == Instruction::SetGE) && BI.getCondition()->hasOneUse()) {
5813 SetCondInst *I = cast<SetCondInst>(BI.getCondition());
5814 std::string Name = I->getName(); I->setName("");
5815 Instruction::BinaryOps NewOpcode = SetCondInst::getInverseCondition(Op);
5816 Value *NewSCC = BinaryOperator::create(NewOpcode, X, Y, Name, I);
Chris Lattnere967b342003-06-04 05:10:11 +00005817 // Swap Destinations and condition...
Chris Lattnerd4252a72004-07-30 07:50:03 +00005818 BI.setCondition(NewSCC);
Chris Lattnere967b342003-06-04 05:10:11 +00005819 BI.setSuccessor(0, FalseDest);
5820 BI.setSuccessor(1, TrueDest);
Chris Lattnerd4252a72004-07-30 07:50:03 +00005821 removeFromWorkList(I);
5822 I->getParent()->getInstList().erase(I);
5823 WorkList.push_back(cast<Instruction>(NewSCC));
Chris Lattnere967b342003-06-04 05:10:11 +00005824 return &BI;
5825 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00005826
Chris Lattner9eef8a72003-06-04 04:46:00 +00005827 return 0;
5828}
Chris Lattner1085bdf2002-11-04 16:18:53 +00005829
Chris Lattner4c9c20a2004-07-03 00:26:11 +00005830Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
5831 Value *Cond = SI.getCondition();
5832 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
5833 if (I->getOpcode() == Instruction::Add)
5834 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
5835 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
5836 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattner81a7a232004-10-16 18:11:37 +00005837 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner4c9c20a2004-07-03 00:26:11 +00005838 AddRHS));
5839 SI.setOperand(0, I->getOperand(0));
5840 WorkList.push_back(I);
5841 return &SI;
5842 }
5843 }
5844 return 0;
5845}
5846
Chris Lattner99f48c62002-09-02 04:59:56 +00005847void InstCombiner::removeFromWorkList(Instruction *I) {
5848 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
5849 WorkList.end());
5850}
5851
Chris Lattner39c98bb2004-12-08 23:43:58 +00005852
5853/// TryToSinkInstruction - Try to move the specified instruction from its
5854/// current block into the beginning of DestBlock, which can only happen if it's
5855/// safe to move the instruction past all of the instructions between it and the
5856/// end of its block.
5857static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
5858 assert(I->hasOneUse() && "Invariants didn't hold!");
5859
Chris Lattnerc4f67e62005-10-27 17:13:11 +00005860 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
5861 if (isa<PHINode>(I) || I->mayWriteToMemory()) return false;
Misha Brukmanb1c93172005-04-21 23:48:37 +00005862
Chris Lattner39c98bb2004-12-08 23:43:58 +00005863 // Do not sink alloca instructions out of the entry block.
5864 if (isa<AllocaInst>(I) && I->getParent() == &DestBlock->getParent()->front())
5865 return false;
5866
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00005867 // We can only sink load instructions if there is nothing between the load and
5868 // the end of block that could change the value.
5869 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00005870 for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
5871 Scan != E; ++Scan)
5872 if (Scan->mayWriteToMemory())
5873 return false;
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00005874 }
Chris Lattner39c98bb2004-12-08 23:43:58 +00005875
5876 BasicBlock::iterator InsertPos = DestBlock->begin();
5877 while (isa<PHINode>(InsertPos)) ++InsertPos;
5878
Chris Lattner9f269e42005-08-08 19:11:57 +00005879 I->moveBefore(InsertPos);
Chris Lattner39c98bb2004-12-08 23:43:58 +00005880 ++NumSunkInst;
5881 return true;
5882}
5883
Chris Lattner113f4f42002-06-25 16:13:24 +00005884bool InstCombiner::runOnFunction(Function &F) {
Chris Lattner260ab202002-04-18 17:39:14 +00005885 bool Changed = false;
Chris Lattnerf4ad1652003-11-02 05:57:39 +00005886 TD = &getAnalysis<TargetData>();
Chris Lattnerca081252001-12-14 16:52:21 +00005887
Chris Lattner4ed40f72005-07-07 20:40:38 +00005888 {
5889 // Populate the worklist with the reachable instructions.
5890 std::set<BasicBlock*> Visited;
5891 for (df_ext_iterator<BasicBlock*> BB = df_ext_begin(&F.front(), Visited),
5892 E = df_ext_end(&F.front(), Visited); BB != E; ++BB)
5893 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
5894 WorkList.push_back(I);
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00005895
Chris Lattner4ed40f72005-07-07 20:40:38 +00005896 // Do a quick scan over the function. If we find any blocks that are
5897 // unreachable, remove any instructions inside of them. This prevents
5898 // the instcombine code from having to deal with some bad special cases.
5899 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
5900 if (!Visited.count(BB)) {
5901 Instruction *Term = BB->getTerminator();
5902 while (Term != BB->begin()) { // Remove instrs bottom-up
5903 BasicBlock::iterator I = Term; --I;
Chris Lattner2d3a7a62004-04-27 15:13:33 +00005904
Chris Lattner4ed40f72005-07-07 20:40:38 +00005905 DEBUG(std::cerr << "IC: DCE: " << *I);
5906 ++NumDeadInst;
5907
5908 if (!I->use_empty())
5909 I->replaceAllUsesWith(UndefValue::get(I->getType()));
5910 I->eraseFromParent();
5911 }
5912 }
5913 }
Chris Lattnerca081252001-12-14 16:52:21 +00005914
5915 while (!WorkList.empty()) {
5916 Instruction *I = WorkList.back(); // Get an instruction from the worklist
5917 WorkList.pop_back();
5918
Misha Brukman632df282002-10-29 23:06:16 +00005919 // Check to see if we can DCE or ConstantPropagate the instruction...
Chris Lattner99f48c62002-09-02 04:59:56 +00005920 // Check to see if we can DIE the instruction...
5921 if (isInstructionTriviallyDead(I)) {
5922 // Add operands to the worklist...
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00005923 if (I->getNumOperands() < 4)
Chris Lattner51ea1272004-02-28 05:22:00 +00005924 AddUsesToWorkList(*I);
Chris Lattner99f48c62002-09-02 04:59:56 +00005925 ++NumDeadInst;
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00005926
Chris Lattnercd517ff2005-01-28 19:32:01 +00005927 DEBUG(std::cerr << "IC: DCE: " << *I);
5928
5929 I->eraseFromParent();
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00005930 removeFromWorkList(I);
5931 continue;
5932 }
Chris Lattner99f48c62002-09-02 04:59:56 +00005933
Misha Brukman632df282002-10-29 23:06:16 +00005934 // Instruction isn't dead, see if we can constant propagate it...
Chris Lattner99f48c62002-09-02 04:59:56 +00005935 if (Constant *C = ConstantFoldInstruction(I)) {
Alkis Evlogimenosa1291a02004-12-08 23:10:30 +00005936 Value* Ptr = I->getOperand(0);
Chris Lattner6580e092004-10-16 19:44:59 +00005937 if (isa<GetElementPtrInst>(I) &&
Alkis Evlogimenosa1291a02004-12-08 23:10:30 +00005938 cast<Constant>(Ptr)->isNullValue() &&
5939 !isa<ConstantPointerNull>(C) &&
5940 cast<PointerType>(Ptr->getType())->getElementType()->isSized()) {
Chris Lattner6580e092004-10-16 19:44:59 +00005941 // If this is a constant expr gep that is effectively computing an
5942 // "offsetof", fold it into 'cast int X to T*' instead of 'gep 0, 0, 12'
5943 bool isFoldableGEP = true;
5944 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i)
5945 if (!isa<ConstantInt>(I->getOperand(i)))
5946 isFoldableGEP = false;
5947 if (isFoldableGEP) {
Alkis Evlogimenosa1291a02004-12-08 23:10:30 +00005948 uint64_t Offset = TD->getIndexedOffset(Ptr->getType(),
Chris Lattner6580e092004-10-16 19:44:59 +00005949 std::vector<Value*>(I->op_begin()+1, I->op_end()));
5950 C = ConstantUInt::get(Type::ULongTy, Offset);
Chris Lattner684c5c62004-10-16 19:46:33 +00005951 C = ConstantExpr::getCast(C, TD->getIntPtrType());
Chris Lattner6580e092004-10-16 19:44:59 +00005952 C = ConstantExpr::getCast(C, I->getType());
5953 }
5954 }
5955
Chris Lattnercd517ff2005-01-28 19:32:01 +00005956 DEBUG(std::cerr << "IC: ConstFold to: " << *C << " from: " << *I);
5957
Chris Lattner99f48c62002-09-02 04:59:56 +00005958 // Add operands to the worklist...
Chris Lattner51ea1272004-02-28 05:22:00 +00005959 AddUsesToWorkList(*I);
Chris Lattnerc6509f42002-12-05 22:41:53 +00005960 ReplaceInstUsesWith(*I, C);
5961
Chris Lattner99f48c62002-09-02 04:59:56 +00005962 ++NumConstProp;
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00005963 I->getParent()->getInstList().erase(I);
Chris Lattner800aaaf2003-10-07 15:17:02 +00005964 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00005965 continue;
Chris Lattner99f48c62002-09-02 04:59:56 +00005966 }
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00005967
Chris Lattner39c98bb2004-12-08 23:43:58 +00005968 // See if we can trivially sink this instruction to a successor basic block.
5969 if (I->hasOneUse()) {
5970 BasicBlock *BB = I->getParent();
5971 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
5972 if (UserParent != BB) {
5973 bool UserIsSuccessor = false;
5974 // See if the user is one of our successors.
5975 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
5976 if (*SI == UserParent) {
5977 UserIsSuccessor = true;
5978 break;
5979 }
5980
5981 // If the user is one of our immediate successors, and if that successor
5982 // only has us as a predecessors (we'd have to split the critical edge
5983 // otherwise), we can keep going.
5984 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
5985 next(pred_begin(UserParent)) == pred_end(UserParent))
5986 // Okay, the CFG is simple enough, try to sink this instruction.
5987 Changed |= TryToSinkInstruction(I, UserParent);
5988 }
5989 }
5990
Chris Lattnerca081252001-12-14 16:52:21 +00005991 // Now that we have an instruction, try combining it to simplify it...
Chris Lattnerae7a0d32002-08-02 19:29:35 +00005992 if (Instruction *Result = visit(*I)) {
Chris Lattner0b18c1d2002-05-10 15:38:35 +00005993 ++NumCombined;
Chris Lattner260ab202002-04-18 17:39:14 +00005994 // Should we replace the old instruction with a new one?
Chris Lattner053c0932002-05-14 15:24:07 +00005995 if (Result != I) {
Chris Lattner7d2a5392004-03-13 23:54:27 +00005996 DEBUG(std::cerr << "IC: Old = " << *I
5997 << " New = " << *Result);
5998
Chris Lattner396dbfe2004-06-09 05:08:07 +00005999 // Everything uses the new instruction now.
6000 I->replaceAllUsesWith(Result);
6001
6002 // Push the new instruction and any users onto the worklist.
6003 WorkList.push_back(Result);
6004 AddUsersToWorkList(*Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00006005
6006 // Move the name to the new instruction first...
6007 std::string OldName = I->getName(); I->setName("");
Chris Lattner950fc782003-10-07 22:58:41 +00006008 Result->setName(OldName);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00006009
6010 // Insert the new instruction into the basic block...
6011 BasicBlock *InstParent = I->getParent();
Chris Lattner7515cab2004-11-14 19:13:23 +00006012 BasicBlock::iterator InsertPos = I;
6013
6014 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
6015 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
6016 ++InsertPos;
6017
6018 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00006019
Chris Lattner63d75af2004-05-01 23:27:23 +00006020 // Make sure that we reprocess all operands now that we reduced their
6021 // use counts.
Chris Lattnerb643a9e2004-05-01 23:19:52 +00006022 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
6023 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
6024 WorkList.push_back(OpI);
6025
Chris Lattner396dbfe2004-06-09 05:08:07 +00006026 // Instructions can end up on the worklist more than once. Make sure
6027 // we do not process an instruction that has been deleted.
6028 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00006029
6030 // Erase the old instruction.
6031 InstParent->getInstList().erase(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00006032 } else {
Chris Lattner7d2a5392004-03-13 23:54:27 +00006033 DEBUG(std::cerr << "IC: MOD = " << *I);
6034
Chris Lattnerae7a0d32002-08-02 19:29:35 +00006035 // If the instruction was modified, it's possible that it is now dead.
6036 // if so, remove it.
Chris Lattner63d75af2004-05-01 23:27:23 +00006037 if (isInstructionTriviallyDead(I)) {
6038 // Make sure we process all operands now that we are reducing their
6039 // use counts.
6040 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
6041 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
6042 WorkList.push_back(OpI);
Misha Brukmanb1c93172005-04-21 23:48:37 +00006043
Chris Lattner63d75af2004-05-01 23:27:23 +00006044 // Instructions may end up in the worklist more than once. Erase all
6045 // occurrances of this instruction.
Chris Lattner99f48c62002-09-02 04:59:56 +00006046 removeFromWorkList(I);
Chris Lattner31f486c2005-01-31 05:36:43 +00006047 I->eraseFromParent();
Chris Lattner396dbfe2004-06-09 05:08:07 +00006048 } else {
6049 WorkList.push_back(Result);
6050 AddUsersToWorkList(*Result);
Chris Lattnerae7a0d32002-08-02 19:29:35 +00006051 }
Chris Lattner053c0932002-05-14 15:24:07 +00006052 }
Chris Lattner260ab202002-04-18 17:39:14 +00006053 Changed = true;
Chris Lattnerca081252001-12-14 16:52:21 +00006054 }
6055 }
6056
Chris Lattner260ab202002-04-18 17:39:14 +00006057 return Changed;
Chris Lattner04805fa2002-02-26 21:46:54 +00006058}
6059
Brian Gaeke38b79e82004-07-27 17:43:21 +00006060FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattner260ab202002-04-18 17:39:14 +00006061 return new InstCombiner();
Chris Lattner04805fa2002-02-26 21:46:54 +00006062}
Brian Gaeke960707c2003-11-11 22:41:34 +00006063