blob: d2827af3d74def1f6026682d295f7390cd576cdc [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 Lattner60a65912002-02-12 21:07:25 +000048#include "llvm/Support/InstIterator.h"
Chris Lattner260ab202002-04-18 17:39:14 +000049#include "llvm/Support/InstVisitor.h"
Chris Lattnerd4252a72004-07-30 07:50:03 +000050#include "llvm/Support/PatternMatch.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000051#include "llvm/ADT/Statistic.h"
Chris Lattner39c98bb2004-12-08 23:43:58 +000052#include "llvm/ADT/STLExtras.h"
Chris Lattner053c0932002-05-14 15:24:07 +000053#include <algorithm>
Chris Lattner8427bff2003-12-07 01:24:23 +000054using namespace llvm;
Chris Lattnerd4252a72004-07-30 07:50:03 +000055using namespace llvm::PatternMatch;
Brian Gaeke960707c2003-11-11 22:41:34 +000056
Chris Lattner260ab202002-04-18 17:39:14 +000057namespace {
Chris Lattnerbf3a0992002-10-01 22:38:41 +000058 Statistic<> NumCombined ("instcombine", "Number of insts combined");
59 Statistic<> NumConstProp("instcombine", "Number of constant folds");
60 Statistic<> NumDeadInst ("instcombine", "Number of dead inst eliminated");
Chris Lattner39c98bb2004-12-08 23:43:58 +000061 Statistic<> NumSunkInst ("instcombine", "Number of instructions sunk");
Chris Lattnerbf3a0992002-10-01 22:38:41 +000062
Chris Lattnerc8e66542002-04-27 06:56:12 +000063 class InstCombiner : public FunctionPass,
Chris Lattner260ab202002-04-18 17:39:14 +000064 public InstVisitor<InstCombiner, Instruction*> {
65 // Worklist of all of the instructions that need to be simplified.
66 std::vector<Instruction*> WorkList;
Chris Lattnerf4ad1652003-11-02 05:57:39 +000067 TargetData *TD;
Chris Lattner260ab202002-04-18 17:39:14 +000068
Chris Lattner51ea1272004-02-28 05:22:00 +000069 /// AddUsersToWorkList - When an instruction is simplified, add all users of
70 /// the instruction to the work lists because they might get more simplified
71 /// now.
72 ///
73 void AddUsersToWorkList(Instruction &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +000074 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
Chris Lattner260ab202002-04-18 17:39:14 +000075 UI != UE; ++UI)
76 WorkList.push_back(cast<Instruction>(*UI));
77 }
78
Chris Lattner51ea1272004-02-28 05:22:00 +000079 /// AddUsesToWorkList - When an instruction is simplified, add operands to
80 /// the work lists because they might get more simplified now.
81 ///
82 void AddUsesToWorkList(Instruction &I) {
83 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
84 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i)))
85 WorkList.push_back(Op);
86 }
87
Chris Lattner99f48c62002-09-02 04:59:56 +000088 // removeFromWorkList - remove all instances of I from the worklist.
89 void removeFromWorkList(Instruction *I);
Chris Lattner260ab202002-04-18 17:39:14 +000090 public:
Chris Lattner113f4f42002-06-25 16:13:24 +000091 virtual bool runOnFunction(Function &F);
Chris Lattner260ab202002-04-18 17:39:14 +000092
Chris Lattnerf12cc842002-04-28 21:27:06 +000093 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnerf4ad1652003-11-02 05:57:39 +000094 AU.addRequired<TargetData>();
Chris Lattner820d9712002-10-21 20:00:28 +000095 AU.setPreservesCFG();
Chris Lattnerf12cc842002-04-28 21:27:06 +000096 }
97
Chris Lattner69193f92004-04-05 01:30:19 +000098 TargetData &getTargetData() const { return *TD; }
99
Chris Lattner260ab202002-04-18 17:39:14 +0000100 // Visitation implementation - Implement instruction combining for different
101 // instruction types. The semantics are as follows:
102 // Return Value:
103 // null - No change was made
Chris Lattnere6794492002-08-12 21:17:25 +0000104 // I - Change was made, I is still valid, I may be dead though
Chris Lattner260ab202002-04-18 17:39:14 +0000105 // otherwise - Change was made, replace I with returned instruction
Misha Brukmanb1c93172005-04-21 23:48:37 +0000106 //
Chris Lattner113f4f42002-06-25 16:13:24 +0000107 Instruction *visitAdd(BinaryOperator &I);
108 Instruction *visitSub(BinaryOperator &I);
109 Instruction *visitMul(BinaryOperator &I);
110 Instruction *visitDiv(BinaryOperator &I);
111 Instruction *visitRem(BinaryOperator &I);
112 Instruction *visitAnd(BinaryOperator &I);
113 Instruction *visitOr (BinaryOperator &I);
114 Instruction *visitXor(BinaryOperator &I);
Chris Lattnerd1f46d32005-04-24 06:59:08 +0000115 Instruction *visitSetCondInst(SetCondInst &I);
116 Instruction *visitSetCondInstWithCastAndCast(SetCondInst &SCI);
117
Chris Lattner0798af32005-01-13 20:14:25 +0000118 Instruction *FoldGEPSetCC(User *GEPLHS, Value *RHS,
119 Instruction::BinaryOps Cond, Instruction &I);
Chris Lattnere8d6c602003-03-10 19:16:08 +0000120 Instruction *visitShiftInst(ShiftInst &I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000121 Instruction *visitCastInst(CastInst &CI);
Chris Lattner411336f2005-01-19 21:50:18 +0000122 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
123 Instruction *FI);
Chris Lattnerb909e8b2004-03-12 05:52:32 +0000124 Instruction *visitSelectInst(SelectInst &CI);
Chris Lattner970c33a2003-06-19 17:00:31 +0000125 Instruction *visitCallInst(CallInst &CI);
126 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner113f4f42002-06-25 16:13:24 +0000127 Instruction *visitPHINode(PHINode &PN);
128 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Chris Lattner1085bdf2002-11-04 16:18:53 +0000129 Instruction *visitAllocationInst(AllocationInst &AI);
Chris Lattner8427bff2003-12-07 01:24:23 +0000130 Instruction *visitFreeInst(FreeInst &FI);
Chris Lattner0f1d8a32003-06-26 05:06:25 +0000131 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattner31f486c2005-01-31 05:36:43 +0000132 Instruction *visitStoreInst(StoreInst &SI);
Chris Lattner9eef8a72003-06-04 04:46:00 +0000133 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner4c9c20a2004-07-03 00:26:11 +0000134 Instruction *visitSwitchInst(SwitchInst &SI);
Chris Lattner260ab202002-04-18 17:39:14 +0000135
136 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner113f4f42002-06-25 16:13:24 +0000137 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000138
Chris Lattner970c33a2003-06-19 17:00:31 +0000139 private:
Chris Lattneraec3d942003-10-07 22:32:43 +0000140 Instruction *visitCallSite(CallSite CS);
Chris Lattner970c33a2003-06-19 17:00:31 +0000141 bool transformConstExprCastCall(CallSite CS);
142
Chris Lattner69193f92004-04-05 01:30:19 +0000143 public:
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000144 // InsertNewInstBefore - insert an instruction New before instruction Old
145 // in the program. Add the new instruction to the worklist.
146 //
Chris Lattner623826c2004-09-28 21:48:02 +0000147 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattner65217ff2002-08-23 18:32:43 +0000148 assert(New && New->getParent() == 0 &&
149 "New instruction already inserted into a basic block!");
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000150 BasicBlock *BB = Old.getParent();
151 BB->getInstList().insert(&Old, New); // Insert inst
152 WorkList.push_back(New); // Add to worklist
Chris Lattnere79e8542004-02-23 06:38:22 +0000153 return New;
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000154 }
155
Chris Lattner7e794272004-09-24 15:21:34 +0000156 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
157 /// This also adds the cast to the worklist. Finally, this returns the
158 /// cast.
159 Value *InsertCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
160 if (V->getType() == Ty) return V;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000161
Chris Lattner7e794272004-09-24 15:21:34 +0000162 Instruction *C = new CastInst(V, Ty, V->getName(), &Pos);
163 WorkList.push_back(C);
164 return C;
165 }
166
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000167 // ReplaceInstUsesWith - This method is to be used when an instruction is
168 // found to be dead, replacable with another preexisting expression. Here
169 // we add all uses of I to the worklist, replace all uses of I with the new
170 // value, then return I, so that the inst combiner will know that I was
171 // modified.
172 //
173 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattner51ea1272004-02-28 05:22:00 +0000174 AddUsersToWorkList(I); // Add all modified instrs to worklist
Chris Lattner8953b902004-04-05 02:10:19 +0000175 if (&I != V) {
176 I.replaceAllUsesWith(V);
177 return &I;
178 } else {
179 // If we are replacing the instruction with itself, this must be in a
180 // segment of unreachable code, so just clobber the instruction.
Chris Lattner8ba9ec92004-10-18 02:59:09 +0000181 I.replaceAllUsesWith(UndefValue::get(I.getType()));
Chris Lattner8953b902004-04-05 02:10:19 +0000182 return &I;
183 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000184 }
Chris Lattner51ea1272004-02-28 05:22:00 +0000185
186 // EraseInstFromFunction - When dealing with an instruction that has side
187 // effects or produces a void value, we can't rely on DCE to delete the
188 // instruction. Instead, visit methods should return the value returned by
189 // this function.
190 Instruction *EraseInstFromFunction(Instruction &I) {
191 assert(I.use_empty() && "Cannot erase instruction that is used!");
192 AddUsesToWorkList(I);
193 removeFromWorkList(&I);
Chris Lattner95307542004-11-18 21:41:39 +0000194 I.eraseFromParent();
Chris Lattner51ea1272004-02-28 05:22:00 +0000195 return 0; // Don't do anything with FI
196 }
197
198
Chris Lattner3ac7c262003-08-13 20:16:26 +0000199 private:
Chris Lattnerdfae8be2003-07-24 17:35:25 +0000200 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
201 /// InsertBefore instruction. This is specialized a bit to avoid inserting
202 /// casts that are known to not do anything...
203 ///
204 Value *InsertOperandCastBefore(Value *V, const Type *DestTy,
205 Instruction *InsertBefore);
206
Chris Lattner7fb29e12003-03-11 00:12:48 +0000207 // SimplifyCommutative - This performs a few simplifications for commutative
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000208 // operators.
Chris Lattner7fb29e12003-03-11 00:12:48 +0000209 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerba1cb382003-09-19 17:17:26 +0000210
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000211
212 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
213 // PHI node as operand #0, see if we can fold the instruction into the PHI
214 // (which is only possible if all operands to the PHI are constants).
215 Instruction *FoldOpIntoPhi(Instruction &I);
216
Chris Lattner7515cab2004-11-14 19:13:23 +0000217 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
218 // operator and they all are only used by the PHI, PHI together their
219 // inputs, and do the operation once, to the result of the PHI.
220 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
221
Chris Lattnerba1cb382003-09-19 17:17:26 +0000222 Instruction *OptAndOp(Instruction *Op, ConstantIntegral *OpRHS,
223 ConstantIntegral *AndRHS, BinaryOperator &TheAnd);
Chris Lattner6862fbd2004-09-29 17:40:11 +0000224
225 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
226 bool Inside, Instruction &IB);
Chris Lattner260ab202002-04-18 17:39:14 +0000227 };
Chris Lattnerb28b6802002-07-23 18:06:35 +0000228
Chris Lattnerc8b70922002-07-26 21:12:46 +0000229 RegisterOpt<InstCombiner> X("instcombine", "Combine redundant instructions");
Chris Lattner260ab202002-04-18 17:39:14 +0000230}
231
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000232// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattner81a7a232004-10-16 18:11:37 +0000233// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000234static unsigned getComplexity(Value *V) {
235 if (isa<Instruction>(V)) {
236 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
Chris Lattner81a7a232004-10-16 18:11:37 +0000237 return 3;
238 return 4;
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000239 }
Chris Lattner81a7a232004-10-16 18:11:37 +0000240 if (isa<Argument>(V)) return 3;
241 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000242}
Chris Lattner260ab202002-04-18 17:39:14 +0000243
Chris Lattner7fb29e12003-03-11 00:12:48 +0000244// isOnlyUse - Return true if this instruction will be deleted if we stop using
245// it.
246static bool isOnlyUse(Value *V) {
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000247 return V->hasOneUse() || isa<Constant>(V);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000248}
249
Chris Lattnere79e8542004-02-23 06:38:22 +0000250// getPromotedType - Return the specified type promoted as it would be to pass
251// though a va_arg area...
252static const Type *getPromotedType(const Type *Ty) {
Chris Lattner97bfcea2004-06-17 18:16:02 +0000253 switch (Ty->getTypeID()) {
Chris Lattnere79e8542004-02-23 06:38:22 +0000254 case Type::SByteTyID:
255 case Type::ShortTyID: return Type::IntTy;
256 case Type::UByteTyID:
257 case Type::UShortTyID: return Type::UIntTy;
258 case Type::FloatTyID: return Type::DoubleTy;
259 default: return Ty;
260 }
261}
262
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000263// SimplifyCommutative - This performs a few simplifications for commutative
264// operators:
Chris Lattner260ab202002-04-18 17:39:14 +0000265//
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000266// 1. Order operands such that they are listed from right (least complex) to
267// left (most complex). This puts constants before unary operators before
268// binary operators.
269//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000270// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
271// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000272//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000273bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000274 bool Changed = false;
275 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
276 Changed = !I.swapOperands();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000277
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000278 if (!I.isAssociative()) return Changed;
279 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattner7fb29e12003-03-11 00:12:48 +0000280 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
281 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
282 if (isa<Constant>(I.getOperand(1))) {
Chris Lattner34428442003-05-27 16:40:51 +0000283 Constant *Folded = ConstantExpr::get(I.getOpcode(),
284 cast<Constant>(I.getOperand(1)),
285 cast<Constant>(Op->getOperand(1)));
Chris Lattner7fb29e12003-03-11 00:12:48 +0000286 I.setOperand(0, Op->getOperand(0));
287 I.setOperand(1, Folded);
288 return true;
289 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
290 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
291 isOnlyUse(Op) && isOnlyUse(Op1)) {
292 Constant *C1 = cast<Constant>(Op->getOperand(1));
293 Constant *C2 = cast<Constant>(Op1->getOperand(1));
294
295 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner34428442003-05-27 16:40:51 +0000296 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000297 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
298 Op1->getOperand(0),
299 Op1->getName(), &I);
300 WorkList.push_back(New);
301 I.setOperand(0, New);
302 I.setOperand(1, Folded);
303 return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000304 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000305 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000306 return Changed;
Chris Lattner260ab202002-04-18 17:39:14 +0000307}
Chris Lattnerca081252001-12-14 16:52:21 +0000308
Chris Lattnerbb74e222003-03-10 23:06:50 +0000309// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
310// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattner9fa53de2002-05-06 16:49:18 +0000311//
Chris Lattnerbb74e222003-03-10 23:06:50 +0000312static inline Value *dyn_castNegVal(Value *V) {
313 if (BinaryOperator::isNeg(V))
Chris Lattnerd6f636a2005-04-24 07:30:14 +0000314 return BinaryOperator::getNegArgument(V);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000315
Chris Lattner9ad0d552004-12-14 20:08:06 +0000316 // Constants can be considered to be negated values if they can be folded.
317 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
318 return ConstantExpr::getNeg(C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000319 return 0;
Chris Lattner9fa53de2002-05-06 16:49:18 +0000320}
321
Chris Lattnerbb74e222003-03-10 23:06:50 +0000322static inline Value *dyn_castNotVal(Value *V) {
323 if (BinaryOperator::isNot(V))
Chris Lattnerd6f636a2005-04-24 07:30:14 +0000324 return BinaryOperator::getNotArgument(V);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000325
326 // Constants can be considered to be not'ed values...
Chris Lattnerdd65d862003-04-30 22:34:06 +0000327 if (ConstantIntegral *C = dyn_cast<ConstantIntegral>(V))
Chris Lattnerc8e7e292004-06-10 02:12:35 +0000328 return ConstantExpr::getNot(C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000329 return 0;
330}
331
Chris Lattner7fb29e12003-03-11 00:12:48 +0000332// dyn_castFoldableMul - If this value is a multiply that can be folded into
333// other computations (because it has a constant operand), return the
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000334// non-constant operand of the multiply, and set CST to point to the multiplier.
335// Otherwise, return null.
Chris Lattner7fb29e12003-03-11 00:12:48 +0000336//
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000337static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000338 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000339 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattner7fb29e12003-03-11 00:12:48 +0000340 if (I->getOpcode() == Instruction::Mul)
Chris Lattner970136362004-11-15 05:54:07 +0000341 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattner7fb29e12003-03-11 00:12:48 +0000342 return I->getOperand(0);
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000343 if (I->getOpcode() == Instruction::Shl)
Chris Lattner970136362004-11-15 05:54:07 +0000344 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000345 // The multiplier is really 1 << CST.
346 Constant *One = ConstantInt::get(V->getType(), 1);
347 CST = cast<ConstantInt>(ConstantExpr::getShl(One, CST));
348 return I->getOperand(0);
349 }
350 }
Chris Lattner7fb29e12003-03-11 00:12:48 +0000351 return 0;
Chris Lattner3082c5a2003-02-18 19:28:33 +0000352}
Chris Lattner31ae8632002-08-14 17:51:49 +0000353
Chris Lattner0798af32005-01-13 20:14:25 +0000354/// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
355/// expression, return it.
356static User *dyn_castGetElementPtr(Value *V) {
357 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
358 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
359 if (CE->getOpcode() == Instruction::GetElementPtr)
360 return cast<User>(V);
361 return false;
362}
363
Chris Lattner3082c5a2003-02-18 19:28:33 +0000364// Log2 - Calculate the log base 2 for the specified value if it is exactly a
365// power of 2.
366static unsigned Log2(uint64_t Val) {
367 assert(Val > 1 && "Values 0 and 1 should be handled elsewhere!");
368 unsigned Count = 0;
369 while (Val != 1) {
370 if (Val & 1) return 0; // Multiple bits set?
371 Val >>= 1;
372 ++Count;
373 }
374 return Count;
Chris Lattner31ae8632002-08-14 17:51:49 +0000375}
376
Chris Lattner623826c2004-09-28 21:48:02 +0000377// AddOne, SubOne - Add or subtract a constant one from an integer constant...
Chris Lattner6862fbd2004-09-29 17:40:11 +0000378static ConstantInt *AddOne(ConstantInt *C) {
379 return cast<ConstantInt>(ConstantExpr::getAdd(C,
380 ConstantInt::get(C->getType(), 1)));
Chris Lattner623826c2004-09-28 21:48:02 +0000381}
Chris Lattner6862fbd2004-09-29 17:40:11 +0000382static ConstantInt *SubOne(ConstantInt *C) {
383 return cast<ConstantInt>(ConstantExpr::getSub(C,
384 ConstantInt::get(C->getType(), 1)));
Chris Lattner623826c2004-09-28 21:48:02 +0000385}
386
387// isTrueWhenEqual - Return true if the specified setcondinst instruction is
388// true when both operands are equal...
389//
390static bool isTrueWhenEqual(Instruction &I) {
391 return I.getOpcode() == Instruction::SetEQ ||
392 I.getOpcode() == Instruction::SetGE ||
393 I.getOpcode() == Instruction::SetLE;
394}
Chris Lattnerb8b97502003-08-13 19:01:45 +0000395
396/// AssociativeOpt - Perform an optimization on an associative operator. This
397/// function is designed to check a chain of associative operators for a
398/// potential to apply a certain optimization. Since the optimization may be
399/// applicable if the expression was reassociated, this checks the chain, then
400/// reassociates the expression as necessary to expose the optimization
401/// opportunity. This makes use of a special Functor, which must define
402/// 'shouldApply' and 'apply' methods.
403///
404template<typename Functor>
405Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
406 unsigned Opcode = Root.getOpcode();
407 Value *LHS = Root.getOperand(0);
408
409 // Quick check, see if the immediate LHS matches...
410 if (F.shouldApply(LHS))
411 return F.apply(Root);
412
413 // Otherwise, if the LHS is not of the same opcode as the root, return.
414 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000415 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattnerb8b97502003-08-13 19:01:45 +0000416 // Should we apply this transform to the RHS?
417 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
418
419 // If not to the RHS, check to see if we should apply to the LHS...
420 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
421 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
422 ShouldApply = true;
423 }
424
425 // If the functor wants to apply the optimization to the RHS of LHSI,
426 // reassociate the expression from ((? op A) op B) to (? op (A op B))
427 if (ShouldApply) {
428 BasicBlock *BB = Root.getParent();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000429
Chris Lattnerb8b97502003-08-13 19:01:45 +0000430 // Now all of the instructions are in the current basic block, go ahead
431 // and perform the reassociation.
432 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
433
434 // First move the selected RHS to the LHS of the root...
435 Root.setOperand(0, LHSI->getOperand(1));
436
437 // Make what used to be the LHS of the root be the user of the root...
438 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner284d3b02004-04-16 18:08:07 +0000439 if (&Root == TmpLHSI) {
Chris Lattner8953b902004-04-05 02:10:19 +0000440 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
441 return 0;
442 }
Chris Lattner284d3b02004-04-16 18:08:07 +0000443 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattnerb8b97502003-08-13 19:01:45 +0000444 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner284d3b02004-04-16 18:08:07 +0000445 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
446 BasicBlock::iterator ARI = &Root; ++ARI;
447 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
448 ARI = Root;
Chris Lattnerb8b97502003-08-13 19:01:45 +0000449
450 // Now propagate the ExtraOperand down the chain of instructions until we
451 // get to LHSI.
452 while (TmpLHSI != LHSI) {
453 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner284d3b02004-04-16 18:08:07 +0000454 // Move the instruction to immediately before the chain we are
455 // constructing to avoid breaking dominance properties.
456 NextLHSI->getParent()->getInstList().remove(NextLHSI);
457 BB->getInstList().insert(ARI, NextLHSI);
458 ARI = NextLHSI;
459
Chris Lattnerb8b97502003-08-13 19:01:45 +0000460 Value *NextOp = NextLHSI->getOperand(1);
461 NextLHSI->setOperand(1, ExtraOperand);
462 TmpLHSI = NextLHSI;
463 ExtraOperand = NextOp;
464 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000465
Chris Lattnerb8b97502003-08-13 19:01:45 +0000466 // Now that the instructions are reassociated, have the functor perform
467 // the transformation...
468 return F.apply(Root);
469 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000470
Chris Lattnerb8b97502003-08-13 19:01:45 +0000471 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
472 }
473 return 0;
474}
475
476
477// AddRHS - Implements: X + X --> X << 1
478struct AddRHS {
479 Value *RHS;
480 AddRHS(Value *rhs) : RHS(rhs) {}
481 bool shouldApply(Value *LHS) const { return LHS == RHS; }
482 Instruction *apply(BinaryOperator &Add) const {
483 return new ShiftInst(Instruction::Shl, Add.getOperand(0),
484 ConstantInt::get(Type::UByteTy, 1));
485 }
486};
487
488// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
489// iff C1&C2 == 0
490struct AddMaskingAnd {
491 Constant *C2;
492 AddMaskingAnd(Constant *c) : C2(c) {}
493 bool shouldApply(Value *LHS) const {
Chris Lattnerd4252a72004-07-30 07:50:03 +0000494 ConstantInt *C1;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000495 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Chris Lattnerd4252a72004-07-30 07:50:03 +0000496 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattnerb8b97502003-08-13 19:01:45 +0000497 }
498 Instruction *apply(BinaryOperator &Add) const {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000499 return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattnerb8b97502003-08-13 19:01:45 +0000500 }
501};
502
Chris Lattner86102b82005-01-01 16:22:27 +0000503static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner183b3362004-04-09 19:05:30 +0000504 InstCombiner *IC) {
Chris Lattner86102b82005-01-01 16:22:27 +0000505 if (isa<CastInst>(I)) {
506 if (Constant *SOC = dyn_cast<Constant>(SO))
507 return ConstantExpr::getCast(SOC, I.getType());
Misha Brukmanb1c93172005-04-21 23:48:37 +0000508
Chris Lattner86102b82005-01-01 16:22:27 +0000509 return IC->InsertNewInstBefore(new CastInst(SO, I.getType(),
510 SO->getName() + ".cast"), I);
511 }
512
Chris Lattner183b3362004-04-09 19:05:30 +0000513 // Figure out if the constant is the left or the right argument.
Chris Lattner86102b82005-01-01 16:22:27 +0000514 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
515 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattnerb8b97502003-08-13 19:01:45 +0000516
Chris Lattner183b3362004-04-09 19:05:30 +0000517 if (Constant *SOC = dyn_cast<Constant>(SO)) {
518 if (ConstIsRHS)
Chris Lattner86102b82005-01-01 16:22:27 +0000519 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
520 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner183b3362004-04-09 19:05:30 +0000521 }
522
523 Value *Op0 = SO, *Op1 = ConstOperand;
524 if (!ConstIsRHS)
525 std::swap(Op0, Op1);
526 Instruction *New;
Chris Lattner86102b82005-01-01 16:22:27 +0000527 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
528 New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
529 else if (ShiftInst *SI = dyn_cast<ShiftInst>(&I))
530 New = new ShiftInst(SI->getOpcode(), Op0, Op1, SO->getName()+".sh");
Chris Lattnerf9d96652004-04-10 19:15:56 +0000531 else {
Chris Lattner183b3362004-04-09 19:05:30 +0000532 assert(0 && "Unknown binary instruction type!");
Chris Lattnerf9d96652004-04-10 19:15:56 +0000533 abort();
534 }
Chris Lattner86102b82005-01-01 16:22:27 +0000535 return IC->InsertNewInstBefore(New, I);
536}
537
538// FoldOpIntoSelect - Given an instruction with a select as one operand and a
539// constant as the other operand, try to fold the binary operator into the
540// select arguments. This also works for Cast instructions, which obviously do
541// not have a second operand.
542static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
543 InstCombiner *IC) {
544 // Don't modify shared select instructions
545 if (!SI->hasOneUse()) return 0;
546 Value *TV = SI->getOperand(1);
547 Value *FV = SI->getOperand(2);
548
549 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner374e6592005-04-21 05:43:13 +0000550 // Bool selects with constant operands can be folded to logical ops.
551 if (SI->getType() == Type::BoolTy) return 0;
552
Chris Lattner86102b82005-01-01 16:22:27 +0000553 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
554 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
555
556 return new SelectInst(SI->getCondition(), SelectTrueVal,
557 SelectFalseVal);
558 }
559 return 0;
Chris Lattner183b3362004-04-09 19:05:30 +0000560}
561
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000562
563/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
564/// node as operand #0, see if we can fold the instruction into the PHI (which
565/// is only possible if all operands to the PHI are constants).
566Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
567 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattner7515cab2004-11-14 19:13:23 +0000568 unsigned NumPHIValues = PN->getNumIncomingValues();
569 if (!PN->hasOneUse() || NumPHIValues == 0 ||
570 !isa<Constant>(PN->getIncomingValue(0))) return 0;
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000571
572 // Check to see if all of the operands of the PHI are constants. If not, we
573 // cannot do the transformation.
Chris Lattner7515cab2004-11-14 19:13:23 +0000574 for (unsigned i = 1; i != NumPHIValues; ++i)
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000575 if (!isa<Constant>(PN->getIncomingValue(i)))
576 return 0;
577
578 // Okay, we can do the transformation: create the new PHI node.
579 PHINode *NewPN = new PHINode(I.getType(), I.getName());
580 I.setName("");
Chris Lattnerd8e20182005-01-29 00:39:08 +0000581 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000582 InsertNewInstBefore(NewPN, *PN);
583
584 // Next, add all of the operands to the PHI.
585 if (I.getNumOperands() == 2) {
586 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattner7515cab2004-11-14 19:13:23 +0000587 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000588 Constant *InV = cast<Constant>(PN->getIncomingValue(i));
589 NewPN->addIncoming(ConstantExpr::get(I.getOpcode(), InV, C),
590 PN->getIncomingBlock(i));
591 }
592 } else {
593 assert(isa<CastInst>(I) && "Unary op should be a cast!");
594 const Type *RetTy = I.getType();
Chris Lattner7515cab2004-11-14 19:13:23 +0000595 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000596 Constant *InV = cast<Constant>(PN->getIncomingValue(i));
597 NewPN->addIncoming(ConstantExpr::getCast(InV, RetTy),
598 PN->getIncomingBlock(i));
599 }
600 }
601 return ReplaceInstUsesWith(I, NewPN);
602}
603
Chris Lattner113f4f42002-06-25 16:13:24 +0000604Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000605 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000606 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000607
Chris Lattnercf4a9962004-04-10 22:01:55 +0000608 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattner81a7a232004-10-16 18:11:37 +0000609 // X + undef -> undef
610 if (isa<UndefValue>(RHS))
611 return ReplaceInstUsesWith(I, RHS);
612
Chris Lattnercf4a9962004-04-10 22:01:55 +0000613 // X + 0 --> X
614 if (!I.getType()->isFloatingPoint() && // -0 + +0 = +0, so it's not a noop
615 RHSC->isNullValue())
616 return ReplaceInstUsesWith(I, LHS);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000617
Chris Lattnercf4a9962004-04-10 22:01:55 +0000618 // X + (signbit) --> X ^ signbit
619 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +0000620 unsigned NumBits = CI->getType()->getPrimitiveSizeInBits();
Chris Lattnercf4a9962004-04-10 22:01:55 +0000621 uint64_t Val = CI->getRawValue() & (1ULL << NumBits)-1;
Chris Lattner33eb9092004-11-05 04:45:43 +0000622 if (Val == (1ULL << (NumBits-1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000623 return BinaryOperator::createXor(LHS, RHS);
Chris Lattnercf4a9962004-04-10 22:01:55 +0000624 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000625
626 if (isa<PHINode>(LHS))
627 if (Instruction *NV = FoldOpIntoPhi(I))
628 return NV;
Chris Lattnercf4a9962004-04-10 22:01:55 +0000629 }
Chris Lattner9fa53de2002-05-06 16:49:18 +0000630
Chris Lattnerb8b97502003-08-13 19:01:45 +0000631 // X + X --> X << 1
Robert Bocchino7b5b86c2004-07-27 21:02:21 +0000632 if (I.getType()->isInteger()) {
Chris Lattnerb8b97502003-08-13 19:01:45 +0000633 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Chris Lattner47060462005-04-07 17:14:51 +0000634
635 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
636 if (RHSI->getOpcode() == Instruction::Sub)
637 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
638 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
639 }
640 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
641 if (LHSI->getOpcode() == Instruction::Sub)
642 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
643 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
644 }
Robert Bocchino7b5b86c2004-07-27 21:02:21 +0000645 }
Chris Lattnerede3fe02003-08-13 04:18:28 +0000646
Chris Lattner147e9752002-05-08 22:46:53 +0000647 // -A + B --> B - A
Chris Lattnerbb74e222003-03-10 23:06:50 +0000648 if (Value *V = dyn_castNegVal(LHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000649 return BinaryOperator::createSub(RHS, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000650
651 // A + -B --> A - B
Chris Lattnerbb74e222003-03-10 23:06:50 +0000652 if (!isa<Constant>(RHS))
653 if (Value *V = dyn_castNegVal(RHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000654 return BinaryOperator::createSub(LHS, V);
Chris Lattner260ab202002-04-18 17:39:14 +0000655
Misha Brukmanb1c93172005-04-21 23:48:37 +0000656
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000657 ConstantInt *C2;
658 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
659 if (X == RHS) // X*C + X --> X * (C+1)
660 return BinaryOperator::createMul(RHS, AddOne(C2));
661
662 // X*C1 + X*C2 --> X * (C1+C2)
663 ConstantInt *C1;
664 if (X == dyn_castFoldableMul(RHS, C1))
665 return BinaryOperator::createMul(X, ConstantExpr::getAdd(C1, C2));
Chris Lattner57c8d992003-02-18 19:57:07 +0000666 }
667
668 // X + X*C --> X * (C+1)
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000669 if (dyn_castFoldableMul(RHS, C2) == LHS)
670 return BinaryOperator::createMul(LHS, AddOne(C2));
671
Chris Lattner57c8d992003-02-18 19:57:07 +0000672
Chris Lattnerb8b97502003-08-13 19:01:45 +0000673 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattnerd4252a72004-07-30 07:50:03 +0000674 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattnerb8b97502003-08-13 19:01:45 +0000675 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2))) return R;
Chris Lattner7fb29e12003-03-11 00:12:48 +0000676
Chris Lattnerb9cde762003-10-02 15:11:26 +0000677 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattnerd4252a72004-07-30 07:50:03 +0000678 Value *X;
679 if (match(LHS, m_Not(m_Value(X)))) { // ~X + C --> (C-1) - X
680 Constant *C= ConstantExpr::getSub(CRHS, ConstantInt::get(I.getType(), 1));
681 return BinaryOperator::createSub(C, X);
Chris Lattnerb9cde762003-10-02 15:11:26 +0000682 }
Chris Lattnerd4252a72004-07-30 07:50:03 +0000683
Chris Lattnerbff91d92004-10-08 05:07:56 +0000684 // (X & FF00) + xx00 -> (X+xx00) & FF00
685 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
686 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
687 if (Anded == CRHS) {
688 // See if all bits from the first bit set in the Add RHS up are included
689 // in the mask. First, get the rightmost bit.
690 uint64_t AddRHSV = CRHS->getRawValue();
691
692 // Form a mask of all bits from the lowest bit added through the top.
693 uint64_t AddRHSHighBits = ~((AddRHSV & -AddRHSV)-1);
Chris Lattner2f1457f2005-04-24 17:46:05 +0000694 AddRHSHighBits &= ~0ULL >> (64-C2->getType()->getPrimitiveSizeInBits());
Chris Lattnerbff91d92004-10-08 05:07:56 +0000695
696 // See if the and mask includes all of these bits.
697 uint64_t AddRHSHighBitsAnd = AddRHSHighBits & C2->getRawValue();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000698
Chris Lattnerbff91d92004-10-08 05:07:56 +0000699 if (AddRHSHighBits == AddRHSHighBitsAnd) {
700 // Okay, the xform is safe. Insert the new add pronto.
701 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
702 LHS->getName()), I);
703 return BinaryOperator::createAnd(NewAdd, C2);
704 }
705 }
706 }
707
Chris Lattnerd4252a72004-07-30 07:50:03 +0000708 // Try to fold constant add into select arguments.
709 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner86102b82005-01-01 16:22:27 +0000710 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattnerd4252a72004-07-30 07:50:03 +0000711 return R;
Chris Lattnerb9cde762003-10-02 15:11:26 +0000712 }
713
Chris Lattner113f4f42002-06-25 16:13:24 +0000714 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +0000715}
716
Chris Lattnerbdb0ce02003-07-22 21:46:59 +0000717// isSignBit - Return true if the value represented by the constant only has the
718// highest order bit set.
719static bool isSignBit(ConstantInt *CI) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +0000720 unsigned NumBits = CI->getType()->getPrimitiveSizeInBits();
Chris Lattner2f1457f2005-04-24 17:46:05 +0000721 return (CI->getRawValue() & (~0ULL >> (64-NumBits))) == (1ULL << (NumBits-1));
Chris Lattnerbdb0ce02003-07-22 21:46:59 +0000722}
723
Chris Lattner022167f2004-03-13 00:11:49 +0000724/// RemoveNoopCast - Strip off nonconverting casts from the value.
725///
726static Value *RemoveNoopCast(Value *V) {
727 if (CastInst *CI = dyn_cast<CastInst>(V)) {
728 const Type *CTy = CI->getType();
729 const Type *OpTy = CI->getOperand(0)->getType();
730 if (CTy->isInteger() && OpTy->isInteger()) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +0000731 if (CTy->getPrimitiveSizeInBits() == OpTy->getPrimitiveSizeInBits())
Chris Lattner022167f2004-03-13 00:11:49 +0000732 return RemoveNoopCast(CI->getOperand(0));
733 } else if (isa<PointerType>(CTy) && isa<PointerType>(OpTy))
734 return RemoveNoopCast(CI->getOperand(0));
735 }
736 return V;
737}
738
Chris Lattner113f4f42002-06-25 16:13:24 +0000739Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +0000740 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000741
Chris Lattnere6794492002-08-12 21:17:25 +0000742 if (Op0 == Op1) // sub X, X -> 0
743 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner260ab202002-04-18 17:39:14 +0000744
Chris Lattnere6794492002-08-12 21:17:25 +0000745 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattnerbb74e222003-03-10 23:06:50 +0000746 if (Value *V = dyn_castNegVal(Op1))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000747 return BinaryOperator::createAdd(Op0, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000748
Chris Lattner81a7a232004-10-16 18:11:37 +0000749 if (isa<UndefValue>(Op0))
750 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
751 if (isa<UndefValue>(Op1))
752 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
753
Chris Lattner8f2f5982003-11-05 01:06:05 +0000754 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
755 // Replace (-1 - A) with (~A)...
Chris Lattner3082c5a2003-02-18 19:28:33 +0000756 if (C->isAllOnesValue())
757 return BinaryOperator::createNot(Op1);
Chris Lattnerad3c4952002-05-09 01:29:19 +0000758
Chris Lattner8f2f5982003-11-05 01:06:05 +0000759 // C - ~X == X + (1+C)
Chris Lattnerd4252a72004-07-30 07:50:03 +0000760 Value *X;
761 if (match(Op1, m_Not(m_Value(X))))
762 return BinaryOperator::createAdd(X,
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000763 ConstantExpr::getAdd(C, ConstantInt::get(I.getType(), 1)));
Chris Lattner92295c52004-03-12 23:53:13 +0000764 // -((uint)X >> 31) -> ((int)X >> 31)
765 // -((int)X >> 31) -> ((uint)X >> 31)
Chris Lattner022167f2004-03-13 00:11:49 +0000766 if (C->isNullValue()) {
767 Value *NoopCastedRHS = RemoveNoopCast(Op1);
768 if (ShiftInst *SI = dyn_cast<ShiftInst>(NoopCastedRHS))
Chris Lattner92295c52004-03-12 23:53:13 +0000769 if (SI->getOpcode() == Instruction::Shr)
770 if (ConstantUInt *CU = dyn_cast<ConstantUInt>(SI->getOperand(1))) {
771 const Type *NewTy;
Chris Lattner022167f2004-03-13 00:11:49 +0000772 if (SI->getType()->isSigned())
Chris Lattner97bfcea2004-06-17 18:16:02 +0000773 NewTy = SI->getType()->getUnsignedVersion();
Chris Lattner92295c52004-03-12 23:53:13 +0000774 else
Chris Lattner97bfcea2004-06-17 18:16:02 +0000775 NewTy = SI->getType()->getSignedVersion();
Chris Lattner92295c52004-03-12 23:53:13 +0000776 // Check to see if we are shifting out everything but the sign bit.
Chris Lattnerd1f46d32005-04-24 06:59:08 +0000777 if (CU->getValue() == SI->getType()->getPrimitiveSizeInBits()-1) {
Chris Lattner92295c52004-03-12 23:53:13 +0000778 // Ok, the transformation is safe. Insert a cast of the incoming
779 // value, then the new shift, then the new cast.
780 Instruction *FirstCast = new CastInst(SI->getOperand(0), NewTy,
781 SI->getOperand(0)->getName());
782 Value *InV = InsertNewInstBefore(FirstCast, I);
783 Instruction *NewShift = new ShiftInst(Instruction::Shr, FirstCast,
784 CU, SI->getName());
Chris Lattner022167f2004-03-13 00:11:49 +0000785 if (NewShift->getType() == I.getType())
786 return NewShift;
787 else {
788 InV = InsertNewInstBefore(NewShift, I);
789 return new CastInst(NewShift, I.getType());
790 }
Chris Lattner92295c52004-03-12 23:53:13 +0000791 }
792 }
Chris Lattner022167f2004-03-13 00:11:49 +0000793 }
Chris Lattner183b3362004-04-09 19:05:30 +0000794
795 // Try to fold constant sub into select arguments.
796 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner86102b82005-01-01 16:22:27 +0000797 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +0000798 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000799
800 if (isa<PHINode>(Op0))
801 if (Instruction *NV = FoldOpIntoPhi(I))
802 return NV;
Chris Lattner8f2f5982003-11-05 01:06:05 +0000803 }
804
Chris Lattnera9be4492005-04-07 16:15:25 +0000805 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
806 if (Op1I->getOpcode() == Instruction::Add &&
807 !Op0->getType()->isFloatingPoint()) {
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +0000808 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Chris Lattnera9be4492005-04-07 16:15:25 +0000809 return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +0000810 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Chris Lattnera9be4492005-04-07 16:15:25 +0000811 return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +0000812 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
813 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
814 // C1-(X+C2) --> (C1-C2)-X
815 return BinaryOperator::createSub(ConstantExpr::getSub(CI1, CI2),
816 Op1I->getOperand(0));
817 }
Chris Lattnera9be4492005-04-07 16:15:25 +0000818 }
819
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000820 if (Op1I->hasOneUse()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +0000821 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
822 // is not used by anyone else...
823 //
Chris Lattnerc2f0aa52004-02-02 20:09:56 +0000824 if (Op1I->getOpcode() == Instruction::Sub &&
825 !Op1I->getType()->isFloatingPoint()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +0000826 // Swap the two operands of the subexpr...
827 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
828 Op1I->setOperand(0, IIOp1);
829 Op1I->setOperand(1, IIOp0);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000830
Chris Lattner3082c5a2003-02-18 19:28:33 +0000831 // Create the new top level add instruction...
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000832 return BinaryOperator::createAdd(Op0, Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000833 }
834
835 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
836 //
837 if (Op1I->getOpcode() == Instruction::And &&
838 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
839 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
840
Chris Lattner396dbfe2004-06-09 05:08:07 +0000841 Value *NewNot =
842 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000843 return BinaryOperator::createAnd(Op0, NewNot);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000844 }
Chris Lattner57c8d992003-02-18 19:57:07 +0000845
Chris Lattner0aee4b72004-10-06 15:08:25 +0000846 // -(X sdiv C) -> (X sdiv -C)
847 if (Op1I->getOpcode() == Instruction::Div)
848 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
Chris Lattnera9be4492005-04-07 16:15:25 +0000849 if (CSI->isNullValue())
Chris Lattner0aee4b72004-10-06 15:08:25 +0000850 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Misha Brukmanb1c93172005-04-21 23:48:37 +0000851 return BinaryOperator::createDiv(Op1I->getOperand(0),
Chris Lattner0aee4b72004-10-06 15:08:25 +0000852 ConstantExpr::getNeg(DivRHS));
853
Chris Lattner57c8d992003-02-18 19:57:07 +0000854 // X - X*C --> X * (1-C)
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000855 ConstantInt *C2;
856 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Misha Brukmanb1c93172005-04-21 23:48:37 +0000857 Constant *CP1 =
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000858 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1), C2);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000859 return BinaryOperator::createMul(Op0, CP1);
Chris Lattner57c8d992003-02-18 19:57:07 +0000860 }
Chris Lattnerad3c4952002-05-09 01:29:19 +0000861 }
Chris Lattnera9be4492005-04-07 16:15:25 +0000862 }
Chris Lattner3082c5a2003-02-18 19:28:33 +0000863
Chris Lattner47060462005-04-07 17:14:51 +0000864 if (!Op0->getType()->isFloatingPoint())
865 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
866 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner411336f2005-01-19 21:50:18 +0000867 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
868 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
869 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
870 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner47060462005-04-07 17:14:51 +0000871 } else if (Op0I->getOpcode() == Instruction::Sub) {
872 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
873 return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
Chris Lattner411336f2005-01-19 21:50:18 +0000874 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000875
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000876 ConstantInt *C1;
877 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
878 if (X == Op1) { // X*C - X --> X * (C-1)
879 Constant *CP1 = ConstantExpr::getSub(C1, ConstantInt::get(I.getType(),1));
880 return BinaryOperator::createMul(Op1, CP1);
881 }
Chris Lattner57c8d992003-02-18 19:57:07 +0000882
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000883 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
884 if (X == dyn_castFoldableMul(Op1, C2))
885 return BinaryOperator::createMul(Op1, ConstantExpr::getSub(C1, C2));
886 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000887 return 0;
Chris Lattner260ab202002-04-18 17:39:14 +0000888}
889
Chris Lattnere79e8542004-02-23 06:38:22 +0000890/// isSignBitCheck - Given an exploded setcc instruction, return true if it is
891/// really just returns true if the most significant (sign) bit is set.
892static bool isSignBitCheck(unsigned Opcode, Value *LHS, ConstantInt *RHS) {
893 if (RHS->getType()->isSigned()) {
894 // True if source is LHS < 0 or LHS <= -1
895 return Opcode == Instruction::SetLT && RHS->isNullValue() ||
896 Opcode == Instruction::SetLE && RHS->isAllOnesValue();
897 } else {
898 ConstantUInt *RHSC = cast<ConstantUInt>(RHS);
899 // True if source is LHS > 127 or LHS >= 128, where the constants depend on
900 // the size of the integer type.
901 if (Opcode == Instruction::SetGE)
Chris Lattnerd1f46d32005-04-24 06:59:08 +0000902 return RHSC->getValue() ==
903 1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1);
Chris Lattnere79e8542004-02-23 06:38:22 +0000904 if (Opcode == Instruction::SetGT)
905 return RHSC->getValue() ==
Chris Lattnerd1f46d32005-04-24 06:59:08 +0000906 (1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1))-1;
Chris Lattnere79e8542004-02-23 06:38:22 +0000907 }
908 return false;
909}
910
Chris Lattner113f4f42002-06-25 16:13:24 +0000911Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000912 bool Changed = SimplifyCommutative(I);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000913 Value *Op0 = I.getOperand(0);
Chris Lattner260ab202002-04-18 17:39:14 +0000914
Chris Lattner81a7a232004-10-16 18:11:37 +0000915 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
916 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
917
Chris Lattnere6794492002-08-12 21:17:25 +0000918 // Simplify mul instructions with a constant RHS...
Chris Lattner3082c5a2003-02-18 19:28:33 +0000919 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
920 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerede3fe02003-08-13 04:18:28 +0000921
922 // ((X << C1)*C2) == (X * (C2 << C1))
923 if (ShiftInst *SI = dyn_cast<ShiftInst>(Op0))
924 if (SI->getOpcode() == Instruction::Shl)
925 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000926 return BinaryOperator::createMul(SI->getOperand(0),
927 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanb1c93172005-04-21 23:48:37 +0000928
Chris Lattnercce81be2003-09-11 22:24:54 +0000929 if (CI->isNullValue())
930 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
931 if (CI->equalsInt(1)) // X * 1 == X
932 return ReplaceInstUsesWith(I, Op0);
933 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Chris Lattner35236d82003-06-25 17:09:20 +0000934 return BinaryOperator::createNeg(Op0, I.getName());
Chris Lattner31ba1292002-04-29 22:24:47 +0000935
Chris Lattnercce81be2003-09-11 22:24:54 +0000936 int64_t Val = (int64_t)cast<ConstantInt>(CI)->getRawValue();
Chris Lattner3082c5a2003-02-18 19:28:33 +0000937 if (uint64_t C = Log2(Val)) // Replace X*(2^C) with X << C
938 return new ShiftInst(Instruction::Shl, Op0,
939 ConstantUInt::get(Type::UByteTy, C));
Robert Bocchino7b5b86c2004-07-27 21:02:21 +0000940 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattner3082c5a2003-02-18 19:28:33 +0000941 if (Op1F->isNullValue())
942 return ReplaceInstUsesWith(I, Op1);
Chris Lattner31ba1292002-04-29 22:24:47 +0000943
Chris Lattner3082c5a2003-02-18 19:28:33 +0000944 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
945 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
946 if (Op1F->getValue() == 1.0)
947 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
948 }
Chris Lattner183b3362004-04-09 19:05:30 +0000949
950 // Try to fold constant mul into select arguments.
951 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +0000952 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +0000953 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000954
955 if (isa<PHINode>(Op0))
956 if (Instruction *NV = FoldOpIntoPhi(I))
957 return NV;
Chris Lattner260ab202002-04-18 17:39:14 +0000958 }
959
Chris Lattner934a64cf2003-03-10 23:23:04 +0000960 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
961 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000962 return BinaryOperator::createMul(Op0v, Op1v);
Chris Lattner934a64cf2003-03-10 23:23:04 +0000963
Chris Lattner2635b522004-02-23 05:39:21 +0000964 // If one of the operands of the multiply is a cast from a boolean value, then
965 // we know the bool is either zero or one, so this is a 'masking' multiply.
966 // See if we can simplify things based on how the boolean was originally
967 // formed.
968 CastInst *BoolCast = 0;
969 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(0)))
970 if (CI->getOperand(0)->getType() == Type::BoolTy)
971 BoolCast = CI;
972 if (!BoolCast)
973 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(1)))
974 if (CI->getOperand(0)->getType() == Type::BoolTy)
975 BoolCast = CI;
976 if (BoolCast) {
977 if (SetCondInst *SCI = dyn_cast<SetCondInst>(BoolCast->getOperand(0))) {
978 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
979 const Type *SCOpTy = SCIOp0->getType();
980
Chris Lattnere79e8542004-02-23 06:38:22 +0000981 // If the setcc is true iff the sign bit of X is set, then convert this
982 // multiply into a shift/and combination.
983 if (isa<ConstantInt>(SCIOp1) &&
984 isSignBitCheck(SCI->getOpcode(), SCIOp0, cast<ConstantInt>(SCIOp1))) {
Chris Lattner2635b522004-02-23 05:39:21 +0000985 // Shift the X value right to turn it into "all signbits".
986 Constant *Amt = ConstantUInt::get(Type::UByteTy,
Chris Lattnerd1f46d32005-04-24 06:59:08 +0000987 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattnere79e8542004-02-23 06:38:22 +0000988 if (SCIOp0->getType()->isUnsigned()) {
Chris Lattner97bfcea2004-06-17 18:16:02 +0000989 const Type *NewTy = SCIOp0->getType()->getSignedVersion();
Chris Lattnere79e8542004-02-23 06:38:22 +0000990 SCIOp0 = InsertNewInstBefore(new CastInst(SCIOp0, NewTy,
991 SCIOp0->getName()), I);
992 }
993
994 Value *V =
995 InsertNewInstBefore(new ShiftInst(Instruction::Shr, SCIOp0, Amt,
996 BoolCast->getOperand(0)->getName()+
997 ".mask"), I);
Chris Lattner2635b522004-02-23 05:39:21 +0000998
999 // If the multiply type is not the same as the source type, sign extend
1000 // or truncate to the multiply type.
1001 if (I.getType() != V->getType())
Chris Lattnere79e8542004-02-23 06:38:22 +00001002 V = InsertNewInstBefore(new CastInst(V, I.getType(), V->getName()),I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001003
Chris Lattner2635b522004-02-23 05:39:21 +00001004 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001005 return BinaryOperator::createAnd(V, OtherOp);
Chris Lattner2635b522004-02-23 05:39:21 +00001006 }
1007 }
1008 }
1009
Chris Lattner113f4f42002-06-25 16:13:24 +00001010 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +00001011}
1012
Chris Lattner113f4f42002-06-25 16:13:24 +00001013Instruction *InstCombiner::visitDiv(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001014 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner81a7a232004-10-16 18:11:37 +00001015
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001016 if (isa<UndefValue>(Op0)) // undef / X -> 0
1017 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1018 if (isa<UndefValue>(Op1))
1019 return ReplaceInstUsesWith(I, Op1); // X / undef -> undef
1020
1021 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnere20c3342004-04-26 14:01:59 +00001022 // div X, 1 == X
Chris Lattnere6794492002-08-12 21:17:25 +00001023 if (RHS->equalsInt(1))
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001024 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001025
Chris Lattnere20c3342004-04-26 14:01:59 +00001026 // div X, -1 == -X
1027 if (RHS->isAllOnesValue())
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001028 return BinaryOperator::createNeg(Op0);
Chris Lattnere20c3342004-04-26 14:01:59 +00001029
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001030 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
Chris Lattner272d5ca2004-09-28 18:22:15 +00001031 if (LHS->getOpcode() == Instruction::Div)
1032 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Chris Lattner272d5ca2004-09-28 18:22:15 +00001033 // (X / C1) / C2 -> X / (C1*C2)
1034 return BinaryOperator::createDiv(LHS->getOperand(0),
1035 ConstantExpr::getMul(RHS, LHSRHS));
1036 }
1037
Chris Lattner3082c5a2003-02-18 19:28:33 +00001038 // Check to see if this is an unsigned division with an exact power of 2,
1039 // if so, convert to a right shift.
1040 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
1041 if (uint64_t Val = C->getValue()) // Don't break X / 0
1042 if (uint64_t C = Log2(Val))
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001043 return new ShiftInst(Instruction::Shr, Op0,
Chris Lattner3082c5a2003-02-18 19:28:33 +00001044 ConstantUInt::get(Type::UByteTy, C));
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001045
Chris Lattner4ad08352004-10-09 02:50:40 +00001046 // -X/C -> X/-C
1047 if (RHS->getType()->isSigned())
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001048 if (Value *LHSNeg = dyn_castNegVal(Op0))
Chris Lattner4ad08352004-10-09 02:50:40 +00001049 return BinaryOperator::createDiv(LHSNeg, ConstantExpr::getNeg(RHS));
1050
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001051 if (!RHS->isNullValue()) {
1052 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00001053 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001054 return R;
1055 if (isa<PHINode>(Op0))
1056 if (Instruction *NV = FoldOpIntoPhi(I))
1057 return NV;
1058 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00001059 }
1060
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001061 // If this is 'udiv X, (Cond ? C1, C2)' where C1&C2 are powers of two,
1062 // transform this into: '(Cond ? (udiv X, C1) : (udiv X, C2))'.
1063 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1064 if (ConstantUInt *STO = dyn_cast<ConstantUInt>(SI->getOperand(1)))
1065 if (ConstantUInt *SFO = dyn_cast<ConstantUInt>(SI->getOperand(2))) {
1066 if (STO->getValue() == 0) { // Couldn't be this argument.
1067 I.setOperand(1, SFO);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001068 return &I;
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001069 } else if (SFO->getValue() == 0) {
Chris Lattner89dc4f12005-06-16 04:55:52 +00001070 I.setOperand(1, STO);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001071 return &I;
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001072 }
1073
Chris Lattner42362612005-04-08 04:03:26 +00001074 uint64_t TVA = STO->getValue(), FVA = SFO->getValue();
1075 unsigned TSA = 0, FSA = 0;
1076 if ((TVA == 1 || (TSA = Log2(TVA))) && // Log2 fails for 0 & 1.
1077 (FVA == 1 || (FSA = Log2(FVA)))) {
1078 Constant *TC = ConstantUInt::get(Type::UByteTy, TSA);
1079 Instruction *TSI = new ShiftInst(Instruction::Shr, Op0,
1080 TC, SI->getName()+".t");
1081 TSI = InsertNewInstBefore(TSI, I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001082
Chris Lattner42362612005-04-08 04:03:26 +00001083 Constant *FC = ConstantUInt::get(Type::UByteTy, FSA);
1084 Instruction *FSI = new ShiftInst(Instruction::Shr, Op0,
1085 FC, SI->getName()+".f");
1086 FSI = InsertNewInstBefore(FSI, I);
1087 return new SelectInst(SI->getOperand(0), TSI, FSI);
1088 }
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001089 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001090
Chris Lattner3082c5a2003-02-18 19:28:33 +00001091 // 0 / X == 0, we don't need to preserve faults!
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001092 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattner3082c5a2003-02-18 19:28:33 +00001093 if (LHS->equalsInt(0))
1094 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1095
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001096 return 0;
1097}
1098
1099
Chris Lattner113f4f42002-06-25 16:13:24 +00001100Instruction *InstCombiner::visitRem(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001101 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner7fd5f072004-07-06 07:01:22 +00001102 if (I.getType()->isSigned())
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001103 if (Value *RHSNeg = dyn_castNegVal(Op1))
Chris Lattner98c6bdf2004-07-06 07:11:42 +00001104 if (!isa<ConstantSInt>(RHSNeg) ||
Chris Lattner8e726062004-08-09 21:05:48 +00001105 cast<ConstantSInt>(RHSNeg)->getValue() > 0) {
Chris Lattner7fd5f072004-07-06 07:01:22 +00001106 // X % -Y -> X % Y
1107 AddUsesToWorkList(I);
1108 I.setOperand(1, RHSNeg);
1109 return &I;
1110 }
1111
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001112 if (isa<UndefValue>(Op0)) // undef % X -> 0
Chris Lattner81a7a232004-10-16 18:11:37 +00001113 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001114 if (isa<UndefValue>(Op1))
1115 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Chris Lattner81a7a232004-10-16 18:11:37 +00001116
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001117 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00001118 if (RHS->equalsInt(1)) // X % 1 == 0
1119 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1120
1121 // Check to see if this is an unsigned remainder with an exact power of 2,
1122 // if so, convert to a bitwise and.
1123 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
1124 if (uint64_t Val = C->getValue()) // Don't break X % 0 (divide by zero)
Chris Lattnerd9e58132004-05-07 15:35:56 +00001125 if (!(Val & (Val-1))) // Power of 2
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001126 return BinaryOperator::createAnd(Op0,
1127 ConstantUInt::get(I.getType(), Val-1));
1128
1129 if (!RHS->isNullValue()) {
1130 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00001131 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001132 return R;
1133 if (isa<PHINode>(Op0))
1134 if (Instruction *NV = FoldOpIntoPhi(I))
1135 return NV;
1136 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00001137 }
1138
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001139 // If this is 'urem X, (Cond ? C1, C2)' where C1&C2 are powers of two,
1140 // transform this into: '(Cond ? (urem X, C1) : (urem X, C2))'.
1141 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1142 if (ConstantUInt *STO = dyn_cast<ConstantUInt>(SI->getOperand(1)))
1143 if (ConstantUInt *SFO = dyn_cast<ConstantUInt>(SI->getOperand(2))) {
1144 if (STO->getValue() == 0) { // Couldn't be this argument.
1145 I.setOperand(1, SFO);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001146 return &I;
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001147 } else if (SFO->getValue() == 0) {
1148 I.setOperand(1, STO);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001149 return &I;
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001150 }
1151
1152 if (!(STO->getValue() & (STO->getValue()-1)) &&
1153 !(SFO->getValue() & (SFO->getValue()-1))) {
1154 Value *TrueAnd = InsertNewInstBefore(BinaryOperator::createAnd(Op0,
1155 SubOne(STO), SI->getName()+".t"), I);
1156 Value *FalseAnd = InsertNewInstBefore(BinaryOperator::createAnd(Op0,
1157 SubOne(SFO), SI->getName()+".f"), I);
1158 return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
1159 }
1160 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001161
Chris Lattner3082c5a2003-02-18 19:28:33 +00001162 // 0 % X == 0, we don't need to preserve faults!
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001163 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattner3082c5a2003-02-18 19:28:33 +00001164 if (LHS->equalsInt(0))
Chris Lattnere6794492002-08-12 21:17:25 +00001165 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1166
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001167 return 0;
1168}
1169
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001170// isMaxValueMinusOne - return true if this is Max-1
Chris Lattnere6794492002-08-12 21:17:25 +00001171static bool isMaxValueMinusOne(const ConstantInt *C) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001172 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C)) {
1173 // Calculate -1 casted to the right type...
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001174 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001175 uint64_t Val = ~0ULL; // All ones
1176 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
1177 return CU->getValue() == Val-1;
1178 }
1179
1180 const ConstantSInt *CS = cast<ConstantSInt>(C);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001181
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001182 // Calculate 0111111111..11111
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001183 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001184 int64_t Val = INT64_MAX; // All ones
1185 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
1186 return CS->getValue() == Val-1;
1187}
1188
1189// isMinValuePlusOne - return true if this is Min+1
Chris Lattnere6794492002-08-12 21:17:25 +00001190static bool isMinValuePlusOne(const ConstantInt *C) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001191 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
1192 return CU->getValue() == 1;
1193
1194 const ConstantSInt *CS = cast<ConstantSInt>(C);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001195
1196 // Calculate 1111111111000000000000
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001197 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001198 int64_t Val = -1; // All ones
1199 Val <<= TypeBits-1; // Shift over to the right spot
1200 return CS->getValue() == Val+1;
1201}
1202
Chris Lattner35167c32004-06-09 07:59:58 +00001203// isOneBitSet - Return true if there is exactly one bit set in the specified
1204// constant.
1205static bool isOneBitSet(const ConstantInt *CI) {
1206 uint64_t V = CI->getRawValue();
1207 return V && (V & (V-1)) == 0;
1208}
1209
Chris Lattner8fc5af42004-09-23 21:46:38 +00001210#if 0 // Currently unused
1211// isLowOnes - Return true if the constant is of the form 0+1+.
1212static bool isLowOnes(const ConstantInt *CI) {
1213 uint64_t V = CI->getRawValue();
1214
1215 // There won't be bits set in parts that the type doesn't contain.
1216 V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
1217
1218 uint64_t U = V+1; // If it is low ones, this should be a power of two.
1219 return U && V && (U & V) == 0;
1220}
1221#endif
1222
1223// isHighOnes - Return true if the constant is of the form 1+0+.
1224// This is the same as lowones(~X).
1225static bool isHighOnes(const ConstantInt *CI) {
1226 uint64_t V = ~CI->getRawValue();
1227
1228 // There won't be bits set in parts that the type doesn't contain.
1229 V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
1230
1231 uint64_t U = V+1; // If it is low ones, this should be a power of two.
1232 return U && V && (U & V) == 0;
1233}
1234
1235
Chris Lattner3ac7c262003-08-13 20:16:26 +00001236/// getSetCondCode - Encode a setcc opcode into a three bit mask. These bits
1237/// are carefully arranged to allow folding of expressions such as:
1238///
1239/// (A < B) | (A > B) --> (A != B)
1240///
1241/// Bit value '4' represents that the comparison is true if A > B, bit value '2'
1242/// represents that the comparison is true if A == B, and bit value '1' is true
1243/// if A < B.
1244///
1245static unsigned getSetCondCode(const SetCondInst *SCI) {
1246 switch (SCI->getOpcode()) {
1247 // False -> 0
1248 case Instruction::SetGT: return 1;
1249 case Instruction::SetEQ: return 2;
1250 case Instruction::SetGE: return 3;
1251 case Instruction::SetLT: return 4;
1252 case Instruction::SetNE: return 5;
1253 case Instruction::SetLE: return 6;
1254 // True -> 7
1255 default:
1256 assert(0 && "Invalid SetCC opcode!");
1257 return 0;
1258 }
1259}
1260
1261/// getSetCCValue - This is the complement of getSetCondCode, which turns an
1262/// opcode and two operands into either a constant true or false, or a brand new
1263/// SetCC instruction.
1264static Value *getSetCCValue(unsigned Opcode, Value *LHS, Value *RHS) {
1265 switch (Opcode) {
1266 case 0: return ConstantBool::False;
1267 case 1: return new SetCondInst(Instruction::SetGT, LHS, RHS);
1268 case 2: return new SetCondInst(Instruction::SetEQ, LHS, RHS);
1269 case 3: return new SetCondInst(Instruction::SetGE, LHS, RHS);
1270 case 4: return new SetCondInst(Instruction::SetLT, LHS, RHS);
1271 case 5: return new SetCondInst(Instruction::SetNE, LHS, RHS);
1272 case 6: return new SetCondInst(Instruction::SetLE, LHS, RHS);
1273 case 7: return ConstantBool::True;
1274 default: assert(0 && "Illegal SetCCCode!"); return 0;
1275 }
1276}
1277
1278// FoldSetCCLogical - Implements (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
1279struct FoldSetCCLogical {
1280 InstCombiner &IC;
1281 Value *LHS, *RHS;
1282 FoldSetCCLogical(InstCombiner &ic, SetCondInst *SCI)
1283 : IC(ic), LHS(SCI->getOperand(0)), RHS(SCI->getOperand(1)) {}
1284 bool shouldApply(Value *V) const {
1285 if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
1286 return (SCI->getOperand(0) == LHS && SCI->getOperand(1) == RHS ||
1287 SCI->getOperand(0) == RHS && SCI->getOperand(1) == LHS);
1288 return false;
1289 }
1290 Instruction *apply(BinaryOperator &Log) const {
1291 SetCondInst *SCI = cast<SetCondInst>(Log.getOperand(0));
1292 if (SCI->getOperand(0) != LHS) {
1293 assert(SCI->getOperand(1) == LHS);
1294 SCI->swapOperands(); // Swap the LHS and RHS of the SetCC
1295 }
1296
1297 unsigned LHSCode = getSetCondCode(SCI);
1298 unsigned RHSCode = getSetCondCode(cast<SetCondInst>(Log.getOperand(1)));
1299 unsigned Code;
1300 switch (Log.getOpcode()) {
1301 case Instruction::And: Code = LHSCode & RHSCode; break;
1302 case Instruction::Or: Code = LHSCode | RHSCode; break;
1303 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner2caaaba2003-09-22 20:33:34 +00001304 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattner3ac7c262003-08-13 20:16:26 +00001305 }
1306
1307 Value *RV = getSetCCValue(Code, LHS, RHS);
1308 if (Instruction *I = dyn_cast<Instruction>(RV))
1309 return I;
1310 // Otherwise, it's a constant boolean value...
1311 return IC.ReplaceInstUsesWith(Log, RV);
1312 }
1313};
1314
1315
Chris Lattner86102b82005-01-01 16:22:27 +00001316/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
1317/// this predicate to simplify operations downstream. V and Mask are known to
1318/// be the same type.
1319static bool MaskedValueIsZero(Value *V, ConstantIntegral *Mask) {
1320 if (isa<UndefValue>(V) || Mask->isNullValue())
1321 return true;
1322 if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(V))
1323 return ConstantExpr::getAnd(CI, Mask)->isNullValue();
Misha Brukmanb1c93172005-04-21 23:48:37 +00001324
Chris Lattner86102b82005-01-01 16:22:27 +00001325 if (Instruction *I = dyn_cast<Instruction>(V)) {
1326 switch (I->getOpcode()) {
1327 case Instruction::And:
1328 // (X & C1) & C2 == 0 iff C1 & C2 == 0.
1329 if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(I->getOperand(1)))
1330 if (ConstantExpr::getAnd(CI, Mask)->isNullValue())
1331 return true;
1332 break;
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00001333 case Instruction::Or:
1334 // If the LHS and the RHS are MaskedValueIsZero, the result is also zero.
Misha Brukmanb1c93172005-04-21 23:48:37 +00001335 return MaskedValueIsZero(I->getOperand(1), Mask) &&
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00001336 MaskedValueIsZero(I->getOperand(0), Mask);
1337 case Instruction::Select:
1338 // If the T and F values are MaskedValueIsZero, the result is also zero.
Misha Brukmanb1c93172005-04-21 23:48:37 +00001339 return MaskedValueIsZero(I->getOperand(2), Mask) &&
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00001340 MaskedValueIsZero(I->getOperand(1), Mask);
Chris Lattner86102b82005-01-01 16:22:27 +00001341 case Instruction::Cast: {
1342 const Type *SrcTy = I->getOperand(0)->getType();
Chris Lattner4c2d3782005-05-06 01:53:19 +00001343 if (SrcTy == Type::BoolTy)
1344 return (Mask->getRawValue() & 1) == 0;
1345
1346 if (SrcTy->isInteger()) {
Chris Lattner86102b82005-01-01 16:22:27 +00001347 // (cast <ty> X to int) & C2 == 0 iff <ty> could not have contained C2.
1348 if (SrcTy->isUnsigned() && // Only handle zero ext.
1349 ConstantExpr::getCast(Mask, SrcTy)->isNullValue())
1350 return true;
1351
1352 // If this is a noop cast, recurse.
Chris Lattner4c2d3782005-05-06 01:53:19 +00001353 if ((SrcTy->isSigned() && SrcTy->getUnsignedVersion() == I->getType())||
1354 SrcTy->getSignedVersion() == I->getType()) {
1355 Constant *NewMask =
1356 ConstantExpr::getCast(Mask, I->getOperand(0)->getType());
1357 return MaskedValueIsZero(I->getOperand(0),
1358 cast<ConstantIntegral>(NewMask));
1359 }
Chris Lattner86102b82005-01-01 16:22:27 +00001360 }
1361 break;
1362 }
1363 case Instruction::Shl:
Chris Lattneref298a32005-05-06 04:53:20 +00001364 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
1365 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1)))
1366 return MaskedValueIsZero(I->getOperand(0),
1367 cast<ConstantIntegral>(ConstantExpr::getUShr(Mask, SA)));
Chris Lattner86102b82005-01-01 16:22:27 +00001368 break;
1369 case Instruction::Shr:
1370 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
1371 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1)))
1372 if (I->getType()->isUnsigned()) {
1373 Constant *C1 = ConstantIntegral::getAllOnesValue(I->getType());
1374 C1 = ConstantExpr::getShr(C1, SA);
1375 C1 = ConstantExpr::getAnd(C1, Mask);
1376 if (C1->isNullValue())
1377 return true;
1378 }
1379 break;
1380 }
1381 }
1382
1383 return false;
1384}
1385
Chris Lattnerba1cb382003-09-19 17:17:26 +00001386// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
1387// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
1388// guaranteed to be either a shift instruction or a binary operator.
1389Instruction *InstCombiner::OptAndOp(Instruction *Op,
1390 ConstantIntegral *OpRHS,
1391 ConstantIntegral *AndRHS,
1392 BinaryOperator &TheAnd) {
1393 Value *X = Op->getOperand(0);
Chris Lattnerfcf21a72004-01-12 19:47:05 +00001394 Constant *Together = 0;
1395 if (!isa<ShiftInst>(Op))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001396 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001397
Chris Lattnerba1cb382003-09-19 17:17:26 +00001398 switch (Op->getOpcode()) {
1399 case Instruction::Xor:
Chris Lattner86102b82005-01-01 16:22:27 +00001400 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001401 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
1402 std::string OpName = Op->getName(); Op->setName("");
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001403 Instruction *And = BinaryOperator::createAnd(X, AndRHS, OpName);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001404 InsertNewInstBefore(And, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001405 return BinaryOperator::createXor(And, Together);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001406 }
1407 break;
1408 case Instruction::Or:
Chris Lattner86102b82005-01-01 16:22:27 +00001409 if (Together == AndRHS) // (X | C) & C --> C
1410 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001411
Chris Lattner86102b82005-01-01 16:22:27 +00001412 if (Op->hasOneUse() && Together != OpRHS) {
1413 // (X | C1) & C2 --> (X | (C1&C2)) & C2
1414 std::string Op0Name = Op->getName(); Op->setName("");
1415 Instruction *Or = BinaryOperator::createOr(X, Together, Op0Name);
1416 InsertNewInstBefore(Or, TheAnd);
1417 return BinaryOperator::createAnd(Or, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001418 }
1419 break;
1420 case Instruction::Add:
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001421 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001422 // Adding a one to a single bit bit-field should be turned into an XOR
1423 // of the bit. First thing to check is to see if this AND is with a
1424 // single bit constant.
Chris Lattner35167c32004-06-09 07:59:58 +00001425 uint64_t AndRHSV = cast<ConstantInt>(AndRHS)->getRawValue();
Chris Lattnerba1cb382003-09-19 17:17:26 +00001426
1427 // Clear bits that are not part of the constant.
Chris Lattner2f1457f2005-04-24 17:46:05 +00001428 AndRHSV &= ~0ULL >> (64-AndRHS->getType()->getPrimitiveSizeInBits());
Chris Lattnerba1cb382003-09-19 17:17:26 +00001429
1430 // If there is only one bit set...
Chris Lattner35167c32004-06-09 07:59:58 +00001431 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001432 // Ok, at this point, we know that we are masking the result of the
1433 // ADD down to exactly one bit. If the constant we are adding has
1434 // no bits set below this bit, then we can eliminate the ADD.
Chris Lattner35167c32004-06-09 07:59:58 +00001435 uint64_t AddRHS = cast<ConstantInt>(OpRHS)->getRawValue();
Misha Brukmanb1c93172005-04-21 23:48:37 +00001436
Chris Lattnerba1cb382003-09-19 17:17:26 +00001437 // Check to see if any bits below the one bit set in AndRHSV are set.
1438 if ((AddRHS & (AndRHSV-1)) == 0) {
1439 // If not, the only thing that can effect the output of the AND is
1440 // the bit specified by AndRHSV. If that bit is set, the effect of
1441 // the XOR is to toggle the bit. If it is clear, then the ADD has
1442 // no effect.
1443 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
1444 TheAnd.setOperand(0, X);
1445 return &TheAnd;
1446 } else {
1447 std::string Name = Op->getName(); Op->setName("");
1448 // Pull the XOR out of the AND.
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001449 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS, Name);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001450 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001451 return BinaryOperator::createXor(NewAnd, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001452 }
1453 }
1454 }
1455 }
1456 break;
Chris Lattner2da29172003-09-19 19:05:02 +00001457
1458 case Instruction::Shl: {
1459 // We know that the AND will not produce any of the bits shifted in, so if
1460 // the anded constant includes them, clear them now!
1461 //
1462 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner7e794272004-09-24 15:21:34 +00001463 Constant *ShlMask = ConstantExpr::getShl(AllOne, OpRHS);
1464 Constant *CI = ConstantExpr::getAnd(AndRHS, ShlMask);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001465
Chris Lattner7e794272004-09-24 15:21:34 +00001466 if (CI == ShlMask) { // Masking out bits that the shift already masks
1467 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
1468 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner2da29172003-09-19 19:05:02 +00001469 TheAnd.setOperand(1, CI);
1470 return &TheAnd;
1471 }
1472 break;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001473 }
Chris Lattner2da29172003-09-19 19:05:02 +00001474 case Instruction::Shr:
1475 // We know that the AND will not produce any of the bits shifted in, so if
1476 // the anded constant includes them, clear them now! This only applies to
1477 // unsigned shifts, because a signed shr may bring in set bits!
1478 //
1479 if (AndRHS->getType()->isUnsigned()) {
1480 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner7e794272004-09-24 15:21:34 +00001481 Constant *ShrMask = ConstantExpr::getShr(AllOne, OpRHS);
1482 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
1483
1484 if (CI == ShrMask) { // Masking out bits that the shift already masks.
1485 return ReplaceInstUsesWith(TheAnd, Op);
1486 } else if (CI != AndRHS) {
1487 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
Chris Lattner2da29172003-09-19 19:05:02 +00001488 return &TheAnd;
1489 }
Chris Lattner7e794272004-09-24 15:21:34 +00001490 } else { // Signed shr.
1491 // See if this is shifting in some sign extension, then masking it out
1492 // with an and.
1493 if (Op->hasOneUse()) {
1494 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
1495 Constant *ShrMask = ConstantExpr::getUShr(AllOne, OpRHS);
1496 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
Chris Lattner5c3c21e2004-10-22 04:53:16 +00001497 if (CI == AndRHS) { // Masking out bits shifted in.
Chris Lattner7e794272004-09-24 15:21:34 +00001498 // Make the argument unsigned.
1499 Value *ShVal = Op->getOperand(0);
1500 ShVal = InsertCastBefore(ShVal,
1501 ShVal->getType()->getUnsignedVersion(),
1502 TheAnd);
1503 ShVal = InsertNewInstBefore(new ShiftInst(Instruction::Shr, ShVal,
1504 OpRHS, Op->getName()),
1505 TheAnd);
Chris Lattner70c20392004-10-27 05:57:15 +00001506 Value *AndRHS2 = ConstantExpr::getCast(AndRHS, ShVal->getType());
1507 ShVal = InsertNewInstBefore(BinaryOperator::createAnd(ShVal, AndRHS2,
1508 TheAnd.getName()),
1509 TheAnd);
Chris Lattner7e794272004-09-24 15:21:34 +00001510 return new CastInst(ShVal, Op->getType());
1511 }
1512 }
Chris Lattner2da29172003-09-19 19:05:02 +00001513 }
1514 break;
Chris Lattnerba1cb382003-09-19 17:17:26 +00001515 }
1516 return 0;
1517}
1518
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001519
Chris Lattner6862fbd2004-09-29 17:40:11 +00001520/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
1521/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
1522/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. IB is the location to
1523/// insert new instructions.
1524Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
1525 bool Inside, Instruction &IB) {
1526 assert(cast<ConstantBool>(ConstantExpr::getSetLE(Lo, Hi))->getValue() &&
1527 "Lo is not <= Hi in range emission code!");
1528 if (Inside) {
1529 if (Lo == Hi) // Trivially false.
1530 return new SetCondInst(Instruction::SetNE, V, V);
1531 if (cast<ConstantIntegral>(Lo)->isMinValue())
1532 return new SetCondInst(Instruction::SetLT, V, Hi);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001533
Chris Lattner6862fbd2004-09-29 17:40:11 +00001534 Constant *AddCST = ConstantExpr::getNeg(Lo);
1535 Instruction *Add = BinaryOperator::createAdd(V, AddCST,V->getName()+".off");
1536 InsertNewInstBefore(Add, IB);
1537 // Convert to unsigned for the comparison.
1538 const Type *UnsType = Add->getType()->getUnsignedVersion();
1539 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
1540 AddCST = ConstantExpr::getAdd(AddCST, Hi);
1541 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1542 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
1543 }
1544
1545 if (Lo == Hi) // Trivially true.
1546 return new SetCondInst(Instruction::SetEQ, V, V);
1547
1548 Hi = SubOne(cast<ConstantInt>(Hi));
1549 if (cast<ConstantIntegral>(Lo)->isMinValue()) // V < 0 || V >= Hi ->'V > Hi-1'
1550 return new SetCondInst(Instruction::SetGT, V, Hi);
1551
1552 // Emit X-Lo > Hi-Lo-1
1553 Constant *AddCST = ConstantExpr::getNeg(Lo);
1554 Instruction *Add = BinaryOperator::createAdd(V, AddCST, V->getName()+".off");
1555 InsertNewInstBefore(Add, IB);
1556 // Convert to unsigned for the comparison.
1557 const Type *UnsType = Add->getType()->getUnsignedVersion();
1558 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
1559 AddCST = ConstantExpr::getAdd(AddCST, Hi);
1560 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1561 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
1562}
1563
1564
Chris Lattner113f4f42002-06-25 16:13:24 +00001565Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001566 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00001567 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001568
Chris Lattner81a7a232004-10-16 18:11:37 +00001569 if (isa<UndefValue>(Op1)) // X & undef -> 0
1570 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1571
Chris Lattner86102b82005-01-01 16:22:27 +00001572 // and X, X = X
1573 if (Op0 == Op1)
Chris Lattnere6794492002-08-12 21:17:25 +00001574 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001575
Chris Lattner86102b82005-01-01 16:22:27 +00001576 if (ConstantIntegral *AndRHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00001577 // and X, -1 == X
1578 if (AndRHS->isAllOnesValue())
Chris Lattnere6794492002-08-12 21:17:25 +00001579 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001580
Chris Lattner86102b82005-01-01 16:22:27 +00001581 if (MaskedValueIsZero(Op0, AndRHS)) // LHS & RHS == 0
1582 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1583
1584 // If the mask is not masking out any bits, there is no reason to do the
1585 // and in the first place.
Misha Brukmanb1c93172005-04-21 23:48:37 +00001586 ConstantIntegral *NotAndRHS =
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00001587 cast<ConstantIntegral>(ConstantExpr::getNot(AndRHS));
Misha Brukmanb1c93172005-04-21 23:48:37 +00001588 if (MaskedValueIsZero(Op0, NotAndRHS))
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00001589 return ReplaceInstUsesWith(I, Op0);
Chris Lattner86102b82005-01-01 16:22:27 +00001590
Chris Lattnerba1cb382003-09-19 17:17:26 +00001591 // Optimize a variety of ((val OP C1) & C2) combinations...
1592 if (isa<BinaryOperator>(Op0) || isa<ShiftInst>(Op0)) {
1593 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner86102b82005-01-01 16:22:27 +00001594 Value *Op0LHS = Op0I->getOperand(0);
1595 Value *Op0RHS = Op0I->getOperand(1);
1596 switch (Op0I->getOpcode()) {
1597 case Instruction::Xor:
1598 case Instruction::Or:
1599 // (X ^ V) & C2 --> (X & C2) iff (V & C2) == 0
1600 // (X | V) & C2 --> (X & C2) iff (V & C2) == 0
1601 if (MaskedValueIsZero(Op0LHS, AndRHS))
Misha Brukmanb1c93172005-04-21 23:48:37 +00001602 return BinaryOperator::createAnd(Op0RHS, AndRHS);
Chris Lattner86102b82005-01-01 16:22:27 +00001603 if (MaskedValueIsZero(Op0RHS, AndRHS))
Misha Brukmanb1c93172005-04-21 23:48:37 +00001604 return BinaryOperator::createAnd(Op0LHS, AndRHS);
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00001605
1606 // If the mask is only needed on one incoming arm, push it up.
1607 if (Op0I->hasOneUse()) {
1608 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
1609 // Not masking anything out for the LHS, move to RHS.
1610 Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
1611 Op0RHS->getName()+".masked");
1612 InsertNewInstBefore(NewRHS, I);
1613 return BinaryOperator::create(
1614 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001615 }
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00001616 if (!isa<Constant>(NotAndRHS) &&
1617 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
1618 // Not masking anything out for the RHS, move to LHS.
1619 Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
1620 Op0LHS->getName()+".masked");
1621 InsertNewInstBefore(NewLHS, I);
1622 return BinaryOperator::create(
1623 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
1624 }
1625 }
1626
Chris Lattner86102b82005-01-01 16:22:27 +00001627 break;
1628 case Instruction::And:
1629 // (X & V) & C2 --> 0 iff (V & C2) == 0
1630 if (MaskedValueIsZero(Op0LHS, AndRHS) ||
1631 MaskedValueIsZero(Op0RHS, AndRHS))
1632 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1633 break;
1634 }
1635
Chris Lattner16464b32003-07-23 19:25:52 +00001636 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner86102b82005-01-01 16:22:27 +00001637 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerba1cb382003-09-19 17:17:26 +00001638 return Res;
Chris Lattner86102b82005-01-01 16:22:27 +00001639 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
1640 const Type *SrcTy = CI->getOperand(0)->getType();
1641
1642 // If this is an integer sign or zero extension instruction.
1643 if (SrcTy->isIntegral() &&
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001644 SrcTy->getPrimitiveSizeInBits() <
1645 CI->getType()->getPrimitiveSizeInBits()) {
Chris Lattner86102b82005-01-01 16:22:27 +00001646
1647 if (SrcTy->isUnsigned()) {
1648 // See if this and is clearing out bits that are known to be zero
1649 // anyway (due to the zero extension).
1650 Constant *Mask = ConstantIntegral::getAllOnesValue(SrcTy);
1651 Mask = ConstantExpr::getZeroExtend(Mask, CI->getType());
1652 Constant *Result = ConstantExpr::getAnd(Mask, AndRHS);
1653 if (Result == Mask) // The "and" isn't doing anything, remove it.
1654 return ReplaceInstUsesWith(I, CI);
1655 if (Result != AndRHS) { // Reduce the and RHS constant.
1656 I.setOperand(1, Result);
1657 return &I;
1658 }
1659
1660 } else {
1661 if (CI->hasOneUse() && SrcTy->isInteger()) {
1662 // We can only do this if all of the sign bits brought in are masked
1663 // out. Compute this by first getting 0000011111, then inverting
1664 // it.
1665 Constant *Mask = ConstantIntegral::getAllOnesValue(SrcTy);
1666 Mask = ConstantExpr::getZeroExtend(Mask, CI->getType());
1667 Mask = ConstantExpr::getNot(Mask); // 1's in the new bits.
1668 if (ConstantExpr::getAnd(Mask, AndRHS)->isNullValue()) {
1669 // If the and is clearing all of the sign bits, change this to a
1670 // zero extension cast. To do this, cast the cast input to
1671 // unsigned, then to the requested size.
1672 Value *CastOp = CI->getOperand(0);
1673 Instruction *NC =
1674 new CastInst(CastOp, CastOp->getType()->getUnsignedVersion(),
1675 CI->getName()+".uns");
1676 NC = InsertNewInstBefore(NC, I);
1677 // Finally, insert a replacement for CI.
1678 NC = new CastInst(NC, CI->getType(), CI->getName());
1679 CI->setName("");
1680 NC = InsertNewInstBefore(NC, I);
1681 WorkList.push_back(CI); // Delete CI later.
1682 I.setOperand(0, NC);
1683 return &I; // The AND operand was modified.
1684 }
1685 }
1686 }
1687 }
Chris Lattner33217db2003-07-23 19:36:21 +00001688 }
Chris Lattner183b3362004-04-09 19:05:30 +00001689
1690 // Try to fold constant and into select arguments.
1691 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00001692 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00001693 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001694 if (isa<PHINode>(Op0))
1695 if (Instruction *NV = FoldOpIntoPhi(I))
1696 return NV;
Chris Lattner49b47ae2003-07-23 17:57:01 +00001697 }
1698
Chris Lattnerbb74e222003-03-10 23:06:50 +00001699 Value *Op0NotVal = dyn_castNotVal(Op0);
1700 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001701
Chris Lattner023a4832004-06-18 06:07:51 +00001702 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
1703 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1704
Misha Brukman9c003d82004-07-30 12:50:08 +00001705 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattnerbb74e222003-03-10 23:06:50 +00001706 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001707 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
1708 I.getName()+".demorgan");
Chris Lattner49b47ae2003-07-23 17:57:01 +00001709 InsertNewInstBefore(Or, I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001710 return BinaryOperator::createNot(Or);
1711 }
1712
Chris Lattner623826c2004-09-28 21:48:02 +00001713 if (SetCondInst *RHS = dyn_cast<SetCondInst>(Op1)) {
1714 // (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
Chris Lattner3ac7c262003-08-13 20:16:26 +00001715 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
1716 return R;
1717
Chris Lattner623826c2004-09-28 21:48:02 +00001718 Value *LHSVal, *RHSVal;
1719 ConstantInt *LHSCst, *RHSCst;
1720 Instruction::BinaryOps LHSCC, RHSCC;
1721 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
1722 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
1723 if (LHSVal == RHSVal && // Found (X setcc C1) & (X setcc C2)
1724 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
Misha Brukmanb1c93172005-04-21 23:48:37 +00001725 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
Chris Lattner623826c2004-09-28 21:48:02 +00001726 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
1727 // Ensure that the larger constant is on the RHS.
1728 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
1729 SetCondInst *LHS = cast<SetCondInst>(Op0);
1730 if (cast<ConstantBool>(Cmp)->getValue()) {
1731 std::swap(LHS, RHS);
1732 std::swap(LHSCst, RHSCst);
1733 std::swap(LHSCC, RHSCC);
1734 }
1735
1736 // At this point, we know we have have two setcc instructions
1737 // comparing a value against two constants and and'ing the result
1738 // together. Because of the above check, we know that we only have
1739 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
1740 // FoldSetCCLogical check above), that the two constants are not
1741 // equal.
1742 assert(LHSCst != RHSCst && "Compares not folded above?");
1743
1744 switch (LHSCC) {
1745 default: assert(0 && "Unknown integer condition code!");
1746 case Instruction::SetEQ:
1747 switch (RHSCC) {
1748 default: assert(0 && "Unknown integer condition code!");
1749 case Instruction::SetEQ: // (X == 13 & X == 15) -> false
1750 case Instruction::SetGT: // (X == 13 & X > 15) -> false
1751 return ReplaceInstUsesWith(I, ConstantBool::False);
1752 case Instruction::SetNE: // (X == 13 & X != 15) -> X == 13
1753 case Instruction::SetLT: // (X == 13 & X < 15) -> X == 13
1754 return ReplaceInstUsesWith(I, LHS);
1755 }
1756 case Instruction::SetNE:
1757 switch (RHSCC) {
1758 default: assert(0 && "Unknown integer condition code!");
1759 case Instruction::SetLT:
1760 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X < 14) -> X < 13
1761 return new SetCondInst(Instruction::SetLT, LHSVal, LHSCst);
1762 break; // (X != 13 & X < 15) -> no change
1763 case Instruction::SetEQ: // (X != 13 & X == 15) -> X == 15
1764 case Instruction::SetGT: // (X != 13 & X > 15) -> X > 15
1765 return ReplaceInstUsesWith(I, RHS);
1766 case Instruction::SetNE:
1767 if (LHSCst == SubOne(RHSCst)) {// (X != 13 & X != 14) -> X-13 >u 1
1768 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
1769 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
1770 LHSVal->getName()+".off");
1771 InsertNewInstBefore(Add, I);
1772 const Type *UnsType = Add->getType()->getUnsignedVersion();
1773 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
1774 AddCST = ConstantExpr::getSub(RHSCst, LHSCst);
1775 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1776 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
1777 }
1778 break; // (X != 13 & X != 15) -> no change
1779 }
1780 break;
1781 case Instruction::SetLT:
1782 switch (RHSCC) {
1783 default: assert(0 && "Unknown integer condition code!");
1784 case Instruction::SetEQ: // (X < 13 & X == 15) -> false
1785 case Instruction::SetGT: // (X < 13 & X > 15) -> false
1786 return ReplaceInstUsesWith(I, ConstantBool::False);
1787 case Instruction::SetNE: // (X < 13 & X != 15) -> X < 13
1788 case Instruction::SetLT: // (X < 13 & X < 15) -> X < 13
1789 return ReplaceInstUsesWith(I, LHS);
1790 }
1791 case Instruction::SetGT:
1792 switch (RHSCC) {
1793 default: assert(0 && "Unknown integer condition code!");
1794 case Instruction::SetEQ: // (X > 13 & X == 15) -> X > 13
1795 return ReplaceInstUsesWith(I, LHS);
1796 case Instruction::SetGT: // (X > 13 & X > 15) -> X > 15
1797 return ReplaceInstUsesWith(I, RHS);
1798 case Instruction::SetNE:
1799 if (RHSCst == AddOne(LHSCst)) // (X > 13 & X != 14) -> X > 14
1800 return new SetCondInst(Instruction::SetGT, LHSVal, RHSCst);
1801 break; // (X > 13 & X != 15) -> no change
Chris Lattner6862fbd2004-09-29 17:40:11 +00001802 case Instruction::SetLT: // (X > 13 & X < 15) -> (X-14) <u 1
1803 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true, I);
Chris Lattner623826c2004-09-28 21:48:02 +00001804 }
1805 }
1806 }
1807 }
1808
Chris Lattner113f4f42002-06-25 16:13:24 +00001809 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001810}
1811
Chris Lattner113f4f42002-06-25 16:13:24 +00001812Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001813 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00001814 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001815
Chris Lattner81a7a232004-10-16 18:11:37 +00001816 if (isa<UndefValue>(Op1))
1817 return ReplaceInstUsesWith(I, // X | undef -> -1
1818 ConstantIntegral::getAllOnesValue(I.getType()));
1819
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001820 // or X, X = X or X, 0 == X
Chris Lattnere6794492002-08-12 21:17:25 +00001821 if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
1822 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001823
1824 // or X, -1 == -1
Chris Lattner8f0d1562003-07-23 18:29:44 +00001825 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner86102b82005-01-01 16:22:27 +00001826 // If X is known to only contain bits that already exist in RHS, just
1827 // replace this instruction with RHS directly.
1828 if (MaskedValueIsZero(Op0,
1829 cast<ConstantIntegral>(ConstantExpr::getNot(RHS))))
1830 return ReplaceInstUsesWith(I, RHS);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001831
Chris Lattnerd4252a72004-07-30 07:50:03 +00001832 ConstantInt *C1; Value *X;
1833 // (X & C1) | C2 --> (X | C2) & (C1|C2)
1834 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Chris Lattnerb62f5082005-05-09 04:58:36 +00001835 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0->getName());
1836 Op0->setName("");
Chris Lattnerd4252a72004-07-30 07:50:03 +00001837 InsertNewInstBefore(Or, I);
1838 return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, C1));
1839 }
Chris Lattner8f0d1562003-07-23 18:29:44 +00001840
Chris Lattnerd4252a72004-07-30 07:50:03 +00001841 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
1842 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
1843 std::string Op0Name = Op0->getName(); Op0->setName("");
1844 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
1845 InsertNewInstBefore(Or, I);
1846 return BinaryOperator::createXor(Or,
1847 ConstantExpr::getAnd(C1, ConstantExpr::getNot(RHS)));
Chris Lattner8f0d1562003-07-23 18:29:44 +00001848 }
Chris Lattner183b3362004-04-09 19:05:30 +00001849
1850 // Try to fold constant and into select arguments.
1851 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00001852 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00001853 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001854 if (isa<PHINode>(Op0))
1855 if (Instruction *NV = FoldOpIntoPhi(I))
1856 return NV;
Chris Lattner8f0d1562003-07-23 18:29:44 +00001857 }
1858
Chris Lattnerd4252a72004-07-30 07:50:03 +00001859 Value *A, *B; ConstantInt *C1, *C2;
Chris Lattner4294cec2005-05-07 23:49:08 +00001860
1861 if (match(Op0, m_And(m_Value(A), m_Value(B))))
1862 if (A == Op1 || B == Op1) // (A & ?) | A --> A
1863 return ReplaceInstUsesWith(I, Op1);
1864 if (match(Op1, m_And(m_Value(A), m_Value(B))))
1865 if (A == Op0 || B == Op0) // A | (A & ?) --> A
1866 return ReplaceInstUsesWith(I, Op0);
1867
Chris Lattnerb62f5082005-05-09 04:58:36 +00001868 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
1869 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
1870 MaskedValueIsZero(Op1, C1)) {
1871 Instruction *NOr = BinaryOperator::createOr(A, Op1, Op0->getName());
1872 Op0->setName("");
1873 return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
1874 }
1875
1876 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
1877 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
1878 MaskedValueIsZero(Op0, C1)) {
1879 Instruction *NOr = BinaryOperator::createOr(A, Op0, Op1->getName());
1880 Op0->setName("");
1881 return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
1882 }
1883
Chris Lattner4294cec2005-05-07 23:49:08 +00001884 // (A & C1)|(A & C2) == A & (C1|C2)
Chris Lattnerd4252a72004-07-30 07:50:03 +00001885 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
1886 match(Op1, m_And(m_Value(B), m_ConstantInt(C2))) && A == B)
1887 return BinaryOperator::createAnd(A, ConstantExpr::getOr(C1, C2));
Chris Lattner812aab72003-08-12 19:11:07 +00001888
Chris Lattnerd4252a72004-07-30 07:50:03 +00001889 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
1890 if (A == Op1) // ~A | A == -1
Misha Brukmanb1c93172005-04-21 23:48:37 +00001891 return ReplaceInstUsesWith(I,
Chris Lattnerd4252a72004-07-30 07:50:03 +00001892 ConstantIntegral::getAllOnesValue(I.getType()));
1893 } else {
1894 A = 0;
1895 }
Chris Lattner4294cec2005-05-07 23:49:08 +00001896 // Note, A is still live here!
Chris Lattnerd4252a72004-07-30 07:50:03 +00001897 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
1898 if (Op0 == B)
Misha Brukmanb1c93172005-04-21 23:48:37 +00001899 return ReplaceInstUsesWith(I,
Chris Lattnerd4252a72004-07-30 07:50:03 +00001900 ConstantIntegral::getAllOnesValue(I.getType()));
Chris Lattner3e327a42003-03-10 23:13:59 +00001901
Misha Brukman9c003d82004-07-30 12:50:08 +00001902 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattnerd4252a72004-07-30 07:50:03 +00001903 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
1904 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
1905 I.getName()+".demorgan"), I);
1906 return BinaryOperator::createNot(And);
1907 }
Chris Lattner3e327a42003-03-10 23:13:59 +00001908 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00001909
Chris Lattner3ac7c262003-08-13 20:16:26 +00001910 // (setcc1 A, B) | (setcc2 A, B) --> (setcc3 A, B)
Chris Lattnerdcf756e2004-09-28 22:33:08 +00001911 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1))) {
Chris Lattner3ac7c262003-08-13 20:16:26 +00001912 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
1913 return R;
1914
Chris Lattnerdcf756e2004-09-28 22:33:08 +00001915 Value *LHSVal, *RHSVal;
1916 ConstantInt *LHSCst, *RHSCst;
1917 Instruction::BinaryOps LHSCC, RHSCC;
1918 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
1919 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
1920 if (LHSVal == RHSVal && // Found (X setcc C1) | (X setcc C2)
1921 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
Misha Brukmanb1c93172005-04-21 23:48:37 +00001922 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
Chris Lattnerdcf756e2004-09-28 22:33:08 +00001923 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
1924 // Ensure that the larger constant is on the RHS.
1925 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
1926 SetCondInst *LHS = cast<SetCondInst>(Op0);
1927 if (cast<ConstantBool>(Cmp)->getValue()) {
1928 std::swap(LHS, RHS);
1929 std::swap(LHSCst, RHSCst);
1930 std::swap(LHSCC, RHSCC);
1931 }
1932
1933 // At this point, we know we have have two setcc instructions
1934 // comparing a value against two constants and or'ing the result
1935 // together. Because of the above check, we know that we only have
1936 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
1937 // FoldSetCCLogical check above), that the two constants are not
1938 // equal.
1939 assert(LHSCst != RHSCst && "Compares not folded above?");
1940
1941 switch (LHSCC) {
1942 default: assert(0 && "Unknown integer condition code!");
1943 case Instruction::SetEQ:
1944 switch (RHSCC) {
1945 default: assert(0 && "Unknown integer condition code!");
1946 case Instruction::SetEQ:
1947 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
1948 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
1949 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
1950 LHSVal->getName()+".off");
1951 InsertNewInstBefore(Add, I);
1952 const Type *UnsType = Add->getType()->getUnsignedVersion();
1953 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
1954 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
1955 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1956 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
1957 }
1958 break; // (X == 13 | X == 15) -> no change
1959
Chris Lattner5c219462005-04-19 06:04:18 +00001960 case Instruction::SetGT: // (X == 13 | X > 14) -> no change
1961 break;
Chris Lattnerdcf756e2004-09-28 22:33:08 +00001962 case Instruction::SetNE: // (X == 13 | X != 15) -> X != 15
1963 case Instruction::SetLT: // (X == 13 | X < 15) -> X < 15
1964 return ReplaceInstUsesWith(I, RHS);
1965 }
1966 break;
1967 case Instruction::SetNE:
1968 switch (RHSCC) {
1969 default: assert(0 && "Unknown integer condition code!");
1970 case Instruction::SetLT: // (X != 13 | X < 15) -> X < 15
1971 return ReplaceInstUsesWith(I, RHS);
1972 case Instruction::SetEQ: // (X != 13 | X == 15) -> X != 13
1973 case Instruction::SetGT: // (X != 13 | X > 15) -> X != 13
1974 return ReplaceInstUsesWith(I, LHS);
1975 case Instruction::SetNE: // (X != 13 | X != 15) -> true
1976 return ReplaceInstUsesWith(I, ConstantBool::True);
1977 }
1978 break;
1979 case Instruction::SetLT:
1980 switch (RHSCC) {
1981 default: assert(0 && "Unknown integer condition code!");
1982 case Instruction::SetEQ: // (X < 13 | X == 14) -> no change
1983 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00001984 case Instruction::SetGT: // (X < 13 | X > 15) -> (X-13) > 2
1985 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false, I);
Chris Lattnerdcf756e2004-09-28 22:33:08 +00001986 case Instruction::SetNE: // (X < 13 | X != 15) -> X != 15
1987 case Instruction::SetLT: // (X < 13 | X < 15) -> X < 15
1988 return ReplaceInstUsesWith(I, RHS);
1989 }
1990 break;
1991 case Instruction::SetGT:
1992 switch (RHSCC) {
1993 default: assert(0 && "Unknown integer condition code!");
1994 case Instruction::SetEQ: // (X > 13 | X == 15) -> X > 13
1995 case Instruction::SetGT: // (X > 13 | X > 15) -> X > 13
1996 return ReplaceInstUsesWith(I, LHS);
1997 case Instruction::SetNE: // (X > 13 | X != 15) -> true
1998 case Instruction::SetLT: // (X > 13 | X < 15) -> true
1999 return ReplaceInstUsesWith(I, ConstantBool::True);
2000 }
2001 }
2002 }
2003 }
Chris Lattner113f4f42002-06-25 16:13:24 +00002004 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002005}
2006
Chris Lattnerc2076352004-02-16 01:20:27 +00002007// XorSelf - Implements: X ^ X --> 0
2008struct XorSelf {
2009 Value *RHS;
2010 XorSelf(Value *rhs) : RHS(rhs) {}
2011 bool shouldApply(Value *LHS) const { return LHS == RHS; }
2012 Instruction *apply(BinaryOperator &Xor) const {
2013 return &Xor;
2014 }
2015};
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002016
2017
Chris Lattner113f4f42002-06-25 16:13:24 +00002018Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00002019 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00002020 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002021
Chris Lattner81a7a232004-10-16 18:11:37 +00002022 if (isa<UndefValue>(Op1))
2023 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
2024
Chris Lattnerc2076352004-02-16 01:20:27 +00002025 // xor X, X = 0, even if X is nested in a sequence of Xor's.
2026 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
2027 assert(Result == &I && "AssociativeOpt didn't work?");
Chris Lattnere6794492002-08-12 21:17:25 +00002028 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc2076352004-02-16 01:20:27 +00002029 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002030
Chris Lattner97638592003-07-23 21:37:07 +00002031 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002032 // xor X, 0 == X
Chris Lattner97638592003-07-23 21:37:07 +00002033 if (RHS->isNullValue())
Chris Lattnere6794492002-08-12 21:17:25 +00002034 return ReplaceInstUsesWith(I, Op0);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002035
Chris Lattner97638592003-07-23 21:37:07 +00002036 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerb8d6e402002-08-20 18:24:26 +00002037 // xor (setcc A, B), true = not (setcc A, B) = setncc A, B
Chris Lattner97638592003-07-23 21:37:07 +00002038 if (SetCondInst *SCI = dyn_cast<SetCondInst>(Op0I))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002039 if (RHS == ConstantBool::True && SCI->hasOneUse())
Chris Lattnerb8d6e402002-08-20 18:24:26 +00002040 return new SetCondInst(SCI->getInverseCondition(),
2041 SCI->getOperand(0), SCI->getOperand(1));
Chris Lattnere5806662003-11-04 23:50:51 +00002042
Chris Lattner8f2f5982003-11-05 01:06:05 +00002043 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002044 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
2045 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002046 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
2047 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002048 ConstantInt::get(I.getType(), 1));
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002049 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002050 }
Chris Lattner023a4832004-06-18 06:07:51 +00002051
2052 // ~(~X & Y) --> (X | ~Y)
2053 if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
2054 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
2055 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
2056 Instruction *NotY =
Misha Brukmanb1c93172005-04-21 23:48:37 +00002057 BinaryOperator::createNot(Op0I->getOperand(1),
Chris Lattner023a4832004-06-18 06:07:51 +00002058 Op0I->getOperand(1)->getName()+".not");
2059 InsertNewInstBefore(NotY, I);
2060 return BinaryOperator::createOr(Op0NotVal, NotY);
2061 }
2062 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002063
Chris Lattner97638592003-07-23 21:37:07 +00002064 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattnere5806662003-11-04 23:50:51 +00002065 switch (Op0I->getOpcode()) {
2066 case Instruction::Add:
Chris Lattner0f68fa62003-11-04 23:37:10 +00002067 // ~(X-c) --> (-c-1)-X
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002068 if (RHS->isAllOnesValue()) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002069 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
2070 return BinaryOperator::createSub(
2071 ConstantExpr::getSub(NegOp0CI,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002072 ConstantInt::get(I.getType(), 1)),
Chris Lattner0f68fa62003-11-04 23:37:10 +00002073 Op0I->getOperand(0));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002074 }
Chris Lattnere5806662003-11-04 23:50:51 +00002075 break;
2076 case Instruction::And:
Chris Lattner97638592003-07-23 21:37:07 +00002077 // (X & C1) ^ C2 --> (X & C1) | C2 iff (C1&C2) == 0
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002078 if (ConstantExpr::getAnd(RHS, Op0CI)->isNullValue())
2079 return BinaryOperator::createOr(Op0, RHS);
Chris Lattnere5806662003-11-04 23:50:51 +00002080 break;
2081 case Instruction::Or:
Chris Lattner97638592003-07-23 21:37:07 +00002082 // (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002083 if (ConstantExpr::getAnd(RHS, Op0CI) == RHS)
Chris Lattnerc8e7e292004-06-10 02:12:35 +00002084 return BinaryOperator::createAnd(Op0, ConstantExpr::getNot(RHS));
Chris Lattnere5806662003-11-04 23:50:51 +00002085 break;
2086 default: break;
Chris Lattner97638592003-07-23 21:37:07 +00002087 }
Chris Lattnerb8d6e402002-08-20 18:24:26 +00002088 }
Chris Lattner183b3362004-04-09 19:05:30 +00002089
2090 // Try to fold constant and into select arguments.
2091 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00002092 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00002093 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002094 if (isa<PHINode>(Op0))
2095 if (Instruction *NV = FoldOpIntoPhi(I))
2096 return NV;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002097 }
2098
Chris Lattnerbb74e222003-03-10 23:06:50 +00002099 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00002100 if (X == Op1)
2101 return ReplaceInstUsesWith(I,
2102 ConstantIntegral::getAllOnesValue(I.getType()));
2103
Chris Lattnerbb74e222003-03-10 23:06:50 +00002104 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00002105 if (X == Op0)
2106 return ReplaceInstUsesWith(I,
2107 ConstantIntegral::getAllOnesValue(I.getType()));
2108
Chris Lattner1bbb7b62003-03-10 18:24:17 +00002109 if (Instruction *Op1I = dyn_cast<Instruction>(Op1))
Chris Lattnerb36d9082004-02-16 03:54:20 +00002110 if (Op1I->getOpcode() == Instruction::Or) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00002111 if (Op1I->getOperand(0) == Op0) { // B^(B|A) == (A|B)^B
2112 cast<BinaryOperator>(Op1I)->swapOperands();
2113 I.swapOperands();
2114 std::swap(Op0, Op1);
2115 } else if (Op1I->getOperand(1) == Op0) { // B^(A|B) == (A|B)^B
2116 I.swapOperands();
2117 std::swap(Op0, Op1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002118 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00002119 } else if (Op1I->getOpcode() == Instruction::Xor) {
2120 if (Op0 == Op1I->getOperand(0)) // A^(A^B) == B
2121 return ReplaceInstUsesWith(I, Op1I->getOperand(1));
2122 else if (Op0 == Op1I->getOperand(1)) // A^(B^A) == B
2123 return ReplaceInstUsesWith(I, Op1I->getOperand(0));
2124 }
Chris Lattner1bbb7b62003-03-10 18:24:17 +00002125
2126 if (Instruction *Op0I = dyn_cast<Instruction>(Op0))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002127 if (Op0I->getOpcode() == Instruction::Or && Op0I->hasOneUse()) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00002128 if (Op0I->getOperand(0) == Op1) // (B|A)^B == (A|B)^B
2129 cast<BinaryOperator>(Op0I)->swapOperands();
Chris Lattnerdcf240a2003-03-10 21:43:22 +00002130 if (Op0I->getOperand(1) == Op1) { // (A|B)^B == A & ~B
Chris Lattner396dbfe2004-06-09 05:08:07 +00002131 Value *NotB = InsertNewInstBefore(BinaryOperator::createNot(Op1,
2132 Op1->getName()+".not"), I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002133 return BinaryOperator::createAnd(Op0I->getOperand(0), NotB);
Chris Lattner1bbb7b62003-03-10 18:24:17 +00002134 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00002135 } else if (Op0I->getOpcode() == Instruction::Xor) {
2136 if (Op1 == Op0I->getOperand(0)) // (A^B)^A == B
2137 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2138 else if (Op1 == Op0I->getOperand(1)) // (B^A)^A == B
2139 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner1bbb7b62003-03-10 18:24:17 +00002140 }
2141
Chris Lattner7aa2d472004-08-01 19:42:59 +00002142 // (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattnerd4252a72004-07-30 07:50:03 +00002143 Value *A, *B; ConstantInt *C1, *C2;
2144 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
2145 match(Op1, m_And(m_Value(B), m_ConstantInt(C2))) &&
Chris Lattner7aa2d472004-08-01 19:42:59 +00002146 ConstantExpr::getAnd(C1, C2)->isNullValue())
Chris Lattnerd4252a72004-07-30 07:50:03 +00002147 return BinaryOperator::createOr(Op0, Op1);
Chris Lattner7fb29e12003-03-11 00:12:48 +00002148
Chris Lattner3ac7c262003-08-13 20:16:26 +00002149 // (setcc1 A, B) ^ (setcc2 A, B) --> (setcc3 A, B)
2150 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
2151 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
2152 return R;
2153
Chris Lattner113f4f42002-06-25 16:13:24 +00002154 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002155}
2156
Chris Lattner6862fbd2004-09-29 17:40:11 +00002157/// MulWithOverflow - Compute Result = In1*In2, returning true if the result
2158/// overflowed for this type.
2159static bool MulWithOverflow(ConstantInt *&Result, ConstantInt *In1,
2160 ConstantInt *In2) {
2161 Result = cast<ConstantInt>(ConstantExpr::getMul(In1, In2));
2162 return !In2->isNullValue() && ConstantExpr::getDiv(Result, In2) != In1;
2163}
2164
2165static bool isPositive(ConstantInt *C) {
2166 return cast<ConstantSInt>(C)->getValue() >= 0;
2167}
2168
2169/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
2170/// overflowed for this type.
2171static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
2172 ConstantInt *In2) {
2173 Result = cast<ConstantInt>(ConstantExpr::getAdd(In1, In2));
2174
2175 if (In1->getType()->isUnsigned())
2176 return cast<ConstantUInt>(Result)->getValue() <
2177 cast<ConstantUInt>(In1)->getValue();
2178 if (isPositive(In1) != isPositive(In2))
2179 return false;
2180 if (isPositive(In1))
2181 return cast<ConstantSInt>(Result)->getValue() <
2182 cast<ConstantSInt>(In1)->getValue();
2183 return cast<ConstantSInt>(Result)->getValue() >
2184 cast<ConstantSInt>(In1)->getValue();
2185}
2186
Chris Lattner0798af32005-01-13 20:14:25 +00002187/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
2188/// code necessary to compute the offset from the base pointer (without adding
2189/// in the base pointer). Return the result as a signed integer of intptr size.
2190static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
2191 TargetData &TD = IC.getTargetData();
2192 gep_type_iterator GTI = gep_type_begin(GEP);
2193 const Type *UIntPtrTy = TD.getIntPtrType();
2194 const Type *SIntPtrTy = UIntPtrTy->getSignedVersion();
2195 Value *Result = Constant::getNullValue(SIntPtrTy);
2196
2197 // Build a mask for high order bits.
2198 uint64_t PtrSizeMask = ~0ULL;
2199 PtrSizeMask >>= 64-(TD.getPointerSize()*8);
2200
Chris Lattner0798af32005-01-13 20:14:25 +00002201 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
2202 Value *Op = GEP->getOperand(i);
Chris Lattnerd35d2102005-01-13 23:26:48 +00002203 uint64_t Size = TD.getTypeSize(GTI.getIndexedType()) & PtrSizeMask;
Chris Lattner0798af32005-01-13 20:14:25 +00002204 Constant *Scale = ConstantExpr::getCast(ConstantUInt::get(UIntPtrTy, Size),
2205 SIntPtrTy);
2206 if (Constant *OpC = dyn_cast<Constant>(Op)) {
2207 if (!OpC->isNullValue()) {
Chris Lattner4cb9fa32005-01-13 20:40:58 +00002208 OpC = ConstantExpr::getCast(OpC, SIntPtrTy);
Chris Lattner0798af32005-01-13 20:14:25 +00002209 Scale = ConstantExpr::getMul(OpC, Scale);
2210 if (Constant *RC = dyn_cast<Constant>(Result))
2211 Result = ConstantExpr::getAdd(RC, Scale);
2212 else {
2213 // Emit an add instruction.
2214 Result = IC.InsertNewInstBefore(
2215 BinaryOperator::createAdd(Result, Scale,
2216 GEP->getName()+".offs"), I);
2217 }
2218 }
2219 } else {
Chris Lattner7aa41cf2005-01-14 17:17:59 +00002220 // Convert to correct type.
2221 Op = IC.InsertNewInstBefore(new CastInst(Op, SIntPtrTy,
2222 Op->getName()+".c"), I);
2223 if (Size != 1)
Chris Lattner4cb9fa32005-01-13 20:40:58 +00002224 // We'll let instcombine(mul) convert this to a shl if possible.
2225 Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
2226 GEP->getName()+".idx"), I);
Chris Lattner0798af32005-01-13 20:14:25 +00002227
2228 // Emit an add instruction.
Chris Lattner4cb9fa32005-01-13 20:40:58 +00002229 Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
Chris Lattner0798af32005-01-13 20:14:25 +00002230 GEP->getName()+".offs"), I);
2231 }
2232 }
2233 return Result;
2234}
2235
2236/// FoldGEPSetCC - Fold comparisons between a GEP instruction and something
2237/// else. At this point we know that the GEP is on the LHS of the comparison.
2238Instruction *InstCombiner::FoldGEPSetCC(User *GEPLHS, Value *RHS,
2239 Instruction::BinaryOps Cond,
2240 Instruction &I) {
2241 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattner81e84172005-01-13 22:25:21 +00002242
2243 if (CastInst *CI = dyn_cast<CastInst>(RHS))
2244 if (isa<PointerType>(CI->getOperand(0)->getType()))
2245 RHS = CI->getOperand(0);
2246
Chris Lattner0798af32005-01-13 20:14:25 +00002247 Value *PtrBase = GEPLHS->getOperand(0);
2248 if (PtrBase == RHS) {
2249 // As an optimization, we don't actually have to compute the actual value of
2250 // OFFSET if this is a seteq or setne comparison, just return whether each
2251 // index is zero or not.
Chris Lattner81e84172005-01-13 22:25:21 +00002252 if (Cond == Instruction::SetEQ || Cond == Instruction::SetNE) {
2253 Instruction *InVal = 0;
Chris Lattnercd517ff2005-01-28 19:32:01 +00002254 gep_type_iterator GTI = gep_type_begin(GEPLHS);
2255 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i, ++GTI) {
Chris Lattner81e84172005-01-13 22:25:21 +00002256 bool EmitIt = true;
2257 if (Constant *C = dyn_cast<Constant>(GEPLHS->getOperand(i))) {
2258 if (isa<UndefValue>(C)) // undef index -> undef.
2259 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2260 if (C->isNullValue())
2261 EmitIt = false;
Chris Lattnercd517ff2005-01-28 19:32:01 +00002262 else if (TD->getTypeSize(GTI.getIndexedType()) == 0) {
2263 EmitIt = false; // This is indexing into a zero sized array?
Misha Brukmanb1c93172005-04-21 23:48:37 +00002264 } else if (isa<ConstantInt>(C))
Chris Lattner81e84172005-01-13 22:25:21 +00002265 return ReplaceInstUsesWith(I, // No comparison is needed here.
2266 ConstantBool::get(Cond == Instruction::SetNE));
2267 }
2268
2269 if (EmitIt) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00002270 Instruction *Comp =
Chris Lattner81e84172005-01-13 22:25:21 +00002271 new SetCondInst(Cond, GEPLHS->getOperand(i),
2272 Constant::getNullValue(GEPLHS->getOperand(i)->getType()));
2273 if (InVal == 0)
2274 InVal = Comp;
2275 else {
2276 InVal = InsertNewInstBefore(InVal, I);
2277 InsertNewInstBefore(Comp, I);
2278 if (Cond == Instruction::SetNE) // True if any are unequal
2279 InVal = BinaryOperator::createOr(InVal, Comp);
2280 else // True if all are equal
2281 InVal = BinaryOperator::createAnd(InVal, Comp);
2282 }
2283 }
2284 }
2285
2286 if (InVal)
2287 return InVal;
2288 else
2289 ReplaceInstUsesWith(I, // No comparison is needed here, all indexes = 0
2290 ConstantBool::get(Cond == Instruction::SetEQ));
2291 }
Chris Lattner0798af32005-01-13 20:14:25 +00002292
2293 // Only lower this if the setcc is the only user of the GEP or if we expect
2294 // the result to fold to a constant!
2295 if (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) {
2296 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
2297 Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
2298 return new SetCondInst(Cond, Offset,
2299 Constant::getNullValue(Offset->getType()));
2300 }
2301 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
Chris Lattnera21bf8d2005-04-25 20:17:30 +00002302 // If the base pointers are different, but the indices are the same, just
2303 // compare the base pointer.
2304 if (PtrBase != GEPRHS->getOperand(0)) {
2305 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Chris Lattnerbd43b9d2005-04-26 14:40:41 +00002306 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
2307 GEPRHS->getOperand(0)->getType();
Chris Lattnera21bf8d2005-04-25 20:17:30 +00002308 if (IndicesTheSame)
2309 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
2310 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
2311 IndicesTheSame = false;
2312 break;
2313 }
2314
2315 // If all indices are the same, just compare the base pointers.
2316 if (IndicesTheSame)
2317 return new SetCondInst(Cond, GEPLHS->getOperand(0),
2318 GEPRHS->getOperand(0));
2319
2320 // Otherwise, the base pointers are different and the indices are
2321 // different, bail out.
Chris Lattner0798af32005-01-13 20:14:25 +00002322 return 0;
Chris Lattnera21bf8d2005-04-25 20:17:30 +00002323 }
Chris Lattner0798af32005-01-13 20:14:25 +00002324
Chris Lattner81e84172005-01-13 22:25:21 +00002325 // If one of the GEPs has all zero indices, recurse.
2326 bool AllZeros = true;
2327 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
2328 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
2329 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
2330 AllZeros = false;
2331 break;
2332 }
2333 if (AllZeros)
2334 return FoldGEPSetCC(GEPRHS, GEPLHS->getOperand(0),
2335 SetCondInst::getSwappedCondition(Cond), I);
Chris Lattner4fa89822005-01-14 00:20:05 +00002336
2337 // If the other GEP has all zero indices, recurse.
Chris Lattner81e84172005-01-13 22:25:21 +00002338 AllZeros = true;
2339 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
2340 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
2341 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
2342 AllZeros = false;
2343 break;
2344 }
2345 if (AllZeros)
2346 return FoldGEPSetCC(GEPLHS, GEPRHS->getOperand(0), Cond, I);
2347
Chris Lattner4fa89822005-01-14 00:20:05 +00002348 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
2349 // If the GEPs only differ by one index, compare it.
2350 unsigned NumDifferences = 0; // Keep track of # differences.
2351 unsigned DiffOperand = 0; // The operand that differs.
2352 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
2353 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002354 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
2355 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattnerfc4429e2005-01-21 23:06:49 +00002356 // Irreconcilable differences.
Chris Lattner4fa89822005-01-14 00:20:05 +00002357 NumDifferences = 2;
2358 break;
2359 } else {
2360 if (NumDifferences++) break;
2361 DiffOperand = i;
2362 }
2363 }
2364
2365 if (NumDifferences == 0) // SAME GEP?
2366 return ReplaceInstUsesWith(I, // No comparison is needed here.
2367 ConstantBool::get(Cond == Instruction::SetEQ));
2368 else if (NumDifferences == 1) {
Chris Lattnerfc4429e2005-01-21 23:06:49 +00002369 Value *LHSV = GEPLHS->getOperand(DiffOperand);
2370 Value *RHSV = GEPRHS->getOperand(DiffOperand);
2371 if (LHSV->getType() != RHSV->getType())
2372 LHSV = InsertNewInstBefore(new CastInst(LHSV, RHSV->getType(),
2373 LHSV->getName()+".c"), I);
2374 return new SetCondInst(Cond, LHSV, RHSV);
Chris Lattner4fa89822005-01-14 00:20:05 +00002375 }
2376 }
2377
Chris Lattner0798af32005-01-13 20:14:25 +00002378 // Only lower this if the setcc is the only user of the GEP or if we expect
2379 // the result to fold to a constant!
2380 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
2381 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
2382 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
2383 Value *L = EmitGEPOffset(GEPLHS, I, *this);
2384 Value *R = EmitGEPOffset(GEPRHS, I, *this);
2385 return new SetCondInst(Cond, L, R);
2386 }
2387 }
2388 return 0;
2389}
2390
2391
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002392Instruction *InstCombiner::visitSetCondInst(SetCondInst &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00002393 bool Changed = SimplifyCommutative(I);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002394 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2395 const Type *Ty = Op0->getType();
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002396
2397 // setcc X, X
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002398 if (Op0 == Op1)
2399 return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
Chris Lattner1fc23f32002-05-09 20:11:54 +00002400
Chris Lattner81a7a232004-10-16 18:11:37 +00002401 if (isa<UndefValue>(Op1)) // X setcc undef -> undef
2402 return ReplaceInstUsesWith(I, UndefValue::get(Type::BoolTy));
2403
Chris Lattner15ff1e12004-11-14 07:33:16 +00002404 // setcc <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
2405 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanb1c93172005-04-21 23:48:37 +00002406 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
2407 isa<ConstantPointerNull>(Op0)) &&
2408 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner15ff1e12004-11-14 07:33:16 +00002409 isa<ConstantPointerNull>(Op1)))
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002410 return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
2411
2412 // setcc's with boolean values can always be turned into bitwise operations
2413 if (Ty == Type::BoolTy) {
Chris Lattner4456da62004-08-11 00:50:51 +00002414 switch (I.getOpcode()) {
2415 default: assert(0 && "Invalid setcc instruction!");
2416 case Instruction::SetEQ: { // seteq bool %A, %B -> ~(A^B)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002417 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002418 InsertNewInstBefore(Xor, I);
Chris Lattner16930792003-11-03 04:25:02 +00002419 return BinaryOperator::createNot(Xor);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002420 }
Chris Lattner4456da62004-08-11 00:50:51 +00002421 case Instruction::SetNE:
2422 return BinaryOperator::createXor(Op0, Op1);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002423
Chris Lattner4456da62004-08-11 00:50:51 +00002424 case Instruction::SetGT:
2425 std::swap(Op0, Op1); // Change setgt -> setlt
2426 // FALL THROUGH
2427 case Instruction::SetLT: { // setlt bool A, B -> ~X & Y
2428 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
2429 InsertNewInstBefore(Not, I);
2430 return BinaryOperator::createAnd(Not, Op1);
2431 }
2432 case Instruction::SetGE:
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002433 std::swap(Op0, Op1); // Change setge -> setle
Chris Lattner4456da62004-08-11 00:50:51 +00002434 // FALL THROUGH
2435 case Instruction::SetLE: { // setle bool %A, %B -> ~A | B
2436 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
2437 InsertNewInstBefore(Not, I);
2438 return BinaryOperator::createOr(Not, Op1);
2439 }
2440 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002441 }
2442
Chris Lattner2dd01742004-06-09 04:24:29 +00002443 // See if we are doing a comparison between a constant and an instruction that
2444 // can be folded into the comparison.
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002445 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner6862fbd2004-09-29 17:40:11 +00002446 // Check to see if we are comparing against the minimum or maximum value...
2447 if (CI->isMinValue()) {
2448 if (I.getOpcode() == Instruction::SetLT) // A < MIN -> FALSE
2449 return ReplaceInstUsesWith(I, ConstantBool::False);
2450 if (I.getOpcode() == Instruction::SetGE) // A >= MIN -> TRUE
2451 return ReplaceInstUsesWith(I, ConstantBool::True);
2452 if (I.getOpcode() == Instruction::SetLE) // A <= MIN -> A == MIN
2453 return BinaryOperator::createSetEQ(Op0, Op1);
2454 if (I.getOpcode() == Instruction::SetGT) // A > MIN -> A != MIN
2455 return BinaryOperator::createSetNE(Op0, Op1);
2456
2457 } else if (CI->isMaxValue()) {
2458 if (I.getOpcode() == Instruction::SetGT) // A > MAX -> FALSE
2459 return ReplaceInstUsesWith(I, ConstantBool::False);
2460 if (I.getOpcode() == Instruction::SetLE) // A <= MAX -> TRUE
2461 return ReplaceInstUsesWith(I, ConstantBool::True);
2462 if (I.getOpcode() == Instruction::SetGE) // A >= MAX -> A == MAX
2463 return BinaryOperator::createSetEQ(Op0, Op1);
2464 if (I.getOpcode() == Instruction::SetLT) // A < MAX -> A != MAX
2465 return BinaryOperator::createSetNE(Op0, Op1);
2466
2467 // Comparing against a value really close to min or max?
2468 } else if (isMinValuePlusOne(CI)) {
2469 if (I.getOpcode() == Instruction::SetLT) // A < MIN+1 -> A == MIN
2470 return BinaryOperator::createSetEQ(Op0, SubOne(CI));
2471 if (I.getOpcode() == Instruction::SetGE) // A >= MIN-1 -> A != MIN
2472 return BinaryOperator::createSetNE(Op0, SubOne(CI));
2473
2474 } else if (isMaxValueMinusOne(CI)) {
2475 if (I.getOpcode() == Instruction::SetGT) // A > MAX-1 -> A == MAX
2476 return BinaryOperator::createSetEQ(Op0, AddOne(CI));
2477 if (I.getOpcode() == Instruction::SetLE) // A <= MAX-1 -> A != MAX
2478 return BinaryOperator::createSetNE(Op0, AddOne(CI));
2479 }
2480
2481 // If we still have a setle or setge instruction, turn it into the
2482 // appropriate setlt or setgt instruction. Since the border cases have
2483 // already been handled above, this requires little checking.
2484 //
2485 if (I.getOpcode() == Instruction::SetLE)
2486 return BinaryOperator::createSetLT(Op0, AddOne(CI));
2487 if (I.getOpcode() == Instruction::SetGE)
2488 return BinaryOperator::createSetGT(Op0, SubOne(CI));
2489
Chris Lattnere1e10e12004-05-25 06:32:08 +00002490 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002491 switch (LHSI->getOpcode()) {
2492 case Instruction::And:
2493 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
2494 LHSI->getOperand(0)->hasOneUse()) {
2495 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
2496 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
2497 // happens a LOT in code produced by the C front-end, for bitfield
2498 // access.
2499 ShiftInst *Shift = dyn_cast<ShiftInst>(LHSI->getOperand(0));
2500 ConstantUInt *ShAmt;
2501 ShAmt = Shift ? dyn_cast<ConstantUInt>(Shift->getOperand(1)) : 0;
2502 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
2503 const Type *Ty = LHSI->getType();
Misha Brukmanb1c93172005-04-21 23:48:37 +00002504
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002505 // We can fold this as long as we can't shift unknown bits
2506 // into the mask. This can only happen with signed shift
2507 // rights, as they sign-extend.
2508 if (ShAmt) {
2509 bool CanFold = Shift->getOpcode() != Instruction::Shr ||
Chris Lattner6afc02f2004-09-28 17:54:07 +00002510 Shift->getType()->isUnsigned();
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002511 if (!CanFold) {
2512 // To test for the bad case of the signed shr, see if any
2513 // of the bits shifted in could be tested after the mask.
Chris Lattnerc53cb9d2005-06-17 01:29:28 +00002514 int ShAmtVal = Ty->getPrimitiveSizeInBits()-ShAmt->getValue();
2515 if (ShAmtVal < 0) ShAmtVal = 0; // Out of range shift.
2516
2517 Constant *OShAmt = ConstantUInt::get(Type::UByteTy, ShAmtVal);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002518 Constant *ShVal =
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002519 ConstantExpr::getShl(ConstantInt::getAllOnesValue(Ty), OShAmt);
2520 if (ConstantExpr::getAnd(ShVal, AndCST)->isNullValue())
2521 CanFold = true;
2522 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002523
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002524 if (CanFold) {
Chris Lattner6afc02f2004-09-28 17:54:07 +00002525 Constant *NewCst;
2526 if (Shift->getOpcode() == Instruction::Shl)
2527 NewCst = ConstantExpr::getUShr(CI, ShAmt);
2528 else
2529 NewCst = ConstantExpr::getShl(CI, ShAmt);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002530
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002531 // Check to see if we are shifting out any of the bits being
2532 // compared.
2533 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != CI){
2534 // If we shifted bits out, the fold is not going to work out.
2535 // As a special case, check to see if this means that the
2536 // result is always true or false now.
2537 if (I.getOpcode() == Instruction::SetEQ)
2538 return ReplaceInstUsesWith(I, ConstantBool::False);
2539 if (I.getOpcode() == Instruction::SetNE)
2540 return ReplaceInstUsesWith(I, ConstantBool::True);
2541 } else {
2542 I.setOperand(1, NewCst);
Chris Lattner6afc02f2004-09-28 17:54:07 +00002543 Constant *NewAndCST;
2544 if (Shift->getOpcode() == Instruction::Shl)
2545 NewAndCST = ConstantExpr::getUShr(AndCST, ShAmt);
2546 else
2547 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
2548 LHSI->setOperand(1, NewAndCST);
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002549 LHSI->setOperand(0, Shift->getOperand(0));
2550 WorkList.push_back(Shift); // Shift is dead.
2551 AddUsesToWorkList(I);
2552 return &I;
Chris Lattner1638de42004-07-21 19:50:44 +00002553 }
2554 }
Chris Lattner35167c32004-06-09 07:59:58 +00002555 }
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002556 }
2557 break;
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002558
Chris Lattner272d5ca2004-09-28 18:22:15 +00002559 case Instruction::Shl: // (setcc (shl X, ShAmt), CI)
2560 if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
2561 switch (I.getOpcode()) {
2562 default: break;
2563 case Instruction::SetEQ:
2564 case Instruction::SetNE: {
Chris Lattner19b57f52005-06-15 20:53:31 +00002565 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
2566
2567 // Check that the shift amount is in range. If not, don't perform
2568 // undefined shifts. When the shift is visited it will be
2569 // simplified.
2570 if (ShAmt->getValue() >= TypeBits)
2571 break;
2572
Chris Lattner272d5ca2004-09-28 18:22:15 +00002573 // If we are comparing against bits always shifted out, the
2574 // comparison cannot succeed.
Misha Brukmanb1c93172005-04-21 23:48:37 +00002575 Constant *Comp =
Chris Lattner272d5ca2004-09-28 18:22:15 +00002576 ConstantExpr::getShl(ConstantExpr::getShr(CI, ShAmt), ShAmt);
2577 if (Comp != CI) {// Comparing against a bit that we know is zero.
2578 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
2579 Constant *Cst = ConstantBool::get(IsSetNE);
2580 return ReplaceInstUsesWith(I, Cst);
2581 }
2582
2583 if (LHSI->hasOneUse()) {
2584 // Otherwise strength reduce the shift into an and.
Chris Lattnerfdfe3e492005-01-08 19:42:22 +00002585 unsigned ShAmtVal = (unsigned)ShAmt->getValue();
Chris Lattner272d5ca2004-09-28 18:22:15 +00002586 uint64_t Val = (1ULL << (TypeBits-ShAmtVal))-1;
2587
2588 Constant *Mask;
2589 if (CI->getType()->isUnsigned()) {
2590 Mask = ConstantUInt::get(CI->getType(), Val);
2591 } else if (ShAmtVal != 0) {
2592 Mask = ConstantSInt::get(CI->getType(), Val);
2593 } else {
2594 Mask = ConstantInt::getAllOnesValue(CI->getType());
2595 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002596
Chris Lattner272d5ca2004-09-28 18:22:15 +00002597 Instruction *AndI =
2598 BinaryOperator::createAnd(LHSI->getOperand(0),
2599 Mask, LHSI->getName()+".mask");
2600 Value *And = InsertNewInstBefore(AndI, I);
2601 return new SetCondInst(I.getOpcode(), And,
2602 ConstantExpr::getUShr(CI, ShAmt));
2603 }
2604 }
2605 }
2606 }
2607 break;
2608
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002609 case Instruction::Shr: // (setcc (shr X, ShAmt), CI)
Chris Lattner1023b872004-09-27 16:18:50 +00002610 if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
Chris Lattner1023b872004-09-27 16:18:50 +00002611 switch (I.getOpcode()) {
2612 default: break;
2613 case Instruction::SetEQ:
2614 case Instruction::SetNE: {
Chris Lattner19b57f52005-06-15 20:53:31 +00002615
2616 // Check that the shift amount is in range. If not, don't perform
2617 // undefined shifts. When the shift is visited it will be
2618 // simplified.
Chris Lattner104002b2005-06-16 01:52:07 +00002619 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
Chris Lattner19b57f52005-06-15 20:53:31 +00002620 if (ShAmt->getValue() >= TypeBits)
2621 break;
2622
Chris Lattner1023b872004-09-27 16:18:50 +00002623 // If we are comparing against bits always shifted out, the
2624 // comparison cannot succeed.
Misha Brukmanb1c93172005-04-21 23:48:37 +00002625 Constant *Comp =
Chris Lattner1023b872004-09-27 16:18:50 +00002626 ConstantExpr::getShr(ConstantExpr::getShl(CI, ShAmt), ShAmt);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002627
Chris Lattner1023b872004-09-27 16:18:50 +00002628 if (Comp != CI) {// Comparing against a bit that we know is zero.
2629 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
2630 Constant *Cst = ConstantBool::get(IsSetNE);
2631 return ReplaceInstUsesWith(I, Cst);
2632 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002633
Chris Lattner1023b872004-09-27 16:18:50 +00002634 if (LHSI->hasOneUse() || CI->isNullValue()) {
Chris Lattnerfdfe3e492005-01-08 19:42:22 +00002635 unsigned ShAmtVal = (unsigned)ShAmt->getValue();
Chris Lattner272d5ca2004-09-28 18:22:15 +00002636
Chris Lattner1023b872004-09-27 16:18:50 +00002637 // Otherwise strength reduce the shift into an and.
2638 uint64_t Val = ~0ULL; // All ones.
2639 Val <<= ShAmtVal; // Shift over to the right spot.
2640
2641 Constant *Mask;
2642 if (CI->getType()->isUnsigned()) {
Chris Lattner2f1457f2005-04-24 17:46:05 +00002643 Val &= ~0ULL >> (64-TypeBits);
Chris Lattner1023b872004-09-27 16:18:50 +00002644 Mask = ConstantUInt::get(CI->getType(), Val);
2645 } else {
2646 Mask = ConstantSInt::get(CI->getType(), Val);
2647 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002648
Chris Lattner1023b872004-09-27 16:18:50 +00002649 Instruction *AndI =
2650 BinaryOperator::createAnd(LHSI->getOperand(0),
2651 Mask, LHSI->getName()+".mask");
2652 Value *And = InsertNewInstBefore(AndI, I);
2653 return new SetCondInst(I.getOpcode(), And,
2654 ConstantExpr::getShl(CI, ShAmt));
2655 }
2656 break;
2657 }
2658 }
2659 }
2660 break;
Chris Lattner7e794272004-09-24 15:21:34 +00002661
Chris Lattner6862fbd2004-09-29 17:40:11 +00002662 case Instruction::Div:
2663 // Fold: (div X, C1) op C2 -> range check
2664 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
2665 // Fold this div into the comparison, producing a range check.
2666 // Determine, based on the divide type, what the range is being
2667 // checked. If there is an overflow on the low or high side, remember
2668 // it, otherwise compute the range [low, hi) bounding the new value.
2669 bool LoOverflow = false, HiOverflow = 0;
2670 ConstantInt *LoBound = 0, *HiBound = 0;
2671
2672 ConstantInt *Prod;
2673 bool ProdOV = MulWithOverflow(Prod, CI, DivRHS);
2674
Chris Lattnera92af962004-10-11 19:40:04 +00002675 Instruction::BinaryOps Opcode = I.getOpcode();
2676
Chris Lattner6862fbd2004-09-29 17:40:11 +00002677 if (DivRHS->isNullValue()) { // Don't hack on divide by zeros.
2678 } else if (LHSI->getType()->isUnsigned()) { // udiv
2679 LoBound = Prod;
2680 LoOverflow = ProdOV;
2681 HiOverflow = ProdOV || AddWithOverflow(HiBound, LoBound, DivRHS);
2682 } else if (isPositive(DivRHS)) { // Divisor is > 0.
2683 if (CI->isNullValue()) { // (X / pos) op 0
2684 // Can't overflow.
2685 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
2686 HiBound = DivRHS;
2687 } else if (isPositive(CI)) { // (X / pos) op pos
2688 LoBound = Prod;
2689 LoOverflow = ProdOV;
2690 HiOverflow = ProdOV || AddWithOverflow(HiBound, Prod, DivRHS);
2691 } else { // (X / pos) op neg
2692 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
2693 LoOverflow = AddWithOverflow(LoBound, Prod,
2694 cast<ConstantInt>(DivRHSH));
2695 HiBound = Prod;
2696 HiOverflow = ProdOV;
2697 }
2698 } else { // Divisor is < 0.
2699 if (CI->isNullValue()) { // (X / neg) op 0
2700 LoBound = AddOne(DivRHS);
2701 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner73bcba52005-06-17 02:05:55 +00002702 if (HiBound == DivRHS)
2703 LoBound = 0; // - INTMIN = INTMIN
Chris Lattner6862fbd2004-09-29 17:40:11 +00002704 } else if (isPositive(CI)) { // (X / neg) op pos
2705 HiOverflow = LoOverflow = ProdOV;
2706 if (!LoOverflow)
2707 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS));
2708 HiBound = AddOne(Prod);
2709 } else { // (X / neg) op neg
2710 LoBound = Prod;
2711 LoOverflow = HiOverflow = ProdOV;
2712 HiBound = cast<ConstantInt>(ConstantExpr::getSub(Prod, DivRHS));
2713 }
Chris Lattner0b41e862004-10-08 19:15:44 +00002714
Chris Lattnera92af962004-10-11 19:40:04 +00002715 // Dividing by a negate swaps the condition.
2716 Opcode = SetCondInst::getSwappedCondition(Opcode);
Chris Lattner6862fbd2004-09-29 17:40:11 +00002717 }
2718
2719 if (LoBound) {
2720 Value *X = LHSI->getOperand(0);
Chris Lattnera92af962004-10-11 19:40:04 +00002721 switch (Opcode) {
Chris Lattner6862fbd2004-09-29 17:40:11 +00002722 default: assert(0 && "Unhandled setcc opcode!");
2723 case Instruction::SetEQ:
2724 if (LoOverflow && HiOverflow)
2725 return ReplaceInstUsesWith(I, ConstantBool::False);
2726 else if (HiOverflow)
2727 return new SetCondInst(Instruction::SetGE, X, LoBound);
2728 else if (LoOverflow)
2729 return new SetCondInst(Instruction::SetLT, X, HiBound);
2730 else
2731 return InsertRangeTest(X, LoBound, HiBound, true, I);
2732 case Instruction::SetNE:
2733 if (LoOverflow && HiOverflow)
2734 return ReplaceInstUsesWith(I, ConstantBool::True);
2735 else if (HiOverflow)
2736 return new SetCondInst(Instruction::SetLT, X, LoBound);
2737 else if (LoOverflow)
2738 return new SetCondInst(Instruction::SetGE, X, HiBound);
2739 else
2740 return InsertRangeTest(X, LoBound, HiBound, false, I);
2741 case Instruction::SetLT:
2742 if (LoOverflow)
2743 return ReplaceInstUsesWith(I, ConstantBool::False);
2744 return new SetCondInst(Instruction::SetLT, X, LoBound);
2745 case Instruction::SetGT:
2746 if (HiOverflow)
2747 return ReplaceInstUsesWith(I, ConstantBool::False);
2748 return new SetCondInst(Instruction::SetGE, X, HiBound);
2749 }
2750 }
2751 }
2752 break;
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002753 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002754
Chris Lattnerd492a0b2003-07-23 17:02:11 +00002755 // Simplify seteq and setne instructions...
2756 if (I.getOpcode() == Instruction::SetEQ ||
2757 I.getOpcode() == Instruction::SetNE) {
2758 bool isSetNE = I.getOpcode() == Instruction::SetNE;
2759
Chris Lattnercfbce7c2003-07-23 17:26:36 +00002760 // If the first operand is (and|or|xor) with a constant, and the second
Chris Lattnerd492a0b2003-07-23 17:02:11 +00002761 // operand is a constant, simplify a bit.
Chris Lattnerc992add2003-08-13 05:33:12 +00002762 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
2763 switch (BO->getOpcode()) {
Chris Lattner23b47b62004-07-06 07:38:18 +00002764 case Instruction::Rem:
2765 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
2766 if (CI->isNullValue() && isa<ConstantSInt>(BO->getOperand(1)) &&
2767 BO->hasOneUse() &&
2768 cast<ConstantSInt>(BO->getOperand(1))->getValue() > 1)
2769 if (unsigned L2 =
2770 Log2(cast<ConstantSInt>(BO->getOperand(1))->getValue())) {
2771 const Type *UTy = BO->getType()->getUnsignedVersion();
2772 Value *NewX = InsertNewInstBefore(new CastInst(BO->getOperand(0),
2773 UTy, "tmp"), I);
2774 Constant *RHSCst = ConstantUInt::get(UTy, 1ULL << L2);
2775 Value *NewRem =InsertNewInstBefore(BinaryOperator::createRem(NewX,
2776 RHSCst, BO->getName()), I);
2777 return BinaryOperator::create(I.getOpcode(), NewRem,
2778 Constant::getNullValue(UTy));
2779 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002780 break;
Chris Lattner23b47b62004-07-06 07:38:18 +00002781
Chris Lattnerc992add2003-08-13 05:33:12 +00002782 case Instruction::Add:
Chris Lattner6e079362004-06-27 22:51:36 +00002783 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
2784 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerb121ae12004-09-21 21:35:23 +00002785 if (BO->hasOneUse())
2786 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
2787 ConstantExpr::getSub(CI, BOp1C));
Chris Lattner6e079362004-06-27 22:51:36 +00002788 } else if (CI->isNullValue()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00002789 // Replace ((add A, B) != 0) with (A != -B) if A or B is
2790 // efficiently invertible, or if the add has just this one use.
2791 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002792
Chris Lattnerc992add2003-08-13 05:33:12 +00002793 if (Value *NegVal = dyn_castNegVal(BOp1))
2794 return new SetCondInst(I.getOpcode(), BOp0, NegVal);
2795 else if (Value *NegVal = dyn_castNegVal(BOp0))
2796 return new SetCondInst(I.getOpcode(), NegVal, BOp1);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002797 else if (BO->hasOneUse()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00002798 Instruction *Neg = BinaryOperator::createNeg(BOp1, BO->getName());
2799 BO->setName("");
2800 InsertNewInstBefore(Neg, I);
2801 return new SetCondInst(I.getOpcode(), BOp0, Neg);
2802 }
2803 }
2804 break;
2805 case Instruction::Xor:
2806 // For the xor case, we can xor two constants together, eliminating
2807 // the explicit xor.
2808 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
2809 return BinaryOperator::create(I.getOpcode(), BO->getOperand(0),
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002810 ConstantExpr::getXor(CI, BOC));
Chris Lattnerc992add2003-08-13 05:33:12 +00002811
2812 // FALLTHROUGH
2813 case Instruction::Sub:
2814 // Replace (([sub|xor] A, B) != 0) with (A != B)
2815 if (CI->isNullValue())
2816 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
2817 BO->getOperand(1));
2818 break;
2819
2820 case Instruction::Or:
2821 // If bits are being or'd in that are not present in the constant we
2822 // are comparing against, then the comparison could never succeed!
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002823 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Chris Lattnerc8e7e292004-06-10 02:12:35 +00002824 Constant *NotCI = ConstantExpr::getNot(CI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002825 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Chris Lattnerd492a0b2003-07-23 17:02:11 +00002826 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002827 }
Chris Lattnerc992add2003-08-13 05:33:12 +00002828 break;
2829
2830 case Instruction::And:
2831 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerd492a0b2003-07-23 17:02:11 +00002832 // If bits are being compared against that are and'd out, then the
2833 // comparison can never succeed!
Chris Lattnerc8e7e292004-06-10 02:12:35 +00002834 if (!ConstantExpr::getAnd(CI,
2835 ConstantExpr::getNot(BOC))->isNullValue())
Chris Lattnerd492a0b2003-07-23 17:02:11 +00002836 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattnerc992add2003-08-13 05:33:12 +00002837
Chris Lattner35167c32004-06-09 07:59:58 +00002838 // If we have ((X & C) == C), turn it into ((X & C) != 0).
Chris Lattneree59d4b2004-06-10 02:33:20 +00002839 if (CI == BOC && isOneBitSet(CI))
Chris Lattner35167c32004-06-09 07:59:58 +00002840 return new SetCondInst(isSetNE ? Instruction::SetEQ :
2841 Instruction::SetNE, Op0,
2842 Constant::getNullValue(CI->getType()));
Chris Lattner35167c32004-06-09 07:59:58 +00002843
Chris Lattnerc992add2003-08-13 05:33:12 +00002844 // Replace (and X, (1 << size(X)-1) != 0) with x < 0, converting X
2845 // to be a signed value as appropriate.
2846 if (isSignBit(BOC)) {
2847 Value *X = BO->getOperand(0);
2848 // If 'X' is not signed, insert a cast now...
2849 if (!BOC->getType()->isSigned()) {
Chris Lattner97bfcea2004-06-17 18:16:02 +00002850 const Type *DestTy = BOC->getType()->getSignedVersion();
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002851 X = InsertCastBefore(X, DestTy, I);
Chris Lattnerc992add2003-08-13 05:33:12 +00002852 }
2853 return new SetCondInst(isSetNE ? Instruction::SetLT :
2854 Instruction::SetGE, X,
2855 Constant::getNullValue(X->getType()));
2856 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002857
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002858 // ((X & ~7) == 0) --> X < 8
Chris Lattner8fc5af42004-09-23 21:46:38 +00002859 if (CI->isNullValue() && isHighOnes(BOC)) {
2860 Value *X = BO->getOperand(0);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002861 Constant *NegX = ConstantExpr::getNeg(BOC);
Chris Lattner8fc5af42004-09-23 21:46:38 +00002862
2863 // If 'X' is signed, insert a cast now.
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002864 if (NegX->getType()->isSigned()) {
2865 const Type *DestTy = NegX->getType()->getUnsignedVersion();
2866 X = InsertCastBefore(X, DestTy, I);
2867 NegX = ConstantExpr::getCast(NegX, DestTy);
Chris Lattner8fc5af42004-09-23 21:46:38 +00002868 }
2869
2870 return new SetCondInst(isSetNE ? Instruction::SetGE :
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002871 Instruction::SetLT, X, NegX);
Chris Lattner8fc5af42004-09-23 21:46:38 +00002872 }
2873
Chris Lattnerd492a0b2003-07-23 17:02:11 +00002874 }
Chris Lattnerc992add2003-08-13 05:33:12 +00002875 default: break;
2876 }
2877 }
Chris Lattner2b55ea32004-02-23 07:16:20 +00002878 } else { // Not a SetEQ/SetNE
Misha Brukmanb1c93172005-04-21 23:48:37 +00002879 // If the LHS is a cast from an integral value of the same size,
Chris Lattner2b55ea32004-02-23 07:16:20 +00002880 if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
2881 Value *CastOp = Cast->getOperand(0);
2882 const Type *SrcTy = CastOp->getType();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002883 unsigned SrcTySize = SrcTy->getPrimitiveSizeInBits();
Chris Lattner2b55ea32004-02-23 07:16:20 +00002884 if (SrcTy != Cast->getType() && SrcTy->isInteger() &&
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002885 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00002886 assert((SrcTy->isSigned() ^ Cast->getType()->isSigned()) &&
Chris Lattner2b55ea32004-02-23 07:16:20 +00002887 "Source and destination signednesses should differ!");
2888 if (Cast->getType()->isSigned()) {
2889 // If this is a signed comparison, check for comparisons in the
2890 // vicinity of zero.
2891 if (I.getOpcode() == Instruction::SetLT && CI->isNullValue())
2892 // X < 0 => x > 127
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002893 return BinaryOperator::createSetGT(CastOp,
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002894 ConstantUInt::get(SrcTy, (1ULL << (SrcTySize-1))-1));
Chris Lattner2b55ea32004-02-23 07:16:20 +00002895 else if (I.getOpcode() == Instruction::SetGT &&
2896 cast<ConstantSInt>(CI)->getValue() == -1)
2897 // X > -1 => x < 128
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002898 return BinaryOperator::createSetLT(CastOp,
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002899 ConstantUInt::get(SrcTy, 1ULL << (SrcTySize-1)));
Chris Lattner2b55ea32004-02-23 07:16:20 +00002900 } else {
2901 ConstantUInt *CUI = cast<ConstantUInt>(CI);
2902 if (I.getOpcode() == Instruction::SetLT &&
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002903 CUI->getValue() == 1ULL << (SrcTySize-1))
Chris Lattner2b55ea32004-02-23 07:16:20 +00002904 // X < 128 => X > -1
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002905 return BinaryOperator::createSetGT(CastOp,
2906 ConstantSInt::get(SrcTy, -1));
Chris Lattner2b55ea32004-02-23 07:16:20 +00002907 else if (I.getOpcode() == Instruction::SetGT &&
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002908 CUI->getValue() == (1ULL << (SrcTySize-1))-1)
Chris Lattner2b55ea32004-02-23 07:16:20 +00002909 // X > 127 => X < 0
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002910 return BinaryOperator::createSetLT(CastOp,
2911 Constant::getNullValue(SrcTy));
Chris Lattner2b55ea32004-02-23 07:16:20 +00002912 }
2913 }
2914 }
Chris Lattnere967b342003-06-04 05:10:11 +00002915 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002916 }
2917
Chris Lattner77c32c32005-04-23 15:31:55 +00002918 // Handle setcc with constant RHS's that can be integer, FP or pointer.
2919 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
2920 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
2921 switch (LHSI->getOpcode()) {
Chris Lattnera816eee2005-05-01 04:42:15 +00002922 case Instruction::GetElementPtr:
2923 if (RHSC->isNullValue()) {
2924 // Transform setcc GEP P, int 0, int 0, int 0, null -> setcc P, null
2925 bool isAllZeros = true;
2926 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
2927 if (!isa<Constant>(LHSI->getOperand(i)) ||
2928 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
2929 isAllZeros = false;
2930 break;
2931 }
2932 if (isAllZeros)
2933 return new SetCondInst(I.getOpcode(), LHSI->getOperand(0),
2934 Constant::getNullValue(LHSI->getOperand(0)->getType()));
2935 }
2936 break;
2937
Chris Lattner77c32c32005-04-23 15:31:55 +00002938 case Instruction::PHI:
2939 if (Instruction *NV = FoldOpIntoPhi(I))
2940 return NV;
2941 break;
2942 case Instruction::Select:
2943 // If either operand of the select is a constant, we can fold the
2944 // comparison into the select arms, which will cause one to be
2945 // constant folded and the select turned into a bitwise or.
2946 Value *Op1 = 0, *Op2 = 0;
2947 if (LHSI->hasOneUse()) {
2948 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
2949 // Fold the known value into the constant operand.
2950 Op1 = ConstantExpr::get(I.getOpcode(), C, RHSC);
2951 // Insert a new SetCC of the other select operand.
2952 Op2 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
2953 LHSI->getOperand(2), RHSC,
2954 I.getName()), I);
2955 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
2956 // Fold the known value into the constant operand.
2957 Op2 = ConstantExpr::get(I.getOpcode(), C, RHSC);
2958 // Insert a new SetCC of the other select operand.
2959 Op1 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
2960 LHSI->getOperand(1), RHSC,
2961 I.getName()), I);
2962 }
2963 }
Jeff Cohen82639852005-04-23 21:38:35 +00002964
Chris Lattner77c32c32005-04-23 15:31:55 +00002965 if (Op1)
2966 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
2967 break;
2968 }
2969 }
2970
Chris Lattner0798af32005-01-13 20:14:25 +00002971 // If we can optimize a 'setcc GEP, P' or 'setcc P, GEP', do so now.
2972 if (User *GEP = dyn_castGetElementPtr(Op0))
2973 if (Instruction *NI = FoldGEPSetCC(GEP, Op1, I.getOpcode(), I))
2974 return NI;
2975 if (User *GEP = dyn_castGetElementPtr(Op1))
2976 if (Instruction *NI = FoldGEPSetCC(GEP, Op0,
2977 SetCondInst::getSwappedCondition(I.getOpcode()), I))
2978 return NI;
2979
Chris Lattner16930792003-11-03 04:25:02 +00002980 // Test to see if the operands of the setcc are casted versions of other
2981 // values. If the cast can be stripped off both arguments, we do so now.
Chris Lattner6444c372003-11-03 05:17:03 +00002982 if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
2983 Value *CastOp0 = CI->getOperand(0);
2984 if (CastOp0->getType()->isLosslesslyConvertibleTo(CI->getType()) &&
Chris Lattner7d2a5392004-03-13 23:54:27 +00002985 (isa<Constant>(Op1) || isa<CastInst>(Op1)) &&
Chris Lattner16930792003-11-03 04:25:02 +00002986 (I.getOpcode() == Instruction::SetEQ ||
2987 I.getOpcode() == Instruction::SetNE)) {
2988 // We keep moving the cast from the left operand over to the right
2989 // operand, where it can often be eliminated completely.
Chris Lattner6444c372003-11-03 05:17:03 +00002990 Op0 = CastOp0;
Misha Brukmanb1c93172005-04-21 23:48:37 +00002991
Chris Lattner16930792003-11-03 04:25:02 +00002992 // If operand #1 is a cast instruction, see if we can eliminate it as
2993 // well.
Chris Lattner6444c372003-11-03 05:17:03 +00002994 if (CastInst *CI2 = dyn_cast<CastInst>(Op1))
2995 if (CI2->getOperand(0)->getType()->isLosslesslyConvertibleTo(
Chris Lattner16930792003-11-03 04:25:02 +00002996 Op0->getType()))
Chris Lattner6444c372003-11-03 05:17:03 +00002997 Op1 = CI2->getOperand(0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002998
Chris Lattner16930792003-11-03 04:25:02 +00002999 // If Op1 is a constant, we can fold the cast into the constant.
3000 if (Op1->getType() != Op0->getType())
3001 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
3002 Op1 = ConstantExpr::getCast(Op1C, Op0->getType());
3003 } else {
3004 // Otherwise, cast the RHS right before the setcc
3005 Op1 = new CastInst(Op1, Op0->getType(), Op1->getName());
3006 InsertNewInstBefore(cast<Instruction>(Op1), I);
3007 }
3008 return BinaryOperator::create(I.getOpcode(), Op0, Op1);
3009 }
3010
Chris Lattner6444c372003-11-03 05:17:03 +00003011 // Handle the special case of: setcc (cast bool to X), <cst>
3012 // This comes up when you have code like
3013 // int X = A < B;
3014 // if (X) ...
3015 // For generality, we handle any zero-extension of any operand comparison
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003016 // with a constant or another cast from the same type.
3017 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
3018 if (Instruction *R = visitSetCondInstWithCastAndCast(I))
3019 return R;
Chris Lattner6444c372003-11-03 05:17:03 +00003020 }
Chris Lattner113f4f42002-06-25 16:13:24 +00003021 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003022}
3023
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003024// visitSetCondInstWithCastAndCast - Handle setcond (cast x to y), (cast/cst).
3025// We only handle extending casts so far.
3026//
3027Instruction *InstCombiner::visitSetCondInstWithCastAndCast(SetCondInst &SCI) {
3028 Value *LHSCIOp = cast<CastInst>(SCI.getOperand(0))->getOperand(0);
3029 const Type *SrcTy = LHSCIOp->getType();
3030 const Type *DestTy = SCI.getOperand(0)->getType();
3031 Value *RHSCIOp;
3032
3033 if (!DestTy->isIntegral() || !SrcTy->isIntegral())
Chris Lattner03f06f12005-01-17 03:20:02 +00003034 return 0;
3035
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003036 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
3037 unsigned DestBits = DestTy->getPrimitiveSizeInBits();
3038 if (SrcBits >= DestBits) return 0; // Only handle extending cast.
3039
3040 // Is this a sign or zero extension?
3041 bool isSignSrc = SrcTy->isSigned();
3042 bool isSignDest = DestTy->isSigned();
3043
3044 if (CastInst *CI = dyn_cast<CastInst>(SCI.getOperand(1))) {
3045 // Not an extension from the same type?
3046 RHSCIOp = CI->getOperand(0);
3047 if (RHSCIOp->getType() != LHSCIOp->getType()) return 0;
3048 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(SCI.getOperand(1))) {
3049 // Compute the constant that would happen if we truncated to SrcTy then
3050 // reextended to DestTy.
3051 Constant *Res = ConstantExpr::getCast(CI, SrcTy);
3052
3053 if (ConstantExpr::getCast(Res, DestTy) == CI) {
3054 RHSCIOp = Res;
3055 } else {
3056 // If the value cannot be represented in the shorter type, we cannot emit
3057 // a simple comparison.
3058 if (SCI.getOpcode() == Instruction::SetEQ)
3059 return ReplaceInstUsesWith(SCI, ConstantBool::False);
3060 if (SCI.getOpcode() == Instruction::SetNE)
3061 return ReplaceInstUsesWith(SCI, ConstantBool::True);
3062
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003063 // Evaluate the comparison for LT.
3064 Value *Result;
3065 if (DestTy->isSigned()) {
3066 // We're performing a signed comparison.
3067 if (isSignSrc) {
3068 // Signed extend and signed comparison.
3069 if (cast<ConstantSInt>(CI)->getValue() < 0) // X < (small) --> false
3070 Result = ConstantBool::False;
3071 else
3072 Result = ConstantBool::True; // X < (large) --> true
3073 } else {
3074 // Unsigned extend and signed comparison.
3075 if (cast<ConstantSInt>(CI)->getValue() < 0)
3076 Result = ConstantBool::False;
3077 else
3078 Result = ConstantBool::True;
3079 }
3080 } else {
3081 // We're performing an unsigned comparison.
3082 if (!isSignSrc) {
3083 // Unsigned extend & compare -> always true.
3084 Result = ConstantBool::True;
3085 } else {
3086 // We're performing an unsigned comp with a sign extended value.
3087 // This is true if the input is >= 0. [aka >s -1]
3088 Constant *NegOne = ConstantIntegral::getAllOnesValue(SrcTy);
3089 Result = InsertNewInstBefore(BinaryOperator::createSetGT(LHSCIOp,
3090 NegOne, SCI.getName()), SCI);
3091 }
Reid Spencer279fa252004-11-28 21:31:15 +00003092 }
Chris Lattner03f06f12005-01-17 03:20:02 +00003093
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003094 // Finally, return the value computed.
3095 if (SCI.getOpcode() == Instruction::SetLT) {
3096 return ReplaceInstUsesWith(SCI, Result);
3097 } else {
3098 assert(SCI.getOpcode()==Instruction::SetGT &&"SetCC should be folded!");
3099 if (Constant *CI = dyn_cast<Constant>(Result))
3100 return ReplaceInstUsesWith(SCI, ConstantExpr::getNot(CI));
3101 else
3102 return BinaryOperator::createNot(Result);
3103 }
Chris Lattner03f06f12005-01-17 03:20:02 +00003104 }
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003105 } else {
3106 return 0;
Reid Spencer279fa252004-11-28 21:31:15 +00003107 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003108
Chris Lattner252a8452005-06-16 03:00:08 +00003109 // Okay, just insert a compare of the reduced operands now!
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003110 return BinaryOperator::create(SCI.getOpcode(), LHSCIOp, RHSCIOp);
3111}
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003112
Chris Lattnere8d6c602003-03-10 19:16:08 +00003113Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +00003114 assert(I.getOperand(1)->getType() == Type::UByteTy);
3115 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003116 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003117
3118 // shl X, 0 == X and shr X, 0 == X
3119 // shl 0, X == 0 and shr 0, X == 0
3120 if (Op1 == Constant::getNullValue(Type::UByteTy) ||
Chris Lattnere6794492002-08-12 21:17:25 +00003121 Op0 == Constant::getNullValue(Op0->getType()))
3122 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003123
Chris Lattner81a7a232004-10-16 18:11:37 +00003124 if (isa<UndefValue>(Op0)) { // undef >>s X -> undef
3125 if (!isLeftShift && I.getType()->isSigned())
Chris Lattner67f05452004-10-16 23:28:04 +00003126 return ReplaceInstUsesWith(I, Op0);
Chris Lattner81a7a232004-10-16 18:11:37 +00003127 else // undef << X -> 0 AND undef >>u X -> 0
3128 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3129 }
3130 if (isa<UndefValue>(Op1)) {
3131 if (isLeftShift || I.getType()->isUnsigned())
3132 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3133 else
3134 return ReplaceInstUsesWith(I, Op0); // X >>s undef -> X
3135 }
3136
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003137 // shr int -1, X = -1 (for any arithmetic shift rights of ~0)
3138 if (!isLeftShift)
3139 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
3140 if (CSI->isAllOnesValue())
3141 return ReplaceInstUsesWith(I, CSI);
3142
Chris Lattner183b3362004-04-09 19:05:30 +00003143 // Try to fold constant and into select arguments.
3144 if (isa<Constant>(Op0))
3145 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner86102b82005-01-01 16:22:27 +00003146 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00003147 return R;
3148
Chris Lattnerb18dbbf2005-05-08 17:34:56 +00003149 // See if we can turn a signed shr into an unsigned shr.
3150 if (!isLeftShift && I.getType()->isSigned()) {
3151 if (MaskedValueIsZero(Op0, ConstantInt::getMinValue(I.getType()))) {
3152 Value *V = InsertCastBefore(Op0, I.getType()->getUnsignedVersion(), I);
3153 V = InsertNewInstBefore(new ShiftInst(Instruction::Shr, V, Op1,
3154 I.getName()), I);
3155 return new CastInst(V, I.getType());
3156 }
3157 }
3158
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003159 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op1)) {
Chris Lattner3204d4e2003-07-24 17:52:58 +00003160 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
3161 // of a signed value.
3162 //
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003163 unsigned TypeBits = Op0->getType()->getPrimitiveSizeInBits();
Chris Lattnerf5ce2542004-02-23 20:30:06 +00003164 if (CUI->getValue() >= TypeBits) {
3165 if (!Op0->getType()->isSigned() || isLeftShift)
3166 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
3167 else {
3168 I.setOperand(1, ConstantUInt::get(Type::UByteTy, TypeBits-1));
3169 return &I;
3170 }
3171 }
Chris Lattner55f3d942002-09-10 23:04:09 +00003172
Chris Lattnerede3fe02003-08-13 04:18:28 +00003173 // ((X*C1) << C2) == (X * (C1 << C2))
3174 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
3175 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
3176 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003177 return BinaryOperator::createMul(BO->getOperand(0),
3178 ConstantExpr::getShl(BOOp, CUI));
Misha Brukmanb1c93172005-04-21 23:48:37 +00003179
Chris Lattner183b3362004-04-09 19:05:30 +00003180 // Try to fold constant and into select arguments.
3181 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00003182 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00003183 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00003184 if (isa<PHINode>(Op0))
3185 if (Instruction *NV = FoldOpIntoPhi(I))
3186 return NV;
Chris Lattnerede3fe02003-08-13 04:18:28 +00003187
Chris Lattner86102b82005-01-01 16:22:27 +00003188 if (Op0->hasOneUse()) {
3189 // If this is a SHL of a sign-extending cast, see if we can turn the input
3190 // into a zero extending cast (a simple strength reduction).
3191 if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3192 const Type *SrcTy = CI->getOperand(0)->getType();
3193 if (isLeftShift && SrcTy->isInteger() && SrcTy->isSigned() &&
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003194 SrcTy->getPrimitiveSizeInBits() <
3195 CI->getType()->getPrimitiveSizeInBits()) {
Chris Lattner86102b82005-01-01 16:22:27 +00003196 // We can change it to a zero extension if we are shifting out all of
3197 // the sign extended bits. To check this, form a mask of all of the
3198 // sign extend bits, then shift them left and see if we have anything
3199 // left.
3200 Constant *Mask = ConstantIntegral::getAllOnesValue(SrcTy); // 1111
3201 Mask = ConstantExpr::getZeroExtend(Mask, CI->getType()); // 00001111
3202 Mask = ConstantExpr::getNot(Mask); // 1's in the sign bits: 11110000
3203 if (ConstantExpr::getShl(Mask, CUI)->isNullValue()) {
3204 // If the shift is nuking all of the sign bits, change this to a
3205 // zero extension cast. To do this, cast the cast input to
3206 // unsigned, then to the requested size.
3207 Value *CastOp = CI->getOperand(0);
3208 Instruction *NC =
3209 new CastInst(CastOp, CastOp->getType()->getUnsignedVersion(),
3210 CI->getName()+".uns");
3211 NC = InsertNewInstBefore(NC, I);
3212 // Finally, insert a replacement for CI.
3213 NC = new CastInst(NC, CI->getType(), CI->getName());
3214 CI->setName("");
3215 NC = InsertNewInstBefore(NC, I);
3216 WorkList.push_back(CI); // Delete CI later.
3217 I.setOperand(0, NC);
3218 return &I; // The SHL operand was modified.
3219 }
3220 }
3221 }
3222
3223 // If the operand is an bitwise operator with a constant RHS, and the
3224 // shift is the only use, we can pull it out of the shift.
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003225 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0))
3226 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
3227 bool isValid = true; // Valid only for And, Or, Xor
3228 bool highBitSet = false; // Transform if high bit of constant set?
3229
3230 switch (Op0BO->getOpcode()) {
3231 default: isValid = false; break; // Do not perform transform!
Chris Lattner44bd3922004-10-08 03:46:20 +00003232 case Instruction::Add:
3233 isValid = isLeftShift;
3234 break;
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003235 case Instruction::Or:
3236 case Instruction::Xor:
3237 highBitSet = false;
3238 break;
3239 case Instruction::And:
3240 highBitSet = true;
3241 break;
3242 }
3243
3244 // If this is a signed shift right, and the high bit is modified
3245 // by the logical operation, do not perform the transformation.
3246 // The highBitSet boolean indicates the value of the high bit of
3247 // the constant which would cause it to be modified for this
3248 // operation.
3249 //
3250 if (isValid && !isLeftShift && !I.getType()->isUnsigned()) {
3251 uint64_t Val = Op0C->getRawValue();
3252 isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
3253 }
3254
3255 if (isValid) {
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003256 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, CUI);
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003257
3258 Instruction *NewShift =
3259 new ShiftInst(I.getOpcode(), Op0BO->getOperand(0), CUI,
3260 Op0BO->getName());
3261 Op0BO->setName("");
3262 InsertNewInstBefore(NewShift, I);
3263
3264 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
3265 NewRHS);
3266 }
3267 }
Chris Lattner86102b82005-01-01 16:22:27 +00003268 }
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003269
Chris Lattner3204d4e2003-07-24 17:52:58 +00003270 // If this is a shift of a shift, see if we can fold the two together...
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003271 if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0))
Chris Lattnerab780df2003-07-24 18:38:56 +00003272 if (ConstantUInt *ShiftAmt1C =
3273 dyn_cast<ConstantUInt>(Op0SI->getOperand(1))) {
Chris Lattnerfdfe3e492005-01-08 19:42:22 +00003274 unsigned ShiftAmt1 = (unsigned)ShiftAmt1C->getValue();
3275 unsigned ShiftAmt2 = (unsigned)CUI->getValue();
Misha Brukmanb1c93172005-04-21 23:48:37 +00003276
Chris Lattner3204d4e2003-07-24 17:52:58 +00003277 // Check for (A << c1) << c2 and (A >> c1) >> c2
3278 if (I.getOpcode() == Op0SI->getOpcode()) {
3279 unsigned Amt = ShiftAmt1+ShiftAmt2; // Fold into one big shift...
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003280 if (Op0->getType()->getPrimitiveSizeInBits() < Amt)
3281 Amt = Op0->getType()->getPrimitiveSizeInBits();
Chris Lattner3204d4e2003-07-24 17:52:58 +00003282 return new ShiftInst(I.getOpcode(), Op0SI->getOperand(0),
3283 ConstantUInt::get(Type::UByteTy, Amt));
3284 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003285
Chris Lattnerab780df2003-07-24 18:38:56 +00003286 // Check for (A << c1) >> c2 or visaversa. If we are dealing with
3287 // signed types, we can only support the (A >> c1) << c2 configuration,
3288 // because it can not turn an arbitrary bit of A into a sign bit.
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003289 if (I.getType()->isUnsigned() || isLeftShift) {
Chris Lattner3204d4e2003-07-24 17:52:58 +00003290 // Calculate bitmask for what gets shifted off the edge...
3291 Constant *C = ConstantIntegral::getAllOnesValue(I.getType());
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003292 if (isLeftShift)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003293 C = ConstantExpr::getShl(C, ShiftAmt1C);
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003294 else
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003295 C = ConstantExpr::getShr(C, ShiftAmt1C);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003296
Chris Lattner3204d4e2003-07-24 17:52:58 +00003297 Instruction *Mask =
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003298 BinaryOperator::createAnd(Op0SI->getOperand(0), C,
3299 Op0SI->getOperand(0)->getName()+".mask");
Chris Lattner3204d4e2003-07-24 17:52:58 +00003300 InsertNewInstBefore(Mask, I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003301
Chris Lattner3204d4e2003-07-24 17:52:58 +00003302 // Figure out what flavor of shift we should use...
3303 if (ShiftAmt1 == ShiftAmt2)
3304 return ReplaceInstUsesWith(I, Mask); // (A << c) >> c === A & c2
3305 else if (ShiftAmt1 < ShiftAmt2) {
3306 return new ShiftInst(I.getOpcode(), Mask,
3307 ConstantUInt::get(Type::UByteTy, ShiftAmt2-ShiftAmt1));
3308 } else {
3309 return new ShiftInst(Op0SI->getOpcode(), Mask,
3310 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
3311 }
3312 }
3313 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003314 }
Chris Lattner2e0fb392002-10-08 16:16:40 +00003315
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003316 return 0;
3317}
3318
Chris Lattner4e2dbc62004-07-20 00:59:32 +00003319enum CastType {
3320 Noop = 0,
3321 Truncate = 1,
3322 Signext = 2,
3323 Zeroext = 3
3324};
3325
3326/// getCastType - In the future, we will split the cast instruction into these
3327/// various types. Until then, we have to do the analysis here.
3328static CastType getCastType(const Type *Src, const Type *Dest) {
3329 assert(Src->isIntegral() && Dest->isIntegral() &&
3330 "Only works on integral types!");
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003331 unsigned SrcSize = Src->getPrimitiveSizeInBits();
3332 unsigned DestSize = Dest->getPrimitiveSizeInBits();
Chris Lattner4e2dbc62004-07-20 00:59:32 +00003333
3334 if (SrcSize == DestSize) return Noop;
3335 if (SrcSize > DestSize) return Truncate;
3336 if (Src->isSigned()) return Signext;
3337 return Zeroext;
3338}
3339
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003340
Chris Lattner48a44f72002-05-02 17:06:02 +00003341// isEliminableCastOfCast - Return true if it is valid to eliminate the CI
3342// instruction.
3343//
Chris Lattnerdfae8be2003-07-24 17:35:25 +00003344static inline bool isEliminableCastOfCast(const Type *SrcTy, const Type *MidTy,
Chris Lattner11ffd592004-07-20 05:21:00 +00003345 const Type *DstTy, TargetData *TD) {
Chris Lattner48a44f72002-05-02 17:06:02 +00003346
Chris Lattner650b6da2002-08-02 20:00:25 +00003347 // It is legal to eliminate the instruction if casting A->B->A if the sizes
Misha Brukmanb1c93172005-04-21 23:48:37 +00003348 // are identical and the bits don't get reinterpreted (for example
Chris Lattner1638de42004-07-21 19:50:44 +00003349 // int->float->int would not be allowed).
Misha Brukmane5838c42003-05-20 18:45:36 +00003350 if (SrcTy == DstTy && SrcTy->isLosslesslyConvertibleTo(MidTy))
Chris Lattner650b6da2002-08-02 20:00:25 +00003351 return true;
Chris Lattner48a44f72002-05-02 17:06:02 +00003352
Chris Lattner4fbad962004-07-21 04:27:24 +00003353 // If we are casting between pointer and integer types, treat pointers as
3354 // integers of the appropriate size for the code below.
3355 if (isa<PointerType>(SrcTy)) SrcTy = TD->getIntPtrType();
3356 if (isa<PointerType>(MidTy)) MidTy = TD->getIntPtrType();
3357 if (isa<PointerType>(DstTy)) DstTy = TD->getIntPtrType();
Chris Lattner11ffd592004-07-20 05:21:00 +00003358
Chris Lattner48a44f72002-05-02 17:06:02 +00003359 // Allow free casting and conversion of sizes as long as the sign doesn't
3360 // change...
Chris Lattnerb0b412e2002-09-03 01:08:28 +00003361 if (SrcTy->isIntegral() && MidTy->isIntegral() && DstTy->isIntegral()) {
Chris Lattner4e2dbc62004-07-20 00:59:32 +00003362 CastType FirstCast = getCastType(SrcTy, MidTy);
3363 CastType SecondCast = getCastType(MidTy, DstTy);
Chris Lattner650b6da2002-08-02 20:00:25 +00003364
Chris Lattner4e2dbc62004-07-20 00:59:32 +00003365 // Capture the effect of these two casts. If the result is a legal cast,
3366 // the CastType is stored here, otherwise a special code is used.
3367 static const unsigned CastResult[] = {
3368 // First cast is noop
3369 0, 1, 2, 3,
3370 // First cast is a truncate
3371 1, 1, 4, 4, // trunc->extend is not safe to eliminate
3372 // First cast is a sign ext
Chris Lattner1638de42004-07-21 19:50:44 +00003373 2, 5, 2, 4, // signext->zeroext never ok
Chris Lattner4e2dbc62004-07-20 00:59:32 +00003374 // First cast is a zero ext
Chris Lattner1638de42004-07-21 19:50:44 +00003375 3, 5, 3, 3,
Chris Lattner4e2dbc62004-07-20 00:59:32 +00003376 };
3377
3378 unsigned Result = CastResult[FirstCast*4+SecondCast];
3379 switch (Result) {
3380 default: assert(0 && "Illegal table value!");
3381 case 0:
3382 case 1:
3383 case 2:
3384 case 3:
3385 // FIXME: in the future, when LLVM has explicit sign/zeroextends and
3386 // truncates, we could eliminate more casts.
3387 return (unsigned)getCastType(SrcTy, DstTy) == Result;
3388 case 4:
3389 return false; // Not possible to eliminate this here.
3390 case 5:
Chris Lattner1638de42004-07-21 19:50:44 +00003391 // Sign or zero extend followed by truncate is always ok if the result
3392 // is a truncate or noop.
3393 CastType ResultCast = getCastType(SrcTy, DstTy);
3394 if (ResultCast == Noop || ResultCast == Truncate)
3395 return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +00003396 // Otherwise we are still growing the value, we are only safe if the
Chris Lattner1638de42004-07-21 19:50:44 +00003397 // result will match the sign/zeroextendness of the result.
3398 return ResultCast == FirstCast;
Chris Lattner3732aca2002-08-15 16:15:25 +00003399 }
Chris Lattner650b6da2002-08-02 20:00:25 +00003400 }
Chris Lattner48a44f72002-05-02 17:06:02 +00003401 return false;
3402}
3403
Chris Lattner11ffd592004-07-20 05:21:00 +00003404static bool ValueRequiresCast(const Value *V, const Type *Ty, TargetData *TD) {
Chris Lattnerdfae8be2003-07-24 17:35:25 +00003405 if (V->getType() == Ty || isa<Constant>(V)) return false;
3406 if (const CastInst *CI = dyn_cast<CastInst>(V))
Chris Lattner11ffd592004-07-20 05:21:00 +00003407 if (isEliminableCastOfCast(CI->getOperand(0)->getType(), CI->getType(), Ty,
3408 TD))
Chris Lattnerdfae8be2003-07-24 17:35:25 +00003409 return false;
3410 return true;
3411}
3412
3413/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
3414/// InsertBefore instruction. This is specialized a bit to avoid inserting
3415/// casts that are known to not do anything...
3416///
3417Value *InstCombiner::InsertOperandCastBefore(Value *V, const Type *DestTy,
3418 Instruction *InsertBefore) {
3419 if (V->getType() == DestTy) return V;
3420 if (Constant *C = dyn_cast<Constant>(V))
3421 return ConstantExpr::getCast(C, DestTy);
3422
3423 CastInst *CI = new CastInst(V, DestTy, V->getName());
3424 InsertNewInstBefore(CI, *InsertBefore);
3425 return CI;
3426}
Chris Lattner48a44f72002-05-02 17:06:02 +00003427
3428// CastInst simplification
Chris Lattner260ab202002-04-18 17:39:14 +00003429//
Chris Lattner113f4f42002-06-25 16:13:24 +00003430Instruction *InstCombiner::visitCastInst(CastInst &CI) {
Chris Lattner55d4bda2003-06-23 21:59:52 +00003431 Value *Src = CI.getOperand(0);
3432
Chris Lattner48a44f72002-05-02 17:06:02 +00003433 // If the user is casting a value to the same type, eliminate this cast
3434 // instruction...
Chris Lattner55d4bda2003-06-23 21:59:52 +00003435 if (CI.getType() == Src->getType())
3436 return ReplaceInstUsesWith(CI, Src);
Chris Lattner48a44f72002-05-02 17:06:02 +00003437
Chris Lattner81a7a232004-10-16 18:11:37 +00003438 if (isa<UndefValue>(Src)) // cast undef -> undef
3439 return ReplaceInstUsesWith(CI, UndefValue::get(CI.getType()));
3440
Chris Lattner48a44f72002-05-02 17:06:02 +00003441 // If casting the result of another cast instruction, try to eliminate this
3442 // one!
3443 //
Chris Lattner86102b82005-01-01 16:22:27 +00003444 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
3445 Value *A = CSrc->getOperand(0);
3446 if (isEliminableCastOfCast(A->getType(), CSrc->getType(),
3447 CI.getType(), TD)) {
Chris Lattner48a44f72002-05-02 17:06:02 +00003448 // This instruction now refers directly to the cast's src operand. This
3449 // has a good chance of making CSrc dead.
Chris Lattner113f4f42002-06-25 16:13:24 +00003450 CI.setOperand(0, CSrc->getOperand(0));
3451 return &CI;
Chris Lattner48a44f72002-05-02 17:06:02 +00003452 }
3453
Chris Lattner650b6da2002-08-02 20:00:25 +00003454 // If this is an A->B->A cast, and we are dealing with integral types, try
3455 // to convert this into a logical 'and' instruction.
3456 //
Misha Brukmanb1c93172005-04-21 23:48:37 +00003457 if (A->getType()->isInteger() &&
Chris Lattnerb0b412e2002-09-03 01:08:28 +00003458 CI.getType()->isInteger() && CSrc->getType()->isInteger() &&
Chris Lattner86102b82005-01-01 16:22:27 +00003459 CSrc->getType()->isUnsigned() && // B->A cast must zero extend
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003460 CSrc->getType()->getPrimitiveSizeInBits() <
3461 CI.getType()->getPrimitiveSizeInBits()&&
3462 A->getType()->getPrimitiveSizeInBits() ==
3463 CI.getType()->getPrimitiveSizeInBits()) {
Chris Lattner650b6da2002-08-02 20:00:25 +00003464 assert(CSrc->getType() != Type::ULongTy &&
3465 "Cannot have type bigger than ulong!");
Chris Lattner2f1457f2005-04-24 17:46:05 +00003466 uint64_t AndValue = ~0ULL>>(64-CSrc->getType()->getPrimitiveSizeInBits());
Chris Lattner86102b82005-01-01 16:22:27 +00003467 Constant *AndOp = ConstantUInt::get(A->getType()->getUnsignedVersion(),
3468 AndValue);
3469 AndOp = ConstantExpr::getCast(AndOp, A->getType());
3470 Instruction *And = BinaryOperator::createAnd(CSrc->getOperand(0), AndOp);
3471 if (And->getType() != CI.getType()) {
3472 And->setName(CSrc->getName()+".mask");
3473 InsertNewInstBefore(And, CI);
3474 And = new CastInst(And, CI.getType());
3475 }
3476 return And;
Chris Lattner650b6da2002-08-02 20:00:25 +00003477 }
3478 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003479
Chris Lattner03841652004-05-25 04:29:21 +00003480 // If this is a cast to bool, turn it into the appropriate setne instruction.
3481 if (CI.getType() == Type::BoolTy)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003482 return BinaryOperator::createSetNE(CI.getOperand(0),
Chris Lattner03841652004-05-25 04:29:21 +00003483 Constant::getNullValue(CI.getOperand(0)->getType()));
3484
Chris Lattnerd0d51602003-06-21 23:12:02 +00003485 // If casting the result of a getelementptr instruction with no offset, turn
3486 // this into a cast of the original pointer!
3487 //
Chris Lattner55d4bda2003-06-23 21:59:52 +00003488 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattnerd0d51602003-06-21 23:12:02 +00003489 bool AllZeroOperands = true;
3490 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
3491 if (!isa<Constant>(GEP->getOperand(i)) ||
3492 !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
3493 AllZeroOperands = false;
3494 break;
3495 }
3496 if (AllZeroOperands) {
3497 CI.setOperand(0, GEP->getOperand(0));
3498 return &CI;
3499 }
3500 }
3501
Chris Lattnerf4ad1652003-11-02 05:57:39 +00003502 // If we are casting a malloc or alloca to a pointer to a type of the same
3503 // size, rewrite the allocation instruction to allocate the "right" type.
3504 //
3505 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
Chris Lattnerd4d987d2003-11-02 06:54:48 +00003506 if (AI->hasOneUse() && !AI->isArrayAllocation())
Chris Lattnerf4ad1652003-11-02 05:57:39 +00003507 if (const PointerType *PTy = dyn_cast<PointerType>(CI.getType())) {
3508 // Get the type really allocated and the type casted to...
3509 const Type *AllocElTy = AI->getAllocatedType();
Chris Lattnerf4ad1652003-11-02 05:57:39 +00003510 const Type *CastElTy = PTy->getElementType();
Chris Lattner9eb9ccd2004-07-06 19:28:42 +00003511 if (AllocElTy->isSized() && CastElTy->isSized()) {
Chris Lattnerfdfe3e492005-01-08 19:42:22 +00003512 uint64_t AllocElTySize = TD->getTypeSize(AllocElTy);
3513 uint64_t CastElTySize = TD->getTypeSize(CastElTy);
Chris Lattner7c94d112003-11-05 17:31:36 +00003514
Chris Lattner9eb9ccd2004-07-06 19:28:42 +00003515 // If the allocation is for an even multiple of the cast type size
3516 if (CastElTySize && (AllocElTySize % CastElTySize == 0)) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00003517 Value *Amt = ConstantUInt::get(Type::UIntTy,
Chris Lattnerf4ad1652003-11-02 05:57:39 +00003518 AllocElTySize/CastElTySize);
Chris Lattner9eb9ccd2004-07-06 19:28:42 +00003519 std::string Name = AI->getName(); AI->setName("");
3520 AllocationInst *New;
3521 if (isa<MallocInst>(AI))
3522 New = new MallocInst(CastElTy, Amt, Name);
3523 else
3524 New = new AllocaInst(CastElTy, Amt, Name);
3525 InsertNewInstBefore(New, *AI);
3526 return ReplaceInstUsesWith(CI, New);
3527 }
Chris Lattnerf4ad1652003-11-02 05:57:39 +00003528 }
3529 }
3530
Chris Lattner86102b82005-01-01 16:22:27 +00003531 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
3532 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
3533 return NV;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00003534 if (isa<PHINode>(Src))
3535 if (Instruction *NV = FoldOpIntoPhi(CI))
3536 return NV;
3537
Chris Lattnerdfae8be2003-07-24 17:35:25 +00003538 // If the source value is an instruction with only this use, we can attempt to
3539 // propagate the cast into the instruction. Also, only handle integral types
3540 // for now.
3541 if (Instruction *SrcI = dyn_cast<Instruction>(Src))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00003542 if (SrcI->hasOneUse() && Src->getType()->isIntegral() &&
Chris Lattnerdfae8be2003-07-24 17:35:25 +00003543 CI.getType()->isInteger()) { // Don't mess with casts to bool here
3544 const Type *DestTy = CI.getType();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003545 unsigned SrcBitSize = Src->getType()->getPrimitiveSizeInBits();
3546 unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
Chris Lattnerdfae8be2003-07-24 17:35:25 +00003547
3548 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
3549 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
3550
3551 switch (SrcI->getOpcode()) {
3552 case Instruction::Add:
3553 case Instruction::Mul:
3554 case Instruction::And:
3555 case Instruction::Or:
3556 case Instruction::Xor:
3557 // If we are discarding information, or just changing the sign, rewrite.
3558 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
3559 // Don't insert two casts if they cannot be eliminated. We allow two
3560 // casts to be inserted if the sizes are the same. This could only be
3561 // converting signedness, which is a noop.
Chris Lattner11ffd592004-07-20 05:21:00 +00003562 if (DestBitSize == SrcBitSize || !ValueRequiresCast(Op1, DestTy,TD) ||
3563 !ValueRequiresCast(Op0, DestTy, TD)) {
Chris Lattnerdfae8be2003-07-24 17:35:25 +00003564 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
3565 Value *Op1c = InsertOperandCastBefore(Op1, DestTy, SrcI);
3566 return BinaryOperator::create(cast<BinaryOperator>(SrcI)
3567 ->getOpcode(), Op0c, Op1c);
3568 }
3569 }
Chris Lattner72086162005-05-06 02:07:39 +00003570
3571 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
3572 if (SrcBitSize == 1 && SrcI->getOpcode() == Instruction::Xor &&
3573 Op1 == ConstantBool::True &&
3574 (!Op0->hasOneUse() || !isa<SetCondInst>(Op0))) {
3575 Value *New = InsertOperandCastBefore(Op0, DestTy, &CI);
3576 return BinaryOperator::createXor(New,
3577 ConstantInt::get(CI.getType(), 1));
3578 }
Chris Lattnerdfae8be2003-07-24 17:35:25 +00003579 break;
3580 case Instruction::Shl:
3581 // Allow changing the sign of the source operand. Do not allow changing
3582 // the size of the shift, UNLESS the shift amount is a constant. We
3583 // mush not change variable sized shifts to a smaller size, because it
3584 // is undefined to shift more bits out than exist in the value.
3585 if (DestBitSize == SrcBitSize ||
3586 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
3587 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
3588 return new ShiftInst(Instruction::Shl, Op0c, Op1);
3589 }
3590 break;
Chris Lattner87380412005-05-06 04:18:52 +00003591 case Instruction::Shr:
3592 // If this is a signed shr, and if all bits shifted in are about to be
3593 // truncated off, turn it into an unsigned shr to allow greater
3594 // simplifications.
3595 if (DestBitSize < SrcBitSize && Src->getType()->isSigned() &&
3596 isa<ConstantInt>(Op1)) {
3597 unsigned ShiftAmt = cast<ConstantUInt>(Op1)->getValue();
3598 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
3599 // Convert to unsigned.
3600 Value *N1 = InsertOperandCastBefore(Op0,
3601 Op0->getType()->getUnsignedVersion(), &CI);
3602 // Insert the new shift, which is now unsigned.
3603 N1 = InsertNewInstBefore(new ShiftInst(Instruction::Shr, N1,
3604 Op1, Src->getName()), CI);
3605 return new CastInst(N1, CI.getType());
3606 }
3607 }
3608 break;
3609
Chris Lattner809dfac2005-05-04 19:10:26 +00003610 case Instruction::SetNE:
Chris Lattner809dfac2005-05-04 19:10:26 +00003611 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner4c2d3782005-05-06 01:53:19 +00003612 if (Op1C->getRawValue() == 0) {
3613 // If the input only has the low bit set, simplify directly.
Chris Lattner809dfac2005-05-04 19:10:26 +00003614 Constant *Not1 =
3615 ConstantExpr::getNot(ConstantInt::get(Op0->getType(), 1));
Chris Lattner4c2d3782005-05-06 01:53:19 +00003616 // cast (X != 0) to int --> X if X&~1 == 0
Chris Lattner809dfac2005-05-04 19:10:26 +00003617 if (MaskedValueIsZero(Op0, cast<ConstantIntegral>(Not1))) {
3618 if (CI.getType() == Op0->getType())
3619 return ReplaceInstUsesWith(CI, Op0);
3620 else
3621 return new CastInst(Op0, CI.getType());
3622 }
Chris Lattner4c2d3782005-05-06 01:53:19 +00003623
3624 // If the input is an and with a single bit, shift then simplify.
3625 ConstantInt *AndRHS;
3626 if (match(Op0, m_And(m_Value(), m_ConstantInt(AndRHS))))
3627 if (AndRHS->getRawValue() &&
3628 (AndRHS->getRawValue() & (AndRHS->getRawValue()-1)) == 0) {
3629 unsigned ShiftAmt = Log2(AndRHS->getRawValue());
3630 // Perform an unsigned shr by shiftamt. Convert input to
3631 // unsigned if it is signed.
3632 Value *In = Op0;
3633 if (In->getType()->isSigned())
3634 In = InsertNewInstBefore(new CastInst(In,
3635 In->getType()->getUnsignedVersion(), In->getName()),CI);
3636 // Insert the shift to put the result in the low bit.
3637 In = InsertNewInstBefore(new ShiftInst(Instruction::Shr, In,
3638 ConstantInt::get(Type::UByteTy, ShiftAmt),
3639 In->getName()+".lobit"), CI);
Chris Lattner4c2d3782005-05-06 01:53:19 +00003640 if (CI.getType() == In->getType())
3641 return ReplaceInstUsesWith(CI, In);
3642 else
3643 return new CastInst(In, CI.getType());
3644 }
3645 }
3646 }
3647 break;
3648 case Instruction::SetEQ:
3649 // We if we are just checking for a seteq of a single bit and casting it
3650 // to an integer. If so, shift the bit to the appropriate place then
3651 // cast to integer to avoid the comparison.
3652 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
3653 // Is Op1C a power of two or zero?
3654 if ((Op1C->getRawValue() & Op1C->getRawValue()-1) == 0) {
3655 // cast (X == 1) to int -> X iff X has only the low bit set.
3656 if (Op1C->getRawValue() == 1) {
3657 Constant *Not1 =
3658 ConstantExpr::getNot(ConstantInt::get(Op0->getType(), 1));
3659 if (MaskedValueIsZero(Op0, cast<ConstantIntegral>(Not1))) {
3660 if (CI.getType() == Op0->getType())
3661 return ReplaceInstUsesWith(CI, Op0);
3662 else
3663 return new CastInst(Op0, CI.getType());
3664 }
3665 }
Chris Lattner809dfac2005-05-04 19:10:26 +00003666 }
3667 }
3668 break;
Chris Lattnerdfae8be2003-07-24 17:35:25 +00003669 }
3670 }
Chris Lattner260ab202002-04-18 17:39:14 +00003671 return 0;
Chris Lattnerca081252001-12-14 16:52:21 +00003672}
3673
Chris Lattner56e4d3d2004-04-09 23:46:01 +00003674/// GetSelectFoldableOperands - We want to turn code that looks like this:
3675/// %C = or %A, %B
3676/// %D = select %cond, %C, %A
3677/// into:
3678/// %C = select %cond, %B, 0
3679/// %D = or %A, %C
3680///
3681/// Assuming that the specified instruction is an operand to the select, return
3682/// a bitmask indicating which operands of this instruction are foldable if they
3683/// equal the other incoming value of the select.
3684///
3685static unsigned GetSelectFoldableOperands(Instruction *I) {
3686 switch (I->getOpcode()) {
3687 case Instruction::Add:
3688 case Instruction::Mul:
3689 case Instruction::And:
3690 case Instruction::Or:
3691 case Instruction::Xor:
3692 return 3; // Can fold through either operand.
3693 case Instruction::Sub: // Can only fold on the amount subtracted.
3694 case Instruction::Shl: // Can only fold on the shift amount.
3695 case Instruction::Shr:
Misha Brukmanb1c93172005-04-21 23:48:37 +00003696 return 1;
Chris Lattner56e4d3d2004-04-09 23:46:01 +00003697 default:
3698 return 0; // Cannot fold
3699 }
3700}
3701
3702/// GetSelectFoldableConstant - For the same transformation as the previous
3703/// function, return the identity constant that goes into the select.
3704static Constant *GetSelectFoldableConstant(Instruction *I) {
3705 switch (I->getOpcode()) {
3706 default: assert(0 && "This cannot happen!"); abort();
3707 case Instruction::Add:
3708 case Instruction::Sub:
3709 case Instruction::Or:
3710 case Instruction::Xor:
3711 return Constant::getNullValue(I->getType());
3712 case Instruction::Shl:
3713 case Instruction::Shr:
3714 return Constant::getNullValue(Type::UByteTy);
3715 case Instruction::And:
3716 return ConstantInt::getAllOnesValue(I->getType());
3717 case Instruction::Mul:
3718 return ConstantInt::get(I->getType(), 1);
3719 }
3720}
3721
Chris Lattner411336f2005-01-19 21:50:18 +00003722/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
3723/// have the same opcode and only one use each. Try to simplify this.
3724Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
3725 Instruction *FI) {
3726 if (TI->getNumOperands() == 1) {
3727 // If this is a non-volatile load or a cast from the same type,
3728 // merge.
3729 if (TI->getOpcode() == Instruction::Cast) {
3730 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
3731 return 0;
3732 } else {
3733 return 0; // unknown unary op.
3734 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003735
Chris Lattner411336f2005-01-19 21:50:18 +00003736 // Fold this by inserting a select from the input values.
3737 SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
3738 FI->getOperand(0), SI.getName()+".v");
3739 InsertNewInstBefore(NewSI, SI);
3740 return new CastInst(NewSI, TI->getType());
3741 }
3742
3743 // Only handle binary operators here.
3744 if (!isa<ShiftInst>(TI) && !isa<BinaryOperator>(TI))
3745 return 0;
3746
3747 // Figure out if the operations have any operands in common.
3748 Value *MatchOp, *OtherOpT, *OtherOpF;
3749 bool MatchIsOpZero;
3750 if (TI->getOperand(0) == FI->getOperand(0)) {
3751 MatchOp = TI->getOperand(0);
3752 OtherOpT = TI->getOperand(1);
3753 OtherOpF = FI->getOperand(1);
3754 MatchIsOpZero = true;
3755 } else if (TI->getOperand(1) == FI->getOperand(1)) {
3756 MatchOp = TI->getOperand(1);
3757 OtherOpT = TI->getOperand(0);
3758 OtherOpF = FI->getOperand(0);
3759 MatchIsOpZero = false;
3760 } else if (!TI->isCommutative()) {
3761 return 0;
3762 } else if (TI->getOperand(0) == FI->getOperand(1)) {
3763 MatchOp = TI->getOperand(0);
3764 OtherOpT = TI->getOperand(1);
3765 OtherOpF = FI->getOperand(0);
3766 MatchIsOpZero = true;
3767 } else if (TI->getOperand(1) == FI->getOperand(0)) {
3768 MatchOp = TI->getOperand(1);
3769 OtherOpT = TI->getOperand(0);
3770 OtherOpF = FI->getOperand(1);
3771 MatchIsOpZero = true;
3772 } else {
3773 return 0;
3774 }
3775
3776 // If we reach here, they do have operations in common.
3777 SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
3778 OtherOpF, SI.getName()+".v");
3779 InsertNewInstBefore(NewSI, SI);
3780
3781 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
3782 if (MatchIsOpZero)
3783 return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
3784 else
3785 return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
3786 } else {
3787 if (MatchIsOpZero)
3788 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), MatchOp, NewSI);
3789 else
3790 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), NewSI, MatchOp);
3791 }
3792}
3793
Chris Lattnerb909e8b2004-03-12 05:52:32 +00003794Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattner533bc492004-03-30 19:37:13 +00003795 Value *CondVal = SI.getCondition();
3796 Value *TrueVal = SI.getTrueValue();
3797 Value *FalseVal = SI.getFalseValue();
3798
3799 // select true, X, Y -> X
3800 // select false, X, Y -> Y
3801 if (ConstantBool *C = dyn_cast<ConstantBool>(CondVal))
Chris Lattnerb909e8b2004-03-12 05:52:32 +00003802 if (C == ConstantBool::True)
Chris Lattner533bc492004-03-30 19:37:13 +00003803 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattnerb909e8b2004-03-12 05:52:32 +00003804 else {
3805 assert(C == ConstantBool::False);
Chris Lattner533bc492004-03-30 19:37:13 +00003806 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattnerb909e8b2004-03-12 05:52:32 +00003807 }
Chris Lattner533bc492004-03-30 19:37:13 +00003808
3809 // select C, X, X -> X
3810 if (TrueVal == FalseVal)
3811 return ReplaceInstUsesWith(SI, TrueVal);
3812
Chris Lattner81a7a232004-10-16 18:11:37 +00003813 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
3814 return ReplaceInstUsesWith(SI, FalseVal);
3815 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
3816 return ReplaceInstUsesWith(SI, TrueVal);
3817 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
3818 if (isa<Constant>(TrueVal))
3819 return ReplaceInstUsesWith(SI, TrueVal);
3820 else
3821 return ReplaceInstUsesWith(SI, FalseVal);
3822 }
3823
Chris Lattner1c631e82004-04-08 04:43:23 +00003824 if (SI.getType() == Type::BoolTy)
3825 if (ConstantBool *C = dyn_cast<ConstantBool>(TrueVal)) {
3826 if (C == ConstantBool::True) {
3827 // Change: A = select B, true, C --> A = or B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003828 return BinaryOperator::createOr(CondVal, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00003829 } else {
3830 // Change: A = select B, false, C --> A = and !B, C
3831 Value *NotCond =
3832 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
3833 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003834 return BinaryOperator::createAnd(NotCond, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00003835 }
3836 } else if (ConstantBool *C = dyn_cast<ConstantBool>(FalseVal)) {
3837 if (C == ConstantBool::False) {
3838 // Change: A = select B, C, false --> A = and B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003839 return BinaryOperator::createAnd(CondVal, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00003840 } else {
3841 // Change: A = select B, C, true --> A = or !B, C
3842 Value *NotCond =
3843 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
3844 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003845 return BinaryOperator::createOr(NotCond, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00003846 }
3847 }
3848
Chris Lattner183b3362004-04-09 19:05:30 +00003849 // Selecting between two integer constants?
3850 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
3851 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
3852 // select C, 1, 0 -> cast C to int
3853 if (FalseValC->isNullValue() && TrueValC->getRawValue() == 1) {
3854 return new CastInst(CondVal, SI.getType());
3855 } else if (TrueValC->isNullValue() && FalseValC->getRawValue() == 1) {
3856 // select C, 0, 1 -> cast !C to int
3857 Value *NotCond =
3858 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
Chris Lattnercf7baf32004-04-09 18:19:44 +00003859 "not."+CondVal->getName()), SI);
Chris Lattner183b3362004-04-09 19:05:30 +00003860 return new CastInst(NotCond, SI.getType());
Chris Lattnercf7baf32004-04-09 18:19:44 +00003861 }
Chris Lattner35167c32004-06-09 07:59:58 +00003862
3863 // If one of the constants is zero (we know they can't both be) and we
3864 // have a setcc instruction with zero, and we have an 'and' with the
3865 // non-constant value, eliminate this whole mess. This corresponds to
3866 // cases like this: ((X & 27) ? 27 : 0)
3867 if (TrueValC->isNullValue() || FalseValC->isNullValue())
3868 if (Instruction *IC = dyn_cast<Instruction>(SI.getCondition()))
3869 if ((IC->getOpcode() == Instruction::SetEQ ||
3870 IC->getOpcode() == Instruction::SetNE) &&
3871 isa<ConstantInt>(IC->getOperand(1)) &&
3872 cast<Constant>(IC->getOperand(1))->isNullValue())
3873 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
3874 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00003875 isa<ConstantInt>(ICA->getOperand(1)) &&
3876 (ICA->getOperand(1) == TrueValC ||
3877 ICA->getOperand(1) == FalseValC) &&
Chris Lattner35167c32004-06-09 07:59:58 +00003878 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
3879 // Okay, now we know that everything is set up, we just don't
3880 // know whether we have a setne or seteq and whether the true or
3881 // false val is the zero.
3882 bool ShouldNotVal = !TrueValC->isNullValue();
3883 ShouldNotVal ^= IC->getOpcode() == Instruction::SetNE;
3884 Value *V = ICA;
3885 if (ShouldNotVal)
3886 V = InsertNewInstBefore(BinaryOperator::create(
3887 Instruction::Xor, V, ICA->getOperand(1)), SI);
3888 return ReplaceInstUsesWith(SI, V);
3889 }
Chris Lattner533bc492004-03-30 19:37:13 +00003890 }
Chris Lattner623fba12004-04-10 22:21:27 +00003891
3892 // See if we are selecting two values based on a comparison of the two values.
3893 if (SetCondInst *SCI = dyn_cast<SetCondInst>(CondVal)) {
3894 if (SCI->getOperand(0) == TrueVal && SCI->getOperand(1) == FalseVal) {
3895 // Transform (X == Y) ? X : Y -> Y
3896 if (SCI->getOpcode() == Instruction::SetEQ)
3897 return ReplaceInstUsesWith(SI, FalseVal);
3898 // Transform (X != Y) ? X : Y -> X
3899 if (SCI->getOpcode() == Instruction::SetNE)
3900 return ReplaceInstUsesWith(SI, TrueVal);
3901 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
3902
3903 } else if (SCI->getOperand(0) == FalseVal && SCI->getOperand(1) == TrueVal){
3904 // Transform (X == Y) ? Y : X -> X
3905 if (SCI->getOpcode() == Instruction::SetEQ)
Chris Lattner24cf0202004-04-11 01:39:19 +00003906 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattner623fba12004-04-10 22:21:27 +00003907 // Transform (X != Y) ? Y : X -> Y
3908 if (SCI->getOpcode() == Instruction::SetNE)
Chris Lattner24cf0202004-04-11 01:39:19 +00003909 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattner623fba12004-04-10 22:21:27 +00003910 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
3911 }
3912 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003913
Chris Lattnera04c9042005-01-13 22:52:24 +00003914 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
3915 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
3916 if (TI->hasOneUse() && FI->hasOneUse()) {
3917 bool isInverse = false;
3918 Instruction *AddOp = 0, *SubOp = 0;
3919
Chris Lattner411336f2005-01-19 21:50:18 +00003920 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
3921 if (TI->getOpcode() == FI->getOpcode())
3922 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
3923 return IV;
3924
3925 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
3926 // even legal for FP.
Chris Lattnera04c9042005-01-13 22:52:24 +00003927 if (TI->getOpcode() == Instruction::Sub &&
3928 FI->getOpcode() == Instruction::Add) {
3929 AddOp = FI; SubOp = TI;
3930 } else if (FI->getOpcode() == Instruction::Sub &&
3931 TI->getOpcode() == Instruction::Add) {
3932 AddOp = TI; SubOp = FI;
3933 }
3934
3935 if (AddOp) {
3936 Value *OtherAddOp = 0;
3937 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
3938 OtherAddOp = AddOp->getOperand(1);
3939 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
3940 OtherAddOp = AddOp->getOperand(0);
3941 }
3942
3943 if (OtherAddOp) {
3944 // So at this point we know we have:
3945 // select C, (add X, Y), (sub X, ?)
3946 // We can do the transform profitably if either 'Y' = '?' or '?' is
3947 // a constant.
3948 if (SubOp->getOperand(1) == AddOp ||
3949 isa<Constant>(SubOp->getOperand(1))) {
3950 Value *NegVal;
3951 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
3952 NegVal = ConstantExpr::getNeg(C);
3953 } else {
3954 NegVal = InsertNewInstBefore(
3955 BinaryOperator::createNeg(SubOp->getOperand(1)), SI);
3956 }
3957
Chris Lattner51726c42005-01-14 17:35:12 +00003958 Value *NewTrueOp = OtherAddOp;
Chris Lattnera04c9042005-01-13 22:52:24 +00003959 Value *NewFalseOp = NegVal;
3960 if (AddOp != TI)
3961 std::swap(NewTrueOp, NewFalseOp);
3962 Instruction *NewSel =
3963 new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
Misha Brukmanb1c93172005-04-21 23:48:37 +00003964
Chris Lattnera04c9042005-01-13 22:52:24 +00003965 NewSel = InsertNewInstBefore(NewSel, SI);
Chris Lattner51726c42005-01-14 17:35:12 +00003966 return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
Chris Lattnera04c9042005-01-13 22:52:24 +00003967 }
3968 }
3969 }
3970 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003971
Chris Lattner56e4d3d2004-04-09 23:46:01 +00003972 // See if we can fold the select into one of our operands.
3973 if (SI.getType()->isInteger()) {
3974 // See the comment above GetSelectFoldableOperands for a description of the
3975 // transformation we are doing here.
3976 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
3977 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
3978 !isa<Constant>(FalseVal))
3979 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
3980 unsigned OpToFold = 0;
3981 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
3982 OpToFold = 1;
3983 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
3984 OpToFold = 2;
3985 }
3986
3987 if (OpToFold) {
3988 Constant *C = GetSelectFoldableConstant(TVI);
3989 std::string Name = TVI->getName(); TVI->setName("");
3990 Instruction *NewSel =
3991 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C,
3992 Name);
3993 InsertNewInstBefore(NewSel, SI);
3994 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
3995 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
3996 else if (ShiftInst *SI = dyn_cast<ShiftInst>(TVI))
3997 return new ShiftInst(SI->getOpcode(), FalseVal, NewSel);
3998 else {
3999 assert(0 && "Unknown instruction!!");
4000 }
4001 }
4002 }
Chris Lattner6862fbd2004-09-29 17:40:11 +00004003
Chris Lattner56e4d3d2004-04-09 23:46:01 +00004004 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
4005 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
4006 !isa<Constant>(TrueVal))
4007 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
4008 unsigned OpToFold = 0;
4009 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
4010 OpToFold = 1;
4011 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
4012 OpToFold = 2;
4013 }
4014
4015 if (OpToFold) {
4016 Constant *C = GetSelectFoldableConstant(FVI);
4017 std::string Name = FVI->getName(); FVI->setName("");
4018 Instruction *NewSel =
4019 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold),
4020 Name);
4021 InsertNewInstBefore(NewSel, SI);
4022 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
4023 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
4024 else if (ShiftInst *SI = dyn_cast<ShiftInst>(FVI))
4025 return new ShiftInst(SI->getOpcode(), TrueVal, NewSel);
4026 else {
4027 assert(0 && "Unknown instruction!!");
4028 }
4029 }
4030 }
4031 }
Chris Lattnerd6f636a2005-04-24 07:30:14 +00004032
4033 if (BinaryOperator::isNot(CondVal)) {
4034 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
4035 SI.setOperand(1, FalseVal);
4036 SI.setOperand(2, TrueVal);
4037 return &SI;
4038 }
4039
Chris Lattnerb909e8b2004-03-12 05:52:32 +00004040 return 0;
4041}
4042
4043
Chris Lattner970c33a2003-06-19 17:00:31 +00004044// CallInst simplification
4045//
4046Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattner51ea1272004-02-28 05:22:00 +00004047 // Intrinsics cannot occur in an invoke, so handle them here instead of in
4048 // visitCallSite.
Chris Lattner00648e12004-10-12 04:52:52 +00004049 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(&CI)) {
4050 bool Changed = false;
4051
4052 // memmove/cpy/set of zero bytes is a noop.
4053 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
4054 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
4055
4056 // FIXME: Increase alignment here.
Misha Brukmanb1c93172005-04-21 23:48:37 +00004057
Chris Lattner00648e12004-10-12 04:52:52 +00004058 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
4059 if (CI->getRawValue() == 1) {
4060 // Replace the instruction with just byte operations. We would
4061 // transform other cases to loads/stores, but we don't know if
4062 // alignment is sufficient.
4063 }
Chris Lattner51ea1272004-02-28 05:22:00 +00004064 }
4065
Chris Lattner00648e12004-10-12 04:52:52 +00004066 // If we have a memmove and the source operation is a constant global,
4067 // then the source and dest pointers can't alias, so we can change this
4068 // into a call to memcpy.
4069 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI))
4070 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
4071 if (GVSrc->isConstant()) {
4072 Module *M = CI.getParent()->getParent()->getParent();
4073 Function *MemCpy = M->getOrInsertFunction("llvm.memcpy",
4074 CI.getCalledFunction()->getFunctionType());
4075 CI.setOperand(0, MemCpy);
4076 Changed = true;
4077 }
4078
4079 if (Changed) return &CI;
Chris Lattner95307542004-11-18 21:41:39 +00004080 } else if (DbgStopPointInst *SPI = dyn_cast<DbgStopPointInst>(&CI)) {
4081 // If this stoppoint is at the same source location as the previous
4082 // stoppoint in the chain, it is not needed.
4083 if (DbgStopPointInst *PrevSPI =
4084 dyn_cast<DbgStopPointInst>(SPI->getChain()))
4085 if (SPI->getLineNo() == PrevSPI->getLineNo() &&
4086 SPI->getColNo() == PrevSPI->getColNo()) {
4087 SPI->replaceAllUsesWith(PrevSPI);
4088 return EraseInstFromFunction(CI);
4089 }
Chris Lattner00648e12004-10-12 04:52:52 +00004090 }
4091
Chris Lattneraec3d942003-10-07 22:32:43 +00004092 return visitCallSite(&CI);
Chris Lattner970c33a2003-06-19 17:00:31 +00004093}
4094
4095// InvokeInst simplification
4096//
4097Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattneraec3d942003-10-07 22:32:43 +00004098 return visitCallSite(&II);
Chris Lattner970c33a2003-06-19 17:00:31 +00004099}
4100
Chris Lattneraec3d942003-10-07 22:32:43 +00004101// visitCallSite - Improvements for call and invoke instructions.
4102//
4103Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner75b4d1d2003-10-07 22:54:13 +00004104 bool Changed = false;
4105
4106 // If the callee is a constexpr cast of a function, attempt to move the cast
4107 // to the arguments of the call/invoke.
Chris Lattneraec3d942003-10-07 22:32:43 +00004108 if (transformConstExprCastCall(CS)) return 0;
4109
Chris Lattner75b4d1d2003-10-07 22:54:13 +00004110 Value *Callee = CS.getCalledValue();
Chris Lattner81a7a232004-10-16 18:11:37 +00004111
Chris Lattner61d9d812005-05-13 07:09:09 +00004112 if (Function *CalleeF = dyn_cast<Function>(Callee))
4113 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
4114 Instruction *OldCall = CS.getInstruction();
4115 // If the call and callee calling conventions don't match, this call must
4116 // be unreachable, as the call is undefined.
4117 new StoreInst(ConstantBool::True,
4118 UndefValue::get(PointerType::get(Type::BoolTy)), OldCall);
4119 if (!OldCall->use_empty())
4120 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
4121 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
4122 return EraseInstFromFunction(*OldCall);
4123 return 0;
4124 }
4125
Chris Lattner8ba9ec92004-10-18 02:59:09 +00004126 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
4127 // This instruction is not reachable, just remove it. We insert a store to
4128 // undef so that we know that this code is not reachable, despite the fact
4129 // that we can't modify the CFG here.
4130 new StoreInst(ConstantBool::True,
4131 UndefValue::get(PointerType::get(Type::BoolTy)),
4132 CS.getInstruction());
4133
4134 if (!CS.getInstruction()->use_empty())
4135 CS.getInstruction()->
4136 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
4137
4138 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
4139 // Don't break the CFG, insert a dummy cond branch.
4140 new BranchInst(II->getNormalDest(), II->getUnwindDest(),
4141 ConstantBool::True, II);
Chris Lattner81a7a232004-10-16 18:11:37 +00004142 }
Chris Lattner8ba9ec92004-10-18 02:59:09 +00004143 return EraseInstFromFunction(*CS.getInstruction());
4144 }
Chris Lattner81a7a232004-10-16 18:11:37 +00004145
Chris Lattner75b4d1d2003-10-07 22:54:13 +00004146 const PointerType *PTy = cast<PointerType>(Callee->getType());
4147 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
4148 if (FTy->isVarArg()) {
4149 // See if we can optimize any arguments passed through the varargs area of
4150 // the call.
4151 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
4152 E = CS.arg_end(); I != E; ++I)
4153 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
4154 // If this cast does not effect the value passed through the varargs
4155 // area, we can eliminate the use of the cast.
4156 Value *Op = CI->getOperand(0);
4157 if (CI->getType()->isLosslesslyConvertibleTo(Op->getType())) {
4158 *I = Op;
4159 Changed = true;
4160 }
4161 }
4162 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004163
Chris Lattner75b4d1d2003-10-07 22:54:13 +00004164 return Changed ? CS.getInstruction() : 0;
Chris Lattneraec3d942003-10-07 22:32:43 +00004165}
4166
Chris Lattner970c33a2003-06-19 17:00:31 +00004167// transformConstExprCastCall - If the callee is a constexpr cast of a function,
4168// attempt to move the cast to the arguments of the call/invoke.
4169//
4170bool InstCombiner::transformConstExprCastCall(CallSite CS) {
4171 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
4172 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Chris Lattnerf3edc492004-07-18 18:59:44 +00004173 if (CE->getOpcode() != Instruction::Cast || !isa<Function>(CE->getOperand(0)))
Chris Lattner970c33a2003-06-19 17:00:31 +00004174 return false;
Reid Spencer87436872004-07-18 00:38:32 +00004175 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner970c33a2003-06-19 17:00:31 +00004176 Instruction *Caller = CS.getInstruction();
4177
4178 // Okay, this is a cast from a function to a different type. Unless doing so
4179 // would cause a type conversion of one of our arguments, change this call to
4180 // be a direct call with arguments casted to the appropriate types.
4181 //
4182 const FunctionType *FT = Callee->getFunctionType();
4183 const Type *OldRetTy = Caller->getType();
4184
Chris Lattner1f7942f2004-01-14 06:06:08 +00004185 // Check to see if we are changing the return type...
4186 if (OldRetTy != FT->getReturnType()) {
4187 if (Callee->isExternal() &&
4188 !OldRetTy->isLosslesslyConvertibleTo(FT->getReturnType()) &&
4189 !Caller->use_empty())
4190 return false; // Cannot transform this return value...
4191
4192 // If the callsite is an invoke instruction, and the return value is used by
4193 // a PHI node in a successor, we cannot change the return type of the call
4194 // because there is no place to put the cast instruction (without breaking
4195 // the critical edge). Bail out in this case.
4196 if (!Caller->use_empty())
4197 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
4198 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
4199 UI != E; ++UI)
4200 if (PHINode *PN = dyn_cast<PHINode>(*UI))
4201 if (PN->getParent() == II->getNormalDest() ||
Chris Lattnerfae8ab32004-02-08 21:44:31 +00004202 PN->getParent() == II->getUnwindDest())
Chris Lattner1f7942f2004-01-14 06:06:08 +00004203 return false;
4204 }
Chris Lattner970c33a2003-06-19 17:00:31 +00004205
4206 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
4207 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004208
Chris Lattner970c33a2003-06-19 17:00:31 +00004209 CallSite::arg_iterator AI = CS.arg_begin();
4210 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
4211 const Type *ParamTy = FT->getParamType(i);
4212 bool isConvertible = (*AI)->getType()->isLosslesslyConvertibleTo(ParamTy);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004213 if (Callee->isExternal() && !isConvertible) return false;
Chris Lattner970c33a2003-06-19 17:00:31 +00004214 }
4215
4216 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
4217 Callee->isExternal())
4218 return false; // Do not delete arguments unless we have a function body...
4219
4220 // Okay, we decided that this is a safe thing to do: go ahead and start
4221 // inserting cast instructions as necessary...
4222 std::vector<Value*> Args;
4223 Args.reserve(NumActualArgs);
4224
4225 AI = CS.arg_begin();
4226 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
4227 const Type *ParamTy = FT->getParamType(i);
4228 if ((*AI)->getType() == ParamTy) {
4229 Args.push_back(*AI);
4230 } else {
Chris Lattner1c631e82004-04-08 04:43:23 +00004231 Args.push_back(InsertNewInstBefore(new CastInst(*AI, ParamTy, "tmp"),
4232 *Caller));
Chris Lattner970c33a2003-06-19 17:00:31 +00004233 }
4234 }
4235
4236 // If the function takes more arguments than the call was taking, add them
4237 // now...
4238 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
4239 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
4240
4241 // If we are removing arguments to the function, emit an obnoxious warning...
4242 if (FT->getNumParams() < NumActualArgs)
4243 if (!FT->isVarArg()) {
4244 std::cerr << "WARNING: While resolving call to function '"
4245 << Callee->getName() << "' arguments were dropped!\n";
4246 } else {
4247 // Add all of the arguments in their promoted form to the arg list...
4248 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
4249 const Type *PTy = getPromotedType((*AI)->getType());
4250 if (PTy != (*AI)->getType()) {
4251 // Must promote to pass through va_arg area!
4252 Instruction *Cast = new CastInst(*AI, PTy, "tmp");
4253 InsertNewInstBefore(Cast, *Caller);
4254 Args.push_back(Cast);
4255 } else {
4256 Args.push_back(*AI);
4257 }
4258 }
4259 }
4260
4261 if (FT->getReturnType() == Type::VoidTy)
4262 Caller->setName(""); // Void type should not have a name...
4263
4264 Instruction *NC;
4265 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Chris Lattnerfae8ab32004-02-08 21:44:31 +00004266 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
Chris Lattner970c33a2003-06-19 17:00:31 +00004267 Args, Caller->getName(), Caller);
Chris Lattner05c703e2005-05-14 12:25:32 +00004268 cast<InvokeInst>(II)->setCallingConv(II->getCallingConv());
Chris Lattner970c33a2003-06-19 17:00:31 +00004269 } else {
4270 NC = new CallInst(Callee, Args, Caller->getName(), Caller);
Chris Lattner6aacb0f2005-05-06 06:48:21 +00004271 if (cast<CallInst>(Caller)->isTailCall())
4272 cast<CallInst>(NC)->setTailCall();
Chris Lattner05c703e2005-05-14 12:25:32 +00004273 cast<CallInst>(NC)->setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Chris Lattner970c33a2003-06-19 17:00:31 +00004274 }
4275
4276 // Insert a cast of the return type as necessary...
4277 Value *NV = NC;
4278 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
4279 if (NV->getType() != Type::VoidTy) {
4280 NV = NC = new CastInst(NC, Caller->getType(), "tmp");
Chris Lattner686767f2003-10-30 00:46:41 +00004281
4282 // If this is an invoke instruction, we should insert it after the first
4283 // non-phi, instruction in the normal successor block.
4284 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
4285 BasicBlock::iterator I = II->getNormalDest()->begin();
4286 while (isa<PHINode>(I)) ++I;
4287 InsertNewInstBefore(NC, *I);
4288 } else {
4289 // Otherwise, it's a call, just insert cast right after the call instr
4290 InsertNewInstBefore(NC, *Caller);
4291 }
Chris Lattner51ea1272004-02-28 05:22:00 +00004292 AddUsersToWorkList(*Caller);
Chris Lattner970c33a2003-06-19 17:00:31 +00004293 } else {
Chris Lattnere29d6342004-10-17 21:22:38 +00004294 NV = UndefValue::get(Caller->getType());
Chris Lattner970c33a2003-06-19 17:00:31 +00004295 }
4296 }
4297
4298 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
4299 Caller->replaceAllUsesWith(NV);
4300 Caller->getParent()->getInstList().erase(Caller);
4301 removeFromWorkList(Caller);
4302 return true;
4303}
4304
4305
Chris Lattner7515cab2004-11-14 19:13:23 +00004306// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
4307// operator and they all are only used by the PHI, PHI together their
4308// inputs, and do the operation once, to the result of the PHI.
4309Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
4310 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
4311
4312 // Scan the instruction, looking for input operations that can be folded away.
4313 // If all input operands to the phi are the same instruction (e.g. a cast from
4314 // the same type or "+42") we can pull the operation through the PHI, reducing
4315 // code size and simplifying code.
4316 Constant *ConstantOp = 0;
4317 const Type *CastSrcTy = 0;
4318 if (isa<CastInst>(FirstInst)) {
4319 CastSrcTy = FirstInst->getOperand(0)->getType();
4320 } else if (isa<BinaryOperator>(FirstInst) || isa<ShiftInst>(FirstInst)) {
4321 // Can fold binop or shift if the RHS is a constant.
4322 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
4323 if (ConstantOp == 0) return 0;
4324 } else {
4325 return 0; // Cannot fold this operation.
4326 }
4327
4328 // Check to see if all arguments are the same operation.
4329 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
4330 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
4331 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
4332 if (!I->hasOneUse() || I->getOpcode() != FirstInst->getOpcode())
4333 return 0;
4334 if (CastSrcTy) {
4335 if (I->getOperand(0)->getType() != CastSrcTy)
4336 return 0; // Cast operation must match.
4337 } else if (I->getOperand(1) != ConstantOp) {
4338 return 0;
4339 }
4340 }
4341
4342 // Okay, they are all the same operation. Create a new PHI node of the
4343 // correct type, and PHI together all of the LHS's of the instructions.
4344 PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
4345 PN.getName()+".in");
Chris Lattnerd8e20182005-01-29 00:39:08 +00004346 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattner46dd5a62004-11-14 19:29:34 +00004347
4348 Value *InVal = FirstInst->getOperand(0);
4349 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattner7515cab2004-11-14 19:13:23 +00004350
4351 // Add all operands to the new PHI.
Chris Lattner46dd5a62004-11-14 19:29:34 +00004352 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
4353 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
4354 if (NewInVal != InVal)
4355 InVal = 0;
4356 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
4357 }
4358
4359 Value *PhiVal;
4360 if (InVal) {
4361 // The new PHI unions all of the same values together. This is really
4362 // common, so we handle it intelligently here for compile-time speed.
4363 PhiVal = InVal;
4364 delete NewPN;
4365 } else {
4366 InsertNewInstBefore(NewPN, PN);
4367 PhiVal = NewPN;
4368 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004369
Chris Lattner7515cab2004-11-14 19:13:23 +00004370 // Insert and return the new operation.
4371 if (isa<CastInst>(FirstInst))
Chris Lattner46dd5a62004-11-14 19:29:34 +00004372 return new CastInst(PhiVal, PN.getType());
Chris Lattner7515cab2004-11-14 19:13:23 +00004373 else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattner46dd5a62004-11-14 19:29:34 +00004374 return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattner7515cab2004-11-14 19:13:23 +00004375 else
4376 return new ShiftInst(cast<ShiftInst>(FirstInst)->getOpcode(),
Chris Lattner46dd5a62004-11-14 19:29:34 +00004377 PhiVal, ConstantOp);
Chris Lattner7515cab2004-11-14 19:13:23 +00004378}
Chris Lattner48a44f72002-05-02 17:06:02 +00004379
Chris Lattner71536432005-01-17 05:10:15 +00004380/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
4381/// that is dead.
4382static bool DeadPHICycle(PHINode *PN, std::set<PHINode*> &PotentiallyDeadPHIs) {
4383 if (PN->use_empty()) return true;
4384 if (!PN->hasOneUse()) return false;
4385
4386 // Remember this node, and if we find the cycle, return.
4387 if (!PotentiallyDeadPHIs.insert(PN).second)
4388 return true;
4389
4390 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
4391 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004392
Chris Lattner71536432005-01-17 05:10:15 +00004393 return false;
4394}
4395
Chris Lattnerbbbdd852002-05-06 18:06:38 +00004396// PHINode simplification
4397//
Chris Lattner113f4f42002-06-25 16:13:24 +00004398Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Chris Lattnere29d6342004-10-17 21:22:38 +00004399 if (Value *V = hasConstantValue(&PN)) {
4400 // If V is an instruction, we have to be certain that it dominates PN.
4401 // However, because we don't have dom info, we can't do a perfect job.
4402 if (Instruction *I = dyn_cast<Instruction>(V)) {
4403 // We know that the instruction dominates the PHI if there are no undef
4404 // values coming in.
Chris Lattner3b92f172004-10-18 01:48:31 +00004405 if (I->getParent() != &I->getParent()->getParent()->front() ||
4406 isa<InvokeInst>(I))
Chris Lattner107c15c2004-10-17 21:31:34 +00004407 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
4408 if (isa<UndefValue>(PN.getIncomingValue(i))) {
4409 V = 0;
4410 break;
4411 }
Chris Lattnere29d6342004-10-17 21:22:38 +00004412 }
4413
4414 if (V)
4415 return ReplaceInstUsesWith(PN, V);
4416 }
Chris Lattner4db2d222004-02-16 05:07:08 +00004417
4418 // If the only user of this instruction is a cast instruction, and all of the
4419 // incoming values are constants, change this PHI to merge together the casted
4420 // constants.
4421 if (PN.hasOneUse())
4422 if (CastInst *CI = dyn_cast<CastInst>(PN.use_back()))
4423 if (CI->getType() != PN.getType()) { // noop casts will be folded
4424 bool AllConstant = true;
4425 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
4426 if (!isa<Constant>(PN.getIncomingValue(i))) {
4427 AllConstant = false;
4428 break;
4429 }
4430 if (AllConstant) {
4431 // Make a new PHI with all casted values.
4432 PHINode *New = new PHINode(CI->getType(), PN.getName(), &PN);
4433 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
4434 Constant *OldArg = cast<Constant>(PN.getIncomingValue(i));
4435 New->addIncoming(ConstantExpr::getCast(OldArg, New->getType()),
4436 PN.getIncomingBlock(i));
4437 }
4438
4439 // Update the cast instruction.
4440 CI->setOperand(0, New);
4441 WorkList.push_back(CI); // revisit the cast instruction to fold.
4442 WorkList.push_back(New); // Make sure to revisit the new Phi
4443 return &PN; // PN is now dead!
4444 }
4445 }
Chris Lattner7515cab2004-11-14 19:13:23 +00004446
4447 // If all PHI operands are the same operation, pull them through the PHI,
4448 // reducing code size.
4449 if (isa<Instruction>(PN.getIncomingValue(0)) &&
4450 PN.getIncomingValue(0)->hasOneUse())
4451 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
4452 return Result;
4453
Chris Lattner71536432005-01-17 05:10:15 +00004454 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
4455 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
4456 // PHI)... break the cycle.
4457 if (PN.hasOneUse())
4458 if (PHINode *PU = dyn_cast<PHINode>(PN.use_back())) {
4459 std::set<PHINode*> PotentiallyDeadPHIs;
4460 PotentiallyDeadPHIs.insert(&PN);
4461 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
4462 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
4463 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004464
Chris Lattner91daeb52003-12-19 05:58:40 +00004465 return 0;
Chris Lattnerbbbdd852002-05-06 18:06:38 +00004466}
4467
Chris Lattner69193f92004-04-05 01:30:19 +00004468static Value *InsertSignExtendToPtrTy(Value *V, const Type *DTy,
4469 Instruction *InsertPoint,
4470 InstCombiner *IC) {
4471 unsigned PS = IC->getTargetData().getPointerSize();
4472 const Type *VTy = V->getType();
Chris Lattner69193f92004-04-05 01:30:19 +00004473 if (!VTy->isSigned() && VTy->getPrimitiveSize() < PS)
4474 // We must insert a cast to ensure we sign-extend.
4475 V = IC->InsertNewInstBefore(new CastInst(V, VTy->getSignedVersion(),
4476 V->getName()), *InsertPoint);
4477 return IC->InsertNewInstBefore(new CastInst(V, DTy, V->getName()),
4478 *InsertPoint);
4479}
4480
Chris Lattner48a44f72002-05-02 17:06:02 +00004481
Chris Lattner113f4f42002-06-25 16:13:24 +00004482Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner5f667a62004-05-07 22:09:22 +00004483 Value *PtrOp = GEP.getOperand(0);
Chris Lattner471bd762003-05-22 19:07:21 +00004484 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
Chris Lattner113f4f42002-06-25 16:13:24 +00004485 // If so, eliminate the noop.
Chris Lattner8d0bacb2004-02-22 05:25:17 +00004486 if (GEP.getNumOperands() == 1)
Chris Lattner5f667a62004-05-07 22:09:22 +00004487 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner8d0bacb2004-02-22 05:25:17 +00004488
Chris Lattner81a7a232004-10-16 18:11:37 +00004489 if (isa<UndefValue>(GEP.getOperand(0)))
4490 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
4491
Chris Lattner8d0bacb2004-02-22 05:25:17 +00004492 bool HasZeroPointerIndex = false;
4493 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
4494 HasZeroPointerIndex = C->isNullValue();
4495
4496 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner5f667a62004-05-07 22:09:22 +00004497 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner48a44f72002-05-02 17:06:02 +00004498
Chris Lattner69193f92004-04-05 01:30:19 +00004499 // Eliminate unneeded casts for indices.
4500 bool MadeChange = false;
Chris Lattner2b2412d2004-04-07 18:38:20 +00004501 gep_type_iterator GTI = gep_type_begin(GEP);
4502 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI)
4503 if (isa<SequentialType>(*GTI)) {
4504 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
4505 Value *Src = CI->getOperand(0);
4506 const Type *SrcTy = Src->getType();
4507 const Type *DestTy = CI->getType();
4508 if (Src->getType()->isInteger()) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004509 if (SrcTy->getPrimitiveSizeInBits() ==
4510 DestTy->getPrimitiveSizeInBits()) {
Chris Lattner2b2412d2004-04-07 18:38:20 +00004511 // We can always eliminate a cast from ulong or long to the other.
4512 // We can always eliminate a cast from uint to int or the other on
4513 // 32-bit pointer platforms.
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004514 if (DestTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()){
Chris Lattner2b2412d2004-04-07 18:38:20 +00004515 MadeChange = true;
4516 GEP.setOperand(i, Src);
4517 }
4518 } else if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
4519 SrcTy->getPrimitiveSize() == 4) {
4520 // We can always eliminate a cast from int to [u]long. We can
4521 // eliminate a cast from uint to [u]long iff the target is a 32-bit
4522 // pointer target.
Misha Brukmanb1c93172005-04-21 23:48:37 +00004523 if (SrcTy->isSigned() ||
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004524 SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
Chris Lattner2b2412d2004-04-07 18:38:20 +00004525 MadeChange = true;
4526 GEP.setOperand(i, Src);
4527 }
Chris Lattner69193f92004-04-05 01:30:19 +00004528 }
4529 }
4530 }
Chris Lattner2b2412d2004-04-07 18:38:20 +00004531 // If we are using a wider index than needed for this platform, shrink it
4532 // to what we need. If the incoming value needs a cast instruction,
4533 // insert it. This explicit cast can make subsequent optimizations more
4534 // obvious.
4535 Value *Op = GEP.getOperand(i);
4536 if (Op->getType()->getPrimitiveSize() > TD->getPointerSize())
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00004537 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner44d0b952004-07-20 01:48:15 +00004538 GEP.setOperand(i, ConstantExpr::getCast(C,
4539 TD->getIntPtrType()->getSignedVersion()));
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00004540 MadeChange = true;
4541 } else {
Chris Lattner2b2412d2004-04-07 18:38:20 +00004542 Op = InsertNewInstBefore(new CastInst(Op, TD->getIntPtrType(),
4543 Op->getName()), GEP);
4544 GEP.setOperand(i, Op);
4545 MadeChange = true;
4546 }
Chris Lattner44d0b952004-07-20 01:48:15 +00004547
4548 // If this is a constant idx, make sure to canonicalize it to be a signed
4549 // operand, otherwise CSE and other optimizations are pessimized.
4550 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op)) {
4551 GEP.setOperand(i, ConstantExpr::getCast(CUI,
4552 CUI->getType()->getSignedVersion()));
4553 MadeChange = true;
4554 }
Chris Lattner69193f92004-04-05 01:30:19 +00004555 }
4556 if (MadeChange) return &GEP;
4557
Chris Lattnerae7a0d32002-08-02 19:29:35 +00004558 // Combine Indices - If the source pointer to this getelementptr instruction
4559 // is a getelementptr instruction, combine the indices of the two
4560 // getelementptr instructions into a single instruction.
4561 //
Chris Lattner57c67b02004-03-25 22:59:29 +00004562 std::vector<Value*> SrcGEPOperands;
Chris Lattner0798af32005-01-13 20:14:25 +00004563 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattner57c67b02004-03-25 22:59:29 +00004564 SrcGEPOperands.assign(Src->op_begin(), Src->op_end());
Chris Lattner57c67b02004-03-25 22:59:29 +00004565
4566 if (!SrcGEPOperands.empty()) {
Chris Lattner5f667a62004-05-07 22:09:22 +00004567 // Note that if our source is a gep chain itself that we wait for that
4568 // chain to be resolved before we perform this transformation. This
4569 // avoids us creating a TON of code in some cases.
4570 //
4571 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
4572 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
4573 return 0; // Wait until our source is folded to completion.
4574
Chris Lattnerae7a0d32002-08-02 19:29:35 +00004575 std::vector<Value *> Indices;
Chris Lattner5f667a62004-05-07 22:09:22 +00004576
4577 // Find out whether the last index in the source GEP is a sequential idx.
4578 bool EndsWithSequential = false;
4579 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
4580 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattner8ec5f882004-05-08 22:41:42 +00004581 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004582
Chris Lattnerae7a0d32002-08-02 19:29:35 +00004583 // Can we combine the two pointer arithmetics offsets?
Chris Lattner5f667a62004-05-07 22:09:22 +00004584 if (EndsWithSequential) {
Chris Lattner235af562003-03-05 22:33:14 +00004585 // Replace: gep (gep %P, long B), long A, ...
4586 // With: T = long A+B; gep %P, T, ...
4587 //
Chris Lattner5f667a62004-05-07 22:09:22 +00004588 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner69193f92004-04-05 01:30:19 +00004589 if (SO1 == Constant::getNullValue(SO1->getType())) {
4590 Sum = GO1;
4591 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
4592 Sum = SO1;
4593 } else {
4594 // If they aren't the same type, convert both to an integer of the
4595 // target's pointer size.
4596 if (SO1->getType() != GO1->getType()) {
4597 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
4598 SO1 = ConstantExpr::getCast(SO1C, GO1->getType());
4599 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
4600 GO1 = ConstantExpr::getCast(GO1C, SO1->getType());
4601 } else {
4602 unsigned PS = TD->getPointerSize();
Chris Lattner69193f92004-04-05 01:30:19 +00004603 if (SO1->getType()->getPrimitiveSize() == PS) {
4604 // Convert GO1 to SO1's type.
4605 GO1 = InsertSignExtendToPtrTy(GO1, SO1->getType(), &GEP, this);
4606
4607 } else if (GO1->getType()->getPrimitiveSize() == PS) {
4608 // Convert SO1 to GO1's type.
4609 SO1 = InsertSignExtendToPtrTy(SO1, GO1->getType(), &GEP, this);
4610 } else {
4611 const Type *PT = TD->getIntPtrType();
4612 SO1 = InsertSignExtendToPtrTy(SO1, PT, &GEP, this);
4613 GO1 = InsertSignExtendToPtrTy(GO1, PT, &GEP, this);
4614 }
4615 }
4616 }
Chris Lattner5f667a62004-05-07 22:09:22 +00004617 if (isa<Constant>(SO1) && isa<Constant>(GO1))
4618 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
4619 else {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004620 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
4621 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner5f667a62004-05-07 22:09:22 +00004622 }
Chris Lattner69193f92004-04-05 01:30:19 +00004623 }
Chris Lattner5f667a62004-05-07 22:09:22 +00004624
4625 // Recycle the GEP we already have if possible.
4626 if (SrcGEPOperands.size() == 2) {
4627 GEP.setOperand(0, SrcGEPOperands[0]);
4628 GEP.setOperand(1, Sum);
4629 return &GEP;
4630 } else {
4631 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
4632 SrcGEPOperands.end()-1);
4633 Indices.push_back(Sum);
4634 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
4635 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004636 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner69193f92004-04-05 01:30:19 +00004637 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00004638 SrcGEPOperands.size() != 1) {
Chris Lattnerae7a0d32002-08-02 19:29:35 +00004639 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattner57c67b02004-03-25 22:59:29 +00004640 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
4641 SrcGEPOperands.end());
Chris Lattnerae7a0d32002-08-02 19:29:35 +00004642 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
4643 }
4644
4645 if (!Indices.empty())
Chris Lattner57c67b02004-03-25 22:59:29 +00004646 return new GetElementPtrInst(SrcGEPOperands[0], Indices, GEP.getName());
Chris Lattnerc59af1d2002-08-17 22:21:59 +00004647
Chris Lattner5f667a62004-05-07 22:09:22 +00004648 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattnerc59af1d2002-08-17 22:21:59 +00004649 // GEP of global variable. If all of the indices for this GEP are
4650 // constants, we can promote this to a constexpr instead of an instruction.
4651
4652 // Scan for nonconstants...
4653 std::vector<Constant*> Indices;
4654 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
4655 for (; I != E && isa<Constant>(*I); ++I)
4656 Indices.push_back(cast<Constant>(*I));
4657
4658 if (I == E) { // If they are all constants...
Chris Lattnerf3edc492004-07-18 18:59:44 +00004659 Constant *CE = ConstantExpr::getGetElementPtr(GV, Indices);
Chris Lattnerc59af1d2002-08-17 22:21:59 +00004660
4661 // Replace all uses of the GEP with the new constexpr...
4662 return ReplaceInstUsesWith(GEP, CE);
4663 }
Chris Lattner5f667a62004-05-07 22:09:22 +00004664 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(PtrOp)) {
Chris Lattner8d0bacb2004-02-22 05:25:17 +00004665 if (CE->getOpcode() == Instruction::Cast) {
4666 if (HasZeroPointerIndex) {
4667 // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
4668 // into : GEP [10 x ubyte]* X, long 0, ...
4669 //
4670 // This occurs when the program declares an array extern like "int X[];"
4671 //
4672 Constant *X = CE->getOperand(0);
4673 const PointerType *CPTy = cast<PointerType>(CE->getType());
4674 if (const PointerType *XTy = dyn_cast<PointerType>(X->getType()))
4675 if (const ArrayType *XATy =
4676 dyn_cast<ArrayType>(XTy->getElementType()))
4677 if (const ArrayType *CATy =
4678 dyn_cast<ArrayType>(CPTy->getElementType()))
4679 if (CATy->getElementType() == XATy->getElementType()) {
4680 // At this point, we know that the cast source type is a pointer
4681 // to an array of the same type as the destination pointer
4682 // array. Because the array type is never stepped over (there
4683 // is a leading zero) we can fold the cast into this GEP.
4684 GEP.setOperand(0, X);
4685 return &GEP;
4686 }
Chris Lattner0798af32005-01-13 20:14:25 +00004687 } else if (GEP.getNumOperands() == 2 &&
4688 isa<PointerType>(CE->getOperand(0)->getType())) {
Chris Lattner14f3cdc2004-11-27 17:55:46 +00004689 // Transform things like:
4690 // %t = getelementptr ubyte* cast ([2 x sbyte]* %str to ubyte*), uint %V
4691 // into: %t1 = getelementptr [2 x sbyte*]* %str, int 0, uint %V; cast
4692 Constant *X = CE->getOperand(0);
4693 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
4694 const Type *ResElTy =cast<PointerType>(CE->getType())->getElementType();
4695 if (isa<ArrayType>(SrcElTy) &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00004696 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
Chris Lattner14f3cdc2004-11-27 17:55:46 +00004697 TD->getTypeSize(ResElTy)) {
4698 Value *V = InsertNewInstBefore(
4699 new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
4700 GEP.getOperand(1), GEP.getName()), GEP);
4701 return new CastInst(V, GEP.getType());
4702 }
Chris Lattner8d0bacb2004-02-22 05:25:17 +00004703 }
4704 }
Chris Lattnerca081252001-12-14 16:52:21 +00004705 }
4706
Chris Lattnerca081252001-12-14 16:52:21 +00004707 return 0;
4708}
4709
Chris Lattner1085bdf2002-11-04 16:18:53 +00004710Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
4711 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
4712 if (AI.isArrayAllocation()) // Check C != 1
4713 if (const ConstantUInt *C = dyn_cast<ConstantUInt>(AI.getArraySize())) {
4714 const Type *NewTy = ArrayType::get(AI.getAllocatedType(), C->getValue());
Chris Lattnera2620ac2002-11-09 00:49:43 +00004715 AllocationInst *New = 0;
Chris Lattner1085bdf2002-11-04 16:18:53 +00004716
4717 // Create and insert the replacement instruction...
4718 if (isa<MallocInst>(AI))
Chris Lattnerabb77c92004-03-19 06:08:10 +00004719 New = new MallocInst(NewTy, 0, AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00004720 else {
4721 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Chris Lattnerabb77c92004-03-19 06:08:10 +00004722 New = new AllocaInst(NewTy, 0, AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00004723 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00004724
4725 InsertNewInstBefore(New, AI);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004726
Chris Lattner1085bdf2002-11-04 16:18:53 +00004727 // Scan to the end of the allocation instructions, to skip over a block of
4728 // allocas if possible...
4729 //
4730 BasicBlock::iterator It = New;
4731 while (isa<AllocationInst>(*It)) ++It;
4732
4733 // Now that I is pointing to the first non-allocation-inst in the block,
4734 // insert our getelementptr instruction...
4735 //
Chris Lattner809dfac2005-05-04 19:10:26 +00004736 Value *NullIdx = Constant::getNullValue(Type::IntTy);
4737 Value *V = new GetElementPtrInst(New, NullIdx, NullIdx,
4738 New->getName()+".sub", It);
Chris Lattner1085bdf2002-11-04 16:18:53 +00004739
4740 // Now make everything use the getelementptr instead of the original
4741 // allocation.
Chris Lattnerabb77c92004-03-19 06:08:10 +00004742 return ReplaceInstUsesWith(AI, V);
Chris Lattner81a7a232004-10-16 18:11:37 +00004743 } else if (isa<UndefValue>(AI.getArraySize())) {
4744 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner1085bdf2002-11-04 16:18:53 +00004745 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00004746
4747 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
4748 // Note that we only do this for alloca's, because malloc should allocate and
4749 // return a unique pointer, even for a zero byte allocation.
Misha Brukmanb1c93172005-04-21 23:48:37 +00004750 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
Chris Lattner49df6ce2004-07-02 22:55:47 +00004751 TD->getTypeSize(AI.getAllocatedType()) == 0)
Chris Lattnerabb77c92004-03-19 06:08:10 +00004752 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
4753
Chris Lattner1085bdf2002-11-04 16:18:53 +00004754 return 0;
4755}
4756
Chris Lattner8427bff2003-12-07 01:24:23 +00004757Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
4758 Value *Op = FI.getOperand(0);
4759
4760 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
4761 if (CastInst *CI = dyn_cast<CastInst>(Op))
4762 if (isa<PointerType>(CI->getOperand(0)->getType())) {
4763 FI.setOperand(0, CI->getOperand(0));
4764 return &FI;
4765 }
4766
Chris Lattner8ba9ec92004-10-18 02:59:09 +00004767 // free undef -> unreachable.
4768 if (isa<UndefValue>(Op)) {
4769 // Insert a new store to null because we cannot modify the CFG here.
4770 new StoreInst(ConstantBool::True,
4771 UndefValue::get(PointerType::get(Type::BoolTy)), &FI);
4772 return EraseInstFromFunction(FI);
4773 }
4774
Chris Lattnerf3a36602004-02-28 04:57:37 +00004775 // If we have 'free null' delete the instruction. This can happen in stl code
4776 // when lots of inlining happens.
Chris Lattner8ba9ec92004-10-18 02:59:09 +00004777 if (isa<ConstantPointerNull>(Op))
Chris Lattner51ea1272004-02-28 05:22:00 +00004778 return EraseInstFromFunction(FI);
Chris Lattnerf3a36602004-02-28 04:57:37 +00004779
Chris Lattner8427bff2003-12-07 01:24:23 +00004780 return 0;
4781}
4782
4783
Chris Lattner0f1d8a32003-06-26 05:06:25 +00004784/// GetGEPGlobalInitializer - Given a constant, and a getelementptr
4785/// constantexpr, return the constant value being addressed by the constant
4786/// expression, or null if something is funny.
4787///
4788static Constant *GetGEPGlobalInitializer(Constant *C, ConstantExpr *CE) {
Chris Lattner69193f92004-04-05 01:30:19 +00004789 if (CE->getOperand(1) != Constant::getNullValue(CE->getOperand(1)->getType()))
Chris Lattner0f1d8a32003-06-26 05:06:25 +00004790 return 0; // Do not allow stepping over the value!
4791
4792 // Loop over all of the operands, tracking down which value we are
4793 // addressing...
Chris Lattnered79d8a2004-05-27 17:30:27 +00004794 gep_type_iterator I = gep_type_begin(CE), E = gep_type_end(CE);
4795 for (++I; I != E; ++I)
4796 if (const StructType *STy = dyn_cast<StructType>(*I)) {
4797 ConstantUInt *CU = cast<ConstantUInt>(I.getOperand());
4798 assert(CU->getValue() < STy->getNumElements() &&
4799 "Struct index out of range!");
Chris Lattnerfdfe3e492005-01-08 19:42:22 +00004800 unsigned El = (unsigned)CU->getValue();
Chris Lattnered79d8a2004-05-27 17:30:27 +00004801 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(C)) {
Chris Lattnerfdfe3e492005-01-08 19:42:22 +00004802 C = CS->getOperand(El);
Chris Lattnered79d8a2004-05-27 17:30:27 +00004803 } else if (isa<ConstantAggregateZero>(C)) {
Jeff Cohen82639852005-04-23 21:38:35 +00004804 C = Constant::getNullValue(STy->getElementType(El));
Chris Lattner81a7a232004-10-16 18:11:37 +00004805 } else if (isa<UndefValue>(C)) {
Jeff Cohen82639852005-04-23 21:38:35 +00004806 C = UndefValue::get(STy->getElementType(El));
Chris Lattnered79d8a2004-05-27 17:30:27 +00004807 } else {
4808 return 0;
4809 }
4810 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand())) {
4811 const ArrayType *ATy = cast<ArrayType>(*I);
4812 if ((uint64_t)CI->getRawValue() >= ATy->getNumElements()) return 0;
4813 if (ConstantArray *CA = dyn_cast<ConstantArray>(C))
Chris Lattnerfdfe3e492005-01-08 19:42:22 +00004814 C = CA->getOperand((unsigned)CI->getRawValue());
Chris Lattnered79d8a2004-05-27 17:30:27 +00004815 else if (isa<ConstantAggregateZero>(C))
4816 C = Constant::getNullValue(ATy->getElementType());
Chris Lattner81a7a232004-10-16 18:11:37 +00004817 else if (isa<UndefValue>(C))
4818 C = UndefValue::get(ATy->getElementType());
Chris Lattnered79d8a2004-05-27 17:30:27 +00004819 else
4820 return 0;
4821 } else {
Chris Lattner0f1d8a32003-06-26 05:06:25 +00004822 return 0;
Chris Lattnered79d8a2004-05-27 17:30:27 +00004823 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00004824 return C;
4825}
4826
Chris Lattner72684fe2005-01-31 05:51:45 +00004827/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Chris Lattner35e24772004-07-13 01:49:43 +00004828static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
4829 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00004830 Value *CastOp = CI->getOperand(0);
Chris Lattner35e24772004-07-13 01:49:43 +00004831
4832 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00004833 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Chris Lattner35e24772004-07-13 01:49:43 +00004834 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00004835
4836 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
4837 // If the source is an array, the code below will not succeed. Check to
4838 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
4839 // constants.
4840 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
4841 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
4842 if (ASrcTy->getNumElements() != 0) {
4843 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
4844 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
4845 SrcTy = cast<PointerType>(CastOp->getType());
4846 SrcPTy = SrcTy->getElementType();
4847 }
4848
4849 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
Chris Lattnerecfa9b52005-03-29 06:37:47 +00004850 // Do not allow turning this into a load of an integer, which is then
4851 // casted to a pointer, this pessimizes pointer analysis a lot.
4852 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00004853 IC.getTargetData().getTypeSize(SrcPTy) ==
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00004854 IC.getTargetData().getTypeSize(DestPTy)) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00004855
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00004856 // Okay, we are casting from one integer or pointer type to another of
4857 // the same size. Instead of casting the pointer before the load, cast
4858 // the result of the loaded value.
4859 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
4860 CI->getName(),
4861 LI.isVolatile()),LI);
4862 // Now cast the result of the load.
4863 return new CastInst(NewLoad, LI.getType());
4864 }
Chris Lattner35e24772004-07-13 01:49:43 +00004865 }
4866 }
4867 return 0;
4868}
4869
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00004870/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattnere6f13092004-09-19 19:18:10 +00004871/// from this value cannot trap. If it is not obviously safe to load from the
4872/// specified pointer, we do a quick local scan of the basic block containing
4873/// ScanFrom, to determine if the address is already accessed.
4874static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
4875 // If it is an alloca or global variable, it is always safe to load from.
4876 if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
4877
4878 // Otherwise, be a little bit agressive by scanning the local block where we
4879 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00004880 // from/to. If so, the previous load or store would have already trapped,
4881 // so there is no harm doing an extra load (also, CSE will later eliminate
4882 // the load entirely).
Chris Lattnere6f13092004-09-19 19:18:10 +00004883 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
4884
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00004885 while (BBI != E) {
Chris Lattnere6f13092004-09-19 19:18:10 +00004886 --BBI;
4887
4888 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
4889 if (LI->getOperand(0) == V) return true;
4890 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
4891 if (SI->getOperand(1) == V) return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +00004892
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00004893 }
Chris Lattnere6f13092004-09-19 19:18:10 +00004894 return false;
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00004895}
4896
Chris Lattner0f1d8a32003-06-26 05:06:25 +00004897Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
4898 Value *Op = LI.getOperand(0);
Chris Lattner7e8af382004-01-12 04:13:56 +00004899
Chris Lattnera9d84e32005-05-01 04:24:53 +00004900 // load (cast X) --> cast (load X) iff safe
4901 if (CastInst *CI = dyn_cast<CastInst>(Op))
4902 if (Instruction *Res = InstCombineLoadCast(*this, LI))
4903 return Res;
4904
4905 // None of the following transforms are legal for volatile loads.
4906 if (LI.isVolatile()) return 0;
4907
4908 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op))
4909 if (isa<ConstantPointerNull>(GEPI->getOperand(0)) ||
4910 isa<UndefValue>(GEPI->getOperand(0))) {
4911 // Insert a new store to null instruction before the load to indicate
4912 // that this code is not reachable. We do this instead of inserting
4913 // an unreachable instruction directly because we cannot modify the
4914 // CFG.
4915 new StoreInst(UndefValue::get(LI.getType()),
4916 Constant::getNullValue(Op->getType()), &LI);
4917 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
4918 }
4919
Chris Lattner81a7a232004-10-16 18:11:37 +00004920 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattnera9d84e32005-05-01 04:24:53 +00004921 // load null/undef -> undef
4922 if ((C->isNullValue() || isa<UndefValue>(C))) {
Chris Lattner8ba9ec92004-10-18 02:59:09 +00004923 // Insert a new store to null instruction before the load to indicate that
4924 // this code is not reachable. We do this instead of inserting an
4925 // unreachable instruction directly because we cannot modify the CFG.
Chris Lattnera9d84e32005-05-01 04:24:53 +00004926 new StoreInst(UndefValue::get(LI.getType()),
4927 Constant::getNullValue(Op->getType()), &LI);
Chris Lattner81a7a232004-10-16 18:11:37 +00004928 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner8ba9ec92004-10-18 02:59:09 +00004929 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00004930
Chris Lattner81a7a232004-10-16 18:11:37 +00004931 // Instcombine load (constant global) into the value loaded.
4932 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
4933 if (GV->isConstant() && !GV->isExternal())
4934 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanb1c93172005-04-21 23:48:37 +00004935
Chris Lattner81a7a232004-10-16 18:11:37 +00004936 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
4937 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
4938 if (CE->getOpcode() == Instruction::GetElementPtr) {
4939 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
4940 if (GV->isConstant() && !GV->isExternal())
4941 if (Constant *V = GetGEPGlobalInitializer(GV->getInitializer(), CE))
4942 return ReplaceInstUsesWith(LI, V);
Chris Lattnera9d84e32005-05-01 04:24:53 +00004943 if (CE->getOperand(0)->isNullValue()) {
4944 // Insert a new store to null instruction before the load to indicate
4945 // that this code is not reachable. We do this instead of inserting
4946 // an unreachable instruction directly because we cannot modify the
4947 // CFG.
4948 new StoreInst(UndefValue::get(LI.getType()),
4949 Constant::getNullValue(Op->getType()), &LI);
4950 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
4951 }
4952
Chris Lattner81a7a232004-10-16 18:11:37 +00004953 } else if (CE->getOpcode() == Instruction::Cast) {
4954 if (Instruction *Res = InstCombineLoadCast(*this, LI))
4955 return Res;
4956 }
4957 }
Chris Lattnere228ee52004-04-08 20:39:49 +00004958
Chris Lattnera9d84e32005-05-01 04:24:53 +00004959 if (Op->hasOneUse()) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00004960 // Change select and PHI nodes to select values instead of addresses: this
4961 // helps alias analysis out a lot, allows many others simplifications, and
4962 // exposes redundancy in the code.
4963 //
4964 // Note that we cannot do the transformation unless we know that the
4965 // introduced loads cannot trap! Something like this is valid as long as
4966 // the condition is always false: load (select bool %C, int* null, int* %G),
4967 // but it would not be valid if we transformed it to load from null
4968 // unconditionally.
4969 //
4970 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
4971 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattnere6f13092004-09-19 19:18:10 +00004972 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
4973 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00004974 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner42618552004-09-20 10:15:10 +00004975 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00004976 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner42618552004-09-20 10:15:10 +00004977 SI->getOperand(2)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00004978 return new SelectInst(SI->getCondition(), V1, V2);
4979 }
4980
Chris Lattnerbdcf41a2004-09-23 15:46:00 +00004981 // load (select (cond, null, P)) -> load P
4982 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
4983 if (C->isNullValue()) {
4984 LI.setOperand(0, SI->getOperand(2));
4985 return &LI;
4986 }
4987
4988 // load (select (cond, P, null)) -> load P
4989 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
4990 if (C->isNullValue()) {
4991 LI.setOperand(0, SI->getOperand(1));
4992 return &LI;
4993 }
4994
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00004995 } else if (PHINode *PN = dyn_cast<PHINode>(Op)) {
4996 // load (phi (&V1, &V2, &V3)) --> phi(load &V1, load &V2, load &V3)
Chris Lattner42618552004-09-20 10:15:10 +00004997 bool Safe = PN->getParent() == LI.getParent();
4998
4999 // Scan all of the instructions between the PHI and the load to make
5000 // sure there are no instructions that might possibly alter the value
5001 // loaded from the PHI.
5002 if (Safe) {
5003 BasicBlock::iterator I = &LI;
5004 for (--I; !isa<PHINode>(I); --I)
5005 if (isa<StoreInst>(I) || isa<CallInst>(I)) {
5006 Safe = false;
5007 break;
5008 }
5009 }
5010
5011 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e && Safe; ++i)
Chris Lattnere6f13092004-09-19 19:18:10 +00005012 if (!isSafeToLoadUnconditionally(PN->getIncomingValue(i),
Chris Lattner42618552004-09-20 10:15:10 +00005013 PN->getIncomingBlock(i)->getTerminator()))
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00005014 Safe = false;
Chris Lattner42618552004-09-20 10:15:10 +00005015
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00005016 if (Safe) {
5017 // Create the PHI.
5018 PHINode *NewPN = new PHINode(LI.getType(), PN->getName());
5019 InsertNewInstBefore(NewPN, *PN);
5020 std::map<BasicBlock*,Value*> LoadMap; // Don't insert duplicate loads
5021
5022 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
5023 BasicBlock *BB = PN->getIncomingBlock(i);
5024 Value *&TheLoad = LoadMap[BB];
5025 if (TheLoad == 0) {
5026 Value *InVal = PN->getIncomingValue(i);
5027 TheLoad = InsertNewInstBefore(new LoadInst(InVal,
5028 InVal->getName()+".val"),
5029 *BB->getTerminator());
5030 }
5031 NewPN->addIncoming(TheLoad, BB);
5032 }
5033 return ReplaceInstUsesWith(LI, NewPN);
5034 }
5035 }
5036 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00005037 return 0;
5038}
5039
Chris Lattner72684fe2005-01-31 05:51:45 +00005040/// InstCombineStoreToCast - Fold 'store V, (cast P)' -> store (cast V), P'
5041/// when possible.
5042static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
5043 User *CI = cast<User>(SI.getOperand(1));
5044 Value *CastOp = CI->getOperand(0);
5045
5046 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
5047 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
5048 const Type *SrcPTy = SrcTy->getElementType();
5049
5050 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
5051 // If the source is an array, the code below will not succeed. Check to
5052 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
5053 // constants.
5054 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
5055 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
5056 if (ASrcTy->getNumElements() != 0) {
5057 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
5058 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
5059 SrcTy = cast<PointerType>(CastOp->getType());
5060 SrcPTy = SrcTy->getElementType();
5061 }
5062
5063 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00005064 IC.getTargetData().getTypeSize(SrcPTy) ==
Chris Lattner72684fe2005-01-31 05:51:45 +00005065 IC.getTargetData().getTypeSize(DestPTy)) {
5066
5067 // Okay, we are casting from one integer or pointer type to another of
5068 // the same size. Instead of casting the pointer before the store, cast
5069 // the value to be stored.
5070 Value *NewCast;
5071 if (Constant *C = dyn_cast<Constant>(SI.getOperand(0)))
5072 NewCast = ConstantExpr::getCast(C, SrcPTy);
5073 else
5074 NewCast = IC.InsertNewInstBefore(new CastInst(SI.getOperand(0),
5075 SrcPTy,
5076 SI.getOperand(0)->getName()+".c"), SI);
5077
5078 return new StoreInst(NewCast, CastOp);
5079 }
5080 }
5081 }
5082 return 0;
5083}
5084
Chris Lattner31f486c2005-01-31 05:36:43 +00005085Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
5086 Value *Val = SI.getOperand(0);
5087 Value *Ptr = SI.getOperand(1);
5088
5089 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
5090 removeFromWorkList(&SI);
5091 SI.eraseFromParent();
5092 ++NumCombined;
5093 return 0;
5094 }
5095
5096 if (SI.isVolatile()) return 0; // Don't hack volatile loads.
5097
5098 // store X, null -> turns into 'unreachable' in SimplifyCFG
5099 if (isa<ConstantPointerNull>(Ptr)) {
5100 if (!isa<UndefValue>(Val)) {
5101 SI.setOperand(0, UndefValue::get(Val->getType()));
5102 if (Instruction *U = dyn_cast<Instruction>(Val))
5103 WorkList.push_back(U); // Dropped a use.
5104 ++NumCombined;
5105 }
5106 return 0; // Do not modify these!
5107 }
5108
5109 // store undef, Ptr -> noop
5110 if (isa<UndefValue>(Val)) {
5111 removeFromWorkList(&SI);
5112 SI.eraseFromParent();
5113 ++NumCombined;
5114 return 0;
5115 }
5116
Chris Lattner72684fe2005-01-31 05:51:45 +00005117 // If the pointer destination is a cast, see if we can fold the cast into the
5118 // source instead.
5119 if (CastInst *CI = dyn_cast<CastInst>(Ptr))
5120 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
5121 return Res;
5122 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
5123 if (CE->getOpcode() == Instruction::Cast)
5124 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
5125 return Res;
5126
Chris Lattner31f486c2005-01-31 05:36:43 +00005127 return 0;
5128}
5129
5130
Chris Lattner9eef8a72003-06-04 04:46:00 +00005131Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
5132 // Change br (not X), label True, label False to: br X, label False, True
Chris Lattnerd4252a72004-07-30 07:50:03 +00005133 Value *X;
5134 BasicBlock *TrueDest;
5135 BasicBlock *FalseDest;
5136 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
5137 !isa<Constant>(X)) {
5138 // Swap Destinations and condition...
5139 BI.setCondition(X);
5140 BI.setSuccessor(0, FalseDest);
5141 BI.setSuccessor(1, TrueDest);
5142 return &BI;
5143 }
5144
5145 // Cannonicalize setne -> seteq
5146 Instruction::BinaryOps Op; Value *Y;
5147 if (match(&BI, m_Br(m_SetCond(Op, m_Value(X), m_Value(Y)),
5148 TrueDest, FalseDest)))
5149 if ((Op == Instruction::SetNE || Op == Instruction::SetLE ||
5150 Op == Instruction::SetGE) && BI.getCondition()->hasOneUse()) {
5151 SetCondInst *I = cast<SetCondInst>(BI.getCondition());
5152 std::string Name = I->getName(); I->setName("");
5153 Instruction::BinaryOps NewOpcode = SetCondInst::getInverseCondition(Op);
5154 Value *NewSCC = BinaryOperator::create(NewOpcode, X, Y, Name, I);
Chris Lattnere967b342003-06-04 05:10:11 +00005155 // Swap Destinations and condition...
Chris Lattnerd4252a72004-07-30 07:50:03 +00005156 BI.setCondition(NewSCC);
Chris Lattnere967b342003-06-04 05:10:11 +00005157 BI.setSuccessor(0, FalseDest);
5158 BI.setSuccessor(1, TrueDest);
Chris Lattnerd4252a72004-07-30 07:50:03 +00005159 removeFromWorkList(I);
5160 I->getParent()->getInstList().erase(I);
5161 WorkList.push_back(cast<Instruction>(NewSCC));
Chris Lattnere967b342003-06-04 05:10:11 +00005162 return &BI;
5163 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00005164
Chris Lattner9eef8a72003-06-04 04:46:00 +00005165 return 0;
5166}
Chris Lattner1085bdf2002-11-04 16:18:53 +00005167
Chris Lattner4c9c20a2004-07-03 00:26:11 +00005168Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
5169 Value *Cond = SI.getCondition();
5170 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
5171 if (I->getOpcode() == Instruction::Add)
5172 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
5173 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
5174 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattner81a7a232004-10-16 18:11:37 +00005175 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner4c9c20a2004-07-03 00:26:11 +00005176 AddRHS));
5177 SI.setOperand(0, I->getOperand(0));
5178 WorkList.push_back(I);
5179 return &SI;
5180 }
5181 }
5182 return 0;
5183}
5184
Chris Lattnerca081252001-12-14 16:52:21 +00005185
Chris Lattner99f48c62002-09-02 04:59:56 +00005186void InstCombiner::removeFromWorkList(Instruction *I) {
5187 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
5188 WorkList.end());
5189}
5190
Chris Lattner39c98bb2004-12-08 23:43:58 +00005191
5192/// TryToSinkInstruction - Try to move the specified instruction from its
5193/// current block into the beginning of DestBlock, which can only happen if it's
5194/// safe to move the instruction past all of the instructions between it and the
5195/// end of its block.
5196static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
5197 assert(I->hasOneUse() && "Invariants didn't hold!");
5198
5199 // Cannot move control-flow-involving instructions.
5200 if (isa<PHINode>(I) || isa<InvokeInst>(I) || isa<CallInst>(I)) return false;
Misha Brukmanb1c93172005-04-21 23:48:37 +00005201
Chris Lattner39c98bb2004-12-08 23:43:58 +00005202 // Do not sink alloca instructions out of the entry block.
5203 if (isa<AllocaInst>(I) && I->getParent() == &DestBlock->getParent()->front())
5204 return false;
5205
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00005206 // We can only sink load instructions if there is nothing between the load and
5207 // the end of block that could change the value.
5208 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
5209 if (LI->isVolatile()) return false; // Don't sink volatile loads.
5210
5211 for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
5212 Scan != E; ++Scan)
5213 if (Scan->mayWriteToMemory())
5214 return false;
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00005215 }
Chris Lattner39c98bb2004-12-08 23:43:58 +00005216
5217 BasicBlock::iterator InsertPos = DestBlock->begin();
5218 while (isa<PHINode>(InsertPos)) ++InsertPos;
5219
5220 BasicBlock *SrcBlock = I->getParent();
Misha Brukmanb1c93172005-04-21 23:48:37 +00005221 DestBlock->getInstList().splice(InsertPos, SrcBlock->getInstList(), I);
Chris Lattner39c98bb2004-12-08 23:43:58 +00005222 ++NumSunkInst;
5223 return true;
5224}
5225
Chris Lattner113f4f42002-06-25 16:13:24 +00005226bool InstCombiner::runOnFunction(Function &F) {
Chris Lattner260ab202002-04-18 17:39:14 +00005227 bool Changed = false;
Chris Lattnerf4ad1652003-11-02 05:57:39 +00005228 TD = &getAnalysis<TargetData>();
Chris Lattnerca081252001-12-14 16:52:21 +00005229
Chris Lattnerb643a9e2004-05-01 23:19:52 +00005230 for (inst_iterator i = inst_begin(F), e = inst_end(F); i != e; ++i)
5231 WorkList.push_back(&*i);
Chris Lattner2d3a7a62004-04-27 15:13:33 +00005232
Chris Lattnerca081252001-12-14 16:52:21 +00005233
5234 while (!WorkList.empty()) {
5235 Instruction *I = WorkList.back(); // Get an instruction from the worklist
5236 WorkList.pop_back();
5237
Misha Brukman632df282002-10-29 23:06:16 +00005238 // Check to see if we can DCE or ConstantPropagate the instruction...
Chris Lattner99f48c62002-09-02 04:59:56 +00005239 // Check to see if we can DIE the instruction...
5240 if (isInstructionTriviallyDead(I)) {
5241 // Add operands to the worklist...
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00005242 if (I->getNumOperands() < 4)
Chris Lattner51ea1272004-02-28 05:22:00 +00005243 AddUsesToWorkList(*I);
Chris Lattner99f48c62002-09-02 04:59:56 +00005244 ++NumDeadInst;
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00005245
Chris Lattnercd517ff2005-01-28 19:32:01 +00005246 DEBUG(std::cerr << "IC: DCE: " << *I);
5247
5248 I->eraseFromParent();
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00005249 removeFromWorkList(I);
5250 continue;
5251 }
Chris Lattner99f48c62002-09-02 04:59:56 +00005252
Misha Brukman632df282002-10-29 23:06:16 +00005253 // Instruction isn't dead, see if we can constant propagate it...
Chris Lattner99f48c62002-09-02 04:59:56 +00005254 if (Constant *C = ConstantFoldInstruction(I)) {
Alkis Evlogimenosa1291a02004-12-08 23:10:30 +00005255 Value* Ptr = I->getOperand(0);
Chris Lattner6580e092004-10-16 19:44:59 +00005256 if (isa<GetElementPtrInst>(I) &&
Alkis Evlogimenosa1291a02004-12-08 23:10:30 +00005257 cast<Constant>(Ptr)->isNullValue() &&
5258 !isa<ConstantPointerNull>(C) &&
5259 cast<PointerType>(Ptr->getType())->getElementType()->isSized()) {
Chris Lattner6580e092004-10-16 19:44:59 +00005260 // If this is a constant expr gep that is effectively computing an
5261 // "offsetof", fold it into 'cast int X to T*' instead of 'gep 0, 0, 12'
5262 bool isFoldableGEP = true;
5263 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i)
5264 if (!isa<ConstantInt>(I->getOperand(i)))
5265 isFoldableGEP = false;
5266 if (isFoldableGEP) {
Alkis Evlogimenosa1291a02004-12-08 23:10:30 +00005267 uint64_t Offset = TD->getIndexedOffset(Ptr->getType(),
Chris Lattner6580e092004-10-16 19:44:59 +00005268 std::vector<Value*>(I->op_begin()+1, I->op_end()));
5269 C = ConstantUInt::get(Type::ULongTy, Offset);
Chris Lattner684c5c62004-10-16 19:46:33 +00005270 C = ConstantExpr::getCast(C, TD->getIntPtrType());
Chris Lattner6580e092004-10-16 19:44:59 +00005271 C = ConstantExpr::getCast(C, I->getType());
5272 }
5273 }
5274
Chris Lattnercd517ff2005-01-28 19:32:01 +00005275 DEBUG(std::cerr << "IC: ConstFold to: " << *C << " from: " << *I);
5276
Chris Lattner99f48c62002-09-02 04:59:56 +00005277 // Add operands to the worklist...
Chris Lattner51ea1272004-02-28 05:22:00 +00005278 AddUsesToWorkList(*I);
Chris Lattnerc6509f42002-12-05 22:41:53 +00005279 ReplaceInstUsesWith(*I, C);
5280
Chris Lattner99f48c62002-09-02 04:59:56 +00005281 ++NumConstProp;
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00005282 I->getParent()->getInstList().erase(I);
Chris Lattner800aaaf2003-10-07 15:17:02 +00005283 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00005284 continue;
Chris Lattner99f48c62002-09-02 04:59:56 +00005285 }
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00005286
Chris Lattner39c98bb2004-12-08 23:43:58 +00005287 // See if we can trivially sink this instruction to a successor basic block.
5288 if (I->hasOneUse()) {
5289 BasicBlock *BB = I->getParent();
5290 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
5291 if (UserParent != BB) {
5292 bool UserIsSuccessor = false;
5293 // See if the user is one of our successors.
5294 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
5295 if (*SI == UserParent) {
5296 UserIsSuccessor = true;
5297 break;
5298 }
5299
5300 // If the user is one of our immediate successors, and if that successor
5301 // only has us as a predecessors (we'd have to split the critical edge
5302 // otherwise), we can keep going.
5303 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
5304 next(pred_begin(UserParent)) == pred_end(UserParent))
5305 // Okay, the CFG is simple enough, try to sink this instruction.
5306 Changed |= TryToSinkInstruction(I, UserParent);
5307 }
5308 }
5309
Chris Lattnerca081252001-12-14 16:52:21 +00005310 // Now that we have an instruction, try combining it to simplify it...
Chris Lattnerae7a0d32002-08-02 19:29:35 +00005311 if (Instruction *Result = visit(*I)) {
Chris Lattner0b18c1d2002-05-10 15:38:35 +00005312 ++NumCombined;
Chris Lattner260ab202002-04-18 17:39:14 +00005313 // Should we replace the old instruction with a new one?
Chris Lattner053c0932002-05-14 15:24:07 +00005314 if (Result != I) {
Chris Lattner7d2a5392004-03-13 23:54:27 +00005315 DEBUG(std::cerr << "IC: Old = " << *I
5316 << " New = " << *Result);
5317
Chris Lattner396dbfe2004-06-09 05:08:07 +00005318 // Everything uses the new instruction now.
5319 I->replaceAllUsesWith(Result);
5320
5321 // Push the new instruction and any users onto the worklist.
5322 WorkList.push_back(Result);
5323 AddUsersToWorkList(*Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00005324
5325 // Move the name to the new instruction first...
5326 std::string OldName = I->getName(); I->setName("");
Chris Lattner950fc782003-10-07 22:58:41 +00005327 Result->setName(OldName);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00005328
5329 // Insert the new instruction into the basic block...
5330 BasicBlock *InstParent = I->getParent();
Chris Lattner7515cab2004-11-14 19:13:23 +00005331 BasicBlock::iterator InsertPos = I;
5332
5333 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
5334 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
5335 ++InsertPos;
5336
5337 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00005338
Chris Lattner63d75af2004-05-01 23:27:23 +00005339 // Make sure that we reprocess all operands now that we reduced their
5340 // use counts.
Chris Lattnerb643a9e2004-05-01 23:19:52 +00005341 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
5342 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
5343 WorkList.push_back(OpI);
5344
Chris Lattner396dbfe2004-06-09 05:08:07 +00005345 // Instructions can end up on the worklist more than once. Make sure
5346 // we do not process an instruction that has been deleted.
5347 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00005348
5349 // Erase the old instruction.
5350 InstParent->getInstList().erase(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00005351 } else {
Chris Lattner7d2a5392004-03-13 23:54:27 +00005352 DEBUG(std::cerr << "IC: MOD = " << *I);
5353
Chris Lattnerae7a0d32002-08-02 19:29:35 +00005354 // If the instruction was modified, it's possible that it is now dead.
5355 // if so, remove it.
Chris Lattner63d75af2004-05-01 23:27:23 +00005356 if (isInstructionTriviallyDead(I)) {
5357 // Make sure we process all operands now that we are reducing their
5358 // use counts.
5359 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
5360 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
5361 WorkList.push_back(OpI);
Misha Brukmanb1c93172005-04-21 23:48:37 +00005362
Chris Lattner63d75af2004-05-01 23:27:23 +00005363 // Instructions may end up in the worklist more than once. Erase all
5364 // occurrances of this instruction.
Chris Lattner99f48c62002-09-02 04:59:56 +00005365 removeFromWorkList(I);
Chris Lattner31f486c2005-01-31 05:36:43 +00005366 I->eraseFromParent();
Chris Lattner396dbfe2004-06-09 05:08:07 +00005367 } else {
5368 WorkList.push_back(Result);
5369 AddUsersToWorkList(*Result);
Chris Lattnerae7a0d32002-08-02 19:29:35 +00005370 }
Chris Lattner053c0932002-05-14 15:24:07 +00005371 }
Chris Lattner260ab202002-04-18 17:39:14 +00005372 Changed = true;
Chris Lattnerca081252001-12-14 16:52:21 +00005373 }
5374 }
5375
Chris Lattner260ab202002-04-18 17:39:14 +00005376 return Changed;
Chris Lattner04805fa2002-02-26 21:46:54 +00005377}
5378
Brian Gaeke38b79e82004-07-27 17:43:21 +00005379FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattner260ab202002-04-18 17:39:14 +00005380 return new InstCombiner();
Chris Lattner04805fa2002-02-26 21:46:54 +00005381}
Brian Gaeke960707c2003-11-11 22:41:34 +00005382