blob: 4ee833bf6f7a5e901559b19cfaa85511c27d9f22 [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 Lattner113f4f42002-06-25 16:13:24 +0000122 Instruction *visitCastInst(CastInst &CI);
Chris Lattner411336f2005-01-19 21:50:18 +0000123 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
124 Instruction *FI);
Chris Lattnerb909e8b2004-03-12 05:52:32 +0000125 Instruction *visitSelectInst(SelectInst &CI);
Chris Lattner970c33a2003-06-19 17:00:31 +0000126 Instruction *visitCallInst(CallInst &CI);
127 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner113f4f42002-06-25 16:13:24 +0000128 Instruction *visitPHINode(PHINode &PN);
129 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Chris Lattner1085bdf2002-11-04 16:18:53 +0000130 Instruction *visitAllocationInst(AllocationInst &AI);
Chris Lattner8427bff2003-12-07 01:24:23 +0000131 Instruction *visitFreeInst(FreeInst &FI);
Chris Lattner0f1d8a32003-06-26 05:06:25 +0000132 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattner31f486c2005-01-31 05:36:43 +0000133 Instruction *visitStoreInst(StoreInst &SI);
Chris Lattner9eef8a72003-06-04 04:46:00 +0000134 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner4c9c20a2004-07-03 00:26:11 +0000135 Instruction *visitSwitchInst(SwitchInst &SI);
Chris Lattner260ab202002-04-18 17:39:14 +0000136
137 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner113f4f42002-06-25 16:13:24 +0000138 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000139
Chris Lattner970c33a2003-06-19 17:00:31 +0000140 private:
Chris Lattneraec3d942003-10-07 22:32:43 +0000141 Instruction *visitCallSite(CallSite CS);
Chris Lattner970c33a2003-06-19 17:00:31 +0000142 bool transformConstExprCastCall(CallSite CS);
143
Chris Lattner69193f92004-04-05 01:30:19 +0000144 public:
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000145 // InsertNewInstBefore - insert an instruction New before instruction Old
146 // in the program. Add the new instruction to the worklist.
147 //
Chris Lattner623826c2004-09-28 21:48:02 +0000148 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattner65217ff2002-08-23 18:32:43 +0000149 assert(New && New->getParent() == 0 &&
150 "New instruction already inserted into a basic block!");
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000151 BasicBlock *BB = Old.getParent();
152 BB->getInstList().insert(&Old, New); // Insert inst
153 WorkList.push_back(New); // Add to worklist
Chris Lattnere79e8542004-02-23 06:38:22 +0000154 return New;
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000155 }
156
Chris Lattner7e794272004-09-24 15:21:34 +0000157 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
158 /// This also adds the cast to the worklist. Finally, this returns the
159 /// cast.
160 Value *InsertCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
161 if (V->getType() == Ty) return V;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000162
Chris Lattner7e794272004-09-24 15:21:34 +0000163 Instruction *C = new CastInst(V, Ty, V->getName(), &Pos);
164 WorkList.push_back(C);
165 return C;
166 }
167
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000168 // ReplaceInstUsesWith - This method is to be used when an instruction is
169 // found to be dead, replacable with another preexisting expression. Here
170 // we add all uses of I to the worklist, replace all uses of I with the new
171 // value, then return I, so that the inst combiner will know that I was
172 // modified.
173 //
174 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattner51ea1272004-02-28 05:22:00 +0000175 AddUsersToWorkList(I); // Add all modified instrs to worklist
Chris Lattner8953b902004-04-05 02:10:19 +0000176 if (&I != V) {
177 I.replaceAllUsesWith(V);
178 return &I;
179 } else {
180 // If we are replacing the instruction with itself, this must be in a
181 // segment of unreachable code, so just clobber the instruction.
Chris Lattner8ba9ec92004-10-18 02:59:09 +0000182 I.replaceAllUsesWith(UndefValue::get(I.getType()));
Chris Lattner8953b902004-04-05 02:10:19 +0000183 return &I;
184 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000185 }
Chris Lattner51ea1272004-02-28 05:22:00 +0000186
187 // EraseInstFromFunction - When dealing with an instruction that has side
188 // effects or produces a void value, we can't rely on DCE to delete the
189 // instruction. Instead, visit methods should return the value returned by
190 // this function.
191 Instruction *EraseInstFromFunction(Instruction &I) {
192 assert(I.use_empty() && "Cannot erase instruction that is used!");
193 AddUsesToWorkList(I);
194 removeFromWorkList(&I);
Chris Lattner95307542004-11-18 21:41:39 +0000195 I.eraseFromParent();
Chris Lattner51ea1272004-02-28 05:22:00 +0000196 return 0; // Don't do anything with FI
197 }
198
199
Chris Lattner3ac7c262003-08-13 20:16:26 +0000200 private:
Chris Lattnerdfae8be2003-07-24 17:35:25 +0000201 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
202 /// InsertBefore instruction. This is specialized a bit to avoid inserting
203 /// casts that are known to not do anything...
204 ///
205 Value *InsertOperandCastBefore(Value *V, const Type *DestTy,
206 Instruction *InsertBefore);
207
Chris Lattner7fb29e12003-03-11 00:12:48 +0000208 // SimplifyCommutative - This performs a few simplifications for commutative
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000209 // operators.
Chris Lattner7fb29e12003-03-11 00:12:48 +0000210 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerba1cb382003-09-19 17:17:26 +0000211
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000212
213 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
214 // PHI node as operand #0, see if we can fold the instruction into the PHI
215 // (which is only possible if all operands to the PHI are constants).
216 Instruction *FoldOpIntoPhi(Instruction &I);
217
Chris Lattner7515cab2004-11-14 19:13:23 +0000218 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
219 // operator and they all are only used by the PHI, PHI together their
220 // inputs, and do the operation once, to the result of the PHI.
221 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
222
Chris Lattnerba1cb382003-09-19 17:17:26 +0000223 Instruction *OptAndOp(Instruction *Op, ConstantIntegral *OpRHS,
224 ConstantIntegral *AndRHS, BinaryOperator &TheAnd);
Chris Lattner6862fbd2004-09-29 17:40:11 +0000225
226 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
227 bool Inside, Instruction &IB);
Chris Lattner260ab202002-04-18 17:39:14 +0000228 };
Chris Lattnerb28b6802002-07-23 18:06:35 +0000229
Chris Lattnerc8b70922002-07-26 21:12:46 +0000230 RegisterOpt<InstCombiner> X("instcombine", "Combine redundant instructions");
Chris Lattner260ab202002-04-18 17:39:14 +0000231}
232
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000233// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattner81a7a232004-10-16 18:11:37 +0000234// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000235static unsigned getComplexity(Value *V) {
236 if (isa<Instruction>(V)) {
237 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
Chris Lattner81a7a232004-10-16 18:11:37 +0000238 return 3;
239 return 4;
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000240 }
Chris Lattner81a7a232004-10-16 18:11:37 +0000241 if (isa<Argument>(V)) return 3;
242 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000243}
Chris Lattner260ab202002-04-18 17:39:14 +0000244
Chris Lattner7fb29e12003-03-11 00:12:48 +0000245// isOnlyUse - Return true if this instruction will be deleted if we stop using
246// it.
247static bool isOnlyUse(Value *V) {
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000248 return V->hasOneUse() || isa<Constant>(V);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000249}
250
Chris Lattnere79e8542004-02-23 06:38:22 +0000251// getPromotedType - Return the specified type promoted as it would be to pass
252// though a va_arg area...
253static const Type *getPromotedType(const Type *Ty) {
Chris Lattner97bfcea2004-06-17 18:16:02 +0000254 switch (Ty->getTypeID()) {
Chris Lattnere79e8542004-02-23 06:38:22 +0000255 case Type::SByteTyID:
256 case Type::ShortTyID: return Type::IntTy;
257 case Type::UByteTyID:
258 case Type::UShortTyID: return Type::UIntTy;
259 case Type::FloatTyID: return Type::DoubleTy;
260 default: return Ty;
261 }
262}
263
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000264// SimplifyCommutative - This performs a few simplifications for commutative
265// operators:
Chris Lattner260ab202002-04-18 17:39:14 +0000266//
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000267// 1. Order operands such that they are listed from right (least complex) to
268// left (most complex). This puts constants before unary operators before
269// binary operators.
270//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000271// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
272// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000273//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000274bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000275 bool Changed = false;
276 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
277 Changed = !I.swapOperands();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000278
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000279 if (!I.isAssociative()) return Changed;
280 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattner7fb29e12003-03-11 00:12:48 +0000281 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
282 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
283 if (isa<Constant>(I.getOperand(1))) {
Chris Lattner34428442003-05-27 16:40:51 +0000284 Constant *Folded = ConstantExpr::get(I.getOpcode(),
285 cast<Constant>(I.getOperand(1)),
286 cast<Constant>(Op->getOperand(1)));
Chris Lattner7fb29e12003-03-11 00:12:48 +0000287 I.setOperand(0, Op->getOperand(0));
288 I.setOperand(1, Folded);
289 return true;
290 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
291 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
292 isOnlyUse(Op) && isOnlyUse(Op1)) {
293 Constant *C1 = cast<Constant>(Op->getOperand(1));
294 Constant *C2 = cast<Constant>(Op1->getOperand(1));
295
296 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner34428442003-05-27 16:40:51 +0000297 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000298 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
299 Op1->getOperand(0),
300 Op1->getName(), &I);
301 WorkList.push_back(New);
302 I.setOperand(0, New);
303 I.setOperand(1, Folded);
304 return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000305 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000306 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000307 return Changed;
Chris Lattner260ab202002-04-18 17:39:14 +0000308}
Chris Lattnerca081252001-12-14 16:52:21 +0000309
Chris Lattnerbb74e222003-03-10 23:06:50 +0000310// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
311// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattner9fa53de2002-05-06 16:49:18 +0000312//
Chris Lattnerbb74e222003-03-10 23:06:50 +0000313static inline Value *dyn_castNegVal(Value *V) {
314 if (BinaryOperator::isNeg(V))
Chris Lattnerd6f636a2005-04-24 07:30:14 +0000315 return BinaryOperator::getNegArgument(V);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000316
Chris Lattner9ad0d552004-12-14 20:08:06 +0000317 // Constants can be considered to be negated values if they can be folded.
318 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
319 return ConstantExpr::getNeg(C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000320 return 0;
Chris Lattner9fa53de2002-05-06 16:49:18 +0000321}
322
Chris Lattnerbb74e222003-03-10 23:06:50 +0000323static inline Value *dyn_castNotVal(Value *V) {
324 if (BinaryOperator::isNot(V))
Chris Lattnerd6f636a2005-04-24 07:30:14 +0000325 return BinaryOperator::getNotArgument(V);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000326
327 // Constants can be considered to be not'ed values...
Chris Lattnerdd65d862003-04-30 22:34:06 +0000328 if (ConstantIntegral *C = dyn_cast<ConstantIntegral>(V))
Chris Lattnerc8e7e292004-06-10 02:12:35 +0000329 return ConstantExpr::getNot(C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000330 return 0;
331}
332
Chris Lattner7fb29e12003-03-11 00:12:48 +0000333// dyn_castFoldableMul - If this value is a multiply that can be folded into
334// other computations (because it has a constant operand), return the
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000335// non-constant operand of the multiply, and set CST to point to the multiplier.
336// Otherwise, return null.
Chris Lattner7fb29e12003-03-11 00:12:48 +0000337//
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000338static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000339 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000340 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattner7fb29e12003-03-11 00:12:48 +0000341 if (I->getOpcode() == Instruction::Mul)
Chris Lattner970136362004-11-15 05:54:07 +0000342 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattner7fb29e12003-03-11 00:12:48 +0000343 return I->getOperand(0);
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000344 if (I->getOpcode() == Instruction::Shl)
Chris Lattner970136362004-11-15 05:54:07 +0000345 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000346 // The multiplier is really 1 << CST.
347 Constant *One = ConstantInt::get(V->getType(), 1);
348 CST = cast<ConstantInt>(ConstantExpr::getShl(One, CST));
349 return I->getOperand(0);
350 }
351 }
Chris Lattner7fb29e12003-03-11 00:12:48 +0000352 return 0;
Chris Lattner3082c5a2003-02-18 19:28:33 +0000353}
Chris Lattner31ae8632002-08-14 17:51:49 +0000354
Chris Lattner0798af32005-01-13 20:14:25 +0000355/// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
356/// expression, return it.
357static User *dyn_castGetElementPtr(Value *V) {
358 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
359 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
360 if (CE->getOpcode() == Instruction::GetElementPtr)
361 return cast<User>(V);
362 return false;
363}
364
Chris Lattner623826c2004-09-28 21:48:02 +0000365// AddOne, SubOne - Add or subtract a constant one from an integer constant...
Chris Lattner6862fbd2004-09-29 17:40:11 +0000366static ConstantInt *AddOne(ConstantInt *C) {
367 return cast<ConstantInt>(ConstantExpr::getAdd(C,
368 ConstantInt::get(C->getType(), 1)));
Chris Lattner623826c2004-09-28 21:48:02 +0000369}
Chris Lattner6862fbd2004-09-29 17:40:11 +0000370static ConstantInt *SubOne(ConstantInt *C) {
371 return cast<ConstantInt>(ConstantExpr::getSub(C,
372 ConstantInt::get(C->getType(), 1)));
Chris Lattner623826c2004-09-28 21:48:02 +0000373}
374
375// isTrueWhenEqual - Return true if the specified setcondinst instruction is
376// true when both operands are equal...
377//
378static bool isTrueWhenEqual(Instruction &I) {
379 return I.getOpcode() == Instruction::SetEQ ||
380 I.getOpcode() == Instruction::SetGE ||
381 I.getOpcode() == Instruction::SetLE;
382}
Chris Lattnerb8b97502003-08-13 19:01:45 +0000383
384/// AssociativeOpt - Perform an optimization on an associative operator. This
385/// function is designed to check a chain of associative operators for a
386/// potential to apply a certain optimization. Since the optimization may be
387/// applicable if the expression was reassociated, this checks the chain, then
388/// reassociates the expression as necessary to expose the optimization
389/// opportunity. This makes use of a special Functor, which must define
390/// 'shouldApply' and 'apply' methods.
391///
392template<typename Functor>
393Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
394 unsigned Opcode = Root.getOpcode();
395 Value *LHS = Root.getOperand(0);
396
397 // Quick check, see if the immediate LHS matches...
398 if (F.shouldApply(LHS))
399 return F.apply(Root);
400
401 // Otherwise, if the LHS is not of the same opcode as the root, return.
402 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000403 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattnerb8b97502003-08-13 19:01:45 +0000404 // Should we apply this transform to the RHS?
405 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
406
407 // If not to the RHS, check to see if we should apply to the LHS...
408 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
409 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
410 ShouldApply = true;
411 }
412
413 // If the functor wants to apply the optimization to the RHS of LHSI,
414 // reassociate the expression from ((? op A) op B) to (? op (A op B))
415 if (ShouldApply) {
416 BasicBlock *BB = Root.getParent();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000417
Chris Lattnerb8b97502003-08-13 19:01:45 +0000418 // Now all of the instructions are in the current basic block, go ahead
419 // and perform the reassociation.
420 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
421
422 // First move the selected RHS to the LHS of the root...
423 Root.setOperand(0, LHSI->getOperand(1));
424
425 // Make what used to be the LHS of the root be the user of the root...
426 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner284d3b02004-04-16 18:08:07 +0000427 if (&Root == TmpLHSI) {
Chris Lattner8953b902004-04-05 02:10:19 +0000428 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
429 return 0;
430 }
Chris Lattner284d3b02004-04-16 18:08:07 +0000431 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattnerb8b97502003-08-13 19:01:45 +0000432 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner284d3b02004-04-16 18:08:07 +0000433 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
434 BasicBlock::iterator ARI = &Root; ++ARI;
435 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
436 ARI = Root;
Chris Lattnerb8b97502003-08-13 19:01:45 +0000437
438 // Now propagate the ExtraOperand down the chain of instructions until we
439 // get to LHSI.
440 while (TmpLHSI != LHSI) {
441 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner284d3b02004-04-16 18:08:07 +0000442 // Move the instruction to immediately before the chain we are
443 // constructing to avoid breaking dominance properties.
444 NextLHSI->getParent()->getInstList().remove(NextLHSI);
445 BB->getInstList().insert(ARI, NextLHSI);
446 ARI = NextLHSI;
447
Chris Lattnerb8b97502003-08-13 19:01:45 +0000448 Value *NextOp = NextLHSI->getOperand(1);
449 NextLHSI->setOperand(1, ExtraOperand);
450 TmpLHSI = NextLHSI;
451 ExtraOperand = NextOp;
452 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000453
Chris Lattnerb8b97502003-08-13 19:01:45 +0000454 // Now that the instructions are reassociated, have the functor perform
455 // the transformation...
456 return F.apply(Root);
457 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000458
Chris Lattnerb8b97502003-08-13 19:01:45 +0000459 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
460 }
461 return 0;
462}
463
464
465// AddRHS - Implements: X + X --> X << 1
466struct AddRHS {
467 Value *RHS;
468 AddRHS(Value *rhs) : RHS(rhs) {}
469 bool shouldApply(Value *LHS) const { return LHS == RHS; }
470 Instruction *apply(BinaryOperator &Add) const {
471 return new ShiftInst(Instruction::Shl, Add.getOperand(0),
472 ConstantInt::get(Type::UByteTy, 1));
473 }
474};
475
476// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
477// iff C1&C2 == 0
478struct AddMaskingAnd {
479 Constant *C2;
480 AddMaskingAnd(Constant *c) : C2(c) {}
481 bool shouldApply(Value *LHS) const {
Chris Lattnerd4252a72004-07-30 07:50:03 +0000482 ConstantInt *C1;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000483 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Chris Lattnerd4252a72004-07-30 07:50:03 +0000484 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattnerb8b97502003-08-13 19:01:45 +0000485 }
486 Instruction *apply(BinaryOperator &Add) const {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000487 return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattnerb8b97502003-08-13 19:01:45 +0000488 }
489};
490
Chris Lattner86102b82005-01-01 16:22:27 +0000491static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner183b3362004-04-09 19:05:30 +0000492 InstCombiner *IC) {
Chris Lattner86102b82005-01-01 16:22:27 +0000493 if (isa<CastInst>(I)) {
494 if (Constant *SOC = dyn_cast<Constant>(SO))
495 return ConstantExpr::getCast(SOC, I.getType());
Misha Brukmanb1c93172005-04-21 23:48:37 +0000496
Chris Lattner86102b82005-01-01 16:22:27 +0000497 return IC->InsertNewInstBefore(new CastInst(SO, I.getType(),
498 SO->getName() + ".cast"), I);
499 }
500
Chris Lattner183b3362004-04-09 19:05:30 +0000501 // Figure out if the constant is the left or the right argument.
Chris Lattner86102b82005-01-01 16:22:27 +0000502 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
503 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattnerb8b97502003-08-13 19:01:45 +0000504
Chris Lattner183b3362004-04-09 19:05:30 +0000505 if (Constant *SOC = dyn_cast<Constant>(SO)) {
506 if (ConstIsRHS)
Chris Lattner86102b82005-01-01 16:22:27 +0000507 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
508 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner183b3362004-04-09 19:05:30 +0000509 }
510
511 Value *Op0 = SO, *Op1 = ConstOperand;
512 if (!ConstIsRHS)
513 std::swap(Op0, Op1);
514 Instruction *New;
Chris Lattner86102b82005-01-01 16:22:27 +0000515 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
516 New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
517 else if (ShiftInst *SI = dyn_cast<ShiftInst>(&I))
518 New = new ShiftInst(SI->getOpcode(), Op0, Op1, SO->getName()+".sh");
Chris Lattnerf9d96652004-04-10 19:15:56 +0000519 else {
Chris Lattner183b3362004-04-09 19:05:30 +0000520 assert(0 && "Unknown binary instruction type!");
Chris Lattnerf9d96652004-04-10 19:15:56 +0000521 abort();
522 }
Chris Lattner86102b82005-01-01 16:22:27 +0000523 return IC->InsertNewInstBefore(New, I);
524}
525
526// FoldOpIntoSelect - Given an instruction with a select as one operand and a
527// constant as the other operand, try to fold the binary operator into the
528// select arguments. This also works for Cast instructions, which obviously do
529// not have a second operand.
530static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
531 InstCombiner *IC) {
532 // Don't modify shared select instructions
533 if (!SI->hasOneUse()) return 0;
534 Value *TV = SI->getOperand(1);
535 Value *FV = SI->getOperand(2);
536
537 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner374e6592005-04-21 05:43:13 +0000538 // Bool selects with constant operands can be folded to logical ops.
539 if (SI->getType() == Type::BoolTy) return 0;
540
Chris Lattner86102b82005-01-01 16:22:27 +0000541 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
542 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
543
544 return new SelectInst(SI->getCondition(), SelectTrueVal,
545 SelectFalseVal);
546 }
547 return 0;
Chris Lattner183b3362004-04-09 19:05:30 +0000548}
549
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000550
551/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
552/// node as operand #0, see if we can fold the instruction into the PHI (which
553/// is only possible if all operands to the PHI are constants).
554Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
555 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattner7515cab2004-11-14 19:13:23 +0000556 unsigned NumPHIValues = PN->getNumIncomingValues();
557 if (!PN->hasOneUse() || NumPHIValues == 0 ||
558 !isa<Constant>(PN->getIncomingValue(0))) return 0;
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000559
560 // Check to see if all of the operands of the PHI are constants. If not, we
561 // cannot do the transformation.
Chris Lattner7515cab2004-11-14 19:13:23 +0000562 for (unsigned i = 1; i != NumPHIValues; ++i)
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000563 if (!isa<Constant>(PN->getIncomingValue(i)))
564 return 0;
565
566 // Okay, we can do the transformation: create the new PHI node.
567 PHINode *NewPN = new PHINode(I.getType(), I.getName());
568 I.setName("");
Chris Lattnerd8e20182005-01-29 00:39:08 +0000569 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000570 InsertNewInstBefore(NewPN, *PN);
571
572 // Next, add all of the operands to the PHI.
573 if (I.getNumOperands() == 2) {
574 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattner7515cab2004-11-14 19:13:23 +0000575 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000576 Constant *InV = cast<Constant>(PN->getIncomingValue(i));
577 NewPN->addIncoming(ConstantExpr::get(I.getOpcode(), InV, C),
578 PN->getIncomingBlock(i));
579 }
580 } else {
581 assert(isa<CastInst>(I) && "Unary op should be a cast!");
582 const Type *RetTy = I.getType();
Chris Lattner7515cab2004-11-14 19:13:23 +0000583 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000584 Constant *InV = cast<Constant>(PN->getIncomingValue(i));
585 NewPN->addIncoming(ConstantExpr::getCast(InV, RetTy),
586 PN->getIncomingBlock(i));
587 }
588 }
589 return ReplaceInstUsesWith(I, NewPN);
590}
591
Chris Lattner113f4f42002-06-25 16:13:24 +0000592Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000593 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000594 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000595
Chris Lattnercf4a9962004-04-10 22:01:55 +0000596 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattner81a7a232004-10-16 18:11:37 +0000597 // X + undef -> undef
598 if (isa<UndefValue>(RHS))
599 return ReplaceInstUsesWith(I, RHS);
600
Chris Lattnercf4a9962004-04-10 22:01:55 +0000601 // X + 0 --> X
602 if (!I.getType()->isFloatingPoint() && // -0 + +0 = +0, so it's not a noop
603 RHSC->isNullValue())
604 return ReplaceInstUsesWith(I, LHS);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000605
Chris Lattnercf4a9962004-04-10 22:01:55 +0000606 // X + (signbit) --> X ^ signbit
607 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +0000608 unsigned NumBits = CI->getType()->getPrimitiveSizeInBits();
Chris Lattnercf4a9962004-04-10 22:01:55 +0000609 uint64_t Val = CI->getRawValue() & (1ULL << NumBits)-1;
Chris Lattner33eb9092004-11-05 04:45:43 +0000610 if (Val == (1ULL << (NumBits-1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000611 return BinaryOperator::createXor(LHS, RHS);
Chris Lattnercf4a9962004-04-10 22:01:55 +0000612 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000613
614 if (isa<PHINode>(LHS))
615 if (Instruction *NV = FoldOpIntoPhi(I))
616 return NV;
Chris Lattnercf4a9962004-04-10 22:01:55 +0000617 }
Chris Lattner9fa53de2002-05-06 16:49:18 +0000618
Chris Lattnerb8b97502003-08-13 19:01:45 +0000619 // X + X --> X << 1
Robert Bocchino7b5b86c2004-07-27 21:02:21 +0000620 if (I.getType()->isInteger()) {
Chris Lattnerb8b97502003-08-13 19:01:45 +0000621 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Chris Lattner47060462005-04-07 17:14:51 +0000622
623 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
624 if (RHSI->getOpcode() == Instruction::Sub)
625 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
626 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
627 }
628 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
629 if (LHSI->getOpcode() == Instruction::Sub)
630 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
631 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
632 }
Robert Bocchino7b5b86c2004-07-27 21:02:21 +0000633 }
Chris Lattnerede3fe02003-08-13 04:18:28 +0000634
Chris Lattner147e9752002-05-08 22:46:53 +0000635 // -A + B --> B - A
Chris Lattnerbb74e222003-03-10 23:06:50 +0000636 if (Value *V = dyn_castNegVal(LHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000637 return BinaryOperator::createSub(RHS, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000638
639 // A + -B --> A - B
Chris Lattnerbb74e222003-03-10 23:06:50 +0000640 if (!isa<Constant>(RHS))
641 if (Value *V = dyn_castNegVal(RHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000642 return BinaryOperator::createSub(LHS, V);
Chris Lattner260ab202002-04-18 17:39:14 +0000643
Misha Brukmanb1c93172005-04-21 23:48:37 +0000644
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000645 ConstantInt *C2;
646 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
647 if (X == RHS) // X*C + X --> X * (C+1)
648 return BinaryOperator::createMul(RHS, AddOne(C2));
649
650 // X*C1 + X*C2 --> X * (C1+C2)
651 ConstantInt *C1;
652 if (X == dyn_castFoldableMul(RHS, C1))
653 return BinaryOperator::createMul(X, ConstantExpr::getAdd(C1, C2));
Chris Lattner57c8d992003-02-18 19:57:07 +0000654 }
655
656 // X + X*C --> X * (C+1)
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000657 if (dyn_castFoldableMul(RHS, C2) == LHS)
658 return BinaryOperator::createMul(LHS, AddOne(C2));
659
Chris Lattner57c8d992003-02-18 19:57:07 +0000660
Chris Lattnerb8b97502003-08-13 19:01:45 +0000661 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattnerd4252a72004-07-30 07:50:03 +0000662 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattnerb8b97502003-08-13 19:01:45 +0000663 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2))) return R;
Chris Lattner7fb29e12003-03-11 00:12:48 +0000664
Chris Lattnerb9cde762003-10-02 15:11:26 +0000665 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattnerd4252a72004-07-30 07:50:03 +0000666 Value *X;
667 if (match(LHS, m_Not(m_Value(X)))) { // ~X + C --> (C-1) - X
668 Constant *C= ConstantExpr::getSub(CRHS, ConstantInt::get(I.getType(), 1));
669 return BinaryOperator::createSub(C, X);
Chris Lattnerb9cde762003-10-02 15:11:26 +0000670 }
Chris Lattnerd4252a72004-07-30 07:50:03 +0000671
Chris Lattnerbff91d92004-10-08 05:07:56 +0000672 // (X & FF00) + xx00 -> (X+xx00) & FF00
673 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
674 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
675 if (Anded == CRHS) {
676 // See if all bits from the first bit set in the Add RHS up are included
677 // in the mask. First, get the rightmost bit.
678 uint64_t AddRHSV = CRHS->getRawValue();
679
680 // Form a mask of all bits from the lowest bit added through the top.
681 uint64_t AddRHSHighBits = ~((AddRHSV & -AddRHSV)-1);
Chris Lattner2f1457f2005-04-24 17:46:05 +0000682 AddRHSHighBits &= ~0ULL >> (64-C2->getType()->getPrimitiveSizeInBits());
Chris Lattnerbff91d92004-10-08 05:07:56 +0000683
684 // See if the and mask includes all of these bits.
685 uint64_t AddRHSHighBitsAnd = AddRHSHighBits & C2->getRawValue();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000686
Chris Lattnerbff91d92004-10-08 05:07:56 +0000687 if (AddRHSHighBits == AddRHSHighBitsAnd) {
688 // Okay, the xform is safe. Insert the new add pronto.
689 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
690 LHS->getName()), I);
691 return BinaryOperator::createAnd(NewAdd, C2);
692 }
693 }
694 }
695
Chris Lattnerd4252a72004-07-30 07:50:03 +0000696 // Try to fold constant add into select arguments.
697 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner86102b82005-01-01 16:22:27 +0000698 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattnerd4252a72004-07-30 07:50:03 +0000699 return R;
Chris Lattnerb9cde762003-10-02 15:11:26 +0000700 }
701
Chris Lattner113f4f42002-06-25 16:13:24 +0000702 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +0000703}
704
Chris Lattnerbdb0ce02003-07-22 21:46:59 +0000705// isSignBit - Return true if the value represented by the constant only has the
706// highest order bit set.
707static bool isSignBit(ConstantInt *CI) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +0000708 unsigned NumBits = CI->getType()->getPrimitiveSizeInBits();
Chris Lattner2f1457f2005-04-24 17:46:05 +0000709 return (CI->getRawValue() & (~0ULL >> (64-NumBits))) == (1ULL << (NumBits-1));
Chris Lattnerbdb0ce02003-07-22 21:46:59 +0000710}
711
Chris Lattner022167f2004-03-13 00:11:49 +0000712/// RemoveNoopCast - Strip off nonconverting casts from the value.
713///
714static Value *RemoveNoopCast(Value *V) {
715 if (CastInst *CI = dyn_cast<CastInst>(V)) {
716 const Type *CTy = CI->getType();
717 const Type *OpTy = CI->getOperand(0)->getType();
718 if (CTy->isInteger() && OpTy->isInteger()) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +0000719 if (CTy->getPrimitiveSizeInBits() == OpTy->getPrimitiveSizeInBits())
Chris Lattner022167f2004-03-13 00:11:49 +0000720 return RemoveNoopCast(CI->getOperand(0));
721 } else if (isa<PointerType>(CTy) && isa<PointerType>(OpTy))
722 return RemoveNoopCast(CI->getOperand(0));
723 }
724 return V;
725}
726
Chris Lattner113f4f42002-06-25 16:13:24 +0000727Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +0000728 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000729
Chris Lattnere6794492002-08-12 21:17:25 +0000730 if (Op0 == Op1) // sub X, X -> 0
731 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner260ab202002-04-18 17:39:14 +0000732
Chris Lattnere6794492002-08-12 21:17:25 +0000733 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattnerbb74e222003-03-10 23:06:50 +0000734 if (Value *V = dyn_castNegVal(Op1))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000735 return BinaryOperator::createAdd(Op0, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000736
Chris Lattner81a7a232004-10-16 18:11:37 +0000737 if (isa<UndefValue>(Op0))
738 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
739 if (isa<UndefValue>(Op1))
740 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
741
Chris Lattner8f2f5982003-11-05 01:06:05 +0000742 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
743 // Replace (-1 - A) with (~A)...
Chris Lattner3082c5a2003-02-18 19:28:33 +0000744 if (C->isAllOnesValue())
745 return BinaryOperator::createNot(Op1);
Chris Lattnerad3c4952002-05-09 01:29:19 +0000746
Chris Lattner8f2f5982003-11-05 01:06:05 +0000747 // C - ~X == X + (1+C)
Reid Spencer4fdd96c2005-06-18 17:37:34 +0000748 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +0000749 if (match(Op1, m_Not(m_Value(X))))
750 return BinaryOperator::createAdd(X,
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000751 ConstantExpr::getAdd(C, ConstantInt::get(I.getType(), 1)));
Chris Lattner92295c52004-03-12 23:53:13 +0000752 // -((uint)X >> 31) -> ((int)X >> 31)
753 // -((int)X >> 31) -> ((uint)X >> 31)
Chris Lattner022167f2004-03-13 00:11:49 +0000754 if (C->isNullValue()) {
755 Value *NoopCastedRHS = RemoveNoopCast(Op1);
756 if (ShiftInst *SI = dyn_cast<ShiftInst>(NoopCastedRHS))
Chris Lattner92295c52004-03-12 23:53:13 +0000757 if (SI->getOpcode() == Instruction::Shr)
758 if (ConstantUInt *CU = dyn_cast<ConstantUInt>(SI->getOperand(1))) {
759 const Type *NewTy;
Chris Lattner022167f2004-03-13 00:11:49 +0000760 if (SI->getType()->isSigned())
Chris Lattner97bfcea2004-06-17 18:16:02 +0000761 NewTy = SI->getType()->getUnsignedVersion();
Chris Lattner92295c52004-03-12 23:53:13 +0000762 else
Chris Lattner97bfcea2004-06-17 18:16:02 +0000763 NewTy = SI->getType()->getSignedVersion();
Chris Lattner92295c52004-03-12 23:53:13 +0000764 // Check to see if we are shifting out everything but the sign bit.
Chris Lattnerd1f46d32005-04-24 06:59:08 +0000765 if (CU->getValue() == SI->getType()->getPrimitiveSizeInBits()-1) {
Chris Lattner92295c52004-03-12 23:53:13 +0000766 // Ok, the transformation is safe. Insert a cast of the incoming
767 // value, then the new shift, then the new cast.
768 Instruction *FirstCast = new CastInst(SI->getOperand(0), NewTy,
769 SI->getOperand(0)->getName());
770 Value *InV = InsertNewInstBefore(FirstCast, I);
771 Instruction *NewShift = new ShiftInst(Instruction::Shr, FirstCast,
772 CU, SI->getName());
Chris Lattner022167f2004-03-13 00:11:49 +0000773 if (NewShift->getType() == I.getType())
774 return NewShift;
775 else {
776 InV = InsertNewInstBefore(NewShift, I);
777 return new CastInst(NewShift, I.getType());
778 }
Chris Lattner92295c52004-03-12 23:53:13 +0000779 }
780 }
Chris Lattner022167f2004-03-13 00:11:49 +0000781 }
Chris Lattner183b3362004-04-09 19:05:30 +0000782
783 // Try to fold constant sub into select arguments.
784 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner86102b82005-01-01 16:22:27 +0000785 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +0000786 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000787
788 if (isa<PHINode>(Op0))
789 if (Instruction *NV = FoldOpIntoPhi(I))
790 return NV;
Chris Lattner8f2f5982003-11-05 01:06:05 +0000791 }
792
Chris Lattnera9be4492005-04-07 16:15:25 +0000793 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
794 if (Op1I->getOpcode() == Instruction::Add &&
795 !Op0->getType()->isFloatingPoint()) {
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +0000796 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Chris Lattnera9be4492005-04-07 16:15:25 +0000797 return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +0000798 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Chris Lattnera9be4492005-04-07 16:15:25 +0000799 return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +0000800 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
801 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
802 // C1-(X+C2) --> (C1-C2)-X
803 return BinaryOperator::createSub(ConstantExpr::getSub(CI1, CI2),
804 Op1I->getOperand(0));
805 }
Chris Lattnera9be4492005-04-07 16:15:25 +0000806 }
807
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000808 if (Op1I->hasOneUse()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +0000809 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
810 // is not used by anyone else...
811 //
Chris Lattnerc2f0aa52004-02-02 20:09:56 +0000812 if (Op1I->getOpcode() == Instruction::Sub &&
813 !Op1I->getType()->isFloatingPoint()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +0000814 // Swap the two operands of the subexpr...
815 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
816 Op1I->setOperand(0, IIOp1);
817 Op1I->setOperand(1, IIOp0);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000818
Chris Lattner3082c5a2003-02-18 19:28:33 +0000819 // Create the new top level add instruction...
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000820 return BinaryOperator::createAdd(Op0, Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000821 }
822
823 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
824 //
825 if (Op1I->getOpcode() == Instruction::And &&
826 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
827 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
828
Chris Lattner396dbfe2004-06-09 05:08:07 +0000829 Value *NewNot =
830 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000831 return BinaryOperator::createAnd(Op0, NewNot);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000832 }
Chris Lattner57c8d992003-02-18 19:57:07 +0000833
Chris Lattner0aee4b72004-10-06 15:08:25 +0000834 // -(X sdiv C) -> (X sdiv -C)
835 if (Op1I->getOpcode() == Instruction::Div)
836 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
Chris Lattnera9be4492005-04-07 16:15:25 +0000837 if (CSI->isNullValue())
Chris Lattner0aee4b72004-10-06 15:08:25 +0000838 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Misha Brukmanb1c93172005-04-21 23:48:37 +0000839 return BinaryOperator::createDiv(Op1I->getOperand(0),
Chris Lattner0aee4b72004-10-06 15:08:25 +0000840 ConstantExpr::getNeg(DivRHS));
841
Chris Lattner57c8d992003-02-18 19:57:07 +0000842 // X - X*C --> X * (1-C)
Reid Spencer4fdd96c2005-06-18 17:37:34 +0000843 ConstantInt *C2 = 0;
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000844 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Misha Brukmanb1c93172005-04-21 23:48:37 +0000845 Constant *CP1 =
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000846 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1), C2);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000847 return BinaryOperator::createMul(Op0, CP1);
Chris Lattner57c8d992003-02-18 19:57:07 +0000848 }
Chris Lattnerad3c4952002-05-09 01:29:19 +0000849 }
Chris Lattnera9be4492005-04-07 16:15:25 +0000850 }
Chris Lattner3082c5a2003-02-18 19:28:33 +0000851
Chris Lattner47060462005-04-07 17:14:51 +0000852 if (!Op0->getType()->isFloatingPoint())
853 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
854 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner411336f2005-01-19 21:50:18 +0000855 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
856 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
857 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
858 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner47060462005-04-07 17:14:51 +0000859 } else if (Op0I->getOpcode() == Instruction::Sub) {
860 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
861 return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
Chris Lattner411336f2005-01-19 21:50:18 +0000862 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000863
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000864 ConstantInt *C1;
865 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
866 if (X == Op1) { // X*C - X --> X * (C-1)
867 Constant *CP1 = ConstantExpr::getSub(C1, ConstantInt::get(I.getType(),1));
868 return BinaryOperator::createMul(Op1, CP1);
869 }
Chris Lattner57c8d992003-02-18 19:57:07 +0000870
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000871 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
872 if (X == dyn_castFoldableMul(Op1, C2))
873 return BinaryOperator::createMul(Op1, ConstantExpr::getSub(C1, C2));
874 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000875 return 0;
Chris Lattner260ab202002-04-18 17:39:14 +0000876}
877
Chris Lattnere79e8542004-02-23 06:38:22 +0000878/// isSignBitCheck - Given an exploded setcc instruction, return true if it is
879/// really just returns true if the most significant (sign) bit is set.
880static bool isSignBitCheck(unsigned Opcode, Value *LHS, ConstantInt *RHS) {
881 if (RHS->getType()->isSigned()) {
882 // True if source is LHS < 0 or LHS <= -1
883 return Opcode == Instruction::SetLT && RHS->isNullValue() ||
884 Opcode == Instruction::SetLE && RHS->isAllOnesValue();
885 } else {
886 ConstantUInt *RHSC = cast<ConstantUInt>(RHS);
887 // True if source is LHS > 127 or LHS >= 128, where the constants depend on
888 // the size of the integer type.
889 if (Opcode == Instruction::SetGE)
Chris Lattnerd1f46d32005-04-24 06:59:08 +0000890 return RHSC->getValue() ==
891 1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1);
Chris Lattnere79e8542004-02-23 06:38:22 +0000892 if (Opcode == Instruction::SetGT)
893 return RHSC->getValue() ==
Chris Lattnerd1f46d32005-04-24 06:59:08 +0000894 (1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1))-1;
Chris Lattnere79e8542004-02-23 06:38:22 +0000895 }
896 return false;
897}
898
Chris Lattner113f4f42002-06-25 16:13:24 +0000899Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000900 bool Changed = SimplifyCommutative(I);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000901 Value *Op0 = I.getOperand(0);
Chris Lattner260ab202002-04-18 17:39:14 +0000902
Chris Lattner81a7a232004-10-16 18:11:37 +0000903 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
904 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
905
Chris Lattnere6794492002-08-12 21:17:25 +0000906 // Simplify mul instructions with a constant RHS...
Chris Lattner3082c5a2003-02-18 19:28:33 +0000907 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
908 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerede3fe02003-08-13 04:18:28 +0000909
910 // ((X << C1)*C2) == (X * (C2 << C1))
911 if (ShiftInst *SI = dyn_cast<ShiftInst>(Op0))
912 if (SI->getOpcode() == Instruction::Shl)
913 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000914 return BinaryOperator::createMul(SI->getOperand(0),
915 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanb1c93172005-04-21 23:48:37 +0000916
Chris Lattnercce81be2003-09-11 22:24:54 +0000917 if (CI->isNullValue())
918 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
919 if (CI->equalsInt(1)) // X * 1 == X
920 return ReplaceInstUsesWith(I, Op0);
921 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Chris Lattner35236d82003-06-25 17:09:20 +0000922 return BinaryOperator::createNeg(Op0, I.getName());
Chris Lattner31ba1292002-04-29 22:24:47 +0000923
Chris Lattnercce81be2003-09-11 22:24:54 +0000924 int64_t Val = (int64_t)cast<ConstantInt>(CI)->getRawValue();
Chris Lattner22d00a82005-08-02 19:16:58 +0000925 if (isPowerOf2_64(Val)) { // Replace X*(2^C) with X << C
926 uint64_t C = Log2_64(Val);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000927 return new ShiftInst(Instruction::Shl, Op0,
928 ConstantUInt::get(Type::UByteTy, C));
Chris Lattner22d00a82005-08-02 19:16:58 +0000929 }
Robert Bocchino7b5b86c2004-07-27 21:02:21 +0000930 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattner3082c5a2003-02-18 19:28:33 +0000931 if (Op1F->isNullValue())
932 return ReplaceInstUsesWith(I, Op1);
Chris Lattner31ba1292002-04-29 22:24:47 +0000933
Chris Lattner3082c5a2003-02-18 19:28:33 +0000934 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
935 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
936 if (Op1F->getValue() == 1.0)
937 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
938 }
Chris Lattner183b3362004-04-09 19:05:30 +0000939
940 // Try to fold constant mul into select arguments.
941 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +0000942 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +0000943 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000944
945 if (isa<PHINode>(Op0))
946 if (Instruction *NV = FoldOpIntoPhi(I))
947 return NV;
Chris Lattner260ab202002-04-18 17:39:14 +0000948 }
949
Chris Lattner934a64cf2003-03-10 23:23:04 +0000950 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
951 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000952 return BinaryOperator::createMul(Op0v, Op1v);
Chris Lattner934a64cf2003-03-10 23:23:04 +0000953
Chris Lattner2635b522004-02-23 05:39:21 +0000954 // If one of the operands of the multiply is a cast from a boolean value, then
955 // we know the bool is either zero or one, so this is a 'masking' multiply.
956 // See if we can simplify things based on how the boolean was originally
957 // formed.
958 CastInst *BoolCast = 0;
959 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(0)))
960 if (CI->getOperand(0)->getType() == Type::BoolTy)
961 BoolCast = CI;
962 if (!BoolCast)
963 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(1)))
964 if (CI->getOperand(0)->getType() == Type::BoolTy)
965 BoolCast = CI;
966 if (BoolCast) {
967 if (SetCondInst *SCI = dyn_cast<SetCondInst>(BoolCast->getOperand(0))) {
968 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
969 const Type *SCOpTy = SCIOp0->getType();
970
Chris Lattnere79e8542004-02-23 06:38:22 +0000971 // If the setcc is true iff the sign bit of X is set, then convert this
972 // multiply into a shift/and combination.
973 if (isa<ConstantInt>(SCIOp1) &&
974 isSignBitCheck(SCI->getOpcode(), SCIOp0, cast<ConstantInt>(SCIOp1))) {
Chris Lattner2635b522004-02-23 05:39:21 +0000975 // Shift the X value right to turn it into "all signbits".
976 Constant *Amt = ConstantUInt::get(Type::UByteTy,
Chris Lattnerd1f46d32005-04-24 06:59:08 +0000977 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattnere79e8542004-02-23 06:38:22 +0000978 if (SCIOp0->getType()->isUnsigned()) {
Chris Lattner97bfcea2004-06-17 18:16:02 +0000979 const Type *NewTy = SCIOp0->getType()->getSignedVersion();
Chris Lattnere79e8542004-02-23 06:38:22 +0000980 SCIOp0 = InsertNewInstBefore(new CastInst(SCIOp0, NewTy,
981 SCIOp0->getName()), I);
982 }
983
984 Value *V =
985 InsertNewInstBefore(new ShiftInst(Instruction::Shr, SCIOp0, Amt,
986 BoolCast->getOperand(0)->getName()+
987 ".mask"), I);
Chris Lattner2635b522004-02-23 05:39:21 +0000988
989 // If the multiply type is not the same as the source type, sign extend
990 // or truncate to the multiply type.
991 if (I.getType() != V->getType())
Chris Lattnere79e8542004-02-23 06:38:22 +0000992 V = InsertNewInstBefore(new CastInst(V, I.getType(), V->getName()),I);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000993
Chris Lattner2635b522004-02-23 05:39:21 +0000994 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000995 return BinaryOperator::createAnd(V, OtherOp);
Chris Lattner2635b522004-02-23 05:39:21 +0000996 }
997 }
998 }
999
Chris Lattner113f4f42002-06-25 16:13:24 +00001000 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +00001001}
1002
Chris Lattner113f4f42002-06-25 16:13:24 +00001003Instruction *InstCombiner::visitDiv(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001004 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner81a7a232004-10-16 18:11:37 +00001005
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001006 if (isa<UndefValue>(Op0)) // undef / X -> 0
1007 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1008 if (isa<UndefValue>(Op1))
1009 return ReplaceInstUsesWith(I, Op1); // X / undef -> undef
1010
1011 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnere20c3342004-04-26 14:01:59 +00001012 // div X, 1 == X
Chris Lattnere6794492002-08-12 21:17:25 +00001013 if (RHS->equalsInt(1))
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001014 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001015
Chris Lattnere20c3342004-04-26 14:01:59 +00001016 // div X, -1 == -X
1017 if (RHS->isAllOnesValue())
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001018 return BinaryOperator::createNeg(Op0);
Chris Lattnere20c3342004-04-26 14:01:59 +00001019
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001020 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
Chris Lattner272d5ca2004-09-28 18:22:15 +00001021 if (LHS->getOpcode() == Instruction::Div)
1022 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Chris Lattner272d5ca2004-09-28 18:22:15 +00001023 // (X / C1) / C2 -> X / (C1*C2)
1024 return BinaryOperator::createDiv(LHS->getOperand(0),
1025 ConstantExpr::getMul(RHS, LHSRHS));
1026 }
1027
Chris Lattner3082c5a2003-02-18 19:28:33 +00001028 // Check to see if this is an unsigned division with an exact power of 2,
1029 // if so, convert to a right shift.
1030 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
1031 if (uint64_t Val = C->getValue()) // Don't break X / 0
Chris Lattner22d00a82005-08-02 19:16:58 +00001032 if (isPowerOf2_64(Val)) {
1033 uint64_t C = Log2_64(Val);
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001034 return new ShiftInst(Instruction::Shr, Op0,
Chris Lattner3082c5a2003-02-18 19:28:33 +00001035 ConstantUInt::get(Type::UByteTy, C));
Chris Lattner22d00a82005-08-02 19:16:58 +00001036 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001037
Chris Lattner4ad08352004-10-09 02:50:40 +00001038 // -X/C -> X/-C
1039 if (RHS->getType()->isSigned())
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001040 if (Value *LHSNeg = dyn_castNegVal(Op0))
Chris Lattner4ad08352004-10-09 02:50:40 +00001041 return BinaryOperator::createDiv(LHSNeg, ConstantExpr::getNeg(RHS));
1042
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001043 if (!RHS->isNullValue()) {
1044 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00001045 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001046 return R;
1047 if (isa<PHINode>(Op0))
1048 if (Instruction *NV = FoldOpIntoPhi(I))
1049 return NV;
1050 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00001051 }
1052
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001053 // If this is 'udiv X, (Cond ? C1, C2)' where C1&C2 are powers of two,
1054 // transform this into: '(Cond ? (udiv X, C1) : (udiv X, C2))'.
1055 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1056 if (ConstantUInt *STO = dyn_cast<ConstantUInt>(SI->getOperand(1)))
1057 if (ConstantUInt *SFO = dyn_cast<ConstantUInt>(SI->getOperand(2))) {
1058 if (STO->getValue() == 0) { // Couldn't be this argument.
1059 I.setOperand(1, SFO);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001060 return &I;
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001061 } else if (SFO->getValue() == 0) {
Chris Lattner89dc4f12005-06-16 04:55:52 +00001062 I.setOperand(1, STO);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001063 return &I;
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001064 }
1065
Chris Lattner42362612005-04-08 04:03:26 +00001066 uint64_t TVA = STO->getValue(), FVA = SFO->getValue();
Chris Lattner22d00a82005-08-02 19:16:58 +00001067 if (isPowerOf2_64(TVA) && isPowerOf2_64(FVA)) {
1068 unsigned TSA = Log2_64(TVA), FSA = Log2_64(FVA);
Chris Lattner42362612005-04-08 04:03:26 +00001069 Constant *TC = ConstantUInt::get(Type::UByteTy, TSA);
1070 Instruction *TSI = new ShiftInst(Instruction::Shr, Op0,
1071 TC, SI->getName()+".t");
1072 TSI = InsertNewInstBefore(TSI, I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001073
Chris Lattner42362612005-04-08 04:03:26 +00001074 Constant *FC = ConstantUInt::get(Type::UByteTy, FSA);
1075 Instruction *FSI = new ShiftInst(Instruction::Shr, Op0,
1076 FC, SI->getName()+".f");
1077 FSI = InsertNewInstBefore(FSI, I);
1078 return new SelectInst(SI->getOperand(0), TSI, FSI);
1079 }
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001080 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001081
Chris Lattner3082c5a2003-02-18 19:28:33 +00001082 // 0 / X == 0, we don't need to preserve faults!
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001083 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattner3082c5a2003-02-18 19:28:33 +00001084 if (LHS->equalsInt(0))
1085 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1086
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001087 return 0;
1088}
1089
1090
Chris Lattner113f4f42002-06-25 16:13:24 +00001091Instruction *InstCombiner::visitRem(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001092 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner7fd5f072004-07-06 07:01:22 +00001093 if (I.getType()->isSigned())
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001094 if (Value *RHSNeg = dyn_castNegVal(Op1))
Chris Lattner98c6bdf2004-07-06 07:11:42 +00001095 if (!isa<ConstantSInt>(RHSNeg) ||
Chris Lattner8e726062004-08-09 21:05:48 +00001096 cast<ConstantSInt>(RHSNeg)->getValue() > 0) {
Chris Lattner7fd5f072004-07-06 07:01:22 +00001097 // X % -Y -> X % Y
1098 AddUsesToWorkList(I);
1099 I.setOperand(1, RHSNeg);
1100 return &I;
1101 }
1102
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001103 if (isa<UndefValue>(Op0)) // undef % X -> 0
Chris Lattner81a7a232004-10-16 18:11:37 +00001104 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001105 if (isa<UndefValue>(Op1))
1106 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Chris Lattner81a7a232004-10-16 18:11:37 +00001107
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001108 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00001109 if (RHS->equalsInt(1)) // X % 1 == 0
1110 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1111
1112 // Check to see if this is an unsigned remainder with an exact power of 2,
1113 // if so, convert to a bitwise and.
1114 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
1115 if (uint64_t Val = C->getValue()) // Don't break X % 0 (divide by zero)
Chris Lattnerd9e58132004-05-07 15:35:56 +00001116 if (!(Val & (Val-1))) // Power of 2
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001117 return BinaryOperator::createAnd(Op0,
1118 ConstantUInt::get(I.getType(), Val-1));
1119
1120 if (!RHS->isNullValue()) {
1121 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00001122 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001123 return R;
1124 if (isa<PHINode>(Op0))
1125 if (Instruction *NV = FoldOpIntoPhi(I))
1126 return NV;
1127 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00001128 }
1129
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001130 // If this is 'urem X, (Cond ? C1, C2)' where C1&C2 are powers of two,
1131 // transform this into: '(Cond ? (urem X, C1) : (urem X, C2))'.
1132 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1133 if (ConstantUInt *STO = dyn_cast<ConstantUInt>(SI->getOperand(1)))
1134 if (ConstantUInt *SFO = dyn_cast<ConstantUInt>(SI->getOperand(2))) {
1135 if (STO->getValue() == 0) { // Couldn't be this argument.
1136 I.setOperand(1, SFO);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001137 return &I;
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001138 } else if (SFO->getValue() == 0) {
1139 I.setOperand(1, STO);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001140 return &I;
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001141 }
1142
1143 if (!(STO->getValue() & (STO->getValue()-1)) &&
1144 !(SFO->getValue() & (SFO->getValue()-1))) {
1145 Value *TrueAnd = InsertNewInstBefore(BinaryOperator::createAnd(Op0,
1146 SubOne(STO), SI->getName()+".t"), I);
1147 Value *FalseAnd = InsertNewInstBefore(BinaryOperator::createAnd(Op0,
1148 SubOne(SFO), SI->getName()+".f"), I);
1149 return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
1150 }
1151 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001152
Chris Lattner3082c5a2003-02-18 19:28:33 +00001153 // 0 % X == 0, we don't need to preserve faults!
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001154 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattner3082c5a2003-02-18 19:28:33 +00001155 if (LHS->equalsInt(0))
Chris Lattnere6794492002-08-12 21:17:25 +00001156 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1157
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001158 return 0;
1159}
1160
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001161// isMaxValueMinusOne - return true if this is Max-1
Chris Lattnere6794492002-08-12 21:17:25 +00001162static bool isMaxValueMinusOne(const ConstantInt *C) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001163 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C)) {
1164 // Calculate -1 casted to the right type...
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001165 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001166 uint64_t Val = ~0ULL; // All ones
1167 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
1168 return CU->getValue() == Val-1;
1169 }
1170
1171 const ConstantSInt *CS = cast<ConstantSInt>(C);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001172
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001173 // Calculate 0111111111..11111
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001174 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001175 int64_t Val = INT64_MAX; // All ones
1176 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
1177 return CS->getValue() == Val-1;
1178}
1179
1180// isMinValuePlusOne - return true if this is Min+1
Chris Lattnere6794492002-08-12 21:17:25 +00001181static bool isMinValuePlusOne(const ConstantInt *C) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001182 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
1183 return CU->getValue() == 1;
1184
1185 const ConstantSInt *CS = cast<ConstantSInt>(C);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001186
1187 // Calculate 1111111111000000000000
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001188 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001189 int64_t Val = -1; // All ones
1190 Val <<= TypeBits-1; // Shift over to the right spot
1191 return CS->getValue() == Val+1;
1192}
1193
Chris Lattner35167c32004-06-09 07:59:58 +00001194// isOneBitSet - Return true if there is exactly one bit set in the specified
1195// constant.
1196static bool isOneBitSet(const ConstantInt *CI) {
1197 uint64_t V = CI->getRawValue();
1198 return V && (V & (V-1)) == 0;
1199}
1200
Chris Lattner8fc5af42004-09-23 21:46:38 +00001201#if 0 // Currently unused
1202// isLowOnes - Return true if the constant is of the form 0+1+.
1203static bool isLowOnes(const ConstantInt *CI) {
1204 uint64_t V = CI->getRawValue();
1205
1206 // There won't be bits set in parts that the type doesn't contain.
1207 V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
1208
1209 uint64_t U = V+1; // If it is low ones, this should be a power of two.
1210 return U && V && (U & V) == 0;
1211}
1212#endif
1213
1214// isHighOnes - Return true if the constant is of the form 1+0+.
1215// This is the same as lowones(~X).
1216static bool isHighOnes(const ConstantInt *CI) {
1217 uint64_t V = ~CI->getRawValue();
1218
1219 // There won't be bits set in parts that the type doesn't contain.
1220 V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
1221
1222 uint64_t U = V+1; // If it is low ones, this should be a power of two.
1223 return U && V && (U & V) == 0;
1224}
1225
1226
Chris Lattner3ac7c262003-08-13 20:16:26 +00001227/// getSetCondCode - Encode a setcc opcode into a three bit mask. These bits
1228/// are carefully arranged to allow folding of expressions such as:
1229///
1230/// (A < B) | (A > B) --> (A != B)
1231///
1232/// Bit value '4' represents that the comparison is true if A > B, bit value '2'
1233/// represents that the comparison is true if A == B, and bit value '1' is true
1234/// if A < B.
1235///
1236static unsigned getSetCondCode(const SetCondInst *SCI) {
1237 switch (SCI->getOpcode()) {
1238 // False -> 0
1239 case Instruction::SetGT: return 1;
1240 case Instruction::SetEQ: return 2;
1241 case Instruction::SetGE: return 3;
1242 case Instruction::SetLT: return 4;
1243 case Instruction::SetNE: return 5;
1244 case Instruction::SetLE: return 6;
1245 // True -> 7
1246 default:
1247 assert(0 && "Invalid SetCC opcode!");
1248 return 0;
1249 }
1250}
1251
1252/// getSetCCValue - This is the complement of getSetCondCode, which turns an
1253/// opcode and two operands into either a constant true or false, or a brand new
1254/// SetCC instruction.
1255static Value *getSetCCValue(unsigned Opcode, Value *LHS, Value *RHS) {
1256 switch (Opcode) {
1257 case 0: return ConstantBool::False;
1258 case 1: return new SetCondInst(Instruction::SetGT, LHS, RHS);
1259 case 2: return new SetCondInst(Instruction::SetEQ, LHS, RHS);
1260 case 3: return new SetCondInst(Instruction::SetGE, LHS, RHS);
1261 case 4: return new SetCondInst(Instruction::SetLT, LHS, RHS);
1262 case 5: return new SetCondInst(Instruction::SetNE, LHS, RHS);
1263 case 6: return new SetCondInst(Instruction::SetLE, LHS, RHS);
1264 case 7: return ConstantBool::True;
1265 default: assert(0 && "Illegal SetCCCode!"); return 0;
1266 }
1267}
1268
1269// FoldSetCCLogical - Implements (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
1270struct FoldSetCCLogical {
1271 InstCombiner &IC;
1272 Value *LHS, *RHS;
1273 FoldSetCCLogical(InstCombiner &ic, SetCondInst *SCI)
1274 : IC(ic), LHS(SCI->getOperand(0)), RHS(SCI->getOperand(1)) {}
1275 bool shouldApply(Value *V) const {
1276 if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
1277 return (SCI->getOperand(0) == LHS && SCI->getOperand(1) == RHS ||
1278 SCI->getOperand(0) == RHS && SCI->getOperand(1) == LHS);
1279 return false;
1280 }
1281 Instruction *apply(BinaryOperator &Log) const {
1282 SetCondInst *SCI = cast<SetCondInst>(Log.getOperand(0));
1283 if (SCI->getOperand(0) != LHS) {
1284 assert(SCI->getOperand(1) == LHS);
1285 SCI->swapOperands(); // Swap the LHS and RHS of the SetCC
1286 }
1287
1288 unsigned LHSCode = getSetCondCode(SCI);
1289 unsigned RHSCode = getSetCondCode(cast<SetCondInst>(Log.getOperand(1)));
1290 unsigned Code;
1291 switch (Log.getOpcode()) {
1292 case Instruction::And: Code = LHSCode & RHSCode; break;
1293 case Instruction::Or: Code = LHSCode | RHSCode; break;
1294 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner2caaaba2003-09-22 20:33:34 +00001295 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattner3ac7c262003-08-13 20:16:26 +00001296 }
1297
1298 Value *RV = getSetCCValue(Code, LHS, RHS);
1299 if (Instruction *I = dyn_cast<Instruction>(RV))
1300 return I;
1301 // Otherwise, it's a constant boolean value...
1302 return IC.ReplaceInstUsesWith(Log, RV);
1303 }
1304};
1305
1306
Chris Lattner86102b82005-01-01 16:22:27 +00001307/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
1308/// this predicate to simplify operations downstream. V and Mask are known to
1309/// be the same type.
1310static bool MaskedValueIsZero(Value *V, ConstantIntegral *Mask) {
Chris Lattner18aa4d82005-07-20 18:49:28 +00001311 // Note, we cannot consider 'undef' to be "IsZero" here. The problem is that
1312 // we cannot optimize based on the assumption that it is zero without changing
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00001313 // to to an explicit zero. If we don't change it to zero, other code could
Chris Lattner18aa4d82005-07-20 18:49:28 +00001314 // optimized based on the contradictory assumption that it is non-zero.
1315 // Because instcombine aggressively folds operations with undef args anyway,
1316 // this won't lose us code quality.
1317 if (Mask->isNullValue())
Chris Lattner86102b82005-01-01 16:22:27 +00001318 return true;
1319 if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(V))
1320 return ConstantExpr::getAnd(CI, Mask)->isNullValue();
Misha Brukmanb1c93172005-04-21 23:48:37 +00001321
Chris Lattner86102b82005-01-01 16:22:27 +00001322 if (Instruction *I = dyn_cast<Instruction>(V)) {
1323 switch (I->getOpcode()) {
1324 case Instruction::And:
1325 // (X & C1) & C2 == 0 iff C1 & C2 == 0.
1326 if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(I->getOperand(1)))
1327 if (ConstantExpr::getAnd(CI, Mask)->isNullValue())
1328 return true;
1329 break;
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00001330 case Instruction::Or:
1331 // If the LHS and the RHS are MaskedValueIsZero, the result is also zero.
Misha Brukmanb1c93172005-04-21 23:48:37 +00001332 return MaskedValueIsZero(I->getOperand(1), Mask) &&
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00001333 MaskedValueIsZero(I->getOperand(0), Mask);
1334 case Instruction::Select:
1335 // If the T and F values are MaskedValueIsZero, the result is also zero.
Misha Brukmanb1c93172005-04-21 23:48:37 +00001336 return MaskedValueIsZero(I->getOperand(2), Mask) &&
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00001337 MaskedValueIsZero(I->getOperand(1), Mask);
Chris Lattner86102b82005-01-01 16:22:27 +00001338 case Instruction::Cast: {
1339 const Type *SrcTy = I->getOperand(0)->getType();
Chris Lattner4c2d3782005-05-06 01:53:19 +00001340 if (SrcTy == Type::BoolTy)
1341 return (Mask->getRawValue() & 1) == 0;
1342
1343 if (SrcTy->isInteger()) {
Chris Lattner86102b82005-01-01 16:22:27 +00001344 // (cast <ty> X to int) & C2 == 0 iff <ty> could not have contained C2.
1345 if (SrcTy->isUnsigned() && // Only handle zero ext.
1346 ConstantExpr::getCast(Mask, SrcTy)->isNullValue())
1347 return true;
1348
1349 // If this is a noop cast, recurse.
Chris Lattner4c2d3782005-05-06 01:53:19 +00001350 if ((SrcTy->isSigned() && SrcTy->getUnsignedVersion() == I->getType())||
1351 SrcTy->getSignedVersion() == I->getType()) {
1352 Constant *NewMask =
1353 ConstantExpr::getCast(Mask, I->getOperand(0)->getType());
1354 return MaskedValueIsZero(I->getOperand(0),
1355 cast<ConstantIntegral>(NewMask));
1356 }
Chris Lattner86102b82005-01-01 16:22:27 +00001357 }
1358 break;
1359 }
1360 case Instruction::Shl:
Chris Lattneref298a32005-05-06 04:53:20 +00001361 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
1362 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1)))
1363 return MaskedValueIsZero(I->getOperand(0),
1364 cast<ConstantIntegral>(ConstantExpr::getUShr(Mask, SA)));
Chris Lattner86102b82005-01-01 16:22:27 +00001365 break;
1366 case Instruction::Shr:
1367 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
1368 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1)))
1369 if (I->getType()->isUnsigned()) {
1370 Constant *C1 = ConstantIntegral::getAllOnesValue(I->getType());
1371 C1 = ConstantExpr::getShr(C1, SA);
1372 C1 = ConstantExpr::getAnd(C1, Mask);
1373 if (C1->isNullValue())
1374 return true;
1375 }
1376 break;
1377 }
1378 }
1379
1380 return false;
1381}
1382
Chris Lattnerba1cb382003-09-19 17:17:26 +00001383// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
1384// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
1385// guaranteed to be either a shift instruction or a binary operator.
1386Instruction *InstCombiner::OptAndOp(Instruction *Op,
1387 ConstantIntegral *OpRHS,
1388 ConstantIntegral *AndRHS,
1389 BinaryOperator &TheAnd) {
1390 Value *X = Op->getOperand(0);
Chris Lattnerfcf21a72004-01-12 19:47:05 +00001391 Constant *Together = 0;
1392 if (!isa<ShiftInst>(Op))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001393 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001394
Chris Lattnerba1cb382003-09-19 17:17:26 +00001395 switch (Op->getOpcode()) {
1396 case Instruction::Xor:
Chris Lattner86102b82005-01-01 16:22:27 +00001397 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001398 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
1399 std::string OpName = Op->getName(); Op->setName("");
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001400 Instruction *And = BinaryOperator::createAnd(X, AndRHS, OpName);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001401 InsertNewInstBefore(And, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001402 return BinaryOperator::createXor(And, Together);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001403 }
1404 break;
1405 case Instruction::Or:
Chris Lattner86102b82005-01-01 16:22:27 +00001406 if (Together == AndRHS) // (X | C) & C --> C
1407 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001408
Chris Lattner86102b82005-01-01 16:22:27 +00001409 if (Op->hasOneUse() && Together != OpRHS) {
1410 // (X | C1) & C2 --> (X | (C1&C2)) & C2
1411 std::string Op0Name = Op->getName(); Op->setName("");
1412 Instruction *Or = BinaryOperator::createOr(X, Together, Op0Name);
1413 InsertNewInstBefore(Or, TheAnd);
1414 return BinaryOperator::createAnd(Or, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001415 }
1416 break;
1417 case Instruction::Add:
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001418 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001419 // Adding a one to a single bit bit-field should be turned into an XOR
1420 // of the bit. First thing to check is to see if this AND is with a
1421 // single bit constant.
Chris Lattner35167c32004-06-09 07:59:58 +00001422 uint64_t AndRHSV = cast<ConstantInt>(AndRHS)->getRawValue();
Chris Lattnerba1cb382003-09-19 17:17:26 +00001423
1424 // Clear bits that are not part of the constant.
Chris Lattner2f1457f2005-04-24 17:46:05 +00001425 AndRHSV &= ~0ULL >> (64-AndRHS->getType()->getPrimitiveSizeInBits());
Chris Lattnerba1cb382003-09-19 17:17:26 +00001426
1427 // If there is only one bit set...
Chris Lattner35167c32004-06-09 07:59:58 +00001428 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001429 // Ok, at this point, we know that we are masking the result of the
1430 // ADD down to exactly one bit. If the constant we are adding has
1431 // no bits set below this bit, then we can eliminate the ADD.
Chris Lattner35167c32004-06-09 07:59:58 +00001432 uint64_t AddRHS = cast<ConstantInt>(OpRHS)->getRawValue();
Misha Brukmanb1c93172005-04-21 23:48:37 +00001433
Chris Lattnerba1cb382003-09-19 17:17:26 +00001434 // Check to see if any bits below the one bit set in AndRHSV are set.
1435 if ((AddRHS & (AndRHSV-1)) == 0) {
1436 // If not, the only thing that can effect the output of the AND is
1437 // the bit specified by AndRHSV. If that bit is set, the effect of
1438 // the XOR is to toggle the bit. If it is clear, then the ADD has
1439 // no effect.
1440 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
1441 TheAnd.setOperand(0, X);
1442 return &TheAnd;
1443 } else {
1444 std::string Name = Op->getName(); Op->setName("");
1445 // Pull the XOR out of the AND.
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001446 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS, Name);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001447 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001448 return BinaryOperator::createXor(NewAnd, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001449 }
1450 }
1451 }
1452 }
1453 break;
Chris Lattner2da29172003-09-19 19:05:02 +00001454
1455 case Instruction::Shl: {
1456 // We know that the AND will not produce any of the bits shifted in, so if
1457 // the anded constant includes them, clear them now!
1458 //
1459 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner7e794272004-09-24 15:21:34 +00001460 Constant *ShlMask = ConstantExpr::getShl(AllOne, OpRHS);
1461 Constant *CI = ConstantExpr::getAnd(AndRHS, ShlMask);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001462
Chris Lattner7e794272004-09-24 15:21:34 +00001463 if (CI == ShlMask) { // Masking out bits that the shift already masks
1464 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
1465 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner2da29172003-09-19 19:05:02 +00001466 TheAnd.setOperand(1, CI);
1467 return &TheAnd;
1468 }
1469 break;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001470 }
Chris Lattner2da29172003-09-19 19:05:02 +00001471 case Instruction::Shr:
1472 // We know that the AND will not produce any of the bits shifted in, so if
1473 // the anded constant includes them, clear them now! This only applies to
1474 // unsigned shifts, because a signed shr may bring in set bits!
1475 //
1476 if (AndRHS->getType()->isUnsigned()) {
1477 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner7e794272004-09-24 15:21:34 +00001478 Constant *ShrMask = ConstantExpr::getShr(AllOne, OpRHS);
1479 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
1480
1481 if (CI == ShrMask) { // Masking out bits that the shift already masks.
1482 return ReplaceInstUsesWith(TheAnd, Op);
1483 } else if (CI != AndRHS) {
1484 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
Chris Lattner2da29172003-09-19 19:05:02 +00001485 return &TheAnd;
1486 }
Chris Lattner7e794272004-09-24 15:21:34 +00001487 } else { // Signed shr.
1488 // See if this is shifting in some sign extension, then masking it out
1489 // with an and.
1490 if (Op->hasOneUse()) {
1491 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
1492 Constant *ShrMask = ConstantExpr::getUShr(AllOne, OpRHS);
1493 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
Chris Lattner5c3c21e2004-10-22 04:53:16 +00001494 if (CI == AndRHS) { // Masking out bits shifted in.
Chris Lattner7e794272004-09-24 15:21:34 +00001495 // Make the argument unsigned.
1496 Value *ShVal = Op->getOperand(0);
1497 ShVal = InsertCastBefore(ShVal,
1498 ShVal->getType()->getUnsignedVersion(),
1499 TheAnd);
1500 ShVal = InsertNewInstBefore(new ShiftInst(Instruction::Shr, ShVal,
1501 OpRHS, Op->getName()),
1502 TheAnd);
Chris Lattner70c20392004-10-27 05:57:15 +00001503 Value *AndRHS2 = ConstantExpr::getCast(AndRHS, ShVal->getType());
1504 ShVal = InsertNewInstBefore(BinaryOperator::createAnd(ShVal, AndRHS2,
1505 TheAnd.getName()),
1506 TheAnd);
Chris Lattner7e794272004-09-24 15:21:34 +00001507 return new CastInst(ShVal, Op->getType());
1508 }
1509 }
Chris Lattner2da29172003-09-19 19:05:02 +00001510 }
1511 break;
Chris Lattnerba1cb382003-09-19 17:17:26 +00001512 }
1513 return 0;
1514}
1515
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001516
Chris Lattner6862fbd2004-09-29 17:40:11 +00001517/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
1518/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
1519/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. IB is the location to
1520/// insert new instructions.
1521Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
1522 bool Inside, Instruction &IB) {
1523 assert(cast<ConstantBool>(ConstantExpr::getSetLE(Lo, Hi))->getValue() &&
1524 "Lo is not <= Hi in range emission code!");
1525 if (Inside) {
1526 if (Lo == Hi) // Trivially false.
1527 return new SetCondInst(Instruction::SetNE, V, V);
1528 if (cast<ConstantIntegral>(Lo)->isMinValue())
1529 return new SetCondInst(Instruction::SetLT, V, Hi);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001530
Chris Lattner6862fbd2004-09-29 17:40:11 +00001531 Constant *AddCST = ConstantExpr::getNeg(Lo);
1532 Instruction *Add = BinaryOperator::createAdd(V, AddCST,V->getName()+".off");
1533 InsertNewInstBefore(Add, IB);
1534 // Convert to unsigned for the comparison.
1535 const Type *UnsType = Add->getType()->getUnsignedVersion();
1536 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
1537 AddCST = ConstantExpr::getAdd(AddCST, Hi);
1538 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1539 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
1540 }
1541
1542 if (Lo == Hi) // Trivially true.
1543 return new SetCondInst(Instruction::SetEQ, V, V);
1544
1545 Hi = SubOne(cast<ConstantInt>(Hi));
1546 if (cast<ConstantIntegral>(Lo)->isMinValue()) // V < 0 || V >= Hi ->'V > Hi-1'
1547 return new SetCondInst(Instruction::SetGT, V, Hi);
1548
1549 // Emit X-Lo > Hi-Lo-1
1550 Constant *AddCST = ConstantExpr::getNeg(Lo);
1551 Instruction *Add = BinaryOperator::createAdd(V, AddCST, V->getName()+".off");
1552 InsertNewInstBefore(Add, IB);
1553 // Convert to unsigned for the comparison.
1554 const Type *UnsType = Add->getType()->getUnsignedVersion();
1555 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
1556 AddCST = ConstantExpr::getAdd(AddCST, Hi);
1557 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1558 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
1559}
1560
1561
Chris Lattner113f4f42002-06-25 16:13:24 +00001562Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001563 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00001564 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001565
Chris Lattner81a7a232004-10-16 18:11:37 +00001566 if (isa<UndefValue>(Op1)) // X & undef -> 0
1567 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1568
Chris Lattner86102b82005-01-01 16:22:27 +00001569 // and X, X = X
1570 if (Op0 == Op1)
Chris Lattnere6794492002-08-12 21:17:25 +00001571 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001572
Chris Lattner86102b82005-01-01 16:22:27 +00001573 if (ConstantIntegral *AndRHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00001574 // and X, -1 == X
1575 if (AndRHS->isAllOnesValue())
Chris Lattnere6794492002-08-12 21:17:25 +00001576 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001577
Chris Lattner86102b82005-01-01 16:22:27 +00001578 if (MaskedValueIsZero(Op0, AndRHS)) // LHS & RHS == 0
1579 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1580
1581 // If the mask is not masking out any bits, there is no reason to do the
1582 // and in the first place.
Misha Brukmanb1c93172005-04-21 23:48:37 +00001583 ConstantIntegral *NotAndRHS =
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00001584 cast<ConstantIntegral>(ConstantExpr::getNot(AndRHS));
Misha Brukmanb1c93172005-04-21 23:48:37 +00001585 if (MaskedValueIsZero(Op0, NotAndRHS))
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00001586 return ReplaceInstUsesWith(I, Op0);
Chris Lattner86102b82005-01-01 16:22:27 +00001587
Chris Lattnerba1cb382003-09-19 17:17:26 +00001588 // Optimize a variety of ((val OP C1) & C2) combinations...
1589 if (isa<BinaryOperator>(Op0) || isa<ShiftInst>(Op0)) {
1590 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner86102b82005-01-01 16:22:27 +00001591 Value *Op0LHS = Op0I->getOperand(0);
1592 Value *Op0RHS = Op0I->getOperand(1);
1593 switch (Op0I->getOpcode()) {
1594 case Instruction::Xor:
1595 case Instruction::Or:
1596 // (X ^ V) & C2 --> (X & C2) iff (V & C2) == 0
1597 // (X | V) & C2 --> (X & C2) iff (V & C2) == 0
1598 if (MaskedValueIsZero(Op0LHS, AndRHS))
Misha Brukmanb1c93172005-04-21 23:48:37 +00001599 return BinaryOperator::createAnd(Op0RHS, AndRHS);
Chris Lattner86102b82005-01-01 16:22:27 +00001600 if (MaskedValueIsZero(Op0RHS, AndRHS))
Misha Brukmanb1c93172005-04-21 23:48:37 +00001601 return BinaryOperator::createAnd(Op0LHS, AndRHS);
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00001602
1603 // If the mask is only needed on one incoming arm, push it up.
1604 if (Op0I->hasOneUse()) {
1605 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
1606 // Not masking anything out for the LHS, move to RHS.
1607 Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
1608 Op0RHS->getName()+".masked");
1609 InsertNewInstBefore(NewRHS, I);
1610 return BinaryOperator::create(
1611 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001612 }
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00001613 if (!isa<Constant>(NotAndRHS) &&
1614 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
1615 // Not masking anything out for the RHS, move to LHS.
1616 Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
1617 Op0LHS->getName()+".masked");
1618 InsertNewInstBefore(NewLHS, I);
1619 return BinaryOperator::create(
1620 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
1621 }
1622 }
1623
Chris Lattner86102b82005-01-01 16:22:27 +00001624 break;
1625 case Instruction::And:
1626 // (X & V) & C2 --> 0 iff (V & C2) == 0
1627 if (MaskedValueIsZero(Op0LHS, AndRHS) ||
1628 MaskedValueIsZero(Op0RHS, AndRHS))
1629 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1630 break;
1631 }
1632
Chris Lattner16464b32003-07-23 19:25:52 +00001633 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner86102b82005-01-01 16:22:27 +00001634 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerba1cb382003-09-19 17:17:26 +00001635 return Res;
Chris Lattner86102b82005-01-01 16:22:27 +00001636 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
1637 const Type *SrcTy = CI->getOperand(0)->getType();
1638
1639 // If this is an integer sign or zero extension instruction.
1640 if (SrcTy->isIntegral() &&
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001641 SrcTy->getPrimitiveSizeInBits() <
1642 CI->getType()->getPrimitiveSizeInBits()) {
Chris Lattner86102b82005-01-01 16:22:27 +00001643
1644 if (SrcTy->isUnsigned()) {
1645 // See if this and is clearing out bits that are known to be zero
1646 // anyway (due to the zero extension).
1647 Constant *Mask = ConstantIntegral::getAllOnesValue(SrcTy);
1648 Mask = ConstantExpr::getZeroExtend(Mask, CI->getType());
1649 Constant *Result = ConstantExpr::getAnd(Mask, AndRHS);
1650 if (Result == Mask) // The "and" isn't doing anything, remove it.
1651 return ReplaceInstUsesWith(I, CI);
1652 if (Result != AndRHS) { // Reduce the and RHS constant.
1653 I.setOperand(1, Result);
1654 return &I;
1655 }
1656
1657 } else {
1658 if (CI->hasOneUse() && SrcTy->isInteger()) {
1659 // We can only do this if all of the sign bits brought in are masked
1660 // out. Compute this by first getting 0000011111, then inverting
1661 // it.
1662 Constant *Mask = ConstantIntegral::getAllOnesValue(SrcTy);
1663 Mask = ConstantExpr::getZeroExtend(Mask, CI->getType());
1664 Mask = ConstantExpr::getNot(Mask); // 1's in the new bits.
1665 if (ConstantExpr::getAnd(Mask, AndRHS)->isNullValue()) {
1666 // If the and is clearing all of the sign bits, change this to a
1667 // zero extension cast. To do this, cast the cast input to
1668 // unsigned, then to the requested size.
1669 Value *CastOp = CI->getOperand(0);
1670 Instruction *NC =
1671 new CastInst(CastOp, CastOp->getType()->getUnsignedVersion(),
1672 CI->getName()+".uns");
1673 NC = InsertNewInstBefore(NC, I);
1674 // Finally, insert a replacement for CI.
1675 NC = new CastInst(NC, CI->getType(), CI->getName());
1676 CI->setName("");
1677 NC = InsertNewInstBefore(NC, I);
1678 WorkList.push_back(CI); // Delete CI later.
1679 I.setOperand(0, NC);
1680 return &I; // The AND operand was modified.
1681 }
1682 }
1683 }
1684 }
Chris Lattner33217db2003-07-23 19:36:21 +00001685 }
Chris Lattner183b3362004-04-09 19:05:30 +00001686
1687 // Try to fold constant and into select arguments.
1688 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00001689 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00001690 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001691 if (isa<PHINode>(Op0))
1692 if (Instruction *NV = FoldOpIntoPhi(I))
1693 return NV;
Chris Lattner49b47ae2003-07-23 17:57:01 +00001694 }
1695
Chris Lattnerbb74e222003-03-10 23:06:50 +00001696 Value *Op0NotVal = dyn_castNotVal(Op0);
1697 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001698
Chris Lattner023a4832004-06-18 06:07:51 +00001699 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
1700 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1701
Misha Brukman9c003d82004-07-30 12:50:08 +00001702 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattnerbb74e222003-03-10 23:06:50 +00001703 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001704 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
1705 I.getName()+".demorgan");
Chris Lattner49b47ae2003-07-23 17:57:01 +00001706 InsertNewInstBefore(Or, I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001707 return BinaryOperator::createNot(Or);
1708 }
1709
Chris Lattner623826c2004-09-28 21:48:02 +00001710 if (SetCondInst *RHS = dyn_cast<SetCondInst>(Op1)) {
1711 // (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
Chris Lattner3ac7c262003-08-13 20:16:26 +00001712 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
1713 return R;
1714
Chris Lattner623826c2004-09-28 21:48:02 +00001715 Value *LHSVal, *RHSVal;
1716 ConstantInt *LHSCst, *RHSCst;
1717 Instruction::BinaryOps LHSCC, RHSCC;
1718 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
1719 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
1720 if (LHSVal == RHSVal && // Found (X setcc C1) & (X setcc C2)
1721 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
Misha Brukmanb1c93172005-04-21 23:48:37 +00001722 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
Chris Lattner623826c2004-09-28 21:48:02 +00001723 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
1724 // Ensure that the larger constant is on the RHS.
1725 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
1726 SetCondInst *LHS = cast<SetCondInst>(Op0);
1727 if (cast<ConstantBool>(Cmp)->getValue()) {
1728 std::swap(LHS, RHS);
1729 std::swap(LHSCst, RHSCst);
1730 std::swap(LHSCC, RHSCC);
1731 }
1732
1733 // At this point, we know we have have two setcc instructions
1734 // comparing a value against two constants and and'ing the result
1735 // together. Because of the above check, we know that we only have
1736 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
1737 // FoldSetCCLogical check above), that the two constants are not
1738 // equal.
1739 assert(LHSCst != RHSCst && "Compares not folded above?");
1740
1741 switch (LHSCC) {
1742 default: assert(0 && "Unknown integer condition code!");
1743 case Instruction::SetEQ:
1744 switch (RHSCC) {
1745 default: assert(0 && "Unknown integer condition code!");
1746 case Instruction::SetEQ: // (X == 13 & X == 15) -> false
1747 case Instruction::SetGT: // (X == 13 & X > 15) -> false
1748 return ReplaceInstUsesWith(I, ConstantBool::False);
1749 case Instruction::SetNE: // (X == 13 & X != 15) -> X == 13
1750 case Instruction::SetLT: // (X == 13 & X < 15) -> X == 13
1751 return ReplaceInstUsesWith(I, LHS);
1752 }
1753 case Instruction::SetNE:
1754 switch (RHSCC) {
1755 default: assert(0 && "Unknown integer condition code!");
1756 case Instruction::SetLT:
1757 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X < 14) -> X < 13
1758 return new SetCondInst(Instruction::SetLT, LHSVal, LHSCst);
1759 break; // (X != 13 & X < 15) -> no change
1760 case Instruction::SetEQ: // (X != 13 & X == 15) -> X == 15
1761 case Instruction::SetGT: // (X != 13 & X > 15) -> X > 15
1762 return ReplaceInstUsesWith(I, RHS);
1763 case Instruction::SetNE:
1764 if (LHSCst == SubOne(RHSCst)) {// (X != 13 & X != 14) -> X-13 >u 1
1765 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
1766 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
1767 LHSVal->getName()+".off");
1768 InsertNewInstBefore(Add, I);
1769 const Type *UnsType = Add->getType()->getUnsignedVersion();
1770 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
1771 AddCST = ConstantExpr::getSub(RHSCst, LHSCst);
1772 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1773 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
1774 }
1775 break; // (X != 13 & X != 15) -> no change
1776 }
1777 break;
1778 case Instruction::SetLT:
1779 switch (RHSCC) {
1780 default: assert(0 && "Unknown integer condition code!");
1781 case Instruction::SetEQ: // (X < 13 & X == 15) -> false
1782 case Instruction::SetGT: // (X < 13 & X > 15) -> false
1783 return ReplaceInstUsesWith(I, ConstantBool::False);
1784 case Instruction::SetNE: // (X < 13 & X != 15) -> X < 13
1785 case Instruction::SetLT: // (X < 13 & X < 15) -> X < 13
1786 return ReplaceInstUsesWith(I, LHS);
1787 }
1788 case Instruction::SetGT:
1789 switch (RHSCC) {
1790 default: assert(0 && "Unknown integer condition code!");
1791 case Instruction::SetEQ: // (X > 13 & X == 15) -> X > 13
1792 return ReplaceInstUsesWith(I, LHS);
1793 case Instruction::SetGT: // (X > 13 & X > 15) -> X > 15
1794 return ReplaceInstUsesWith(I, RHS);
1795 case Instruction::SetNE:
1796 if (RHSCst == AddOne(LHSCst)) // (X > 13 & X != 14) -> X > 14
1797 return new SetCondInst(Instruction::SetGT, LHSVal, RHSCst);
1798 break; // (X > 13 & X != 15) -> no change
Chris Lattner6862fbd2004-09-29 17:40:11 +00001799 case Instruction::SetLT: // (X > 13 & X < 15) -> (X-14) <u 1
1800 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true, I);
Chris Lattner623826c2004-09-28 21:48:02 +00001801 }
1802 }
1803 }
1804 }
1805
Chris Lattner113f4f42002-06-25 16:13:24 +00001806 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001807}
1808
Chris Lattner113f4f42002-06-25 16:13:24 +00001809Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001810 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00001811 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001812
Chris Lattner81a7a232004-10-16 18:11:37 +00001813 if (isa<UndefValue>(Op1))
1814 return ReplaceInstUsesWith(I, // X | undef -> -1
1815 ConstantIntegral::getAllOnesValue(I.getType()));
1816
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001817 // or X, X = X or X, 0 == X
Chris Lattnere6794492002-08-12 21:17:25 +00001818 if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
1819 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001820
1821 // or X, -1 == -1
Chris Lattner8f0d1562003-07-23 18:29:44 +00001822 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner86102b82005-01-01 16:22:27 +00001823 // If X is known to only contain bits that already exist in RHS, just
1824 // replace this instruction with RHS directly.
1825 if (MaskedValueIsZero(Op0,
1826 cast<ConstantIntegral>(ConstantExpr::getNot(RHS))))
1827 return ReplaceInstUsesWith(I, RHS);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001828
Chris Lattnerd4252a72004-07-30 07:50:03 +00001829 ConstantInt *C1; Value *X;
1830 // (X & C1) | C2 --> (X | C2) & (C1|C2)
1831 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Chris Lattnerb62f5082005-05-09 04:58:36 +00001832 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0->getName());
1833 Op0->setName("");
Chris Lattnerd4252a72004-07-30 07:50:03 +00001834 InsertNewInstBefore(Or, I);
1835 return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, C1));
1836 }
Chris Lattner8f0d1562003-07-23 18:29:44 +00001837
Chris Lattnerd4252a72004-07-30 07:50:03 +00001838 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
1839 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
1840 std::string Op0Name = Op0->getName(); Op0->setName("");
1841 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
1842 InsertNewInstBefore(Or, I);
1843 return BinaryOperator::createXor(Or,
1844 ConstantExpr::getAnd(C1, ConstantExpr::getNot(RHS)));
Chris Lattner8f0d1562003-07-23 18:29:44 +00001845 }
Chris Lattner183b3362004-04-09 19:05:30 +00001846
1847 // Try to fold constant and into select arguments.
1848 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00001849 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00001850 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001851 if (isa<PHINode>(Op0))
1852 if (Instruction *NV = FoldOpIntoPhi(I))
1853 return NV;
Chris Lattner8f0d1562003-07-23 18:29:44 +00001854 }
1855
Chris Lattnerd4252a72004-07-30 07:50:03 +00001856 Value *A, *B; ConstantInt *C1, *C2;
Chris Lattner4294cec2005-05-07 23:49:08 +00001857
1858 if (match(Op0, m_And(m_Value(A), m_Value(B))))
1859 if (A == Op1 || B == Op1) // (A & ?) | A --> A
1860 return ReplaceInstUsesWith(I, Op1);
1861 if (match(Op1, m_And(m_Value(A), m_Value(B))))
1862 if (A == Op0 || B == Op0) // A | (A & ?) --> A
1863 return ReplaceInstUsesWith(I, Op0);
1864
Chris Lattnerb62f5082005-05-09 04:58:36 +00001865 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
1866 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
1867 MaskedValueIsZero(Op1, C1)) {
1868 Instruction *NOr = BinaryOperator::createOr(A, Op1, Op0->getName());
1869 Op0->setName("");
1870 return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
1871 }
1872
1873 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
1874 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
1875 MaskedValueIsZero(Op0, C1)) {
1876 Instruction *NOr = BinaryOperator::createOr(A, Op0, Op1->getName());
1877 Op0->setName("");
1878 return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
1879 }
1880
Chris Lattner4294cec2005-05-07 23:49:08 +00001881 // (A & C1)|(A & C2) == A & (C1|C2)
Chris Lattnerd4252a72004-07-30 07:50:03 +00001882 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
1883 match(Op1, m_And(m_Value(B), m_ConstantInt(C2))) && A == B)
1884 return BinaryOperator::createAnd(A, ConstantExpr::getOr(C1, C2));
Chris Lattner812aab72003-08-12 19:11:07 +00001885
Chris Lattnerd4252a72004-07-30 07:50:03 +00001886 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
1887 if (A == Op1) // ~A | A == -1
Misha Brukmanb1c93172005-04-21 23:48:37 +00001888 return ReplaceInstUsesWith(I,
Chris Lattnerd4252a72004-07-30 07:50:03 +00001889 ConstantIntegral::getAllOnesValue(I.getType()));
1890 } else {
1891 A = 0;
1892 }
Chris Lattner4294cec2005-05-07 23:49:08 +00001893 // Note, A is still live here!
Chris Lattnerd4252a72004-07-30 07:50:03 +00001894 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
1895 if (Op0 == B)
Misha Brukmanb1c93172005-04-21 23:48:37 +00001896 return ReplaceInstUsesWith(I,
Chris Lattnerd4252a72004-07-30 07:50:03 +00001897 ConstantIntegral::getAllOnesValue(I.getType()));
Chris Lattner3e327a42003-03-10 23:13:59 +00001898
Misha Brukman9c003d82004-07-30 12:50:08 +00001899 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattnerd4252a72004-07-30 07:50:03 +00001900 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
1901 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
1902 I.getName()+".demorgan"), I);
1903 return BinaryOperator::createNot(And);
1904 }
Chris Lattner3e327a42003-03-10 23:13:59 +00001905 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00001906
Chris Lattner3ac7c262003-08-13 20:16:26 +00001907 // (setcc1 A, B) | (setcc2 A, B) --> (setcc3 A, B)
Chris Lattnerdcf756e2004-09-28 22:33:08 +00001908 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1))) {
Chris Lattner3ac7c262003-08-13 20:16:26 +00001909 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
1910 return R;
1911
Chris Lattnerdcf756e2004-09-28 22:33:08 +00001912 Value *LHSVal, *RHSVal;
1913 ConstantInt *LHSCst, *RHSCst;
1914 Instruction::BinaryOps LHSCC, RHSCC;
1915 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
1916 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
1917 if (LHSVal == RHSVal && // Found (X setcc C1) | (X setcc C2)
1918 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
Misha Brukmanb1c93172005-04-21 23:48:37 +00001919 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
Chris Lattnerdcf756e2004-09-28 22:33:08 +00001920 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
1921 // Ensure that the larger constant is on the RHS.
1922 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
1923 SetCondInst *LHS = cast<SetCondInst>(Op0);
1924 if (cast<ConstantBool>(Cmp)->getValue()) {
1925 std::swap(LHS, RHS);
1926 std::swap(LHSCst, RHSCst);
1927 std::swap(LHSCC, RHSCC);
1928 }
1929
1930 // At this point, we know we have have two setcc instructions
1931 // comparing a value against two constants and or'ing the result
1932 // together. Because of the above check, we know that we only have
1933 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
1934 // FoldSetCCLogical check above), that the two constants are not
1935 // equal.
1936 assert(LHSCst != RHSCst && "Compares not folded above?");
1937
1938 switch (LHSCC) {
1939 default: assert(0 && "Unknown integer condition code!");
1940 case Instruction::SetEQ:
1941 switch (RHSCC) {
1942 default: assert(0 && "Unknown integer condition code!");
1943 case Instruction::SetEQ:
1944 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
1945 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
1946 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
1947 LHSVal->getName()+".off");
1948 InsertNewInstBefore(Add, I);
1949 const Type *UnsType = Add->getType()->getUnsignedVersion();
1950 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
1951 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
1952 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1953 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
1954 }
1955 break; // (X == 13 | X == 15) -> no change
1956
Chris Lattner5c219462005-04-19 06:04:18 +00001957 case Instruction::SetGT: // (X == 13 | X > 14) -> no change
1958 break;
Chris Lattnerdcf756e2004-09-28 22:33:08 +00001959 case Instruction::SetNE: // (X == 13 | X != 15) -> X != 15
1960 case Instruction::SetLT: // (X == 13 | X < 15) -> X < 15
1961 return ReplaceInstUsesWith(I, RHS);
1962 }
1963 break;
1964 case Instruction::SetNE:
1965 switch (RHSCC) {
1966 default: assert(0 && "Unknown integer condition code!");
Chris Lattnerdcf756e2004-09-28 22:33:08 +00001967 case Instruction::SetEQ: // (X != 13 | X == 15) -> X != 13
1968 case Instruction::SetGT: // (X != 13 | X > 15) -> X != 13
1969 return ReplaceInstUsesWith(I, LHS);
1970 case Instruction::SetNE: // (X != 13 | X != 15) -> true
Chris Lattner2ceb6ee2005-06-17 03:59:17 +00001971 case Instruction::SetLT: // (X != 13 | X < 15) -> true
Chris Lattnerdcf756e2004-09-28 22:33:08 +00001972 return ReplaceInstUsesWith(I, ConstantBool::True);
1973 }
1974 break;
1975 case Instruction::SetLT:
1976 switch (RHSCC) {
1977 default: assert(0 && "Unknown integer condition code!");
1978 case Instruction::SetEQ: // (X < 13 | X == 14) -> no change
1979 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00001980 case Instruction::SetGT: // (X < 13 | X > 15) -> (X-13) > 2
1981 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false, I);
Chris Lattnerdcf756e2004-09-28 22:33:08 +00001982 case Instruction::SetNE: // (X < 13 | X != 15) -> X != 15
1983 case Instruction::SetLT: // (X < 13 | X < 15) -> X < 15
1984 return ReplaceInstUsesWith(I, RHS);
1985 }
1986 break;
1987 case Instruction::SetGT:
1988 switch (RHSCC) {
1989 default: assert(0 && "Unknown integer condition code!");
1990 case Instruction::SetEQ: // (X > 13 | X == 15) -> X > 13
1991 case Instruction::SetGT: // (X > 13 | X > 15) -> X > 13
1992 return ReplaceInstUsesWith(I, LHS);
1993 case Instruction::SetNE: // (X > 13 | X != 15) -> true
1994 case Instruction::SetLT: // (X > 13 | X < 15) -> true
1995 return ReplaceInstUsesWith(I, ConstantBool::True);
1996 }
1997 }
1998 }
1999 }
Chris Lattner113f4f42002-06-25 16:13:24 +00002000 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002001}
2002
Chris Lattnerc2076352004-02-16 01:20:27 +00002003// XorSelf - Implements: X ^ X --> 0
2004struct XorSelf {
2005 Value *RHS;
2006 XorSelf(Value *rhs) : RHS(rhs) {}
2007 bool shouldApply(Value *LHS) const { return LHS == RHS; }
2008 Instruction *apply(BinaryOperator &Xor) const {
2009 return &Xor;
2010 }
2011};
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002012
2013
Chris Lattner113f4f42002-06-25 16:13:24 +00002014Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00002015 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00002016 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002017
Chris Lattner81a7a232004-10-16 18:11:37 +00002018 if (isa<UndefValue>(Op1))
2019 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
2020
Chris Lattnerc2076352004-02-16 01:20:27 +00002021 // xor X, X = 0, even if X is nested in a sequence of Xor's.
2022 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
2023 assert(Result == &I && "AssociativeOpt didn't work?");
Chris Lattnere6794492002-08-12 21:17:25 +00002024 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc2076352004-02-16 01:20:27 +00002025 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002026
Chris Lattner97638592003-07-23 21:37:07 +00002027 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002028 // xor X, 0 == X
Chris Lattner97638592003-07-23 21:37:07 +00002029 if (RHS->isNullValue())
Chris Lattnere6794492002-08-12 21:17:25 +00002030 return ReplaceInstUsesWith(I, Op0);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002031
Chris Lattner97638592003-07-23 21:37:07 +00002032 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerb8d6e402002-08-20 18:24:26 +00002033 // xor (setcc A, B), true = not (setcc A, B) = setncc A, B
Chris Lattner97638592003-07-23 21:37:07 +00002034 if (SetCondInst *SCI = dyn_cast<SetCondInst>(Op0I))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002035 if (RHS == ConstantBool::True && SCI->hasOneUse())
Chris Lattnerb8d6e402002-08-20 18:24:26 +00002036 return new SetCondInst(SCI->getInverseCondition(),
2037 SCI->getOperand(0), SCI->getOperand(1));
Chris Lattnere5806662003-11-04 23:50:51 +00002038
Chris Lattner8f2f5982003-11-05 01:06:05 +00002039 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002040 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
2041 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002042 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
2043 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002044 ConstantInt::get(I.getType(), 1));
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002045 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002046 }
Chris Lattner023a4832004-06-18 06:07:51 +00002047
2048 // ~(~X & Y) --> (X | ~Y)
2049 if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
2050 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
2051 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
2052 Instruction *NotY =
Misha Brukmanb1c93172005-04-21 23:48:37 +00002053 BinaryOperator::createNot(Op0I->getOperand(1),
Chris Lattner023a4832004-06-18 06:07:51 +00002054 Op0I->getOperand(1)->getName()+".not");
2055 InsertNewInstBefore(NotY, I);
2056 return BinaryOperator::createOr(Op0NotVal, NotY);
2057 }
2058 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002059
Chris Lattner97638592003-07-23 21:37:07 +00002060 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattnere5806662003-11-04 23:50:51 +00002061 switch (Op0I->getOpcode()) {
2062 case Instruction::Add:
Chris Lattner0f68fa62003-11-04 23:37:10 +00002063 // ~(X-c) --> (-c-1)-X
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002064 if (RHS->isAllOnesValue()) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002065 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
2066 return BinaryOperator::createSub(
2067 ConstantExpr::getSub(NegOp0CI,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002068 ConstantInt::get(I.getType(), 1)),
Chris Lattner0f68fa62003-11-04 23:37:10 +00002069 Op0I->getOperand(0));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002070 }
Chris Lattnere5806662003-11-04 23:50:51 +00002071 break;
2072 case Instruction::And:
Chris Lattner97638592003-07-23 21:37:07 +00002073 // (X & C1) ^ C2 --> (X & C1) | C2 iff (C1&C2) == 0
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002074 if (ConstantExpr::getAnd(RHS, Op0CI)->isNullValue())
2075 return BinaryOperator::createOr(Op0, RHS);
Chris Lattnere5806662003-11-04 23:50:51 +00002076 break;
2077 case Instruction::Or:
Chris Lattner97638592003-07-23 21:37:07 +00002078 // (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002079 if (ConstantExpr::getAnd(RHS, Op0CI) == RHS)
Chris Lattnerc8e7e292004-06-10 02:12:35 +00002080 return BinaryOperator::createAnd(Op0, ConstantExpr::getNot(RHS));
Chris Lattnere5806662003-11-04 23:50:51 +00002081 break;
2082 default: break;
Chris Lattner97638592003-07-23 21:37:07 +00002083 }
Chris Lattnerb8d6e402002-08-20 18:24:26 +00002084 }
Chris Lattner183b3362004-04-09 19:05:30 +00002085
2086 // Try to fold constant and into select arguments.
2087 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00002088 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00002089 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002090 if (isa<PHINode>(Op0))
2091 if (Instruction *NV = FoldOpIntoPhi(I))
2092 return NV;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002093 }
2094
Chris Lattnerbb74e222003-03-10 23:06:50 +00002095 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00002096 if (X == Op1)
2097 return ReplaceInstUsesWith(I,
2098 ConstantIntegral::getAllOnesValue(I.getType()));
2099
Chris Lattnerbb74e222003-03-10 23:06:50 +00002100 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00002101 if (X == Op0)
2102 return ReplaceInstUsesWith(I,
2103 ConstantIntegral::getAllOnesValue(I.getType()));
2104
Chris Lattner1bbb7b62003-03-10 18:24:17 +00002105 if (Instruction *Op1I = dyn_cast<Instruction>(Op1))
Chris Lattnerb36d9082004-02-16 03:54:20 +00002106 if (Op1I->getOpcode() == Instruction::Or) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00002107 if (Op1I->getOperand(0) == Op0) { // B^(B|A) == (A|B)^B
2108 cast<BinaryOperator>(Op1I)->swapOperands();
2109 I.swapOperands();
2110 std::swap(Op0, Op1);
2111 } else if (Op1I->getOperand(1) == Op0) { // B^(A|B) == (A|B)^B
2112 I.swapOperands();
2113 std::swap(Op0, Op1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002114 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00002115 } else if (Op1I->getOpcode() == Instruction::Xor) {
2116 if (Op0 == Op1I->getOperand(0)) // A^(A^B) == B
2117 return ReplaceInstUsesWith(I, Op1I->getOperand(1));
2118 else if (Op0 == Op1I->getOperand(1)) // A^(B^A) == B
2119 return ReplaceInstUsesWith(I, Op1I->getOperand(0));
2120 }
Chris Lattner1bbb7b62003-03-10 18:24:17 +00002121
2122 if (Instruction *Op0I = dyn_cast<Instruction>(Op0))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002123 if (Op0I->getOpcode() == Instruction::Or && Op0I->hasOneUse()) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00002124 if (Op0I->getOperand(0) == Op1) // (B|A)^B == (A|B)^B
2125 cast<BinaryOperator>(Op0I)->swapOperands();
Chris Lattnerdcf240a2003-03-10 21:43:22 +00002126 if (Op0I->getOperand(1) == Op1) { // (A|B)^B == A & ~B
Chris Lattner396dbfe2004-06-09 05:08:07 +00002127 Value *NotB = InsertNewInstBefore(BinaryOperator::createNot(Op1,
2128 Op1->getName()+".not"), I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002129 return BinaryOperator::createAnd(Op0I->getOperand(0), NotB);
Chris Lattner1bbb7b62003-03-10 18:24:17 +00002130 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00002131 } else if (Op0I->getOpcode() == Instruction::Xor) {
2132 if (Op1 == Op0I->getOperand(0)) // (A^B)^A == B
2133 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2134 else if (Op1 == Op0I->getOperand(1)) // (B^A)^A == B
2135 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner1bbb7b62003-03-10 18:24:17 +00002136 }
2137
Chris Lattner7aa2d472004-08-01 19:42:59 +00002138 // (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattnerd4252a72004-07-30 07:50:03 +00002139 Value *A, *B; ConstantInt *C1, *C2;
2140 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
2141 match(Op1, m_And(m_Value(B), m_ConstantInt(C2))) &&
Chris Lattner7aa2d472004-08-01 19:42:59 +00002142 ConstantExpr::getAnd(C1, C2)->isNullValue())
Chris Lattnerd4252a72004-07-30 07:50:03 +00002143 return BinaryOperator::createOr(Op0, Op1);
Chris Lattner7fb29e12003-03-11 00:12:48 +00002144
Chris Lattner3ac7c262003-08-13 20:16:26 +00002145 // (setcc1 A, B) ^ (setcc2 A, B) --> (setcc3 A, B)
2146 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
2147 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
2148 return R;
2149
Chris Lattner113f4f42002-06-25 16:13:24 +00002150 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002151}
2152
Chris Lattner6862fbd2004-09-29 17:40:11 +00002153/// MulWithOverflow - Compute Result = In1*In2, returning true if the result
2154/// overflowed for this type.
2155static bool MulWithOverflow(ConstantInt *&Result, ConstantInt *In1,
2156 ConstantInt *In2) {
2157 Result = cast<ConstantInt>(ConstantExpr::getMul(In1, In2));
2158 return !In2->isNullValue() && ConstantExpr::getDiv(Result, In2) != In1;
2159}
2160
2161static bool isPositive(ConstantInt *C) {
2162 return cast<ConstantSInt>(C)->getValue() >= 0;
2163}
2164
2165/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
2166/// overflowed for this type.
2167static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
2168 ConstantInt *In2) {
2169 Result = cast<ConstantInt>(ConstantExpr::getAdd(In1, In2));
2170
2171 if (In1->getType()->isUnsigned())
2172 return cast<ConstantUInt>(Result)->getValue() <
2173 cast<ConstantUInt>(In1)->getValue();
2174 if (isPositive(In1) != isPositive(In2))
2175 return false;
2176 if (isPositive(In1))
2177 return cast<ConstantSInt>(Result)->getValue() <
2178 cast<ConstantSInt>(In1)->getValue();
2179 return cast<ConstantSInt>(Result)->getValue() >
2180 cast<ConstantSInt>(In1)->getValue();
2181}
2182
Chris Lattner0798af32005-01-13 20:14:25 +00002183/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
2184/// code necessary to compute the offset from the base pointer (without adding
2185/// in the base pointer). Return the result as a signed integer of intptr size.
2186static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
2187 TargetData &TD = IC.getTargetData();
2188 gep_type_iterator GTI = gep_type_begin(GEP);
2189 const Type *UIntPtrTy = TD.getIntPtrType();
2190 const Type *SIntPtrTy = UIntPtrTy->getSignedVersion();
2191 Value *Result = Constant::getNullValue(SIntPtrTy);
2192
2193 // Build a mask for high order bits.
2194 uint64_t PtrSizeMask = ~0ULL;
2195 PtrSizeMask >>= 64-(TD.getPointerSize()*8);
2196
Chris Lattner0798af32005-01-13 20:14:25 +00002197 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
2198 Value *Op = GEP->getOperand(i);
Chris Lattnerd35d2102005-01-13 23:26:48 +00002199 uint64_t Size = TD.getTypeSize(GTI.getIndexedType()) & PtrSizeMask;
Chris Lattner0798af32005-01-13 20:14:25 +00002200 Constant *Scale = ConstantExpr::getCast(ConstantUInt::get(UIntPtrTy, Size),
2201 SIntPtrTy);
2202 if (Constant *OpC = dyn_cast<Constant>(Op)) {
2203 if (!OpC->isNullValue()) {
Chris Lattner4cb9fa32005-01-13 20:40:58 +00002204 OpC = ConstantExpr::getCast(OpC, SIntPtrTy);
Chris Lattner0798af32005-01-13 20:14:25 +00002205 Scale = ConstantExpr::getMul(OpC, Scale);
2206 if (Constant *RC = dyn_cast<Constant>(Result))
2207 Result = ConstantExpr::getAdd(RC, Scale);
2208 else {
2209 // Emit an add instruction.
2210 Result = IC.InsertNewInstBefore(
2211 BinaryOperator::createAdd(Result, Scale,
2212 GEP->getName()+".offs"), I);
2213 }
2214 }
2215 } else {
Chris Lattner7aa41cf2005-01-14 17:17:59 +00002216 // Convert to correct type.
2217 Op = IC.InsertNewInstBefore(new CastInst(Op, SIntPtrTy,
2218 Op->getName()+".c"), I);
2219 if (Size != 1)
Chris Lattner4cb9fa32005-01-13 20:40:58 +00002220 // We'll let instcombine(mul) convert this to a shl if possible.
2221 Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
2222 GEP->getName()+".idx"), I);
Chris Lattner0798af32005-01-13 20:14:25 +00002223
2224 // Emit an add instruction.
Chris Lattner4cb9fa32005-01-13 20:40:58 +00002225 Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
Chris Lattner0798af32005-01-13 20:14:25 +00002226 GEP->getName()+".offs"), I);
2227 }
2228 }
2229 return Result;
2230}
2231
2232/// FoldGEPSetCC - Fold comparisons between a GEP instruction and something
2233/// else. At this point we know that the GEP is on the LHS of the comparison.
2234Instruction *InstCombiner::FoldGEPSetCC(User *GEPLHS, Value *RHS,
2235 Instruction::BinaryOps Cond,
2236 Instruction &I) {
2237 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattner81e84172005-01-13 22:25:21 +00002238
2239 if (CastInst *CI = dyn_cast<CastInst>(RHS))
2240 if (isa<PointerType>(CI->getOperand(0)->getType()))
2241 RHS = CI->getOperand(0);
2242
Chris Lattner0798af32005-01-13 20:14:25 +00002243 Value *PtrBase = GEPLHS->getOperand(0);
2244 if (PtrBase == RHS) {
2245 // As an optimization, we don't actually have to compute the actual value of
2246 // OFFSET if this is a seteq or setne comparison, just return whether each
2247 // index is zero or not.
Chris Lattner81e84172005-01-13 22:25:21 +00002248 if (Cond == Instruction::SetEQ || Cond == Instruction::SetNE) {
2249 Instruction *InVal = 0;
Chris Lattnercd517ff2005-01-28 19:32:01 +00002250 gep_type_iterator GTI = gep_type_begin(GEPLHS);
2251 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i, ++GTI) {
Chris Lattner81e84172005-01-13 22:25:21 +00002252 bool EmitIt = true;
2253 if (Constant *C = dyn_cast<Constant>(GEPLHS->getOperand(i))) {
2254 if (isa<UndefValue>(C)) // undef index -> undef.
2255 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2256 if (C->isNullValue())
2257 EmitIt = false;
Chris Lattnercd517ff2005-01-28 19:32:01 +00002258 else if (TD->getTypeSize(GTI.getIndexedType()) == 0) {
2259 EmitIt = false; // This is indexing into a zero sized array?
Misha Brukmanb1c93172005-04-21 23:48:37 +00002260 } else if (isa<ConstantInt>(C))
Chris Lattner81e84172005-01-13 22:25:21 +00002261 return ReplaceInstUsesWith(I, // No comparison is needed here.
2262 ConstantBool::get(Cond == Instruction::SetNE));
2263 }
2264
2265 if (EmitIt) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00002266 Instruction *Comp =
Chris Lattner81e84172005-01-13 22:25:21 +00002267 new SetCondInst(Cond, GEPLHS->getOperand(i),
2268 Constant::getNullValue(GEPLHS->getOperand(i)->getType()));
2269 if (InVal == 0)
2270 InVal = Comp;
2271 else {
2272 InVal = InsertNewInstBefore(InVal, I);
2273 InsertNewInstBefore(Comp, I);
2274 if (Cond == Instruction::SetNE) // True if any are unequal
2275 InVal = BinaryOperator::createOr(InVal, Comp);
2276 else // True if all are equal
2277 InVal = BinaryOperator::createAnd(InVal, Comp);
2278 }
2279 }
2280 }
2281
2282 if (InVal)
2283 return InVal;
2284 else
2285 ReplaceInstUsesWith(I, // No comparison is needed here, all indexes = 0
2286 ConstantBool::get(Cond == Instruction::SetEQ));
2287 }
Chris Lattner0798af32005-01-13 20:14:25 +00002288
2289 // Only lower this if the setcc is the only user of the GEP or if we expect
2290 // the result to fold to a constant!
2291 if (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) {
2292 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
2293 Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
2294 return new SetCondInst(Cond, Offset,
2295 Constant::getNullValue(Offset->getType()));
2296 }
2297 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
Chris Lattnera21bf8d2005-04-25 20:17:30 +00002298 // If the base pointers are different, but the indices are the same, just
2299 // compare the base pointer.
2300 if (PtrBase != GEPRHS->getOperand(0)) {
2301 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00002302 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattnerbd43b9d2005-04-26 14:40:41 +00002303 GEPRHS->getOperand(0)->getType();
Chris Lattnera21bf8d2005-04-25 20:17:30 +00002304 if (IndicesTheSame)
2305 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
2306 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
2307 IndicesTheSame = false;
2308 break;
2309 }
2310
2311 // If all indices are the same, just compare the base pointers.
2312 if (IndicesTheSame)
2313 return new SetCondInst(Cond, GEPLHS->getOperand(0),
2314 GEPRHS->getOperand(0));
2315
2316 // Otherwise, the base pointers are different and the indices are
2317 // different, bail out.
Chris Lattner0798af32005-01-13 20:14:25 +00002318 return 0;
Chris Lattnera21bf8d2005-04-25 20:17:30 +00002319 }
Chris Lattner0798af32005-01-13 20:14:25 +00002320
Chris Lattner81e84172005-01-13 22:25:21 +00002321 // If one of the GEPs has all zero indices, recurse.
2322 bool AllZeros = true;
2323 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
2324 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
2325 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
2326 AllZeros = false;
2327 break;
2328 }
2329 if (AllZeros)
2330 return FoldGEPSetCC(GEPRHS, GEPLHS->getOperand(0),
2331 SetCondInst::getSwappedCondition(Cond), I);
Chris Lattner4fa89822005-01-14 00:20:05 +00002332
2333 // If the other GEP has all zero indices, recurse.
Chris Lattner81e84172005-01-13 22:25:21 +00002334 AllZeros = true;
2335 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
2336 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
2337 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
2338 AllZeros = false;
2339 break;
2340 }
2341 if (AllZeros)
2342 return FoldGEPSetCC(GEPLHS, GEPRHS->getOperand(0), Cond, I);
2343
Chris Lattner4fa89822005-01-14 00:20:05 +00002344 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
2345 // If the GEPs only differ by one index, compare it.
2346 unsigned NumDifferences = 0; // Keep track of # differences.
2347 unsigned DiffOperand = 0; // The operand that differs.
2348 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
2349 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002350 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
2351 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattnerfc4429e2005-01-21 23:06:49 +00002352 // Irreconcilable differences.
Chris Lattner4fa89822005-01-14 00:20:05 +00002353 NumDifferences = 2;
2354 break;
2355 } else {
2356 if (NumDifferences++) break;
2357 DiffOperand = i;
2358 }
2359 }
2360
2361 if (NumDifferences == 0) // SAME GEP?
2362 return ReplaceInstUsesWith(I, // No comparison is needed here.
2363 ConstantBool::get(Cond == Instruction::SetEQ));
2364 else if (NumDifferences == 1) {
Chris Lattnerfc4429e2005-01-21 23:06:49 +00002365 Value *LHSV = GEPLHS->getOperand(DiffOperand);
2366 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Chris Lattner247aef82005-07-18 23:07:33 +00002367
2368 // Convert the operands to signed values to make sure to perform a
2369 // signed comparison.
2370 const Type *NewTy = LHSV->getType()->getSignedVersion();
2371 if (LHSV->getType() != NewTy)
2372 LHSV = InsertNewInstBefore(new CastInst(LHSV, NewTy,
2373 LHSV->getName()), I);
2374 if (RHSV->getType() != NewTy)
2375 RHSV = InsertNewInstBefore(new CastInst(RHSV, NewTy,
2376 RHSV->getName()), I);
2377 return new SetCondInst(Cond, LHSV, RHSV);
Chris Lattner4fa89822005-01-14 00:20:05 +00002378 }
2379 }
2380
Chris Lattner0798af32005-01-13 20:14:25 +00002381 // Only lower this if the setcc is the only user of the GEP or if we expect
2382 // the result to fold to a constant!
2383 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
2384 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
2385 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
2386 Value *L = EmitGEPOffset(GEPLHS, I, *this);
2387 Value *R = EmitGEPOffset(GEPRHS, I, *this);
2388 return new SetCondInst(Cond, L, R);
2389 }
2390 }
2391 return 0;
2392}
2393
2394
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002395Instruction *InstCombiner::visitSetCondInst(SetCondInst &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00002396 bool Changed = SimplifyCommutative(I);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002397 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2398 const Type *Ty = Op0->getType();
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002399
2400 // setcc X, X
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002401 if (Op0 == Op1)
2402 return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
Chris Lattner1fc23f32002-05-09 20:11:54 +00002403
Chris Lattner81a7a232004-10-16 18:11:37 +00002404 if (isa<UndefValue>(Op1)) // X setcc undef -> undef
2405 return ReplaceInstUsesWith(I, UndefValue::get(Type::BoolTy));
2406
Chris Lattner15ff1e12004-11-14 07:33:16 +00002407 // setcc <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
2408 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanb1c93172005-04-21 23:48:37 +00002409 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
2410 isa<ConstantPointerNull>(Op0)) &&
2411 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner15ff1e12004-11-14 07:33:16 +00002412 isa<ConstantPointerNull>(Op1)))
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002413 return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
2414
2415 // setcc's with boolean values can always be turned into bitwise operations
2416 if (Ty == Type::BoolTy) {
Chris Lattner4456da62004-08-11 00:50:51 +00002417 switch (I.getOpcode()) {
2418 default: assert(0 && "Invalid setcc instruction!");
2419 case Instruction::SetEQ: { // seteq bool %A, %B -> ~(A^B)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002420 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002421 InsertNewInstBefore(Xor, I);
Chris Lattner16930792003-11-03 04:25:02 +00002422 return BinaryOperator::createNot(Xor);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002423 }
Chris Lattner4456da62004-08-11 00:50:51 +00002424 case Instruction::SetNE:
2425 return BinaryOperator::createXor(Op0, Op1);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002426
Chris Lattner4456da62004-08-11 00:50:51 +00002427 case Instruction::SetGT:
2428 std::swap(Op0, Op1); // Change setgt -> setlt
2429 // FALL THROUGH
2430 case Instruction::SetLT: { // setlt bool A, B -> ~X & Y
2431 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
2432 InsertNewInstBefore(Not, I);
2433 return BinaryOperator::createAnd(Not, Op1);
2434 }
2435 case Instruction::SetGE:
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002436 std::swap(Op0, Op1); // Change setge -> setle
Chris Lattner4456da62004-08-11 00:50:51 +00002437 // FALL THROUGH
2438 case Instruction::SetLE: { // setle bool %A, %B -> ~A | B
2439 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
2440 InsertNewInstBefore(Not, I);
2441 return BinaryOperator::createOr(Not, Op1);
2442 }
2443 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002444 }
2445
Chris Lattner2dd01742004-06-09 04:24:29 +00002446 // See if we are doing a comparison between a constant and an instruction that
2447 // can be folded into the comparison.
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002448 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner6862fbd2004-09-29 17:40:11 +00002449 // Check to see if we are comparing against the minimum or maximum value...
2450 if (CI->isMinValue()) {
2451 if (I.getOpcode() == Instruction::SetLT) // A < MIN -> FALSE
2452 return ReplaceInstUsesWith(I, ConstantBool::False);
2453 if (I.getOpcode() == Instruction::SetGE) // A >= MIN -> TRUE
2454 return ReplaceInstUsesWith(I, ConstantBool::True);
2455 if (I.getOpcode() == Instruction::SetLE) // A <= MIN -> A == MIN
2456 return BinaryOperator::createSetEQ(Op0, Op1);
2457 if (I.getOpcode() == Instruction::SetGT) // A > MIN -> A != MIN
2458 return BinaryOperator::createSetNE(Op0, Op1);
2459
2460 } else if (CI->isMaxValue()) {
2461 if (I.getOpcode() == Instruction::SetGT) // A > MAX -> FALSE
2462 return ReplaceInstUsesWith(I, ConstantBool::False);
2463 if (I.getOpcode() == Instruction::SetLE) // A <= MAX -> TRUE
2464 return ReplaceInstUsesWith(I, ConstantBool::True);
2465 if (I.getOpcode() == Instruction::SetGE) // A >= MAX -> A == MAX
2466 return BinaryOperator::createSetEQ(Op0, Op1);
2467 if (I.getOpcode() == Instruction::SetLT) // A < MAX -> A != MAX
2468 return BinaryOperator::createSetNE(Op0, Op1);
2469
2470 // Comparing against a value really close to min or max?
2471 } else if (isMinValuePlusOne(CI)) {
2472 if (I.getOpcode() == Instruction::SetLT) // A < MIN+1 -> A == MIN
2473 return BinaryOperator::createSetEQ(Op0, SubOne(CI));
2474 if (I.getOpcode() == Instruction::SetGE) // A >= MIN-1 -> A != MIN
2475 return BinaryOperator::createSetNE(Op0, SubOne(CI));
2476
2477 } else if (isMaxValueMinusOne(CI)) {
2478 if (I.getOpcode() == Instruction::SetGT) // A > MAX-1 -> A == MAX
2479 return BinaryOperator::createSetEQ(Op0, AddOne(CI));
2480 if (I.getOpcode() == Instruction::SetLE) // A <= MAX-1 -> A != MAX
2481 return BinaryOperator::createSetNE(Op0, AddOne(CI));
2482 }
2483
2484 // If we still have a setle or setge instruction, turn it into the
2485 // appropriate setlt or setgt instruction. Since the border cases have
2486 // already been handled above, this requires little checking.
2487 //
2488 if (I.getOpcode() == Instruction::SetLE)
2489 return BinaryOperator::createSetLT(Op0, AddOne(CI));
2490 if (I.getOpcode() == Instruction::SetGE)
2491 return BinaryOperator::createSetGT(Op0, SubOne(CI));
2492
Chris Lattnere1e10e12004-05-25 06:32:08 +00002493 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002494 switch (LHSI->getOpcode()) {
2495 case Instruction::And:
2496 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
2497 LHSI->getOperand(0)->hasOneUse()) {
2498 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
2499 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
2500 // happens a LOT in code produced by the C front-end, for bitfield
2501 // access.
2502 ShiftInst *Shift = dyn_cast<ShiftInst>(LHSI->getOperand(0));
2503 ConstantUInt *ShAmt;
2504 ShAmt = Shift ? dyn_cast<ConstantUInt>(Shift->getOperand(1)) : 0;
2505 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
2506 const Type *Ty = LHSI->getType();
Misha Brukmanb1c93172005-04-21 23:48:37 +00002507
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002508 // We can fold this as long as we can't shift unknown bits
2509 // into the mask. This can only happen with signed shift
2510 // rights, as they sign-extend.
2511 if (ShAmt) {
2512 bool CanFold = Shift->getOpcode() != Instruction::Shr ||
Chris Lattner6afc02f2004-09-28 17:54:07 +00002513 Shift->getType()->isUnsigned();
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002514 if (!CanFold) {
2515 // To test for the bad case of the signed shr, see if any
2516 // of the bits shifted in could be tested after the mask.
Chris Lattnerc53cb9d2005-06-17 01:29:28 +00002517 int ShAmtVal = Ty->getPrimitiveSizeInBits()-ShAmt->getValue();
2518 if (ShAmtVal < 0) ShAmtVal = 0; // Out of range shift.
2519
2520 Constant *OShAmt = ConstantUInt::get(Type::UByteTy, ShAmtVal);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002521 Constant *ShVal =
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002522 ConstantExpr::getShl(ConstantInt::getAllOnesValue(Ty), OShAmt);
2523 if (ConstantExpr::getAnd(ShVal, AndCST)->isNullValue())
2524 CanFold = true;
2525 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002526
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002527 if (CanFold) {
Chris Lattner6afc02f2004-09-28 17:54:07 +00002528 Constant *NewCst;
2529 if (Shift->getOpcode() == Instruction::Shl)
2530 NewCst = ConstantExpr::getUShr(CI, ShAmt);
2531 else
2532 NewCst = ConstantExpr::getShl(CI, ShAmt);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002533
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002534 // Check to see if we are shifting out any of the bits being
2535 // compared.
2536 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != CI){
2537 // If we shifted bits out, the fold is not going to work out.
2538 // As a special case, check to see if this means that the
2539 // result is always true or false now.
2540 if (I.getOpcode() == Instruction::SetEQ)
2541 return ReplaceInstUsesWith(I, ConstantBool::False);
2542 if (I.getOpcode() == Instruction::SetNE)
2543 return ReplaceInstUsesWith(I, ConstantBool::True);
2544 } else {
2545 I.setOperand(1, NewCst);
Chris Lattner6afc02f2004-09-28 17:54:07 +00002546 Constant *NewAndCST;
2547 if (Shift->getOpcode() == Instruction::Shl)
2548 NewAndCST = ConstantExpr::getUShr(AndCST, ShAmt);
2549 else
2550 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
2551 LHSI->setOperand(1, NewAndCST);
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002552 LHSI->setOperand(0, Shift->getOperand(0));
2553 WorkList.push_back(Shift); // Shift is dead.
2554 AddUsesToWorkList(I);
2555 return &I;
Chris Lattner1638de42004-07-21 19:50:44 +00002556 }
2557 }
Chris Lattner35167c32004-06-09 07:59:58 +00002558 }
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002559 }
2560 break;
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002561
Chris Lattner272d5ca2004-09-28 18:22:15 +00002562 case Instruction::Shl: // (setcc (shl X, ShAmt), CI)
2563 if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
2564 switch (I.getOpcode()) {
2565 default: break;
2566 case Instruction::SetEQ:
2567 case Instruction::SetNE: {
Chris Lattner19b57f52005-06-15 20:53:31 +00002568 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
2569
2570 // Check that the shift amount is in range. If not, don't perform
2571 // undefined shifts. When the shift is visited it will be
2572 // simplified.
2573 if (ShAmt->getValue() >= TypeBits)
2574 break;
2575
Chris Lattner272d5ca2004-09-28 18:22:15 +00002576 // If we are comparing against bits always shifted out, the
2577 // comparison cannot succeed.
Misha Brukmanb1c93172005-04-21 23:48:37 +00002578 Constant *Comp =
Chris Lattner272d5ca2004-09-28 18:22:15 +00002579 ConstantExpr::getShl(ConstantExpr::getShr(CI, ShAmt), ShAmt);
2580 if (Comp != CI) {// Comparing against a bit that we know is zero.
2581 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
2582 Constant *Cst = ConstantBool::get(IsSetNE);
2583 return ReplaceInstUsesWith(I, Cst);
2584 }
2585
2586 if (LHSI->hasOneUse()) {
2587 // Otherwise strength reduce the shift into an and.
Chris Lattnerfdfe3e492005-01-08 19:42:22 +00002588 unsigned ShAmtVal = (unsigned)ShAmt->getValue();
Chris Lattner272d5ca2004-09-28 18:22:15 +00002589 uint64_t Val = (1ULL << (TypeBits-ShAmtVal))-1;
2590
2591 Constant *Mask;
2592 if (CI->getType()->isUnsigned()) {
2593 Mask = ConstantUInt::get(CI->getType(), Val);
2594 } else if (ShAmtVal != 0) {
2595 Mask = ConstantSInt::get(CI->getType(), Val);
2596 } else {
2597 Mask = ConstantInt::getAllOnesValue(CI->getType());
2598 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002599
Chris Lattner272d5ca2004-09-28 18:22:15 +00002600 Instruction *AndI =
2601 BinaryOperator::createAnd(LHSI->getOperand(0),
2602 Mask, LHSI->getName()+".mask");
2603 Value *And = InsertNewInstBefore(AndI, I);
2604 return new SetCondInst(I.getOpcode(), And,
2605 ConstantExpr::getUShr(CI, ShAmt));
2606 }
2607 }
2608 }
2609 }
2610 break;
2611
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002612 case Instruction::Shr: // (setcc (shr X, ShAmt), CI)
Chris Lattner1023b872004-09-27 16:18:50 +00002613 if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
Chris Lattner1023b872004-09-27 16:18:50 +00002614 switch (I.getOpcode()) {
2615 default: break;
2616 case Instruction::SetEQ:
2617 case Instruction::SetNE: {
Chris Lattner19b57f52005-06-15 20:53:31 +00002618
2619 // Check that the shift amount is in range. If not, don't perform
2620 // undefined shifts. When the shift is visited it will be
2621 // simplified.
Chris Lattner104002b2005-06-16 01:52:07 +00002622 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
Chris Lattner19b57f52005-06-15 20:53:31 +00002623 if (ShAmt->getValue() >= TypeBits)
2624 break;
2625
Chris Lattner1023b872004-09-27 16:18:50 +00002626 // If we are comparing against bits always shifted out, the
2627 // comparison cannot succeed.
Misha Brukmanb1c93172005-04-21 23:48:37 +00002628 Constant *Comp =
Chris Lattner1023b872004-09-27 16:18:50 +00002629 ConstantExpr::getShr(ConstantExpr::getShl(CI, ShAmt), ShAmt);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002630
Chris Lattner1023b872004-09-27 16:18:50 +00002631 if (Comp != CI) {// Comparing against a bit that we know is zero.
2632 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
2633 Constant *Cst = ConstantBool::get(IsSetNE);
2634 return ReplaceInstUsesWith(I, Cst);
2635 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002636
Chris Lattner1023b872004-09-27 16:18:50 +00002637 if (LHSI->hasOneUse() || CI->isNullValue()) {
Chris Lattnerfdfe3e492005-01-08 19:42:22 +00002638 unsigned ShAmtVal = (unsigned)ShAmt->getValue();
Chris Lattner272d5ca2004-09-28 18:22:15 +00002639
Chris Lattner1023b872004-09-27 16:18:50 +00002640 // Otherwise strength reduce the shift into an and.
2641 uint64_t Val = ~0ULL; // All ones.
2642 Val <<= ShAmtVal; // Shift over to the right spot.
2643
2644 Constant *Mask;
2645 if (CI->getType()->isUnsigned()) {
Chris Lattner2f1457f2005-04-24 17:46:05 +00002646 Val &= ~0ULL >> (64-TypeBits);
Chris Lattner1023b872004-09-27 16:18:50 +00002647 Mask = ConstantUInt::get(CI->getType(), Val);
2648 } else {
2649 Mask = ConstantSInt::get(CI->getType(), Val);
2650 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002651
Chris Lattner1023b872004-09-27 16:18:50 +00002652 Instruction *AndI =
2653 BinaryOperator::createAnd(LHSI->getOperand(0),
2654 Mask, LHSI->getName()+".mask");
2655 Value *And = InsertNewInstBefore(AndI, I);
2656 return new SetCondInst(I.getOpcode(), And,
2657 ConstantExpr::getShl(CI, ShAmt));
2658 }
2659 break;
2660 }
2661 }
2662 }
2663 break;
Chris Lattner7e794272004-09-24 15:21:34 +00002664
Chris Lattner6862fbd2004-09-29 17:40:11 +00002665 case Instruction::Div:
2666 // Fold: (div X, C1) op C2 -> range check
2667 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
2668 // Fold this div into the comparison, producing a range check.
2669 // Determine, based on the divide type, what the range is being
2670 // checked. If there is an overflow on the low or high side, remember
2671 // it, otherwise compute the range [low, hi) bounding the new value.
2672 bool LoOverflow = false, HiOverflow = 0;
2673 ConstantInt *LoBound = 0, *HiBound = 0;
2674
2675 ConstantInt *Prod;
2676 bool ProdOV = MulWithOverflow(Prod, CI, DivRHS);
2677
Chris Lattnera92af962004-10-11 19:40:04 +00002678 Instruction::BinaryOps Opcode = I.getOpcode();
2679
Chris Lattner6862fbd2004-09-29 17:40:11 +00002680 if (DivRHS->isNullValue()) { // Don't hack on divide by zeros.
2681 } else if (LHSI->getType()->isUnsigned()) { // udiv
2682 LoBound = Prod;
2683 LoOverflow = ProdOV;
2684 HiOverflow = ProdOV || AddWithOverflow(HiBound, LoBound, DivRHS);
2685 } else if (isPositive(DivRHS)) { // Divisor is > 0.
2686 if (CI->isNullValue()) { // (X / pos) op 0
2687 // Can't overflow.
2688 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
2689 HiBound = DivRHS;
2690 } else if (isPositive(CI)) { // (X / pos) op pos
2691 LoBound = Prod;
2692 LoOverflow = ProdOV;
2693 HiOverflow = ProdOV || AddWithOverflow(HiBound, Prod, DivRHS);
2694 } else { // (X / pos) op neg
2695 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
2696 LoOverflow = AddWithOverflow(LoBound, Prod,
2697 cast<ConstantInt>(DivRHSH));
2698 HiBound = Prod;
2699 HiOverflow = ProdOV;
2700 }
2701 } else { // Divisor is < 0.
2702 if (CI->isNullValue()) { // (X / neg) op 0
2703 LoBound = AddOne(DivRHS);
2704 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner73bcba52005-06-17 02:05:55 +00002705 if (HiBound == DivRHS)
2706 LoBound = 0; // - INTMIN = INTMIN
Chris Lattner6862fbd2004-09-29 17:40:11 +00002707 } else if (isPositive(CI)) { // (X / neg) op pos
2708 HiOverflow = LoOverflow = ProdOV;
2709 if (!LoOverflow)
2710 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS));
2711 HiBound = AddOne(Prod);
2712 } else { // (X / neg) op neg
2713 LoBound = Prod;
2714 LoOverflow = HiOverflow = ProdOV;
2715 HiBound = cast<ConstantInt>(ConstantExpr::getSub(Prod, DivRHS));
2716 }
Chris Lattner0b41e862004-10-08 19:15:44 +00002717
Chris Lattnera92af962004-10-11 19:40:04 +00002718 // Dividing by a negate swaps the condition.
2719 Opcode = SetCondInst::getSwappedCondition(Opcode);
Chris Lattner6862fbd2004-09-29 17:40:11 +00002720 }
2721
2722 if (LoBound) {
2723 Value *X = LHSI->getOperand(0);
Chris Lattnera92af962004-10-11 19:40:04 +00002724 switch (Opcode) {
Chris Lattner6862fbd2004-09-29 17:40:11 +00002725 default: assert(0 && "Unhandled setcc opcode!");
2726 case Instruction::SetEQ:
2727 if (LoOverflow && HiOverflow)
2728 return ReplaceInstUsesWith(I, ConstantBool::False);
2729 else if (HiOverflow)
2730 return new SetCondInst(Instruction::SetGE, X, LoBound);
2731 else if (LoOverflow)
2732 return new SetCondInst(Instruction::SetLT, X, HiBound);
2733 else
2734 return InsertRangeTest(X, LoBound, HiBound, true, I);
2735 case Instruction::SetNE:
2736 if (LoOverflow && HiOverflow)
2737 return ReplaceInstUsesWith(I, ConstantBool::True);
2738 else if (HiOverflow)
2739 return new SetCondInst(Instruction::SetLT, X, LoBound);
2740 else if (LoOverflow)
2741 return new SetCondInst(Instruction::SetGE, X, HiBound);
2742 else
2743 return InsertRangeTest(X, LoBound, HiBound, false, I);
2744 case Instruction::SetLT:
2745 if (LoOverflow)
2746 return ReplaceInstUsesWith(I, ConstantBool::False);
2747 return new SetCondInst(Instruction::SetLT, X, LoBound);
2748 case Instruction::SetGT:
2749 if (HiOverflow)
2750 return ReplaceInstUsesWith(I, ConstantBool::False);
2751 return new SetCondInst(Instruction::SetGE, X, HiBound);
2752 }
2753 }
2754 }
2755 break;
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002756 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002757
Chris Lattnerd492a0b2003-07-23 17:02:11 +00002758 // Simplify seteq and setne instructions...
2759 if (I.getOpcode() == Instruction::SetEQ ||
2760 I.getOpcode() == Instruction::SetNE) {
2761 bool isSetNE = I.getOpcode() == Instruction::SetNE;
2762
Chris Lattnercfbce7c2003-07-23 17:26:36 +00002763 // If the first operand is (and|or|xor) with a constant, and the second
Chris Lattnerd492a0b2003-07-23 17:02:11 +00002764 // operand is a constant, simplify a bit.
Chris Lattnerc992add2003-08-13 05:33:12 +00002765 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
2766 switch (BO->getOpcode()) {
Chris Lattner23b47b62004-07-06 07:38:18 +00002767 case Instruction::Rem:
2768 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
2769 if (CI->isNullValue() && isa<ConstantSInt>(BO->getOperand(1)) &&
2770 BO->hasOneUse() &&
Chris Lattner22d00a82005-08-02 19:16:58 +00002771 cast<ConstantSInt>(BO->getOperand(1))->getValue() > 1) {
2772 int64_t V = cast<ConstantSInt>(BO->getOperand(1))->getValue();
2773 if (isPowerOf2_64(V)) {
2774 unsigned L2 = Log2_64(V);
Chris Lattner23b47b62004-07-06 07:38:18 +00002775 const Type *UTy = BO->getType()->getUnsignedVersion();
2776 Value *NewX = InsertNewInstBefore(new CastInst(BO->getOperand(0),
2777 UTy, "tmp"), I);
2778 Constant *RHSCst = ConstantUInt::get(UTy, 1ULL << L2);
2779 Value *NewRem =InsertNewInstBefore(BinaryOperator::createRem(NewX,
2780 RHSCst, BO->getName()), I);
2781 return BinaryOperator::create(I.getOpcode(), NewRem,
2782 Constant::getNullValue(UTy));
2783 }
Chris Lattner22d00a82005-08-02 19:16:58 +00002784 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002785 break;
Chris Lattner23b47b62004-07-06 07:38:18 +00002786
Chris Lattnerc992add2003-08-13 05:33:12 +00002787 case Instruction::Add:
Chris Lattner6e079362004-06-27 22:51:36 +00002788 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
2789 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerb121ae12004-09-21 21:35:23 +00002790 if (BO->hasOneUse())
2791 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
2792 ConstantExpr::getSub(CI, BOp1C));
Chris Lattner6e079362004-06-27 22:51:36 +00002793 } else if (CI->isNullValue()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00002794 // Replace ((add A, B) != 0) with (A != -B) if A or B is
2795 // efficiently invertible, or if the add has just this one use.
2796 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002797
Chris Lattnerc992add2003-08-13 05:33:12 +00002798 if (Value *NegVal = dyn_castNegVal(BOp1))
2799 return new SetCondInst(I.getOpcode(), BOp0, NegVal);
2800 else if (Value *NegVal = dyn_castNegVal(BOp0))
2801 return new SetCondInst(I.getOpcode(), NegVal, BOp1);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002802 else if (BO->hasOneUse()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00002803 Instruction *Neg = BinaryOperator::createNeg(BOp1, BO->getName());
2804 BO->setName("");
2805 InsertNewInstBefore(Neg, I);
2806 return new SetCondInst(I.getOpcode(), BOp0, Neg);
2807 }
2808 }
2809 break;
2810 case Instruction::Xor:
2811 // For the xor case, we can xor two constants together, eliminating
2812 // the explicit xor.
2813 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
2814 return BinaryOperator::create(I.getOpcode(), BO->getOperand(0),
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002815 ConstantExpr::getXor(CI, BOC));
Chris Lattnerc992add2003-08-13 05:33:12 +00002816
2817 // FALLTHROUGH
2818 case Instruction::Sub:
2819 // Replace (([sub|xor] A, B) != 0) with (A != B)
2820 if (CI->isNullValue())
2821 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
2822 BO->getOperand(1));
2823 break;
2824
2825 case Instruction::Or:
2826 // If bits are being or'd in that are not present in the constant we
2827 // are comparing against, then the comparison could never succeed!
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002828 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Chris Lattnerc8e7e292004-06-10 02:12:35 +00002829 Constant *NotCI = ConstantExpr::getNot(CI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002830 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Chris Lattnerd492a0b2003-07-23 17:02:11 +00002831 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002832 }
Chris Lattnerc992add2003-08-13 05:33:12 +00002833 break;
2834
2835 case Instruction::And:
2836 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerd492a0b2003-07-23 17:02:11 +00002837 // If bits are being compared against that are and'd out, then the
2838 // comparison can never succeed!
Chris Lattnerc8e7e292004-06-10 02:12:35 +00002839 if (!ConstantExpr::getAnd(CI,
2840 ConstantExpr::getNot(BOC))->isNullValue())
Chris Lattnerd492a0b2003-07-23 17:02:11 +00002841 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattnerc992add2003-08-13 05:33:12 +00002842
Chris Lattner35167c32004-06-09 07:59:58 +00002843 // If we have ((X & C) == C), turn it into ((X & C) != 0).
Chris Lattneree59d4b2004-06-10 02:33:20 +00002844 if (CI == BOC && isOneBitSet(CI))
Chris Lattner35167c32004-06-09 07:59:58 +00002845 return new SetCondInst(isSetNE ? Instruction::SetEQ :
2846 Instruction::SetNE, Op0,
2847 Constant::getNullValue(CI->getType()));
Chris Lattner35167c32004-06-09 07:59:58 +00002848
Chris Lattnerc992add2003-08-13 05:33:12 +00002849 // Replace (and X, (1 << size(X)-1) != 0) with x < 0, converting X
2850 // to be a signed value as appropriate.
2851 if (isSignBit(BOC)) {
2852 Value *X = BO->getOperand(0);
2853 // If 'X' is not signed, insert a cast now...
2854 if (!BOC->getType()->isSigned()) {
Chris Lattner97bfcea2004-06-17 18:16:02 +00002855 const Type *DestTy = BOC->getType()->getSignedVersion();
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002856 X = InsertCastBefore(X, DestTy, I);
Chris Lattnerc992add2003-08-13 05:33:12 +00002857 }
2858 return new SetCondInst(isSetNE ? Instruction::SetLT :
2859 Instruction::SetGE, X,
2860 Constant::getNullValue(X->getType()));
2861 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002862
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002863 // ((X & ~7) == 0) --> X < 8
Chris Lattner8fc5af42004-09-23 21:46:38 +00002864 if (CI->isNullValue() && isHighOnes(BOC)) {
2865 Value *X = BO->getOperand(0);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002866 Constant *NegX = ConstantExpr::getNeg(BOC);
Chris Lattner8fc5af42004-09-23 21:46:38 +00002867
2868 // If 'X' is signed, insert a cast now.
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002869 if (NegX->getType()->isSigned()) {
2870 const Type *DestTy = NegX->getType()->getUnsignedVersion();
2871 X = InsertCastBefore(X, DestTy, I);
2872 NegX = ConstantExpr::getCast(NegX, DestTy);
Chris Lattner8fc5af42004-09-23 21:46:38 +00002873 }
2874
2875 return new SetCondInst(isSetNE ? Instruction::SetGE :
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002876 Instruction::SetLT, X, NegX);
Chris Lattner8fc5af42004-09-23 21:46:38 +00002877 }
2878
Chris Lattnerd492a0b2003-07-23 17:02:11 +00002879 }
Chris Lattnerc992add2003-08-13 05:33:12 +00002880 default: break;
2881 }
2882 }
Chris Lattner2b55ea32004-02-23 07:16:20 +00002883 } else { // Not a SetEQ/SetNE
Misha Brukmanb1c93172005-04-21 23:48:37 +00002884 // If the LHS is a cast from an integral value of the same size,
Chris Lattner2b55ea32004-02-23 07:16:20 +00002885 if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
2886 Value *CastOp = Cast->getOperand(0);
2887 const Type *SrcTy = CastOp->getType();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002888 unsigned SrcTySize = SrcTy->getPrimitiveSizeInBits();
Chris Lattner2b55ea32004-02-23 07:16:20 +00002889 if (SrcTy != Cast->getType() && SrcTy->isInteger() &&
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002890 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00002891 assert((SrcTy->isSigned() ^ Cast->getType()->isSigned()) &&
Chris Lattner2b55ea32004-02-23 07:16:20 +00002892 "Source and destination signednesses should differ!");
2893 if (Cast->getType()->isSigned()) {
2894 // If this is a signed comparison, check for comparisons in the
2895 // vicinity of zero.
2896 if (I.getOpcode() == Instruction::SetLT && CI->isNullValue())
2897 // X < 0 => x > 127
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002898 return BinaryOperator::createSetGT(CastOp,
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002899 ConstantUInt::get(SrcTy, (1ULL << (SrcTySize-1))-1));
Chris Lattner2b55ea32004-02-23 07:16:20 +00002900 else if (I.getOpcode() == Instruction::SetGT &&
2901 cast<ConstantSInt>(CI)->getValue() == -1)
2902 // X > -1 => x < 128
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002903 return BinaryOperator::createSetLT(CastOp,
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002904 ConstantUInt::get(SrcTy, 1ULL << (SrcTySize-1)));
Chris Lattner2b55ea32004-02-23 07:16:20 +00002905 } else {
2906 ConstantUInt *CUI = cast<ConstantUInt>(CI);
2907 if (I.getOpcode() == Instruction::SetLT &&
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002908 CUI->getValue() == 1ULL << (SrcTySize-1))
Chris Lattner2b55ea32004-02-23 07:16:20 +00002909 // X < 128 => X > -1
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002910 return BinaryOperator::createSetGT(CastOp,
2911 ConstantSInt::get(SrcTy, -1));
Chris Lattner2b55ea32004-02-23 07:16:20 +00002912 else if (I.getOpcode() == Instruction::SetGT &&
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002913 CUI->getValue() == (1ULL << (SrcTySize-1))-1)
Chris Lattner2b55ea32004-02-23 07:16:20 +00002914 // X > 127 => X < 0
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002915 return BinaryOperator::createSetLT(CastOp,
2916 Constant::getNullValue(SrcTy));
Chris Lattner2b55ea32004-02-23 07:16:20 +00002917 }
2918 }
2919 }
Chris Lattnere967b342003-06-04 05:10:11 +00002920 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002921 }
2922
Chris Lattner77c32c32005-04-23 15:31:55 +00002923 // Handle setcc with constant RHS's that can be integer, FP or pointer.
2924 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
2925 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
2926 switch (LHSI->getOpcode()) {
Chris Lattnera816eee2005-05-01 04:42:15 +00002927 case Instruction::GetElementPtr:
2928 if (RHSC->isNullValue()) {
2929 // Transform setcc GEP P, int 0, int 0, int 0, null -> setcc P, null
2930 bool isAllZeros = true;
2931 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
2932 if (!isa<Constant>(LHSI->getOperand(i)) ||
2933 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
2934 isAllZeros = false;
2935 break;
2936 }
2937 if (isAllZeros)
2938 return new SetCondInst(I.getOpcode(), LHSI->getOperand(0),
2939 Constant::getNullValue(LHSI->getOperand(0)->getType()));
2940 }
2941 break;
2942
Chris Lattner77c32c32005-04-23 15:31:55 +00002943 case Instruction::PHI:
2944 if (Instruction *NV = FoldOpIntoPhi(I))
2945 return NV;
2946 break;
2947 case Instruction::Select:
2948 // If either operand of the select is a constant, we can fold the
2949 // comparison into the select arms, which will cause one to be
2950 // constant folded and the select turned into a bitwise or.
2951 Value *Op1 = 0, *Op2 = 0;
2952 if (LHSI->hasOneUse()) {
2953 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
2954 // Fold the known value into the constant operand.
2955 Op1 = ConstantExpr::get(I.getOpcode(), C, RHSC);
2956 // Insert a new SetCC of the other select operand.
2957 Op2 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
2958 LHSI->getOperand(2), RHSC,
2959 I.getName()), I);
2960 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
2961 // Fold the known value into the constant operand.
2962 Op2 = ConstantExpr::get(I.getOpcode(), C, RHSC);
2963 // Insert a new SetCC of the other select operand.
2964 Op1 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
2965 LHSI->getOperand(1), RHSC,
2966 I.getName()), I);
2967 }
2968 }
Jeff Cohen82639852005-04-23 21:38:35 +00002969
Chris Lattner77c32c32005-04-23 15:31:55 +00002970 if (Op1)
2971 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
2972 break;
2973 }
2974 }
2975
Chris Lattner0798af32005-01-13 20:14:25 +00002976 // If we can optimize a 'setcc GEP, P' or 'setcc P, GEP', do so now.
2977 if (User *GEP = dyn_castGetElementPtr(Op0))
2978 if (Instruction *NI = FoldGEPSetCC(GEP, Op1, I.getOpcode(), I))
2979 return NI;
2980 if (User *GEP = dyn_castGetElementPtr(Op1))
2981 if (Instruction *NI = FoldGEPSetCC(GEP, Op0,
2982 SetCondInst::getSwappedCondition(I.getOpcode()), I))
2983 return NI;
2984
Chris Lattner16930792003-11-03 04:25:02 +00002985 // Test to see if the operands of the setcc are casted versions of other
2986 // values. If the cast can be stripped off both arguments, we do so now.
Chris Lattner6444c372003-11-03 05:17:03 +00002987 if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
2988 Value *CastOp0 = CI->getOperand(0);
2989 if (CastOp0->getType()->isLosslesslyConvertibleTo(CI->getType()) &&
Chris Lattner7d2a5392004-03-13 23:54:27 +00002990 (isa<Constant>(Op1) || isa<CastInst>(Op1)) &&
Chris Lattner16930792003-11-03 04:25:02 +00002991 (I.getOpcode() == Instruction::SetEQ ||
2992 I.getOpcode() == Instruction::SetNE)) {
2993 // We keep moving the cast from the left operand over to the right
2994 // operand, where it can often be eliminated completely.
Chris Lattner6444c372003-11-03 05:17:03 +00002995 Op0 = CastOp0;
Misha Brukmanb1c93172005-04-21 23:48:37 +00002996
Chris Lattner16930792003-11-03 04:25:02 +00002997 // If operand #1 is a cast instruction, see if we can eliminate it as
2998 // well.
Chris Lattner6444c372003-11-03 05:17:03 +00002999 if (CastInst *CI2 = dyn_cast<CastInst>(Op1))
3000 if (CI2->getOperand(0)->getType()->isLosslesslyConvertibleTo(
Chris Lattner16930792003-11-03 04:25:02 +00003001 Op0->getType()))
Chris Lattner6444c372003-11-03 05:17:03 +00003002 Op1 = CI2->getOperand(0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003003
Chris Lattner16930792003-11-03 04:25:02 +00003004 // If Op1 is a constant, we can fold the cast into the constant.
3005 if (Op1->getType() != Op0->getType())
3006 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
3007 Op1 = ConstantExpr::getCast(Op1C, Op0->getType());
3008 } else {
3009 // Otherwise, cast the RHS right before the setcc
3010 Op1 = new CastInst(Op1, Op0->getType(), Op1->getName());
3011 InsertNewInstBefore(cast<Instruction>(Op1), I);
3012 }
3013 return BinaryOperator::create(I.getOpcode(), Op0, Op1);
3014 }
3015
Chris Lattner6444c372003-11-03 05:17:03 +00003016 // Handle the special case of: setcc (cast bool to X), <cst>
3017 // This comes up when you have code like
3018 // int X = A < B;
3019 // if (X) ...
3020 // For generality, we handle any zero-extension of any operand comparison
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003021 // with a constant or another cast from the same type.
3022 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
3023 if (Instruction *R = visitSetCondInstWithCastAndCast(I))
3024 return R;
Chris Lattner6444c372003-11-03 05:17:03 +00003025 }
Chris Lattner113f4f42002-06-25 16:13:24 +00003026 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003027}
3028
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003029// visitSetCondInstWithCastAndCast - Handle setcond (cast x to y), (cast/cst).
3030// We only handle extending casts so far.
3031//
3032Instruction *InstCombiner::visitSetCondInstWithCastAndCast(SetCondInst &SCI) {
3033 Value *LHSCIOp = cast<CastInst>(SCI.getOperand(0))->getOperand(0);
3034 const Type *SrcTy = LHSCIOp->getType();
3035 const Type *DestTy = SCI.getOperand(0)->getType();
3036 Value *RHSCIOp;
3037
3038 if (!DestTy->isIntegral() || !SrcTy->isIntegral())
Chris Lattner03f06f12005-01-17 03:20:02 +00003039 return 0;
3040
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003041 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
3042 unsigned DestBits = DestTy->getPrimitiveSizeInBits();
3043 if (SrcBits >= DestBits) return 0; // Only handle extending cast.
3044
3045 // Is this a sign or zero extension?
3046 bool isSignSrc = SrcTy->isSigned();
3047 bool isSignDest = DestTy->isSigned();
3048
3049 if (CastInst *CI = dyn_cast<CastInst>(SCI.getOperand(1))) {
3050 // Not an extension from the same type?
3051 RHSCIOp = CI->getOperand(0);
3052 if (RHSCIOp->getType() != LHSCIOp->getType()) return 0;
3053 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(SCI.getOperand(1))) {
3054 // Compute the constant that would happen if we truncated to SrcTy then
3055 // reextended to DestTy.
3056 Constant *Res = ConstantExpr::getCast(CI, SrcTy);
3057
3058 if (ConstantExpr::getCast(Res, DestTy) == CI) {
3059 RHSCIOp = Res;
3060 } else {
3061 // If the value cannot be represented in the shorter type, we cannot emit
3062 // a simple comparison.
3063 if (SCI.getOpcode() == Instruction::SetEQ)
3064 return ReplaceInstUsesWith(SCI, ConstantBool::False);
3065 if (SCI.getOpcode() == Instruction::SetNE)
3066 return ReplaceInstUsesWith(SCI, ConstantBool::True);
3067
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003068 // Evaluate the comparison for LT.
3069 Value *Result;
3070 if (DestTy->isSigned()) {
3071 // We're performing a signed comparison.
3072 if (isSignSrc) {
3073 // Signed extend and signed comparison.
3074 if (cast<ConstantSInt>(CI)->getValue() < 0) // X < (small) --> false
3075 Result = ConstantBool::False;
3076 else
3077 Result = ConstantBool::True; // X < (large) --> true
3078 } else {
3079 // Unsigned extend and signed comparison.
3080 if (cast<ConstantSInt>(CI)->getValue() < 0)
3081 Result = ConstantBool::False;
3082 else
3083 Result = ConstantBool::True;
3084 }
3085 } else {
3086 // We're performing an unsigned comparison.
3087 if (!isSignSrc) {
3088 // Unsigned extend & compare -> always true.
3089 Result = ConstantBool::True;
3090 } else {
3091 // We're performing an unsigned comp with a sign extended value.
3092 // This is true if the input is >= 0. [aka >s -1]
3093 Constant *NegOne = ConstantIntegral::getAllOnesValue(SrcTy);
3094 Result = InsertNewInstBefore(BinaryOperator::createSetGT(LHSCIOp,
3095 NegOne, SCI.getName()), SCI);
3096 }
Reid Spencer279fa252004-11-28 21:31:15 +00003097 }
Chris Lattner03f06f12005-01-17 03:20:02 +00003098
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00003099 // Finally, return the value computed.
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003100 if (SCI.getOpcode() == Instruction::SetLT) {
3101 return ReplaceInstUsesWith(SCI, Result);
3102 } else {
3103 assert(SCI.getOpcode()==Instruction::SetGT &&"SetCC should be folded!");
3104 if (Constant *CI = dyn_cast<Constant>(Result))
3105 return ReplaceInstUsesWith(SCI, ConstantExpr::getNot(CI));
3106 else
3107 return BinaryOperator::createNot(Result);
3108 }
Chris Lattner03f06f12005-01-17 03:20:02 +00003109 }
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003110 } else {
3111 return 0;
Reid Spencer279fa252004-11-28 21:31:15 +00003112 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003113
Chris Lattner252a8452005-06-16 03:00:08 +00003114 // Okay, just insert a compare of the reduced operands now!
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003115 return BinaryOperator::create(SCI.getOpcode(), LHSCIOp, RHSCIOp);
3116}
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003117
Chris Lattnere8d6c602003-03-10 19:16:08 +00003118Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +00003119 assert(I.getOperand(1)->getType() == Type::UByteTy);
3120 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003121 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003122
3123 // shl X, 0 == X and shr X, 0 == X
3124 // shl 0, X == 0 and shr 0, X == 0
3125 if (Op1 == Constant::getNullValue(Type::UByteTy) ||
Chris Lattnere6794492002-08-12 21:17:25 +00003126 Op0 == Constant::getNullValue(Op0->getType()))
3127 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003128
Chris Lattner81a7a232004-10-16 18:11:37 +00003129 if (isa<UndefValue>(Op0)) { // undef >>s X -> undef
3130 if (!isLeftShift && I.getType()->isSigned())
Chris Lattner67f05452004-10-16 23:28:04 +00003131 return ReplaceInstUsesWith(I, Op0);
Chris Lattner81a7a232004-10-16 18:11:37 +00003132 else // undef << X -> 0 AND undef >>u X -> 0
3133 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3134 }
3135 if (isa<UndefValue>(Op1)) {
Chris Lattner18aa4d82005-07-20 18:49:28 +00003136 if (isLeftShift || I.getType()->isUnsigned())// X << undef, X >>u undef -> 0
Chris Lattner81a7a232004-10-16 18:11:37 +00003137 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3138 else
3139 return ReplaceInstUsesWith(I, Op0); // X >>s undef -> X
3140 }
3141
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003142 // shr int -1, X = -1 (for any arithmetic shift rights of ~0)
3143 if (!isLeftShift)
3144 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
3145 if (CSI->isAllOnesValue())
3146 return ReplaceInstUsesWith(I, CSI);
3147
Chris Lattner183b3362004-04-09 19:05:30 +00003148 // Try to fold constant and into select arguments.
3149 if (isa<Constant>(Op0))
3150 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner86102b82005-01-01 16:22:27 +00003151 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00003152 return R;
3153
Chris Lattnerb18dbbf2005-05-08 17:34:56 +00003154 // See if we can turn a signed shr into an unsigned shr.
3155 if (!isLeftShift && I.getType()->isSigned()) {
3156 if (MaskedValueIsZero(Op0, ConstantInt::getMinValue(I.getType()))) {
3157 Value *V = InsertCastBefore(Op0, I.getType()->getUnsignedVersion(), I);
3158 V = InsertNewInstBefore(new ShiftInst(Instruction::Shr, V, Op1,
3159 I.getName()), I);
3160 return new CastInst(V, I.getType());
3161 }
3162 }
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00003163
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003164 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op1)) {
Chris Lattner3204d4e2003-07-24 17:52:58 +00003165 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
3166 // of a signed value.
3167 //
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003168 unsigned TypeBits = Op0->getType()->getPrimitiveSizeInBits();
Chris Lattnerf5ce2542004-02-23 20:30:06 +00003169 if (CUI->getValue() >= TypeBits) {
3170 if (!Op0->getType()->isSigned() || isLeftShift)
3171 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
3172 else {
3173 I.setOperand(1, ConstantUInt::get(Type::UByteTy, TypeBits-1));
3174 return &I;
3175 }
3176 }
Chris Lattner55f3d942002-09-10 23:04:09 +00003177
Chris Lattnerede3fe02003-08-13 04:18:28 +00003178 // ((X*C1) << C2) == (X * (C1 << C2))
3179 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
3180 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
3181 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003182 return BinaryOperator::createMul(BO->getOperand(0),
3183 ConstantExpr::getShl(BOOp, CUI));
Misha Brukmanb1c93172005-04-21 23:48:37 +00003184
Chris Lattner183b3362004-04-09 19:05:30 +00003185 // Try to fold constant and into select arguments.
3186 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00003187 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00003188 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00003189 if (isa<PHINode>(Op0))
3190 if (Instruction *NV = FoldOpIntoPhi(I))
3191 return NV;
Chris Lattnerede3fe02003-08-13 04:18:28 +00003192
Chris Lattner86102b82005-01-01 16:22:27 +00003193 if (Op0->hasOneUse()) {
3194 // If this is a SHL of a sign-extending cast, see if we can turn the input
3195 // into a zero extending cast (a simple strength reduction).
3196 if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3197 const Type *SrcTy = CI->getOperand(0)->getType();
3198 if (isLeftShift && SrcTy->isInteger() && SrcTy->isSigned() &&
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003199 SrcTy->getPrimitiveSizeInBits() <
3200 CI->getType()->getPrimitiveSizeInBits()) {
Chris Lattner86102b82005-01-01 16:22:27 +00003201 // We can change it to a zero extension if we are shifting out all of
3202 // the sign extended bits. To check this, form a mask of all of the
3203 // sign extend bits, then shift them left and see if we have anything
3204 // left.
3205 Constant *Mask = ConstantIntegral::getAllOnesValue(SrcTy); // 1111
3206 Mask = ConstantExpr::getZeroExtend(Mask, CI->getType()); // 00001111
3207 Mask = ConstantExpr::getNot(Mask); // 1's in the sign bits: 11110000
3208 if (ConstantExpr::getShl(Mask, CUI)->isNullValue()) {
3209 // If the shift is nuking all of the sign bits, change this to a
3210 // zero extension cast. To do this, cast the cast input to
3211 // unsigned, then to the requested size.
3212 Value *CastOp = CI->getOperand(0);
3213 Instruction *NC =
3214 new CastInst(CastOp, CastOp->getType()->getUnsignedVersion(),
3215 CI->getName()+".uns");
3216 NC = InsertNewInstBefore(NC, I);
3217 // Finally, insert a replacement for CI.
3218 NC = new CastInst(NC, CI->getType(), CI->getName());
3219 CI->setName("");
3220 NC = InsertNewInstBefore(NC, I);
3221 WorkList.push_back(CI); // Delete CI later.
3222 I.setOperand(0, NC);
3223 return &I; // The SHL operand was modified.
3224 }
3225 }
3226 }
3227
3228 // If the operand is an bitwise operator with a constant RHS, and the
3229 // shift is the only use, we can pull it out of the shift.
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003230 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0))
3231 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
3232 bool isValid = true; // Valid only for And, Or, Xor
3233 bool highBitSet = false; // Transform if high bit of constant set?
3234
3235 switch (Op0BO->getOpcode()) {
3236 default: isValid = false; break; // Do not perform transform!
Chris Lattner44bd3922004-10-08 03:46:20 +00003237 case Instruction::Add:
3238 isValid = isLeftShift;
3239 break;
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003240 case Instruction::Or:
3241 case Instruction::Xor:
3242 highBitSet = false;
3243 break;
3244 case Instruction::And:
3245 highBitSet = true;
3246 break;
3247 }
3248
3249 // If this is a signed shift right, and the high bit is modified
3250 // by the logical operation, do not perform the transformation.
3251 // The highBitSet boolean indicates the value of the high bit of
3252 // the constant which would cause it to be modified for this
3253 // operation.
3254 //
3255 if (isValid && !isLeftShift && !I.getType()->isUnsigned()) {
3256 uint64_t Val = Op0C->getRawValue();
3257 isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
3258 }
3259
3260 if (isValid) {
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003261 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, CUI);
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003262
3263 Instruction *NewShift =
3264 new ShiftInst(I.getOpcode(), Op0BO->getOperand(0), CUI,
3265 Op0BO->getName());
3266 Op0BO->setName("");
3267 InsertNewInstBefore(NewShift, I);
3268
3269 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
3270 NewRHS);
3271 }
3272 }
Chris Lattner86102b82005-01-01 16:22:27 +00003273 }
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003274
Chris Lattner3204d4e2003-07-24 17:52:58 +00003275 // If this is a shift of a shift, see if we can fold the two together...
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003276 if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0))
Chris Lattnerab780df2003-07-24 18:38:56 +00003277 if (ConstantUInt *ShiftAmt1C =
3278 dyn_cast<ConstantUInt>(Op0SI->getOperand(1))) {
Chris Lattnerfdfe3e492005-01-08 19:42:22 +00003279 unsigned ShiftAmt1 = (unsigned)ShiftAmt1C->getValue();
3280 unsigned ShiftAmt2 = (unsigned)CUI->getValue();
Misha Brukmanb1c93172005-04-21 23:48:37 +00003281
Chris Lattner3204d4e2003-07-24 17:52:58 +00003282 // Check for (A << c1) << c2 and (A >> c1) >> c2
3283 if (I.getOpcode() == Op0SI->getOpcode()) {
3284 unsigned Amt = ShiftAmt1+ShiftAmt2; // Fold into one big shift...
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003285 if (Op0->getType()->getPrimitiveSizeInBits() < Amt)
3286 Amt = Op0->getType()->getPrimitiveSizeInBits();
Chris Lattner3204d4e2003-07-24 17:52:58 +00003287 return new ShiftInst(I.getOpcode(), Op0SI->getOperand(0),
3288 ConstantUInt::get(Type::UByteTy, Amt));
3289 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003290
Chris Lattnerab780df2003-07-24 18:38:56 +00003291 // Check for (A << c1) >> c2 or visaversa. If we are dealing with
3292 // signed types, we can only support the (A >> c1) << c2 configuration,
3293 // because it can not turn an arbitrary bit of A into a sign bit.
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003294 if (I.getType()->isUnsigned() || isLeftShift) {
Chris Lattner3204d4e2003-07-24 17:52:58 +00003295 // Calculate bitmask for what gets shifted off the edge...
3296 Constant *C = ConstantIntegral::getAllOnesValue(I.getType());
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003297 if (isLeftShift)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003298 C = ConstantExpr::getShl(C, ShiftAmt1C);
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003299 else
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003300 C = ConstantExpr::getShr(C, ShiftAmt1C);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003301
Chris Lattner3204d4e2003-07-24 17:52:58 +00003302 Instruction *Mask =
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003303 BinaryOperator::createAnd(Op0SI->getOperand(0), C,
3304 Op0SI->getOperand(0)->getName()+".mask");
Chris Lattner3204d4e2003-07-24 17:52:58 +00003305 InsertNewInstBefore(Mask, I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003306
Chris Lattner3204d4e2003-07-24 17:52:58 +00003307 // Figure out what flavor of shift we should use...
3308 if (ShiftAmt1 == ShiftAmt2)
3309 return ReplaceInstUsesWith(I, Mask); // (A << c) >> c === A & c2
3310 else if (ShiftAmt1 < ShiftAmt2) {
3311 return new ShiftInst(I.getOpcode(), Mask,
3312 ConstantUInt::get(Type::UByteTy, ShiftAmt2-ShiftAmt1));
3313 } else {
3314 return new ShiftInst(Op0SI->getOpcode(), Mask,
3315 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
3316 }
3317 }
3318 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003319 }
Chris Lattner2e0fb392002-10-08 16:16:40 +00003320
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003321 return 0;
3322}
3323
Chris Lattner4e2dbc62004-07-20 00:59:32 +00003324enum CastType {
3325 Noop = 0,
3326 Truncate = 1,
3327 Signext = 2,
3328 Zeroext = 3
3329};
3330
3331/// getCastType - In the future, we will split the cast instruction into these
3332/// various types. Until then, we have to do the analysis here.
3333static CastType getCastType(const Type *Src, const Type *Dest) {
3334 assert(Src->isIntegral() && Dest->isIntegral() &&
3335 "Only works on integral types!");
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003336 unsigned SrcSize = Src->getPrimitiveSizeInBits();
3337 unsigned DestSize = Dest->getPrimitiveSizeInBits();
Chris Lattner4e2dbc62004-07-20 00:59:32 +00003338
3339 if (SrcSize == DestSize) return Noop;
3340 if (SrcSize > DestSize) return Truncate;
3341 if (Src->isSigned()) return Signext;
3342 return Zeroext;
3343}
3344
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003345
Chris Lattner48a44f72002-05-02 17:06:02 +00003346// isEliminableCastOfCast - Return true if it is valid to eliminate the CI
3347// instruction.
3348//
Chris Lattnerdfae8be2003-07-24 17:35:25 +00003349static inline bool isEliminableCastOfCast(const Type *SrcTy, const Type *MidTy,
Chris Lattner11ffd592004-07-20 05:21:00 +00003350 const Type *DstTy, TargetData *TD) {
Chris Lattner48a44f72002-05-02 17:06:02 +00003351
Chris Lattner650b6da2002-08-02 20:00:25 +00003352 // It is legal to eliminate the instruction if casting A->B->A if the sizes
Misha Brukmanb1c93172005-04-21 23:48:37 +00003353 // are identical and the bits don't get reinterpreted (for example
Chris Lattner1638de42004-07-21 19:50:44 +00003354 // int->float->int would not be allowed).
Misha Brukmane5838c42003-05-20 18:45:36 +00003355 if (SrcTy == DstTy && SrcTy->isLosslesslyConvertibleTo(MidTy))
Chris Lattner650b6da2002-08-02 20:00:25 +00003356 return true;
Chris Lattner48a44f72002-05-02 17:06:02 +00003357
Chris Lattner4fbad962004-07-21 04:27:24 +00003358 // If we are casting between pointer and integer types, treat pointers as
3359 // integers of the appropriate size for the code below.
3360 if (isa<PointerType>(SrcTy)) SrcTy = TD->getIntPtrType();
3361 if (isa<PointerType>(MidTy)) MidTy = TD->getIntPtrType();
3362 if (isa<PointerType>(DstTy)) DstTy = TD->getIntPtrType();
Chris Lattner11ffd592004-07-20 05:21:00 +00003363
Chris Lattner48a44f72002-05-02 17:06:02 +00003364 // Allow free casting and conversion of sizes as long as the sign doesn't
3365 // change...
Chris Lattnerb0b412e2002-09-03 01:08:28 +00003366 if (SrcTy->isIntegral() && MidTy->isIntegral() && DstTy->isIntegral()) {
Chris Lattner4e2dbc62004-07-20 00:59:32 +00003367 CastType FirstCast = getCastType(SrcTy, MidTy);
3368 CastType SecondCast = getCastType(MidTy, DstTy);
Chris Lattner650b6da2002-08-02 20:00:25 +00003369
Chris Lattner4e2dbc62004-07-20 00:59:32 +00003370 // Capture the effect of these two casts. If the result is a legal cast,
3371 // the CastType is stored here, otherwise a special code is used.
3372 static const unsigned CastResult[] = {
3373 // First cast is noop
3374 0, 1, 2, 3,
3375 // First cast is a truncate
3376 1, 1, 4, 4, // trunc->extend is not safe to eliminate
3377 // First cast is a sign ext
Chris Lattner1638de42004-07-21 19:50:44 +00003378 2, 5, 2, 4, // signext->zeroext never ok
Chris Lattner4e2dbc62004-07-20 00:59:32 +00003379 // First cast is a zero ext
Chris Lattner1638de42004-07-21 19:50:44 +00003380 3, 5, 3, 3,
Chris Lattner4e2dbc62004-07-20 00:59:32 +00003381 };
3382
3383 unsigned Result = CastResult[FirstCast*4+SecondCast];
3384 switch (Result) {
3385 default: assert(0 && "Illegal table value!");
3386 case 0:
3387 case 1:
3388 case 2:
3389 case 3:
3390 // FIXME: in the future, when LLVM has explicit sign/zeroextends and
3391 // truncates, we could eliminate more casts.
3392 return (unsigned)getCastType(SrcTy, DstTy) == Result;
3393 case 4:
3394 return false; // Not possible to eliminate this here.
3395 case 5:
Chris Lattner1638de42004-07-21 19:50:44 +00003396 // Sign or zero extend followed by truncate is always ok if the result
3397 // is a truncate or noop.
3398 CastType ResultCast = getCastType(SrcTy, DstTy);
3399 if (ResultCast == Noop || ResultCast == Truncate)
3400 return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +00003401 // Otherwise we are still growing the value, we are only safe if the
Chris Lattner1638de42004-07-21 19:50:44 +00003402 // result will match the sign/zeroextendness of the result.
3403 return ResultCast == FirstCast;
Chris Lattner3732aca2002-08-15 16:15:25 +00003404 }
Chris Lattner650b6da2002-08-02 20:00:25 +00003405 }
Chris Lattner48a44f72002-05-02 17:06:02 +00003406 return false;
3407}
3408
Chris Lattner11ffd592004-07-20 05:21:00 +00003409static bool ValueRequiresCast(const Value *V, const Type *Ty, TargetData *TD) {
Chris Lattnerdfae8be2003-07-24 17:35:25 +00003410 if (V->getType() == Ty || isa<Constant>(V)) return false;
3411 if (const CastInst *CI = dyn_cast<CastInst>(V))
Chris Lattner11ffd592004-07-20 05:21:00 +00003412 if (isEliminableCastOfCast(CI->getOperand(0)->getType(), CI->getType(), Ty,
3413 TD))
Chris Lattnerdfae8be2003-07-24 17:35:25 +00003414 return false;
3415 return true;
3416}
3417
3418/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
3419/// InsertBefore instruction. This is specialized a bit to avoid inserting
3420/// casts that are known to not do anything...
3421///
3422Value *InstCombiner::InsertOperandCastBefore(Value *V, const Type *DestTy,
3423 Instruction *InsertBefore) {
3424 if (V->getType() == DestTy) return V;
3425 if (Constant *C = dyn_cast<Constant>(V))
3426 return ConstantExpr::getCast(C, DestTy);
3427
3428 CastInst *CI = new CastInst(V, DestTy, V->getName());
3429 InsertNewInstBefore(CI, *InsertBefore);
3430 return CI;
3431}
Chris Lattner48a44f72002-05-02 17:06:02 +00003432
3433// CastInst simplification
Chris Lattner260ab202002-04-18 17:39:14 +00003434//
Chris Lattner113f4f42002-06-25 16:13:24 +00003435Instruction *InstCombiner::visitCastInst(CastInst &CI) {
Chris Lattner55d4bda2003-06-23 21:59:52 +00003436 Value *Src = CI.getOperand(0);
3437
Chris Lattner48a44f72002-05-02 17:06:02 +00003438 // If the user is casting a value to the same type, eliminate this cast
3439 // instruction...
Chris Lattner55d4bda2003-06-23 21:59:52 +00003440 if (CI.getType() == Src->getType())
3441 return ReplaceInstUsesWith(CI, Src);
Chris Lattner48a44f72002-05-02 17:06:02 +00003442
Chris Lattner81a7a232004-10-16 18:11:37 +00003443 if (isa<UndefValue>(Src)) // cast undef -> undef
3444 return ReplaceInstUsesWith(CI, UndefValue::get(CI.getType()));
3445
Chris Lattner48a44f72002-05-02 17:06:02 +00003446 // If casting the result of another cast instruction, try to eliminate this
3447 // one!
3448 //
Chris Lattner86102b82005-01-01 16:22:27 +00003449 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
3450 Value *A = CSrc->getOperand(0);
3451 if (isEliminableCastOfCast(A->getType(), CSrc->getType(),
3452 CI.getType(), TD)) {
Chris Lattner48a44f72002-05-02 17:06:02 +00003453 // This instruction now refers directly to the cast's src operand. This
3454 // has a good chance of making CSrc dead.
Chris Lattner113f4f42002-06-25 16:13:24 +00003455 CI.setOperand(0, CSrc->getOperand(0));
3456 return &CI;
Chris Lattner48a44f72002-05-02 17:06:02 +00003457 }
3458
Chris Lattner650b6da2002-08-02 20:00:25 +00003459 // If this is an A->B->A cast, and we are dealing with integral types, try
3460 // to convert this into a logical 'and' instruction.
3461 //
Misha Brukmanb1c93172005-04-21 23:48:37 +00003462 if (A->getType()->isInteger() &&
Chris Lattnerb0b412e2002-09-03 01:08:28 +00003463 CI.getType()->isInteger() && CSrc->getType()->isInteger() &&
Chris Lattner86102b82005-01-01 16:22:27 +00003464 CSrc->getType()->isUnsigned() && // B->A cast must zero extend
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003465 CSrc->getType()->getPrimitiveSizeInBits() <
3466 CI.getType()->getPrimitiveSizeInBits()&&
3467 A->getType()->getPrimitiveSizeInBits() ==
3468 CI.getType()->getPrimitiveSizeInBits()) {
Chris Lattner650b6da2002-08-02 20:00:25 +00003469 assert(CSrc->getType() != Type::ULongTy &&
3470 "Cannot have type bigger than ulong!");
Chris Lattner2f1457f2005-04-24 17:46:05 +00003471 uint64_t AndValue = ~0ULL>>(64-CSrc->getType()->getPrimitiveSizeInBits());
Chris Lattner86102b82005-01-01 16:22:27 +00003472 Constant *AndOp = ConstantUInt::get(A->getType()->getUnsignedVersion(),
3473 AndValue);
3474 AndOp = ConstantExpr::getCast(AndOp, A->getType());
3475 Instruction *And = BinaryOperator::createAnd(CSrc->getOperand(0), AndOp);
3476 if (And->getType() != CI.getType()) {
3477 And->setName(CSrc->getName()+".mask");
3478 InsertNewInstBefore(And, CI);
3479 And = new CastInst(And, CI.getType());
3480 }
3481 return And;
Chris Lattner650b6da2002-08-02 20:00:25 +00003482 }
3483 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003484
Chris Lattner03841652004-05-25 04:29:21 +00003485 // If this is a cast to bool, turn it into the appropriate setne instruction.
3486 if (CI.getType() == Type::BoolTy)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003487 return BinaryOperator::createSetNE(CI.getOperand(0),
Chris Lattner03841652004-05-25 04:29:21 +00003488 Constant::getNullValue(CI.getOperand(0)->getType()));
3489
Chris Lattnerd0d51602003-06-21 23:12:02 +00003490 // If casting the result of a getelementptr instruction with no offset, turn
3491 // this into a cast of the original pointer!
3492 //
Chris Lattner55d4bda2003-06-23 21:59:52 +00003493 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattnerd0d51602003-06-21 23:12:02 +00003494 bool AllZeroOperands = true;
3495 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
3496 if (!isa<Constant>(GEP->getOperand(i)) ||
3497 !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
3498 AllZeroOperands = false;
3499 break;
3500 }
3501 if (AllZeroOperands) {
3502 CI.setOperand(0, GEP->getOperand(0));
3503 return &CI;
3504 }
3505 }
3506
Chris Lattnerf4ad1652003-11-02 05:57:39 +00003507 // If we are casting a malloc or alloca to a pointer to a type of the same
3508 // size, rewrite the allocation instruction to allocate the "right" type.
3509 //
3510 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
Chris Lattnerd4d987d2003-11-02 06:54:48 +00003511 if (AI->hasOneUse() && !AI->isArrayAllocation())
Chris Lattnerf4ad1652003-11-02 05:57:39 +00003512 if (const PointerType *PTy = dyn_cast<PointerType>(CI.getType())) {
3513 // Get the type really allocated and the type casted to...
3514 const Type *AllocElTy = AI->getAllocatedType();
Chris Lattnerf4ad1652003-11-02 05:57:39 +00003515 const Type *CastElTy = PTy->getElementType();
Chris Lattner9eb9ccd2004-07-06 19:28:42 +00003516 if (AllocElTy->isSized() && CastElTy->isSized()) {
Chris Lattnerfdfe3e492005-01-08 19:42:22 +00003517 uint64_t AllocElTySize = TD->getTypeSize(AllocElTy);
3518 uint64_t CastElTySize = TD->getTypeSize(CastElTy);
Chris Lattner7c94d112003-11-05 17:31:36 +00003519
Chris Lattner9eb9ccd2004-07-06 19:28:42 +00003520 // If the allocation is for an even multiple of the cast type size
3521 if (CastElTySize && (AllocElTySize % CastElTySize == 0)) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00003522 Value *Amt = ConstantUInt::get(Type::UIntTy,
Chris Lattnerf4ad1652003-11-02 05:57:39 +00003523 AllocElTySize/CastElTySize);
Chris Lattner9eb9ccd2004-07-06 19:28:42 +00003524 std::string Name = AI->getName(); AI->setName("");
3525 AllocationInst *New;
3526 if (isa<MallocInst>(AI))
3527 New = new MallocInst(CastElTy, Amt, Name);
3528 else
3529 New = new AllocaInst(CastElTy, Amt, Name);
3530 InsertNewInstBefore(New, *AI);
3531 return ReplaceInstUsesWith(CI, New);
3532 }
Chris Lattnerf4ad1652003-11-02 05:57:39 +00003533 }
3534 }
3535
Chris Lattner86102b82005-01-01 16:22:27 +00003536 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
3537 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
3538 return NV;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00003539 if (isa<PHINode>(Src))
3540 if (Instruction *NV = FoldOpIntoPhi(CI))
3541 return NV;
3542
Chris Lattnerdfae8be2003-07-24 17:35:25 +00003543 // If the source value is an instruction with only this use, we can attempt to
3544 // propagate the cast into the instruction. Also, only handle integral types
3545 // for now.
3546 if (Instruction *SrcI = dyn_cast<Instruction>(Src))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00003547 if (SrcI->hasOneUse() && Src->getType()->isIntegral() &&
Chris Lattnerdfae8be2003-07-24 17:35:25 +00003548 CI.getType()->isInteger()) { // Don't mess with casts to bool here
3549 const Type *DestTy = CI.getType();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003550 unsigned SrcBitSize = Src->getType()->getPrimitiveSizeInBits();
3551 unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
Chris Lattnerdfae8be2003-07-24 17:35:25 +00003552
3553 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
3554 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
3555
3556 switch (SrcI->getOpcode()) {
3557 case Instruction::Add:
3558 case Instruction::Mul:
3559 case Instruction::And:
3560 case Instruction::Or:
3561 case Instruction::Xor:
3562 // If we are discarding information, or just changing the sign, rewrite.
3563 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
3564 // Don't insert two casts if they cannot be eliminated. We allow two
3565 // casts to be inserted if the sizes are the same. This could only be
3566 // converting signedness, which is a noop.
Chris Lattner11ffd592004-07-20 05:21:00 +00003567 if (DestBitSize == SrcBitSize || !ValueRequiresCast(Op1, DestTy,TD) ||
3568 !ValueRequiresCast(Op0, DestTy, TD)) {
Chris Lattnerdfae8be2003-07-24 17:35:25 +00003569 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
3570 Value *Op1c = InsertOperandCastBefore(Op1, DestTy, SrcI);
3571 return BinaryOperator::create(cast<BinaryOperator>(SrcI)
3572 ->getOpcode(), Op0c, Op1c);
3573 }
3574 }
Chris Lattner72086162005-05-06 02:07:39 +00003575
3576 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
3577 if (SrcBitSize == 1 && SrcI->getOpcode() == Instruction::Xor &&
3578 Op1 == ConstantBool::True &&
3579 (!Op0->hasOneUse() || !isa<SetCondInst>(Op0))) {
3580 Value *New = InsertOperandCastBefore(Op0, DestTy, &CI);
3581 return BinaryOperator::createXor(New,
3582 ConstantInt::get(CI.getType(), 1));
3583 }
Chris Lattnerdfae8be2003-07-24 17:35:25 +00003584 break;
3585 case Instruction::Shl:
3586 // Allow changing the sign of the source operand. Do not allow changing
3587 // the size of the shift, UNLESS the shift amount is a constant. We
3588 // mush not change variable sized shifts to a smaller size, because it
3589 // is undefined to shift more bits out than exist in the value.
3590 if (DestBitSize == SrcBitSize ||
3591 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
3592 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
3593 return new ShiftInst(Instruction::Shl, Op0c, Op1);
3594 }
3595 break;
Chris Lattner87380412005-05-06 04:18:52 +00003596 case Instruction::Shr:
3597 // If this is a signed shr, and if all bits shifted in are about to be
3598 // truncated off, turn it into an unsigned shr to allow greater
3599 // simplifications.
3600 if (DestBitSize < SrcBitSize && Src->getType()->isSigned() &&
3601 isa<ConstantInt>(Op1)) {
3602 unsigned ShiftAmt = cast<ConstantUInt>(Op1)->getValue();
3603 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
3604 // Convert to unsigned.
3605 Value *N1 = InsertOperandCastBefore(Op0,
3606 Op0->getType()->getUnsignedVersion(), &CI);
3607 // Insert the new shift, which is now unsigned.
3608 N1 = InsertNewInstBefore(new ShiftInst(Instruction::Shr, N1,
3609 Op1, Src->getName()), CI);
3610 return new CastInst(N1, CI.getType());
3611 }
3612 }
3613 break;
3614
Chris Lattner809dfac2005-05-04 19:10:26 +00003615 case Instruction::SetNE:
Chris Lattner809dfac2005-05-04 19:10:26 +00003616 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner4c2d3782005-05-06 01:53:19 +00003617 if (Op1C->getRawValue() == 0) {
3618 // If the input only has the low bit set, simplify directly.
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00003619 Constant *Not1 =
Chris Lattner809dfac2005-05-04 19:10:26 +00003620 ConstantExpr::getNot(ConstantInt::get(Op0->getType(), 1));
Chris Lattner4c2d3782005-05-06 01:53:19 +00003621 // cast (X != 0) to int --> X if X&~1 == 0
Chris Lattner809dfac2005-05-04 19:10:26 +00003622 if (MaskedValueIsZero(Op0, cast<ConstantIntegral>(Not1))) {
3623 if (CI.getType() == Op0->getType())
3624 return ReplaceInstUsesWith(CI, Op0);
3625 else
3626 return new CastInst(Op0, CI.getType());
3627 }
Chris Lattner4c2d3782005-05-06 01:53:19 +00003628
3629 // If the input is an and with a single bit, shift then simplify.
3630 ConstantInt *AndRHS;
3631 if (match(Op0, m_And(m_Value(), m_ConstantInt(AndRHS))))
3632 if (AndRHS->getRawValue() &&
3633 (AndRHS->getRawValue() & (AndRHS->getRawValue()-1)) == 0) {
Chris Lattner22d00a82005-08-02 19:16:58 +00003634 unsigned ShiftAmt = Log2_64(AndRHS->getRawValue());
Chris Lattner4c2d3782005-05-06 01:53:19 +00003635 // Perform an unsigned shr by shiftamt. Convert input to
3636 // unsigned if it is signed.
3637 Value *In = Op0;
3638 if (In->getType()->isSigned())
3639 In = InsertNewInstBefore(new CastInst(In,
3640 In->getType()->getUnsignedVersion(), In->getName()),CI);
3641 // Insert the shift to put the result in the low bit.
3642 In = InsertNewInstBefore(new ShiftInst(Instruction::Shr, In,
3643 ConstantInt::get(Type::UByteTy, ShiftAmt),
3644 In->getName()+".lobit"), CI);
Chris Lattner4c2d3782005-05-06 01:53:19 +00003645 if (CI.getType() == In->getType())
3646 return ReplaceInstUsesWith(CI, In);
3647 else
3648 return new CastInst(In, CI.getType());
3649 }
3650 }
3651 }
3652 break;
3653 case Instruction::SetEQ:
3654 // We if we are just checking for a seteq of a single bit and casting it
3655 // to an integer. If so, shift the bit to the appropriate place then
3656 // cast to integer to avoid the comparison.
3657 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
3658 // Is Op1C a power of two or zero?
3659 if ((Op1C->getRawValue() & Op1C->getRawValue()-1) == 0) {
3660 // cast (X == 1) to int -> X iff X has only the low bit set.
3661 if (Op1C->getRawValue() == 1) {
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00003662 Constant *Not1 =
Chris Lattner4c2d3782005-05-06 01:53:19 +00003663 ConstantExpr::getNot(ConstantInt::get(Op0->getType(), 1));
3664 if (MaskedValueIsZero(Op0, cast<ConstantIntegral>(Not1))) {
3665 if (CI.getType() == Op0->getType())
3666 return ReplaceInstUsesWith(CI, Op0);
3667 else
3668 return new CastInst(Op0, CI.getType());
3669 }
3670 }
Chris Lattner809dfac2005-05-04 19:10:26 +00003671 }
3672 }
3673 break;
Chris Lattnerdfae8be2003-07-24 17:35:25 +00003674 }
3675 }
Chris Lattner260ab202002-04-18 17:39:14 +00003676 return 0;
Chris Lattnerca081252001-12-14 16:52:21 +00003677}
3678
Chris Lattner56e4d3d2004-04-09 23:46:01 +00003679/// GetSelectFoldableOperands - We want to turn code that looks like this:
3680/// %C = or %A, %B
3681/// %D = select %cond, %C, %A
3682/// into:
3683/// %C = select %cond, %B, 0
3684/// %D = or %A, %C
3685///
3686/// Assuming that the specified instruction is an operand to the select, return
3687/// a bitmask indicating which operands of this instruction are foldable if they
3688/// equal the other incoming value of the select.
3689///
3690static unsigned GetSelectFoldableOperands(Instruction *I) {
3691 switch (I->getOpcode()) {
3692 case Instruction::Add:
3693 case Instruction::Mul:
3694 case Instruction::And:
3695 case Instruction::Or:
3696 case Instruction::Xor:
3697 return 3; // Can fold through either operand.
3698 case Instruction::Sub: // Can only fold on the amount subtracted.
3699 case Instruction::Shl: // Can only fold on the shift amount.
3700 case Instruction::Shr:
Misha Brukmanb1c93172005-04-21 23:48:37 +00003701 return 1;
Chris Lattner56e4d3d2004-04-09 23:46:01 +00003702 default:
3703 return 0; // Cannot fold
3704 }
3705}
3706
3707/// GetSelectFoldableConstant - For the same transformation as the previous
3708/// function, return the identity constant that goes into the select.
3709static Constant *GetSelectFoldableConstant(Instruction *I) {
3710 switch (I->getOpcode()) {
3711 default: assert(0 && "This cannot happen!"); abort();
3712 case Instruction::Add:
3713 case Instruction::Sub:
3714 case Instruction::Or:
3715 case Instruction::Xor:
3716 return Constant::getNullValue(I->getType());
3717 case Instruction::Shl:
3718 case Instruction::Shr:
3719 return Constant::getNullValue(Type::UByteTy);
3720 case Instruction::And:
3721 return ConstantInt::getAllOnesValue(I->getType());
3722 case Instruction::Mul:
3723 return ConstantInt::get(I->getType(), 1);
3724 }
3725}
3726
Chris Lattner411336f2005-01-19 21:50:18 +00003727/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
3728/// have the same opcode and only one use each. Try to simplify this.
3729Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
3730 Instruction *FI) {
3731 if (TI->getNumOperands() == 1) {
3732 // If this is a non-volatile load or a cast from the same type,
3733 // merge.
3734 if (TI->getOpcode() == Instruction::Cast) {
3735 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
3736 return 0;
3737 } else {
3738 return 0; // unknown unary op.
3739 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003740
Chris Lattner411336f2005-01-19 21:50:18 +00003741 // Fold this by inserting a select from the input values.
3742 SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
3743 FI->getOperand(0), SI.getName()+".v");
3744 InsertNewInstBefore(NewSI, SI);
3745 return new CastInst(NewSI, TI->getType());
3746 }
3747
3748 // Only handle binary operators here.
3749 if (!isa<ShiftInst>(TI) && !isa<BinaryOperator>(TI))
3750 return 0;
3751
3752 // Figure out if the operations have any operands in common.
3753 Value *MatchOp, *OtherOpT, *OtherOpF;
3754 bool MatchIsOpZero;
3755 if (TI->getOperand(0) == FI->getOperand(0)) {
3756 MatchOp = TI->getOperand(0);
3757 OtherOpT = TI->getOperand(1);
3758 OtherOpF = FI->getOperand(1);
3759 MatchIsOpZero = true;
3760 } else if (TI->getOperand(1) == FI->getOperand(1)) {
3761 MatchOp = TI->getOperand(1);
3762 OtherOpT = TI->getOperand(0);
3763 OtherOpF = FI->getOperand(0);
3764 MatchIsOpZero = false;
3765 } else if (!TI->isCommutative()) {
3766 return 0;
3767 } else if (TI->getOperand(0) == FI->getOperand(1)) {
3768 MatchOp = TI->getOperand(0);
3769 OtherOpT = TI->getOperand(1);
3770 OtherOpF = FI->getOperand(0);
3771 MatchIsOpZero = true;
3772 } else if (TI->getOperand(1) == FI->getOperand(0)) {
3773 MatchOp = TI->getOperand(1);
3774 OtherOpT = TI->getOperand(0);
3775 OtherOpF = FI->getOperand(1);
3776 MatchIsOpZero = true;
3777 } else {
3778 return 0;
3779 }
3780
3781 // If we reach here, they do have operations in common.
3782 SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
3783 OtherOpF, SI.getName()+".v");
3784 InsertNewInstBefore(NewSI, SI);
3785
3786 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
3787 if (MatchIsOpZero)
3788 return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
3789 else
3790 return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
3791 } else {
3792 if (MatchIsOpZero)
3793 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), MatchOp, NewSI);
3794 else
3795 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), NewSI, MatchOp);
3796 }
3797}
3798
Chris Lattnerb909e8b2004-03-12 05:52:32 +00003799Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattner533bc492004-03-30 19:37:13 +00003800 Value *CondVal = SI.getCondition();
3801 Value *TrueVal = SI.getTrueValue();
3802 Value *FalseVal = SI.getFalseValue();
3803
3804 // select true, X, Y -> X
3805 // select false, X, Y -> Y
3806 if (ConstantBool *C = dyn_cast<ConstantBool>(CondVal))
Chris Lattnerb909e8b2004-03-12 05:52:32 +00003807 if (C == ConstantBool::True)
Chris Lattner533bc492004-03-30 19:37:13 +00003808 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattnerb909e8b2004-03-12 05:52:32 +00003809 else {
3810 assert(C == ConstantBool::False);
Chris Lattner533bc492004-03-30 19:37:13 +00003811 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattnerb909e8b2004-03-12 05:52:32 +00003812 }
Chris Lattner533bc492004-03-30 19:37:13 +00003813
3814 // select C, X, X -> X
3815 if (TrueVal == FalseVal)
3816 return ReplaceInstUsesWith(SI, TrueVal);
3817
Chris Lattner81a7a232004-10-16 18:11:37 +00003818 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
3819 return ReplaceInstUsesWith(SI, FalseVal);
3820 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
3821 return ReplaceInstUsesWith(SI, TrueVal);
3822 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
3823 if (isa<Constant>(TrueVal))
3824 return ReplaceInstUsesWith(SI, TrueVal);
3825 else
3826 return ReplaceInstUsesWith(SI, FalseVal);
3827 }
3828
Chris Lattner1c631e82004-04-08 04:43:23 +00003829 if (SI.getType() == Type::BoolTy)
3830 if (ConstantBool *C = dyn_cast<ConstantBool>(TrueVal)) {
3831 if (C == ConstantBool::True) {
3832 // Change: A = select B, true, C --> A = or B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003833 return BinaryOperator::createOr(CondVal, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00003834 } else {
3835 // Change: A = select B, false, C --> A = and !B, C
3836 Value *NotCond =
3837 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
3838 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003839 return BinaryOperator::createAnd(NotCond, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00003840 }
3841 } else if (ConstantBool *C = dyn_cast<ConstantBool>(FalseVal)) {
3842 if (C == ConstantBool::False) {
3843 // Change: A = select B, C, false --> A = and B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003844 return BinaryOperator::createAnd(CondVal, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00003845 } else {
3846 // Change: A = select B, C, true --> A = or !B, C
3847 Value *NotCond =
3848 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
3849 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003850 return BinaryOperator::createOr(NotCond, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00003851 }
3852 }
3853
Chris Lattner183b3362004-04-09 19:05:30 +00003854 // Selecting between two integer constants?
3855 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
3856 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
3857 // select C, 1, 0 -> cast C to int
3858 if (FalseValC->isNullValue() && TrueValC->getRawValue() == 1) {
3859 return new CastInst(CondVal, SI.getType());
3860 } else if (TrueValC->isNullValue() && FalseValC->getRawValue() == 1) {
3861 // select C, 0, 1 -> cast !C to int
3862 Value *NotCond =
3863 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
Chris Lattnercf7baf32004-04-09 18:19:44 +00003864 "not."+CondVal->getName()), SI);
Chris Lattner183b3362004-04-09 19:05:30 +00003865 return new CastInst(NotCond, SI.getType());
Chris Lattnercf7baf32004-04-09 18:19:44 +00003866 }
Chris Lattner35167c32004-06-09 07:59:58 +00003867
3868 // If one of the constants is zero (we know they can't both be) and we
3869 // have a setcc instruction with zero, and we have an 'and' with the
3870 // non-constant value, eliminate this whole mess. This corresponds to
3871 // cases like this: ((X & 27) ? 27 : 0)
3872 if (TrueValC->isNullValue() || FalseValC->isNullValue())
3873 if (Instruction *IC = dyn_cast<Instruction>(SI.getCondition()))
3874 if ((IC->getOpcode() == Instruction::SetEQ ||
3875 IC->getOpcode() == Instruction::SetNE) &&
3876 isa<ConstantInt>(IC->getOperand(1)) &&
3877 cast<Constant>(IC->getOperand(1))->isNullValue())
3878 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
3879 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00003880 isa<ConstantInt>(ICA->getOperand(1)) &&
3881 (ICA->getOperand(1) == TrueValC ||
3882 ICA->getOperand(1) == FalseValC) &&
Chris Lattner35167c32004-06-09 07:59:58 +00003883 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
3884 // Okay, now we know that everything is set up, we just don't
3885 // know whether we have a setne or seteq and whether the true or
3886 // false val is the zero.
3887 bool ShouldNotVal = !TrueValC->isNullValue();
3888 ShouldNotVal ^= IC->getOpcode() == Instruction::SetNE;
3889 Value *V = ICA;
3890 if (ShouldNotVal)
3891 V = InsertNewInstBefore(BinaryOperator::create(
3892 Instruction::Xor, V, ICA->getOperand(1)), SI);
3893 return ReplaceInstUsesWith(SI, V);
3894 }
Chris Lattner533bc492004-03-30 19:37:13 +00003895 }
Chris Lattner623fba12004-04-10 22:21:27 +00003896
3897 // See if we are selecting two values based on a comparison of the two values.
3898 if (SetCondInst *SCI = dyn_cast<SetCondInst>(CondVal)) {
3899 if (SCI->getOperand(0) == TrueVal && SCI->getOperand(1) == FalseVal) {
3900 // Transform (X == Y) ? X : Y -> Y
3901 if (SCI->getOpcode() == Instruction::SetEQ)
3902 return ReplaceInstUsesWith(SI, FalseVal);
3903 // Transform (X != Y) ? X : Y -> X
3904 if (SCI->getOpcode() == Instruction::SetNE)
3905 return ReplaceInstUsesWith(SI, TrueVal);
3906 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
3907
3908 } else if (SCI->getOperand(0) == FalseVal && SCI->getOperand(1) == TrueVal){
3909 // Transform (X == Y) ? Y : X -> X
3910 if (SCI->getOpcode() == Instruction::SetEQ)
Chris Lattner24cf0202004-04-11 01:39:19 +00003911 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattner623fba12004-04-10 22:21:27 +00003912 // Transform (X != Y) ? Y : X -> Y
3913 if (SCI->getOpcode() == Instruction::SetNE)
Chris Lattner24cf0202004-04-11 01:39:19 +00003914 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattner623fba12004-04-10 22:21:27 +00003915 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
3916 }
3917 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003918
Chris Lattnera04c9042005-01-13 22:52:24 +00003919 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
3920 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
3921 if (TI->hasOneUse() && FI->hasOneUse()) {
3922 bool isInverse = false;
3923 Instruction *AddOp = 0, *SubOp = 0;
3924
Chris Lattner411336f2005-01-19 21:50:18 +00003925 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
3926 if (TI->getOpcode() == FI->getOpcode())
3927 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
3928 return IV;
3929
3930 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
3931 // even legal for FP.
Chris Lattnera04c9042005-01-13 22:52:24 +00003932 if (TI->getOpcode() == Instruction::Sub &&
3933 FI->getOpcode() == Instruction::Add) {
3934 AddOp = FI; SubOp = TI;
3935 } else if (FI->getOpcode() == Instruction::Sub &&
3936 TI->getOpcode() == Instruction::Add) {
3937 AddOp = TI; SubOp = FI;
3938 }
3939
3940 if (AddOp) {
3941 Value *OtherAddOp = 0;
3942 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
3943 OtherAddOp = AddOp->getOperand(1);
3944 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
3945 OtherAddOp = AddOp->getOperand(0);
3946 }
3947
3948 if (OtherAddOp) {
3949 // So at this point we know we have:
3950 // select C, (add X, Y), (sub X, ?)
3951 // We can do the transform profitably if either 'Y' = '?' or '?' is
3952 // a constant.
3953 if (SubOp->getOperand(1) == AddOp ||
3954 isa<Constant>(SubOp->getOperand(1))) {
3955 Value *NegVal;
3956 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
3957 NegVal = ConstantExpr::getNeg(C);
3958 } else {
3959 NegVal = InsertNewInstBefore(
3960 BinaryOperator::createNeg(SubOp->getOperand(1)), SI);
3961 }
3962
Chris Lattner51726c42005-01-14 17:35:12 +00003963 Value *NewTrueOp = OtherAddOp;
Chris Lattnera04c9042005-01-13 22:52:24 +00003964 Value *NewFalseOp = NegVal;
3965 if (AddOp != TI)
3966 std::swap(NewTrueOp, NewFalseOp);
3967 Instruction *NewSel =
3968 new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
Misha Brukmanb1c93172005-04-21 23:48:37 +00003969
Chris Lattnera04c9042005-01-13 22:52:24 +00003970 NewSel = InsertNewInstBefore(NewSel, SI);
Chris Lattner51726c42005-01-14 17:35:12 +00003971 return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
Chris Lattnera04c9042005-01-13 22:52:24 +00003972 }
3973 }
3974 }
3975 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003976
Chris Lattner56e4d3d2004-04-09 23:46:01 +00003977 // See if we can fold the select into one of our operands.
3978 if (SI.getType()->isInteger()) {
3979 // See the comment above GetSelectFoldableOperands for a description of the
3980 // transformation we are doing here.
3981 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
3982 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
3983 !isa<Constant>(FalseVal))
3984 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
3985 unsigned OpToFold = 0;
3986 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
3987 OpToFold = 1;
3988 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
3989 OpToFold = 2;
3990 }
3991
3992 if (OpToFold) {
3993 Constant *C = GetSelectFoldableConstant(TVI);
3994 std::string Name = TVI->getName(); TVI->setName("");
3995 Instruction *NewSel =
3996 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C,
3997 Name);
3998 InsertNewInstBefore(NewSel, SI);
3999 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
4000 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
4001 else if (ShiftInst *SI = dyn_cast<ShiftInst>(TVI))
4002 return new ShiftInst(SI->getOpcode(), FalseVal, NewSel);
4003 else {
4004 assert(0 && "Unknown instruction!!");
4005 }
4006 }
4007 }
Chris Lattner6862fbd2004-09-29 17:40:11 +00004008
Chris Lattner56e4d3d2004-04-09 23:46:01 +00004009 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
4010 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
4011 !isa<Constant>(TrueVal))
4012 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
4013 unsigned OpToFold = 0;
4014 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
4015 OpToFold = 1;
4016 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
4017 OpToFold = 2;
4018 }
4019
4020 if (OpToFold) {
4021 Constant *C = GetSelectFoldableConstant(FVI);
4022 std::string Name = FVI->getName(); FVI->setName("");
4023 Instruction *NewSel =
4024 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold),
4025 Name);
4026 InsertNewInstBefore(NewSel, SI);
4027 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
4028 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
4029 else if (ShiftInst *SI = dyn_cast<ShiftInst>(FVI))
4030 return new ShiftInst(SI->getOpcode(), TrueVal, NewSel);
4031 else {
4032 assert(0 && "Unknown instruction!!");
4033 }
4034 }
4035 }
4036 }
Chris Lattnerd6f636a2005-04-24 07:30:14 +00004037
4038 if (BinaryOperator::isNot(CondVal)) {
4039 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
4040 SI.setOperand(1, FalseVal);
4041 SI.setOperand(2, TrueVal);
4042 return &SI;
4043 }
4044
Chris Lattnerb909e8b2004-03-12 05:52:32 +00004045 return 0;
4046}
4047
4048
Chris Lattner970c33a2003-06-19 17:00:31 +00004049// CallInst simplification
4050//
4051Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattner51ea1272004-02-28 05:22:00 +00004052 // Intrinsics cannot occur in an invoke, so handle them here instead of in
4053 // visitCallSite.
Chris Lattner00648e12004-10-12 04:52:52 +00004054 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(&CI)) {
4055 bool Changed = false;
4056
4057 // memmove/cpy/set of zero bytes is a noop.
4058 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
4059 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
4060
4061 // FIXME: Increase alignment here.
Misha Brukmanb1c93172005-04-21 23:48:37 +00004062
Chris Lattner00648e12004-10-12 04:52:52 +00004063 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
4064 if (CI->getRawValue() == 1) {
4065 // Replace the instruction with just byte operations. We would
4066 // transform other cases to loads/stores, but we don't know if
4067 // alignment is sufficient.
4068 }
Chris Lattner51ea1272004-02-28 05:22:00 +00004069 }
4070
Chris Lattner00648e12004-10-12 04:52:52 +00004071 // If we have a memmove and the source operation is a constant global,
4072 // then the source and dest pointers can't alias, so we can change this
4073 // into a call to memcpy.
4074 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI))
4075 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
4076 if (GVSrc->isConstant()) {
4077 Module *M = CI.getParent()->getParent()->getParent();
4078 Function *MemCpy = M->getOrInsertFunction("llvm.memcpy",
4079 CI.getCalledFunction()->getFunctionType());
4080 CI.setOperand(0, MemCpy);
4081 Changed = true;
4082 }
4083
4084 if (Changed) return &CI;
Chris Lattner95307542004-11-18 21:41:39 +00004085 } else if (DbgStopPointInst *SPI = dyn_cast<DbgStopPointInst>(&CI)) {
4086 // If this stoppoint is at the same source location as the previous
4087 // stoppoint in the chain, it is not needed.
4088 if (DbgStopPointInst *PrevSPI =
4089 dyn_cast<DbgStopPointInst>(SPI->getChain()))
4090 if (SPI->getLineNo() == PrevSPI->getLineNo() &&
4091 SPI->getColNo() == PrevSPI->getColNo()) {
4092 SPI->replaceAllUsesWith(PrevSPI);
4093 return EraseInstFromFunction(CI);
4094 }
Chris Lattner00648e12004-10-12 04:52:52 +00004095 }
4096
Chris Lattneraec3d942003-10-07 22:32:43 +00004097 return visitCallSite(&CI);
Chris Lattner970c33a2003-06-19 17:00:31 +00004098}
4099
4100// InvokeInst simplification
4101//
4102Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattneraec3d942003-10-07 22:32:43 +00004103 return visitCallSite(&II);
Chris Lattner970c33a2003-06-19 17:00:31 +00004104}
4105
Chris Lattneraec3d942003-10-07 22:32:43 +00004106// visitCallSite - Improvements for call and invoke instructions.
4107//
4108Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner75b4d1d2003-10-07 22:54:13 +00004109 bool Changed = false;
4110
4111 // If the callee is a constexpr cast of a function, attempt to move the cast
4112 // to the arguments of the call/invoke.
Chris Lattneraec3d942003-10-07 22:32:43 +00004113 if (transformConstExprCastCall(CS)) return 0;
4114
Chris Lattner75b4d1d2003-10-07 22:54:13 +00004115 Value *Callee = CS.getCalledValue();
Chris Lattner81a7a232004-10-16 18:11:37 +00004116
Chris Lattner61d9d812005-05-13 07:09:09 +00004117 if (Function *CalleeF = dyn_cast<Function>(Callee))
4118 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
4119 Instruction *OldCall = CS.getInstruction();
4120 // If the call and callee calling conventions don't match, this call must
4121 // be unreachable, as the call is undefined.
4122 new StoreInst(ConstantBool::True,
4123 UndefValue::get(PointerType::get(Type::BoolTy)), OldCall);
4124 if (!OldCall->use_empty())
4125 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
4126 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
4127 return EraseInstFromFunction(*OldCall);
4128 return 0;
4129 }
4130
Chris Lattner8ba9ec92004-10-18 02:59:09 +00004131 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
4132 // This instruction is not reachable, just remove it. We insert a store to
4133 // undef so that we know that this code is not reachable, despite the fact
4134 // that we can't modify the CFG here.
4135 new StoreInst(ConstantBool::True,
4136 UndefValue::get(PointerType::get(Type::BoolTy)),
4137 CS.getInstruction());
4138
4139 if (!CS.getInstruction()->use_empty())
4140 CS.getInstruction()->
4141 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
4142
4143 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
4144 // Don't break the CFG, insert a dummy cond branch.
4145 new BranchInst(II->getNormalDest(), II->getUnwindDest(),
4146 ConstantBool::True, II);
Chris Lattner81a7a232004-10-16 18:11:37 +00004147 }
Chris Lattner8ba9ec92004-10-18 02:59:09 +00004148 return EraseInstFromFunction(*CS.getInstruction());
4149 }
Chris Lattner81a7a232004-10-16 18:11:37 +00004150
Chris Lattner75b4d1d2003-10-07 22:54:13 +00004151 const PointerType *PTy = cast<PointerType>(Callee->getType());
4152 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
4153 if (FTy->isVarArg()) {
4154 // See if we can optimize any arguments passed through the varargs area of
4155 // the call.
4156 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
4157 E = CS.arg_end(); I != E; ++I)
4158 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
4159 // If this cast does not effect the value passed through the varargs
4160 // area, we can eliminate the use of the cast.
4161 Value *Op = CI->getOperand(0);
4162 if (CI->getType()->isLosslesslyConvertibleTo(Op->getType())) {
4163 *I = Op;
4164 Changed = true;
4165 }
4166 }
4167 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004168
Chris Lattner75b4d1d2003-10-07 22:54:13 +00004169 return Changed ? CS.getInstruction() : 0;
Chris Lattneraec3d942003-10-07 22:32:43 +00004170}
4171
Chris Lattner970c33a2003-06-19 17:00:31 +00004172// transformConstExprCastCall - If the callee is a constexpr cast of a function,
4173// attempt to move the cast to the arguments of the call/invoke.
4174//
4175bool InstCombiner::transformConstExprCastCall(CallSite CS) {
4176 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
4177 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Chris Lattnerf3edc492004-07-18 18:59:44 +00004178 if (CE->getOpcode() != Instruction::Cast || !isa<Function>(CE->getOperand(0)))
Chris Lattner970c33a2003-06-19 17:00:31 +00004179 return false;
Reid Spencer87436872004-07-18 00:38:32 +00004180 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner970c33a2003-06-19 17:00:31 +00004181 Instruction *Caller = CS.getInstruction();
4182
4183 // Okay, this is a cast from a function to a different type. Unless doing so
4184 // would cause a type conversion of one of our arguments, change this call to
4185 // be a direct call with arguments casted to the appropriate types.
4186 //
4187 const FunctionType *FT = Callee->getFunctionType();
4188 const Type *OldRetTy = Caller->getType();
4189
Chris Lattner1f7942f2004-01-14 06:06:08 +00004190 // Check to see if we are changing the return type...
4191 if (OldRetTy != FT->getReturnType()) {
4192 if (Callee->isExternal() &&
4193 !OldRetTy->isLosslesslyConvertibleTo(FT->getReturnType()) &&
4194 !Caller->use_empty())
4195 return false; // Cannot transform this return value...
4196
4197 // If the callsite is an invoke instruction, and the return value is used by
4198 // a PHI node in a successor, we cannot change the return type of the call
4199 // because there is no place to put the cast instruction (without breaking
4200 // the critical edge). Bail out in this case.
4201 if (!Caller->use_empty())
4202 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
4203 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
4204 UI != E; ++UI)
4205 if (PHINode *PN = dyn_cast<PHINode>(*UI))
4206 if (PN->getParent() == II->getNormalDest() ||
Chris Lattnerfae8ab32004-02-08 21:44:31 +00004207 PN->getParent() == II->getUnwindDest())
Chris Lattner1f7942f2004-01-14 06:06:08 +00004208 return false;
4209 }
Chris Lattner970c33a2003-06-19 17:00:31 +00004210
4211 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
4212 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004213
Chris Lattner970c33a2003-06-19 17:00:31 +00004214 CallSite::arg_iterator AI = CS.arg_begin();
4215 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
4216 const Type *ParamTy = FT->getParamType(i);
4217 bool isConvertible = (*AI)->getType()->isLosslesslyConvertibleTo(ParamTy);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004218 if (Callee->isExternal() && !isConvertible) return false;
Chris Lattner970c33a2003-06-19 17:00:31 +00004219 }
4220
4221 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
4222 Callee->isExternal())
4223 return false; // Do not delete arguments unless we have a function body...
4224
4225 // Okay, we decided that this is a safe thing to do: go ahead and start
4226 // inserting cast instructions as necessary...
4227 std::vector<Value*> Args;
4228 Args.reserve(NumActualArgs);
4229
4230 AI = CS.arg_begin();
4231 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
4232 const Type *ParamTy = FT->getParamType(i);
4233 if ((*AI)->getType() == ParamTy) {
4234 Args.push_back(*AI);
4235 } else {
Chris Lattner1c631e82004-04-08 04:43:23 +00004236 Args.push_back(InsertNewInstBefore(new CastInst(*AI, ParamTy, "tmp"),
4237 *Caller));
Chris Lattner970c33a2003-06-19 17:00:31 +00004238 }
4239 }
4240
4241 // If the function takes more arguments than the call was taking, add them
4242 // now...
4243 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
4244 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
4245
4246 // If we are removing arguments to the function, emit an obnoxious warning...
4247 if (FT->getNumParams() < NumActualArgs)
4248 if (!FT->isVarArg()) {
4249 std::cerr << "WARNING: While resolving call to function '"
4250 << Callee->getName() << "' arguments were dropped!\n";
4251 } else {
4252 // Add all of the arguments in their promoted form to the arg list...
4253 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
4254 const Type *PTy = getPromotedType((*AI)->getType());
4255 if (PTy != (*AI)->getType()) {
4256 // Must promote to pass through va_arg area!
4257 Instruction *Cast = new CastInst(*AI, PTy, "tmp");
4258 InsertNewInstBefore(Cast, *Caller);
4259 Args.push_back(Cast);
4260 } else {
4261 Args.push_back(*AI);
4262 }
4263 }
4264 }
4265
4266 if (FT->getReturnType() == Type::VoidTy)
4267 Caller->setName(""); // Void type should not have a name...
4268
4269 Instruction *NC;
4270 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Chris Lattnerfae8ab32004-02-08 21:44:31 +00004271 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
Chris Lattner970c33a2003-06-19 17:00:31 +00004272 Args, Caller->getName(), Caller);
Chris Lattner05c703e2005-05-14 12:25:32 +00004273 cast<InvokeInst>(II)->setCallingConv(II->getCallingConv());
Chris Lattner970c33a2003-06-19 17:00:31 +00004274 } else {
4275 NC = new CallInst(Callee, Args, Caller->getName(), Caller);
Chris Lattner6aacb0f2005-05-06 06:48:21 +00004276 if (cast<CallInst>(Caller)->isTailCall())
4277 cast<CallInst>(NC)->setTailCall();
Chris Lattner05c703e2005-05-14 12:25:32 +00004278 cast<CallInst>(NC)->setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Chris Lattner970c33a2003-06-19 17:00:31 +00004279 }
4280
4281 // Insert a cast of the return type as necessary...
4282 Value *NV = NC;
4283 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
4284 if (NV->getType() != Type::VoidTy) {
4285 NV = NC = new CastInst(NC, Caller->getType(), "tmp");
Chris Lattner686767f2003-10-30 00:46:41 +00004286
4287 // If this is an invoke instruction, we should insert it after the first
4288 // non-phi, instruction in the normal successor block.
4289 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
4290 BasicBlock::iterator I = II->getNormalDest()->begin();
4291 while (isa<PHINode>(I)) ++I;
4292 InsertNewInstBefore(NC, *I);
4293 } else {
4294 // Otherwise, it's a call, just insert cast right after the call instr
4295 InsertNewInstBefore(NC, *Caller);
4296 }
Chris Lattner51ea1272004-02-28 05:22:00 +00004297 AddUsersToWorkList(*Caller);
Chris Lattner970c33a2003-06-19 17:00:31 +00004298 } else {
Chris Lattnere29d6342004-10-17 21:22:38 +00004299 NV = UndefValue::get(Caller->getType());
Chris Lattner970c33a2003-06-19 17:00:31 +00004300 }
4301 }
4302
4303 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
4304 Caller->replaceAllUsesWith(NV);
4305 Caller->getParent()->getInstList().erase(Caller);
4306 removeFromWorkList(Caller);
4307 return true;
4308}
4309
4310
Chris Lattner7515cab2004-11-14 19:13:23 +00004311// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
4312// operator and they all are only used by the PHI, PHI together their
4313// inputs, and do the operation once, to the result of the PHI.
4314Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
4315 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
4316
4317 // Scan the instruction, looking for input operations that can be folded away.
4318 // If all input operands to the phi are the same instruction (e.g. a cast from
4319 // the same type or "+42") we can pull the operation through the PHI, reducing
4320 // code size and simplifying code.
4321 Constant *ConstantOp = 0;
4322 const Type *CastSrcTy = 0;
4323 if (isa<CastInst>(FirstInst)) {
4324 CastSrcTy = FirstInst->getOperand(0)->getType();
4325 } else if (isa<BinaryOperator>(FirstInst) || isa<ShiftInst>(FirstInst)) {
4326 // Can fold binop or shift if the RHS is a constant.
4327 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
4328 if (ConstantOp == 0) return 0;
4329 } else {
4330 return 0; // Cannot fold this operation.
4331 }
4332
4333 // Check to see if all arguments are the same operation.
4334 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
4335 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
4336 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
4337 if (!I->hasOneUse() || I->getOpcode() != FirstInst->getOpcode())
4338 return 0;
4339 if (CastSrcTy) {
4340 if (I->getOperand(0)->getType() != CastSrcTy)
4341 return 0; // Cast operation must match.
4342 } else if (I->getOperand(1) != ConstantOp) {
4343 return 0;
4344 }
4345 }
4346
4347 // Okay, they are all the same operation. Create a new PHI node of the
4348 // correct type, and PHI together all of the LHS's of the instructions.
4349 PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
4350 PN.getName()+".in");
Chris Lattnerd8e20182005-01-29 00:39:08 +00004351 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattner46dd5a62004-11-14 19:29:34 +00004352
4353 Value *InVal = FirstInst->getOperand(0);
4354 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattner7515cab2004-11-14 19:13:23 +00004355
4356 // Add all operands to the new PHI.
Chris Lattner46dd5a62004-11-14 19:29:34 +00004357 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
4358 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
4359 if (NewInVal != InVal)
4360 InVal = 0;
4361 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
4362 }
4363
4364 Value *PhiVal;
4365 if (InVal) {
4366 // The new PHI unions all of the same values together. This is really
4367 // common, so we handle it intelligently here for compile-time speed.
4368 PhiVal = InVal;
4369 delete NewPN;
4370 } else {
4371 InsertNewInstBefore(NewPN, PN);
4372 PhiVal = NewPN;
4373 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004374
Chris Lattner7515cab2004-11-14 19:13:23 +00004375 // Insert and return the new operation.
4376 if (isa<CastInst>(FirstInst))
Chris Lattner46dd5a62004-11-14 19:29:34 +00004377 return new CastInst(PhiVal, PN.getType());
Chris Lattner7515cab2004-11-14 19:13:23 +00004378 else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattner46dd5a62004-11-14 19:29:34 +00004379 return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattner7515cab2004-11-14 19:13:23 +00004380 else
4381 return new ShiftInst(cast<ShiftInst>(FirstInst)->getOpcode(),
Chris Lattner46dd5a62004-11-14 19:29:34 +00004382 PhiVal, ConstantOp);
Chris Lattner7515cab2004-11-14 19:13:23 +00004383}
Chris Lattner48a44f72002-05-02 17:06:02 +00004384
Chris Lattner71536432005-01-17 05:10:15 +00004385/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
4386/// that is dead.
4387static bool DeadPHICycle(PHINode *PN, std::set<PHINode*> &PotentiallyDeadPHIs) {
4388 if (PN->use_empty()) return true;
4389 if (!PN->hasOneUse()) return false;
4390
4391 // Remember this node, and if we find the cycle, return.
4392 if (!PotentiallyDeadPHIs.insert(PN).second)
4393 return true;
4394
4395 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
4396 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004397
Chris Lattner71536432005-01-17 05:10:15 +00004398 return false;
4399}
4400
Chris Lattnerbbbdd852002-05-06 18:06:38 +00004401// PHINode simplification
4402//
Chris Lattner113f4f42002-06-25 16:13:24 +00004403Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Chris Lattner9f9c2602005-08-05 01:04:30 +00004404 if (Value *V = PN.hasConstantValue())
4405 return ReplaceInstUsesWith(PN, V);
Chris Lattner4db2d222004-02-16 05:07:08 +00004406
4407 // If the only user of this instruction is a cast instruction, and all of the
4408 // incoming values are constants, change this PHI to merge together the casted
4409 // constants.
4410 if (PN.hasOneUse())
4411 if (CastInst *CI = dyn_cast<CastInst>(PN.use_back()))
4412 if (CI->getType() != PN.getType()) { // noop casts will be folded
4413 bool AllConstant = true;
4414 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
4415 if (!isa<Constant>(PN.getIncomingValue(i))) {
4416 AllConstant = false;
4417 break;
4418 }
4419 if (AllConstant) {
4420 // Make a new PHI with all casted values.
4421 PHINode *New = new PHINode(CI->getType(), PN.getName(), &PN);
4422 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
4423 Constant *OldArg = cast<Constant>(PN.getIncomingValue(i));
4424 New->addIncoming(ConstantExpr::getCast(OldArg, New->getType()),
4425 PN.getIncomingBlock(i));
4426 }
4427
4428 // Update the cast instruction.
4429 CI->setOperand(0, New);
4430 WorkList.push_back(CI); // revisit the cast instruction to fold.
4431 WorkList.push_back(New); // Make sure to revisit the new Phi
4432 return &PN; // PN is now dead!
4433 }
4434 }
Chris Lattner7515cab2004-11-14 19:13:23 +00004435
4436 // If all PHI operands are the same operation, pull them through the PHI,
4437 // reducing code size.
4438 if (isa<Instruction>(PN.getIncomingValue(0)) &&
4439 PN.getIncomingValue(0)->hasOneUse())
4440 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
4441 return Result;
4442
Chris Lattner71536432005-01-17 05:10:15 +00004443 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
4444 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
4445 // PHI)... break the cycle.
4446 if (PN.hasOneUse())
4447 if (PHINode *PU = dyn_cast<PHINode>(PN.use_back())) {
4448 std::set<PHINode*> PotentiallyDeadPHIs;
4449 PotentiallyDeadPHIs.insert(&PN);
4450 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
4451 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
4452 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004453
Chris Lattner91daeb52003-12-19 05:58:40 +00004454 return 0;
Chris Lattnerbbbdd852002-05-06 18:06:38 +00004455}
4456
Chris Lattner69193f92004-04-05 01:30:19 +00004457static Value *InsertSignExtendToPtrTy(Value *V, const Type *DTy,
4458 Instruction *InsertPoint,
4459 InstCombiner *IC) {
4460 unsigned PS = IC->getTargetData().getPointerSize();
4461 const Type *VTy = V->getType();
Chris Lattner69193f92004-04-05 01:30:19 +00004462 if (!VTy->isSigned() && VTy->getPrimitiveSize() < PS)
4463 // We must insert a cast to ensure we sign-extend.
4464 V = IC->InsertNewInstBefore(new CastInst(V, VTy->getSignedVersion(),
4465 V->getName()), *InsertPoint);
4466 return IC->InsertNewInstBefore(new CastInst(V, DTy, V->getName()),
4467 *InsertPoint);
4468}
4469
Chris Lattner48a44f72002-05-02 17:06:02 +00004470
Chris Lattner113f4f42002-06-25 16:13:24 +00004471Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner5f667a62004-05-07 22:09:22 +00004472 Value *PtrOp = GEP.getOperand(0);
Chris Lattner471bd762003-05-22 19:07:21 +00004473 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
Chris Lattner113f4f42002-06-25 16:13:24 +00004474 // If so, eliminate the noop.
Chris Lattner8d0bacb2004-02-22 05:25:17 +00004475 if (GEP.getNumOperands() == 1)
Chris Lattner5f667a62004-05-07 22:09:22 +00004476 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner8d0bacb2004-02-22 05:25:17 +00004477
Chris Lattner81a7a232004-10-16 18:11:37 +00004478 if (isa<UndefValue>(GEP.getOperand(0)))
4479 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
4480
Chris Lattner8d0bacb2004-02-22 05:25:17 +00004481 bool HasZeroPointerIndex = false;
4482 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
4483 HasZeroPointerIndex = C->isNullValue();
4484
4485 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner5f667a62004-05-07 22:09:22 +00004486 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner48a44f72002-05-02 17:06:02 +00004487
Chris Lattner69193f92004-04-05 01:30:19 +00004488 // Eliminate unneeded casts for indices.
4489 bool MadeChange = false;
Chris Lattner2b2412d2004-04-07 18:38:20 +00004490 gep_type_iterator GTI = gep_type_begin(GEP);
4491 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI)
4492 if (isa<SequentialType>(*GTI)) {
4493 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
4494 Value *Src = CI->getOperand(0);
4495 const Type *SrcTy = Src->getType();
4496 const Type *DestTy = CI->getType();
4497 if (Src->getType()->isInteger()) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004498 if (SrcTy->getPrimitiveSizeInBits() ==
4499 DestTy->getPrimitiveSizeInBits()) {
Chris Lattner2b2412d2004-04-07 18:38:20 +00004500 // We can always eliminate a cast from ulong or long to the other.
4501 // We can always eliminate a cast from uint to int or the other on
4502 // 32-bit pointer platforms.
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004503 if (DestTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()){
Chris Lattner2b2412d2004-04-07 18:38:20 +00004504 MadeChange = true;
4505 GEP.setOperand(i, Src);
4506 }
4507 } else if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
4508 SrcTy->getPrimitiveSize() == 4) {
4509 // We can always eliminate a cast from int to [u]long. We can
4510 // eliminate a cast from uint to [u]long iff the target is a 32-bit
4511 // pointer target.
Misha Brukmanb1c93172005-04-21 23:48:37 +00004512 if (SrcTy->isSigned() ||
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004513 SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
Chris Lattner2b2412d2004-04-07 18:38:20 +00004514 MadeChange = true;
4515 GEP.setOperand(i, Src);
4516 }
Chris Lattner69193f92004-04-05 01:30:19 +00004517 }
4518 }
4519 }
Chris Lattner2b2412d2004-04-07 18:38:20 +00004520 // If we are using a wider index than needed for this platform, shrink it
4521 // to what we need. If the incoming value needs a cast instruction,
4522 // insert it. This explicit cast can make subsequent optimizations more
4523 // obvious.
4524 Value *Op = GEP.getOperand(i);
4525 if (Op->getType()->getPrimitiveSize() > TD->getPointerSize())
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00004526 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner44d0b952004-07-20 01:48:15 +00004527 GEP.setOperand(i, ConstantExpr::getCast(C,
4528 TD->getIntPtrType()->getSignedVersion()));
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00004529 MadeChange = true;
4530 } else {
Chris Lattner2b2412d2004-04-07 18:38:20 +00004531 Op = InsertNewInstBefore(new CastInst(Op, TD->getIntPtrType(),
4532 Op->getName()), GEP);
4533 GEP.setOperand(i, Op);
4534 MadeChange = true;
4535 }
Chris Lattner44d0b952004-07-20 01:48:15 +00004536
4537 // If this is a constant idx, make sure to canonicalize it to be a signed
4538 // operand, otherwise CSE and other optimizations are pessimized.
4539 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op)) {
4540 GEP.setOperand(i, ConstantExpr::getCast(CUI,
4541 CUI->getType()->getSignedVersion()));
4542 MadeChange = true;
4543 }
Chris Lattner69193f92004-04-05 01:30:19 +00004544 }
4545 if (MadeChange) return &GEP;
4546
Chris Lattnerae7a0d32002-08-02 19:29:35 +00004547 // Combine Indices - If the source pointer to this getelementptr instruction
4548 // is a getelementptr instruction, combine the indices of the two
4549 // getelementptr instructions into a single instruction.
4550 //
Chris Lattner57c67b02004-03-25 22:59:29 +00004551 std::vector<Value*> SrcGEPOperands;
Chris Lattner0798af32005-01-13 20:14:25 +00004552 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattner57c67b02004-03-25 22:59:29 +00004553 SrcGEPOperands.assign(Src->op_begin(), Src->op_end());
Chris Lattner57c67b02004-03-25 22:59:29 +00004554
4555 if (!SrcGEPOperands.empty()) {
Chris Lattner5f667a62004-05-07 22:09:22 +00004556 // Note that if our source is a gep chain itself that we wait for that
4557 // chain to be resolved before we perform this transformation. This
4558 // avoids us creating a TON of code in some cases.
4559 //
4560 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
4561 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
4562 return 0; // Wait until our source is folded to completion.
4563
Chris Lattnerae7a0d32002-08-02 19:29:35 +00004564 std::vector<Value *> Indices;
Chris Lattner5f667a62004-05-07 22:09:22 +00004565
4566 // Find out whether the last index in the source GEP is a sequential idx.
4567 bool EndsWithSequential = false;
4568 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
4569 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattner8ec5f882004-05-08 22:41:42 +00004570 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004571
Chris Lattnerae7a0d32002-08-02 19:29:35 +00004572 // Can we combine the two pointer arithmetics offsets?
Chris Lattner5f667a62004-05-07 22:09:22 +00004573 if (EndsWithSequential) {
Chris Lattner235af562003-03-05 22:33:14 +00004574 // Replace: gep (gep %P, long B), long A, ...
4575 // With: T = long A+B; gep %P, T, ...
4576 //
Chris Lattner5f667a62004-05-07 22:09:22 +00004577 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner69193f92004-04-05 01:30:19 +00004578 if (SO1 == Constant::getNullValue(SO1->getType())) {
4579 Sum = GO1;
4580 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
4581 Sum = SO1;
4582 } else {
4583 // If they aren't the same type, convert both to an integer of the
4584 // target's pointer size.
4585 if (SO1->getType() != GO1->getType()) {
4586 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
4587 SO1 = ConstantExpr::getCast(SO1C, GO1->getType());
4588 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
4589 GO1 = ConstantExpr::getCast(GO1C, SO1->getType());
4590 } else {
4591 unsigned PS = TD->getPointerSize();
Chris Lattner69193f92004-04-05 01:30:19 +00004592 if (SO1->getType()->getPrimitiveSize() == PS) {
4593 // Convert GO1 to SO1's type.
4594 GO1 = InsertSignExtendToPtrTy(GO1, SO1->getType(), &GEP, this);
4595
4596 } else if (GO1->getType()->getPrimitiveSize() == PS) {
4597 // Convert SO1 to GO1's type.
4598 SO1 = InsertSignExtendToPtrTy(SO1, GO1->getType(), &GEP, this);
4599 } else {
4600 const Type *PT = TD->getIntPtrType();
4601 SO1 = InsertSignExtendToPtrTy(SO1, PT, &GEP, this);
4602 GO1 = InsertSignExtendToPtrTy(GO1, PT, &GEP, this);
4603 }
4604 }
4605 }
Chris Lattner5f667a62004-05-07 22:09:22 +00004606 if (isa<Constant>(SO1) && isa<Constant>(GO1))
4607 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
4608 else {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004609 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
4610 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner5f667a62004-05-07 22:09:22 +00004611 }
Chris Lattner69193f92004-04-05 01:30:19 +00004612 }
Chris Lattner5f667a62004-05-07 22:09:22 +00004613
4614 // Recycle the GEP we already have if possible.
4615 if (SrcGEPOperands.size() == 2) {
4616 GEP.setOperand(0, SrcGEPOperands[0]);
4617 GEP.setOperand(1, Sum);
4618 return &GEP;
4619 } else {
4620 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
4621 SrcGEPOperands.end()-1);
4622 Indices.push_back(Sum);
4623 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
4624 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004625 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner69193f92004-04-05 01:30:19 +00004626 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00004627 SrcGEPOperands.size() != 1) {
Chris Lattnerae7a0d32002-08-02 19:29:35 +00004628 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattner57c67b02004-03-25 22:59:29 +00004629 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
4630 SrcGEPOperands.end());
Chris Lattnerae7a0d32002-08-02 19:29:35 +00004631 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
4632 }
4633
4634 if (!Indices.empty())
Chris Lattner57c67b02004-03-25 22:59:29 +00004635 return new GetElementPtrInst(SrcGEPOperands[0], Indices, GEP.getName());
Chris Lattnerc59af1d2002-08-17 22:21:59 +00004636
Chris Lattner5f667a62004-05-07 22:09:22 +00004637 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattnerc59af1d2002-08-17 22:21:59 +00004638 // GEP of global variable. If all of the indices for this GEP are
4639 // constants, we can promote this to a constexpr instead of an instruction.
4640
4641 // Scan for nonconstants...
4642 std::vector<Constant*> Indices;
4643 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
4644 for (; I != E && isa<Constant>(*I); ++I)
4645 Indices.push_back(cast<Constant>(*I));
4646
4647 if (I == E) { // If they are all constants...
Chris Lattnerf3edc492004-07-18 18:59:44 +00004648 Constant *CE = ConstantExpr::getGetElementPtr(GV, Indices);
Chris Lattnerc59af1d2002-08-17 22:21:59 +00004649
4650 // Replace all uses of the GEP with the new constexpr...
4651 return ReplaceInstUsesWith(GEP, CE);
4652 }
Chris Lattner5f667a62004-05-07 22:09:22 +00004653 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(PtrOp)) {
Chris Lattner8d0bacb2004-02-22 05:25:17 +00004654 if (CE->getOpcode() == Instruction::Cast) {
4655 if (HasZeroPointerIndex) {
4656 // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
4657 // into : GEP [10 x ubyte]* X, long 0, ...
4658 //
4659 // This occurs when the program declares an array extern like "int X[];"
4660 //
4661 Constant *X = CE->getOperand(0);
4662 const PointerType *CPTy = cast<PointerType>(CE->getType());
4663 if (const PointerType *XTy = dyn_cast<PointerType>(X->getType()))
4664 if (const ArrayType *XATy =
4665 dyn_cast<ArrayType>(XTy->getElementType()))
4666 if (const ArrayType *CATy =
4667 dyn_cast<ArrayType>(CPTy->getElementType()))
4668 if (CATy->getElementType() == XATy->getElementType()) {
4669 // At this point, we know that the cast source type is a pointer
4670 // to an array of the same type as the destination pointer
4671 // array. Because the array type is never stepped over (there
4672 // is a leading zero) we can fold the cast into this GEP.
4673 GEP.setOperand(0, X);
4674 return &GEP;
4675 }
Chris Lattner0798af32005-01-13 20:14:25 +00004676 } else if (GEP.getNumOperands() == 2 &&
4677 isa<PointerType>(CE->getOperand(0)->getType())) {
Chris Lattner14f3cdc2004-11-27 17:55:46 +00004678 // Transform things like:
4679 // %t = getelementptr ubyte* cast ([2 x sbyte]* %str to ubyte*), uint %V
4680 // into: %t1 = getelementptr [2 x sbyte*]* %str, int 0, uint %V; cast
4681 Constant *X = CE->getOperand(0);
4682 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
4683 const Type *ResElTy =cast<PointerType>(CE->getType())->getElementType();
4684 if (isa<ArrayType>(SrcElTy) &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00004685 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
Chris Lattner14f3cdc2004-11-27 17:55:46 +00004686 TD->getTypeSize(ResElTy)) {
4687 Value *V = InsertNewInstBefore(
4688 new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
4689 GEP.getOperand(1), GEP.getName()), GEP);
4690 return new CastInst(V, GEP.getType());
4691 }
Chris Lattner8d0bacb2004-02-22 05:25:17 +00004692 }
4693 }
Chris Lattnerca081252001-12-14 16:52:21 +00004694 }
4695
Chris Lattnerca081252001-12-14 16:52:21 +00004696 return 0;
4697}
4698
Chris Lattner1085bdf2002-11-04 16:18:53 +00004699Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
4700 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
4701 if (AI.isArrayAllocation()) // Check C != 1
4702 if (const ConstantUInt *C = dyn_cast<ConstantUInt>(AI.getArraySize())) {
4703 const Type *NewTy = ArrayType::get(AI.getAllocatedType(), C->getValue());
Chris Lattnera2620ac2002-11-09 00:49:43 +00004704 AllocationInst *New = 0;
Chris Lattner1085bdf2002-11-04 16:18:53 +00004705
4706 // Create and insert the replacement instruction...
4707 if (isa<MallocInst>(AI))
Chris Lattnerabb77c92004-03-19 06:08:10 +00004708 New = new MallocInst(NewTy, 0, AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00004709 else {
4710 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Chris Lattnerabb77c92004-03-19 06:08:10 +00004711 New = new AllocaInst(NewTy, 0, AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00004712 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00004713
4714 InsertNewInstBefore(New, AI);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004715
Chris Lattner1085bdf2002-11-04 16:18:53 +00004716 // Scan to the end of the allocation instructions, to skip over a block of
4717 // allocas if possible...
4718 //
4719 BasicBlock::iterator It = New;
4720 while (isa<AllocationInst>(*It)) ++It;
4721
4722 // Now that I is pointing to the first non-allocation-inst in the block,
4723 // insert our getelementptr instruction...
4724 //
Chris Lattner809dfac2005-05-04 19:10:26 +00004725 Value *NullIdx = Constant::getNullValue(Type::IntTy);
4726 Value *V = new GetElementPtrInst(New, NullIdx, NullIdx,
4727 New->getName()+".sub", It);
Chris Lattner1085bdf2002-11-04 16:18:53 +00004728
4729 // Now make everything use the getelementptr instead of the original
4730 // allocation.
Chris Lattnerabb77c92004-03-19 06:08:10 +00004731 return ReplaceInstUsesWith(AI, V);
Chris Lattner81a7a232004-10-16 18:11:37 +00004732 } else if (isa<UndefValue>(AI.getArraySize())) {
4733 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner1085bdf2002-11-04 16:18:53 +00004734 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00004735
4736 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
4737 // Note that we only do this for alloca's, because malloc should allocate and
4738 // return a unique pointer, even for a zero byte allocation.
Misha Brukmanb1c93172005-04-21 23:48:37 +00004739 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
Chris Lattner49df6ce2004-07-02 22:55:47 +00004740 TD->getTypeSize(AI.getAllocatedType()) == 0)
Chris Lattnerabb77c92004-03-19 06:08:10 +00004741 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
4742
Chris Lattner1085bdf2002-11-04 16:18:53 +00004743 return 0;
4744}
4745
Chris Lattner8427bff2003-12-07 01:24:23 +00004746Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
4747 Value *Op = FI.getOperand(0);
4748
4749 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
4750 if (CastInst *CI = dyn_cast<CastInst>(Op))
4751 if (isa<PointerType>(CI->getOperand(0)->getType())) {
4752 FI.setOperand(0, CI->getOperand(0));
4753 return &FI;
4754 }
4755
Chris Lattner8ba9ec92004-10-18 02:59:09 +00004756 // free undef -> unreachable.
4757 if (isa<UndefValue>(Op)) {
4758 // Insert a new store to null because we cannot modify the CFG here.
4759 new StoreInst(ConstantBool::True,
4760 UndefValue::get(PointerType::get(Type::BoolTy)), &FI);
4761 return EraseInstFromFunction(FI);
4762 }
4763
Chris Lattnerf3a36602004-02-28 04:57:37 +00004764 // If we have 'free null' delete the instruction. This can happen in stl code
4765 // when lots of inlining happens.
Chris Lattner8ba9ec92004-10-18 02:59:09 +00004766 if (isa<ConstantPointerNull>(Op))
Chris Lattner51ea1272004-02-28 05:22:00 +00004767 return EraseInstFromFunction(FI);
Chris Lattnerf3a36602004-02-28 04:57:37 +00004768
Chris Lattner8427bff2003-12-07 01:24:23 +00004769 return 0;
4770}
4771
4772
Chris Lattner0f1d8a32003-06-26 05:06:25 +00004773/// GetGEPGlobalInitializer - Given a constant, and a getelementptr
4774/// constantexpr, return the constant value being addressed by the constant
4775/// expression, or null if something is funny.
4776///
4777static Constant *GetGEPGlobalInitializer(Constant *C, ConstantExpr *CE) {
Chris Lattner69193f92004-04-05 01:30:19 +00004778 if (CE->getOperand(1) != Constant::getNullValue(CE->getOperand(1)->getType()))
Chris Lattner0f1d8a32003-06-26 05:06:25 +00004779 return 0; // Do not allow stepping over the value!
4780
4781 // Loop over all of the operands, tracking down which value we are
4782 // addressing...
Chris Lattnered79d8a2004-05-27 17:30:27 +00004783 gep_type_iterator I = gep_type_begin(CE), E = gep_type_end(CE);
4784 for (++I; I != E; ++I)
4785 if (const StructType *STy = dyn_cast<StructType>(*I)) {
4786 ConstantUInt *CU = cast<ConstantUInt>(I.getOperand());
4787 assert(CU->getValue() < STy->getNumElements() &&
4788 "Struct index out of range!");
Chris Lattnerfdfe3e492005-01-08 19:42:22 +00004789 unsigned El = (unsigned)CU->getValue();
Chris Lattnered79d8a2004-05-27 17:30:27 +00004790 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(C)) {
Chris Lattnerfdfe3e492005-01-08 19:42:22 +00004791 C = CS->getOperand(El);
Chris Lattnered79d8a2004-05-27 17:30:27 +00004792 } else if (isa<ConstantAggregateZero>(C)) {
Jeff Cohen82639852005-04-23 21:38:35 +00004793 C = Constant::getNullValue(STy->getElementType(El));
Chris Lattner81a7a232004-10-16 18:11:37 +00004794 } else if (isa<UndefValue>(C)) {
Jeff Cohen82639852005-04-23 21:38:35 +00004795 C = UndefValue::get(STy->getElementType(El));
Chris Lattnered79d8a2004-05-27 17:30:27 +00004796 } else {
4797 return 0;
4798 }
4799 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand())) {
4800 const ArrayType *ATy = cast<ArrayType>(*I);
4801 if ((uint64_t)CI->getRawValue() >= ATy->getNumElements()) return 0;
4802 if (ConstantArray *CA = dyn_cast<ConstantArray>(C))
Chris Lattnerfdfe3e492005-01-08 19:42:22 +00004803 C = CA->getOperand((unsigned)CI->getRawValue());
Chris Lattnered79d8a2004-05-27 17:30:27 +00004804 else if (isa<ConstantAggregateZero>(C))
4805 C = Constant::getNullValue(ATy->getElementType());
Chris Lattner81a7a232004-10-16 18:11:37 +00004806 else if (isa<UndefValue>(C))
4807 C = UndefValue::get(ATy->getElementType());
Chris Lattnered79d8a2004-05-27 17:30:27 +00004808 else
4809 return 0;
4810 } else {
Chris Lattner0f1d8a32003-06-26 05:06:25 +00004811 return 0;
Chris Lattnered79d8a2004-05-27 17:30:27 +00004812 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00004813 return C;
4814}
4815
Chris Lattner72684fe2005-01-31 05:51:45 +00004816/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Chris Lattner35e24772004-07-13 01:49:43 +00004817static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
4818 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00004819 Value *CastOp = CI->getOperand(0);
Chris Lattner35e24772004-07-13 01:49:43 +00004820
4821 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00004822 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Chris Lattner35e24772004-07-13 01:49:43 +00004823 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00004824
4825 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
4826 // If the source is an array, the code below will not succeed. Check to
4827 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
4828 // constants.
4829 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
4830 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
4831 if (ASrcTy->getNumElements() != 0) {
4832 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
4833 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
4834 SrcTy = cast<PointerType>(CastOp->getType());
4835 SrcPTy = SrcTy->getElementType();
4836 }
4837
4838 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
Chris Lattnerecfa9b52005-03-29 06:37:47 +00004839 // Do not allow turning this into a load of an integer, which is then
4840 // casted to a pointer, this pessimizes pointer analysis a lot.
4841 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00004842 IC.getTargetData().getTypeSize(SrcPTy) ==
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00004843 IC.getTargetData().getTypeSize(DestPTy)) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00004844
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00004845 // Okay, we are casting from one integer or pointer type to another of
4846 // the same size. Instead of casting the pointer before the load, cast
4847 // the result of the loaded value.
4848 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
4849 CI->getName(),
4850 LI.isVolatile()),LI);
4851 // Now cast the result of the load.
4852 return new CastInst(NewLoad, LI.getType());
4853 }
Chris Lattner35e24772004-07-13 01:49:43 +00004854 }
4855 }
4856 return 0;
4857}
4858
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00004859/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattnere6f13092004-09-19 19:18:10 +00004860/// from this value cannot trap. If it is not obviously safe to load from the
4861/// specified pointer, we do a quick local scan of the basic block containing
4862/// ScanFrom, to determine if the address is already accessed.
4863static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
4864 // If it is an alloca or global variable, it is always safe to load from.
4865 if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
4866
4867 // Otherwise, be a little bit agressive by scanning the local block where we
4868 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00004869 // from/to. If so, the previous load or store would have already trapped,
4870 // so there is no harm doing an extra load (also, CSE will later eliminate
4871 // the load entirely).
Chris Lattnere6f13092004-09-19 19:18:10 +00004872 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
4873
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00004874 while (BBI != E) {
Chris Lattnere6f13092004-09-19 19:18:10 +00004875 --BBI;
4876
4877 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
4878 if (LI->getOperand(0) == V) return true;
4879 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
4880 if (SI->getOperand(1) == V) return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +00004881
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00004882 }
Chris Lattnere6f13092004-09-19 19:18:10 +00004883 return false;
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00004884}
4885
Chris Lattner0f1d8a32003-06-26 05:06:25 +00004886Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
4887 Value *Op = LI.getOperand(0);
Chris Lattner7e8af382004-01-12 04:13:56 +00004888
Chris Lattnera9d84e32005-05-01 04:24:53 +00004889 // load (cast X) --> cast (load X) iff safe
4890 if (CastInst *CI = dyn_cast<CastInst>(Op))
4891 if (Instruction *Res = InstCombineLoadCast(*this, LI))
4892 return Res;
4893
4894 // None of the following transforms are legal for volatile loads.
4895 if (LI.isVolatile()) return 0;
4896
4897 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op))
4898 if (isa<ConstantPointerNull>(GEPI->getOperand(0)) ||
4899 isa<UndefValue>(GEPI->getOperand(0))) {
4900 // Insert a new store to null instruction before the load to indicate
4901 // that this code is not reachable. We do this instead of inserting
4902 // an unreachable instruction directly because we cannot modify the
4903 // CFG.
4904 new StoreInst(UndefValue::get(LI.getType()),
4905 Constant::getNullValue(Op->getType()), &LI);
4906 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
4907 }
4908
Chris Lattner81a7a232004-10-16 18:11:37 +00004909 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattnera9d84e32005-05-01 04:24:53 +00004910 // load null/undef -> undef
4911 if ((C->isNullValue() || isa<UndefValue>(C))) {
Chris Lattner8ba9ec92004-10-18 02:59:09 +00004912 // Insert a new store to null instruction before the load to indicate that
4913 // this code is not reachable. We do this instead of inserting an
4914 // unreachable instruction directly because we cannot modify the CFG.
Chris Lattnera9d84e32005-05-01 04:24:53 +00004915 new StoreInst(UndefValue::get(LI.getType()),
4916 Constant::getNullValue(Op->getType()), &LI);
Chris Lattner81a7a232004-10-16 18:11:37 +00004917 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner8ba9ec92004-10-18 02:59:09 +00004918 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00004919
Chris Lattner81a7a232004-10-16 18:11:37 +00004920 // Instcombine load (constant global) into the value loaded.
4921 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
4922 if (GV->isConstant() && !GV->isExternal())
4923 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanb1c93172005-04-21 23:48:37 +00004924
Chris Lattner81a7a232004-10-16 18:11:37 +00004925 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
4926 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
4927 if (CE->getOpcode() == Instruction::GetElementPtr) {
4928 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
4929 if (GV->isConstant() && !GV->isExternal())
4930 if (Constant *V = GetGEPGlobalInitializer(GV->getInitializer(), CE))
4931 return ReplaceInstUsesWith(LI, V);
Chris Lattnera9d84e32005-05-01 04:24:53 +00004932 if (CE->getOperand(0)->isNullValue()) {
4933 // Insert a new store to null instruction before the load to indicate
4934 // that this code is not reachable. We do this instead of inserting
4935 // an unreachable instruction directly because we cannot modify the
4936 // CFG.
4937 new StoreInst(UndefValue::get(LI.getType()),
4938 Constant::getNullValue(Op->getType()), &LI);
4939 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
4940 }
4941
Chris Lattner81a7a232004-10-16 18:11:37 +00004942 } else if (CE->getOpcode() == Instruction::Cast) {
4943 if (Instruction *Res = InstCombineLoadCast(*this, LI))
4944 return Res;
4945 }
4946 }
Chris Lattnere228ee52004-04-08 20:39:49 +00004947
Chris Lattnera9d84e32005-05-01 04:24:53 +00004948 if (Op->hasOneUse()) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00004949 // Change select and PHI nodes to select values instead of addresses: this
4950 // helps alias analysis out a lot, allows many others simplifications, and
4951 // exposes redundancy in the code.
4952 //
4953 // Note that we cannot do the transformation unless we know that the
4954 // introduced loads cannot trap! Something like this is valid as long as
4955 // the condition is always false: load (select bool %C, int* null, int* %G),
4956 // but it would not be valid if we transformed it to load from null
4957 // unconditionally.
4958 //
4959 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
4960 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattnere6f13092004-09-19 19:18:10 +00004961 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
4962 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00004963 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner42618552004-09-20 10:15:10 +00004964 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00004965 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner42618552004-09-20 10:15:10 +00004966 SI->getOperand(2)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00004967 return new SelectInst(SI->getCondition(), V1, V2);
4968 }
4969
Chris Lattnerbdcf41a2004-09-23 15:46:00 +00004970 // load (select (cond, null, P)) -> load P
4971 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
4972 if (C->isNullValue()) {
4973 LI.setOperand(0, SI->getOperand(2));
4974 return &LI;
4975 }
4976
4977 // load (select (cond, P, null)) -> load P
4978 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
4979 if (C->isNullValue()) {
4980 LI.setOperand(0, SI->getOperand(1));
4981 return &LI;
4982 }
4983
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00004984 } else if (PHINode *PN = dyn_cast<PHINode>(Op)) {
4985 // load (phi (&V1, &V2, &V3)) --> phi(load &V1, load &V2, load &V3)
Chris Lattner42618552004-09-20 10:15:10 +00004986 bool Safe = PN->getParent() == LI.getParent();
4987
4988 // Scan all of the instructions between the PHI and the load to make
4989 // sure there are no instructions that might possibly alter the value
4990 // loaded from the PHI.
4991 if (Safe) {
4992 BasicBlock::iterator I = &LI;
4993 for (--I; !isa<PHINode>(I); --I)
4994 if (isa<StoreInst>(I) || isa<CallInst>(I)) {
4995 Safe = false;
4996 break;
4997 }
4998 }
4999
5000 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e && Safe; ++i)
Chris Lattnere6f13092004-09-19 19:18:10 +00005001 if (!isSafeToLoadUnconditionally(PN->getIncomingValue(i),
Chris Lattner42618552004-09-20 10:15:10 +00005002 PN->getIncomingBlock(i)->getTerminator()))
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00005003 Safe = false;
Chris Lattner42618552004-09-20 10:15:10 +00005004
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00005005 if (Safe) {
5006 // Create the PHI.
5007 PHINode *NewPN = new PHINode(LI.getType(), PN->getName());
5008 InsertNewInstBefore(NewPN, *PN);
5009 std::map<BasicBlock*,Value*> LoadMap; // Don't insert duplicate loads
5010
5011 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
5012 BasicBlock *BB = PN->getIncomingBlock(i);
5013 Value *&TheLoad = LoadMap[BB];
5014 if (TheLoad == 0) {
5015 Value *InVal = PN->getIncomingValue(i);
5016 TheLoad = InsertNewInstBefore(new LoadInst(InVal,
5017 InVal->getName()+".val"),
5018 *BB->getTerminator());
5019 }
5020 NewPN->addIncoming(TheLoad, BB);
5021 }
5022 return ReplaceInstUsesWith(LI, NewPN);
5023 }
5024 }
5025 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00005026 return 0;
5027}
5028
Chris Lattner72684fe2005-01-31 05:51:45 +00005029/// InstCombineStoreToCast - Fold 'store V, (cast P)' -> store (cast V), P'
5030/// when possible.
5031static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
5032 User *CI = cast<User>(SI.getOperand(1));
5033 Value *CastOp = CI->getOperand(0);
5034
5035 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
5036 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
5037 const Type *SrcPTy = SrcTy->getElementType();
5038
5039 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
5040 // If the source is an array, the code below will not succeed. Check to
5041 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
5042 // constants.
5043 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
5044 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
5045 if (ASrcTy->getNumElements() != 0) {
5046 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
5047 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
5048 SrcTy = cast<PointerType>(CastOp->getType());
5049 SrcPTy = SrcTy->getElementType();
5050 }
5051
5052 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00005053 IC.getTargetData().getTypeSize(SrcPTy) ==
Chris Lattner72684fe2005-01-31 05:51:45 +00005054 IC.getTargetData().getTypeSize(DestPTy)) {
5055
5056 // Okay, we are casting from one integer or pointer type to another of
5057 // the same size. Instead of casting the pointer before the store, cast
5058 // the value to be stored.
5059 Value *NewCast;
5060 if (Constant *C = dyn_cast<Constant>(SI.getOperand(0)))
5061 NewCast = ConstantExpr::getCast(C, SrcPTy);
5062 else
5063 NewCast = IC.InsertNewInstBefore(new CastInst(SI.getOperand(0),
5064 SrcPTy,
5065 SI.getOperand(0)->getName()+".c"), SI);
5066
5067 return new StoreInst(NewCast, CastOp);
5068 }
5069 }
5070 }
5071 return 0;
5072}
5073
Chris Lattner31f486c2005-01-31 05:36:43 +00005074Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
5075 Value *Val = SI.getOperand(0);
5076 Value *Ptr = SI.getOperand(1);
5077
5078 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
5079 removeFromWorkList(&SI);
5080 SI.eraseFromParent();
5081 ++NumCombined;
5082 return 0;
5083 }
5084
5085 if (SI.isVolatile()) return 0; // Don't hack volatile loads.
5086
5087 // store X, null -> turns into 'unreachable' in SimplifyCFG
5088 if (isa<ConstantPointerNull>(Ptr)) {
5089 if (!isa<UndefValue>(Val)) {
5090 SI.setOperand(0, UndefValue::get(Val->getType()));
5091 if (Instruction *U = dyn_cast<Instruction>(Val))
5092 WorkList.push_back(U); // Dropped a use.
5093 ++NumCombined;
5094 }
5095 return 0; // Do not modify these!
5096 }
5097
5098 // store undef, Ptr -> noop
5099 if (isa<UndefValue>(Val)) {
5100 removeFromWorkList(&SI);
5101 SI.eraseFromParent();
5102 ++NumCombined;
5103 return 0;
5104 }
5105
Chris Lattner72684fe2005-01-31 05:51:45 +00005106 // If the pointer destination is a cast, see if we can fold the cast into the
5107 // source instead.
5108 if (CastInst *CI = dyn_cast<CastInst>(Ptr))
5109 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
5110 return Res;
5111 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
5112 if (CE->getOpcode() == Instruction::Cast)
5113 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
5114 return Res;
5115
Chris Lattner31f486c2005-01-31 05:36:43 +00005116 return 0;
5117}
5118
5119
Chris Lattner9eef8a72003-06-04 04:46:00 +00005120Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
5121 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4fdd96c2005-06-18 17:37:34 +00005122 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00005123 BasicBlock *TrueDest;
5124 BasicBlock *FalseDest;
5125 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
5126 !isa<Constant>(X)) {
5127 // Swap Destinations and condition...
5128 BI.setCondition(X);
5129 BI.setSuccessor(0, FalseDest);
5130 BI.setSuccessor(1, TrueDest);
5131 return &BI;
5132 }
5133
5134 // Cannonicalize setne -> seteq
5135 Instruction::BinaryOps Op; Value *Y;
5136 if (match(&BI, m_Br(m_SetCond(Op, m_Value(X), m_Value(Y)),
5137 TrueDest, FalseDest)))
5138 if ((Op == Instruction::SetNE || Op == Instruction::SetLE ||
5139 Op == Instruction::SetGE) && BI.getCondition()->hasOneUse()) {
5140 SetCondInst *I = cast<SetCondInst>(BI.getCondition());
5141 std::string Name = I->getName(); I->setName("");
5142 Instruction::BinaryOps NewOpcode = SetCondInst::getInverseCondition(Op);
5143 Value *NewSCC = BinaryOperator::create(NewOpcode, X, Y, Name, I);
Chris Lattnere967b342003-06-04 05:10:11 +00005144 // Swap Destinations and condition...
Chris Lattnerd4252a72004-07-30 07:50:03 +00005145 BI.setCondition(NewSCC);
Chris Lattnere967b342003-06-04 05:10:11 +00005146 BI.setSuccessor(0, FalseDest);
5147 BI.setSuccessor(1, TrueDest);
Chris Lattnerd4252a72004-07-30 07:50:03 +00005148 removeFromWorkList(I);
5149 I->getParent()->getInstList().erase(I);
5150 WorkList.push_back(cast<Instruction>(NewSCC));
Chris Lattnere967b342003-06-04 05:10:11 +00005151 return &BI;
5152 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00005153
Chris Lattner9eef8a72003-06-04 04:46:00 +00005154 return 0;
5155}
Chris Lattner1085bdf2002-11-04 16:18:53 +00005156
Chris Lattner4c9c20a2004-07-03 00:26:11 +00005157Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
5158 Value *Cond = SI.getCondition();
5159 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
5160 if (I->getOpcode() == Instruction::Add)
5161 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
5162 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
5163 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattner81a7a232004-10-16 18:11:37 +00005164 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner4c9c20a2004-07-03 00:26:11 +00005165 AddRHS));
5166 SI.setOperand(0, I->getOperand(0));
5167 WorkList.push_back(I);
5168 return &SI;
5169 }
5170 }
5171 return 0;
5172}
5173
Chris Lattnerca081252001-12-14 16:52:21 +00005174
Chris Lattner99f48c62002-09-02 04:59:56 +00005175void InstCombiner::removeFromWorkList(Instruction *I) {
5176 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
5177 WorkList.end());
5178}
5179
Chris Lattner39c98bb2004-12-08 23:43:58 +00005180
5181/// TryToSinkInstruction - Try to move the specified instruction from its
5182/// current block into the beginning of DestBlock, which can only happen if it's
5183/// safe to move the instruction past all of the instructions between it and the
5184/// end of its block.
5185static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
5186 assert(I->hasOneUse() && "Invariants didn't hold!");
5187
5188 // Cannot move control-flow-involving instructions.
5189 if (isa<PHINode>(I) || isa<InvokeInst>(I) || isa<CallInst>(I)) return false;
Misha Brukmanb1c93172005-04-21 23:48:37 +00005190
Chris Lattner39c98bb2004-12-08 23:43:58 +00005191 // Do not sink alloca instructions out of the entry block.
5192 if (isa<AllocaInst>(I) && I->getParent() == &DestBlock->getParent()->front())
5193 return false;
5194
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00005195 // We can only sink load instructions if there is nothing between the load and
5196 // the end of block that could change the value.
5197 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
5198 if (LI->isVolatile()) return false; // Don't sink volatile loads.
5199
5200 for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
5201 Scan != E; ++Scan)
5202 if (Scan->mayWriteToMemory())
5203 return false;
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00005204 }
Chris Lattner39c98bb2004-12-08 23:43:58 +00005205
5206 BasicBlock::iterator InsertPos = DestBlock->begin();
5207 while (isa<PHINode>(InsertPos)) ++InsertPos;
5208
5209 BasicBlock *SrcBlock = I->getParent();
Misha Brukmanb1c93172005-04-21 23:48:37 +00005210 DestBlock->getInstList().splice(InsertPos, SrcBlock->getInstList(), I);
Chris Lattner39c98bb2004-12-08 23:43:58 +00005211 ++NumSunkInst;
5212 return true;
5213}
5214
Chris Lattner113f4f42002-06-25 16:13:24 +00005215bool InstCombiner::runOnFunction(Function &F) {
Chris Lattner260ab202002-04-18 17:39:14 +00005216 bool Changed = false;
Chris Lattnerf4ad1652003-11-02 05:57:39 +00005217 TD = &getAnalysis<TargetData>();
Chris Lattnerca081252001-12-14 16:52:21 +00005218
Chris Lattner4ed40f72005-07-07 20:40:38 +00005219 {
5220 // Populate the worklist with the reachable instructions.
5221 std::set<BasicBlock*> Visited;
5222 for (df_ext_iterator<BasicBlock*> BB = df_ext_begin(&F.front(), Visited),
5223 E = df_ext_end(&F.front(), Visited); BB != E; ++BB)
5224 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
5225 WorkList.push_back(I);
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00005226
Chris Lattner4ed40f72005-07-07 20:40:38 +00005227 // Do a quick scan over the function. If we find any blocks that are
5228 // unreachable, remove any instructions inside of them. This prevents
5229 // the instcombine code from having to deal with some bad special cases.
5230 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
5231 if (!Visited.count(BB)) {
5232 Instruction *Term = BB->getTerminator();
5233 while (Term != BB->begin()) { // Remove instrs bottom-up
5234 BasicBlock::iterator I = Term; --I;
Chris Lattner2d3a7a62004-04-27 15:13:33 +00005235
Chris Lattner4ed40f72005-07-07 20:40:38 +00005236 DEBUG(std::cerr << "IC: DCE: " << *I);
5237 ++NumDeadInst;
5238
5239 if (!I->use_empty())
5240 I->replaceAllUsesWith(UndefValue::get(I->getType()));
5241 I->eraseFromParent();
5242 }
5243 }
5244 }
Chris Lattnerca081252001-12-14 16:52:21 +00005245
5246 while (!WorkList.empty()) {
5247 Instruction *I = WorkList.back(); // Get an instruction from the worklist
5248 WorkList.pop_back();
5249
Misha Brukman632df282002-10-29 23:06:16 +00005250 // Check to see if we can DCE or ConstantPropagate the instruction...
Chris Lattner99f48c62002-09-02 04:59:56 +00005251 // Check to see if we can DIE the instruction...
5252 if (isInstructionTriviallyDead(I)) {
5253 // Add operands to the worklist...
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00005254 if (I->getNumOperands() < 4)
Chris Lattner51ea1272004-02-28 05:22:00 +00005255 AddUsesToWorkList(*I);
Chris Lattner99f48c62002-09-02 04:59:56 +00005256 ++NumDeadInst;
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00005257
Chris Lattnercd517ff2005-01-28 19:32:01 +00005258 DEBUG(std::cerr << "IC: DCE: " << *I);
5259
5260 I->eraseFromParent();
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00005261 removeFromWorkList(I);
5262 continue;
5263 }
Chris Lattner99f48c62002-09-02 04:59:56 +00005264
Misha Brukman632df282002-10-29 23:06:16 +00005265 // Instruction isn't dead, see if we can constant propagate it...
Chris Lattner99f48c62002-09-02 04:59:56 +00005266 if (Constant *C = ConstantFoldInstruction(I)) {
Alkis Evlogimenosa1291a02004-12-08 23:10:30 +00005267 Value* Ptr = I->getOperand(0);
Chris Lattner6580e092004-10-16 19:44:59 +00005268 if (isa<GetElementPtrInst>(I) &&
Alkis Evlogimenosa1291a02004-12-08 23:10:30 +00005269 cast<Constant>(Ptr)->isNullValue() &&
5270 !isa<ConstantPointerNull>(C) &&
5271 cast<PointerType>(Ptr->getType())->getElementType()->isSized()) {
Chris Lattner6580e092004-10-16 19:44:59 +00005272 // If this is a constant expr gep that is effectively computing an
5273 // "offsetof", fold it into 'cast int X to T*' instead of 'gep 0, 0, 12'
5274 bool isFoldableGEP = true;
5275 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i)
5276 if (!isa<ConstantInt>(I->getOperand(i)))
5277 isFoldableGEP = false;
5278 if (isFoldableGEP) {
Alkis Evlogimenosa1291a02004-12-08 23:10:30 +00005279 uint64_t Offset = TD->getIndexedOffset(Ptr->getType(),
Chris Lattner6580e092004-10-16 19:44:59 +00005280 std::vector<Value*>(I->op_begin()+1, I->op_end()));
5281 C = ConstantUInt::get(Type::ULongTy, Offset);
Chris Lattner684c5c62004-10-16 19:46:33 +00005282 C = ConstantExpr::getCast(C, TD->getIntPtrType());
Chris Lattner6580e092004-10-16 19:44:59 +00005283 C = ConstantExpr::getCast(C, I->getType());
5284 }
5285 }
5286
Chris Lattnercd517ff2005-01-28 19:32:01 +00005287 DEBUG(std::cerr << "IC: ConstFold to: " << *C << " from: " << *I);
5288
Chris Lattner99f48c62002-09-02 04:59:56 +00005289 // Add operands to the worklist...
Chris Lattner51ea1272004-02-28 05:22:00 +00005290 AddUsesToWorkList(*I);
Chris Lattnerc6509f42002-12-05 22:41:53 +00005291 ReplaceInstUsesWith(*I, C);
5292
Chris Lattner99f48c62002-09-02 04:59:56 +00005293 ++NumConstProp;
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00005294 I->getParent()->getInstList().erase(I);
Chris Lattner800aaaf2003-10-07 15:17:02 +00005295 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00005296 continue;
Chris Lattner99f48c62002-09-02 04:59:56 +00005297 }
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00005298
Chris Lattner39c98bb2004-12-08 23:43:58 +00005299 // See if we can trivially sink this instruction to a successor basic block.
5300 if (I->hasOneUse()) {
5301 BasicBlock *BB = I->getParent();
5302 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
5303 if (UserParent != BB) {
5304 bool UserIsSuccessor = false;
5305 // See if the user is one of our successors.
5306 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
5307 if (*SI == UserParent) {
5308 UserIsSuccessor = true;
5309 break;
5310 }
5311
5312 // If the user is one of our immediate successors, and if that successor
5313 // only has us as a predecessors (we'd have to split the critical edge
5314 // otherwise), we can keep going.
5315 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
5316 next(pred_begin(UserParent)) == pred_end(UserParent))
5317 // Okay, the CFG is simple enough, try to sink this instruction.
5318 Changed |= TryToSinkInstruction(I, UserParent);
5319 }
5320 }
5321
Chris Lattnerca081252001-12-14 16:52:21 +00005322 // Now that we have an instruction, try combining it to simplify it...
Chris Lattnerae7a0d32002-08-02 19:29:35 +00005323 if (Instruction *Result = visit(*I)) {
Chris Lattner0b18c1d2002-05-10 15:38:35 +00005324 ++NumCombined;
Chris Lattner260ab202002-04-18 17:39:14 +00005325 // Should we replace the old instruction with a new one?
Chris Lattner053c0932002-05-14 15:24:07 +00005326 if (Result != I) {
Chris Lattner7d2a5392004-03-13 23:54:27 +00005327 DEBUG(std::cerr << "IC: Old = " << *I
5328 << " New = " << *Result);
5329
Chris Lattner396dbfe2004-06-09 05:08:07 +00005330 // Everything uses the new instruction now.
5331 I->replaceAllUsesWith(Result);
5332
5333 // Push the new instruction and any users onto the worklist.
5334 WorkList.push_back(Result);
5335 AddUsersToWorkList(*Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00005336
5337 // Move the name to the new instruction first...
5338 std::string OldName = I->getName(); I->setName("");
Chris Lattner950fc782003-10-07 22:58:41 +00005339 Result->setName(OldName);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00005340
5341 // Insert the new instruction into the basic block...
5342 BasicBlock *InstParent = I->getParent();
Chris Lattner7515cab2004-11-14 19:13:23 +00005343 BasicBlock::iterator InsertPos = I;
5344
5345 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
5346 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
5347 ++InsertPos;
5348
5349 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00005350
Chris Lattner63d75af2004-05-01 23:27:23 +00005351 // Make sure that we reprocess all operands now that we reduced their
5352 // use counts.
Chris Lattnerb643a9e2004-05-01 23:19:52 +00005353 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
5354 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
5355 WorkList.push_back(OpI);
5356
Chris Lattner396dbfe2004-06-09 05:08:07 +00005357 // Instructions can end up on the worklist more than once. Make sure
5358 // we do not process an instruction that has been deleted.
5359 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00005360
5361 // Erase the old instruction.
5362 InstParent->getInstList().erase(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00005363 } else {
Chris Lattner7d2a5392004-03-13 23:54:27 +00005364 DEBUG(std::cerr << "IC: MOD = " << *I);
5365
Chris Lattnerae7a0d32002-08-02 19:29:35 +00005366 // If the instruction was modified, it's possible that it is now dead.
5367 // if so, remove it.
Chris Lattner63d75af2004-05-01 23:27:23 +00005368 if (isInstructionTriviallyDead(I)) {
5369 // Make sure we process all operands now that we are reducing their
5370 // use counts.
5371 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
5372 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
5373 WorkList.push_back(OpI);
Misha Brukmanb1c93172005-04-21 23:48:37 +00005374
Chris Lattner63d75af2004-05-01 23:27:23 +00005375 // Instructions may end up in the worklist more than once. Erase all
5376 // occurrances of this instruction.
Chris Lattner99f48c62002-09-02 04:59:56 +00005377 removeFromWorkList(I);
Chris Lattner31f486c2005-01-31 05:36:43 +00005378 I->eraseFromParent();
Chris Lattner396dbfe2004-06-09 05:08:07 +00005379 } else {
5380 WorkList.push_back(Result);
5381 AddUsersToWorkList(*Result);
Chris Lattnerae7a0d32002-08-02 19:29:35 +00005382 }
Chris Lattner053c0932002-05-14 15:24:07 +00005383 }
Chris Lattner260ab202002-04-18 17:39:14 +00005384 Changed = true;
Chris Lattnerca081252001-12-14 16:52:21 +00005385 }
5386 }
5387
Chris Lattner260ab202002-04-18 17:39:14 +00005388 return Changed;
Chris Lattner04805fa2002-02-26 21:46:54 +00005389}
5390
Brian Gaeke38b79e82004-07-27 17:43:21 +00005391FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattner260ab202002-04-18 17:39:14 +00005392 return new InstCombiner();
Chris Lattner04805fa2002-02-26 21:46:54 +00005393}
Brian Gaeke960707c2003-11-11 22:41:34 +00005394