blob: 2c8f6eda4955a2582e9ff7b05da2bec90eff7475 [file] [log] [blame]
Chris Lattnere6794492002-08-12 21:17:25 +00001//===- InstructionCombining.cpp - Combine multiple instructions -----------===//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
John Criswell482202a2003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
Misha Brukmanb1c93172005-04-21 23:48:37 +00007//
John Criswell482202a2003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattnerca081252001-12-14 16:52:21 +00009//
10// InstructionCombining - Combine instructions to form fewer, simple
Chris Lattner99f48c62002-09-02 04:59:56 +000011// instructions. This pass does not modify the CFG This pass is where algebraic
12// simplification happens.
Chris Lattnerca081252001-12-14 16:52:21 +000013//
14// This pass combines things like:
Chris Lattnerdd1a86d2004-05-04 15:19:33 +000015// %Y = add int %X, 1
16// %Z = add int %Y, 1
Chris Lattnerca081252001-12-14 16:52:21 +000017// into:
Chris Lattnerdd1a86d2004-05-04 15:19:33 +000018// %Z = add int %X, 2
Chris Lattnerca081252001-12-14 16:52:21 +000019//
20// This is a simple worklist driven algorithm.
21//
Chris Lattner216c7b82003-09-10 05:29:43 +000022// This pass guarantees that the following canonicalizations are performed on
Chris Lattnerbfb1d032003-07-23 21:41:57 +000023// the program:
24// 1. If a binary operator has a constant operand, it is moved to the RHS
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +000025// 2. Bitwise operators with constant operands are always grouped so that
26// shifts are performed first, then or's, then and's, then xor's.
Chris Lattnerbfb1d032003-07-23 21:41:57 +000027// 3. SetCC instructions are converted from <,>,<=,>= to ==,!= if possible
28// 4. All SetCC instructions on boolean values are replaced with logical ops
Chris Lattnerede3fe02003-08-13 04:18:28 +000029// 5. add X, X is represented as (X*2) => (X << 1)
30// 6. Multiplies with a power-of-two constant argument are transformed into
31// shifts.
Chris Lattner7515cab2004-11-14 19:13:23 +000032// ... etc.
Chris Lattnerbfb1d032003-07-23 21:41:57 +000033//
Chris Lattnerca081252001-12-14 16:52:21 +000034//===----------------------------------------------------------------------===//
35
Chris Lattner7d2a5392004-03-13 23:54:27 +000036#define DEBUG_TYPE "instcombine"
Chris Lattnerb4cfa7f2002-05-07 20:03:00 +000037#include "llvm/Transforms/Scalar.h"
Chris Lattner00648e12004-10-12 04:52:52 +000038#include "llvm/IntrinsicInst.h"
Chris Lattner04805fa2002-02-26 21:46:54 +000039#include "llvm/Pass.h"
Chris Lattner1085bdf2002-11-04 16:18:53 +000040#include "llvm/DerivedTypes.h"
Chris Lattner0f1d8a32003-06-26 05:06:25 +000041#include "llvm/GlobalVariable.h"
Chris Lattnerf4ad1652003-11-02 05:57:39 +000042#include "llvm/Target/TargetData.h"
43#include "llvm/Transforms/Utils/BasicBlockUtils.h"
44#include "llvm/Transforms/Utils/Local.h"
Chris Lattner69193f92004-04-05 01:30:19 +000045#include "llvm/Support/CallSite.h"
Chris Lattner39c98bb2004-12-08 23:43:58 +000046#include "llvm/Support/Debug.h"
Chris Lattner69193f92004-04-05 01:30:19 +000047#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner260ab202002-04-18 17:39:14 +000048#include "llvm/Support/InstVisitor.h"
Chris Lattner22d00a82005-08-02 19:16:58 +000049#include "llvm/Support/MathExtras.h"
Chris Lattnerd4252a72004-07-30 07:50:03 +000050#include "llvm/Support/PatternMatch.h"
Chris Lattner4ed40f72005-07-07 20:40:38 +000051#include "llvm/ADT/DepthFirstIterator.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000052#include "llvm/ADT/Statistic.h"
Chris Lattner39c98bb2004-12-08 23:43:58 +000053#include "llvm/ADT/STLExtras.h"
Chris Lattner053c0932002-05-14 15:24:07 +000054#include <algorithm>
Chris Lattnerc597b8a2006-01-22 23:32:06 +000055#include <iostream>
Chris Lattner8427bff2003-12-07 01:24:23 +000056using namespace llvm;
Chris Lattnerd4252a72004-07-30 07:50:03 +000057using namespace llvm::PatternMatch;
Brian Gaeke960707c2003-11-11 22:41:34 +000058
Chris Lattner260ab202002-04-18 17:39:14 +000059namespace {
Chris Lattnerbf3a0992002-10-01 22:38:41 +000060 Statistic<> NumCombined ("instcombine", "Number of insts combined");
61 Statistic<> NumConstProp("instcombine", "Number of constant folds");
62 Statistic<> NumDeadInst ("instcombine", "Number of dead inst eliminated");
Chris Lattner5997cf92006-02-08 03:25:32 +000063 Statistic<> NumDeadStore("instcombine", "Number of dead stores eliminated");
Chris Lattner39c98bb2004-12-08 23:43:58 +000064 Statistic<> NumSunkInst ("instcombine", "Number of instructions sunk");
Chris Lattnerbf3a0992002-10-01 22:38:41 +000065
Chris Lattnerc8e66542002-04-27 06:56:12 +000066 class InstCombiner : public FunctionPass,
Chris Lattner260ab202002-04-18 17:39:14 +000067 public InstVisitor<InstCombiner, Instruction*> {
68 // Worklist of all of the instructions that need to be simplified.
69 std::vector<Instruction*> WorkList;
Chris Lattnerf4ad1652003-11-02 05:57:39 +000070 TargetData *TD;
Chris Lattner260ab202002-04-18 17:39:14 +000071
Chris Lattner51ea1272004-02-28 05:22:00 +000072 /// AddUsersToWorkList - When an instruction is simplified, add all users of
73 /// the instruction to the work lists because they might get more simplified
74 /// now.
75 ///
Chris Lattner2590e512006-02-07 06:56:34 +000076 void AddUsersToWorkList(Value &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +000077 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
Chris Lattner260ab202002-04-18 17:39:14 +000078 UI != UE; ++UI)
79 WorkList.push_back(cast<Instruction>(*UI));
80 }
81
Chris Lattner51ea1272004-02-28 05:22:00 +000082 /// AddUsesToWorkList - When an instruction is simplified, add operands to
83 /// the work lists because they might get more simplified now.
84 ///
85 void AddUsesToWorkList(Instruction &I) {
86 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
87 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i)))
88 WorkList.push_back(Op);
89 }
90
Chris Lattner99f48c62002-09-02 04:59:56 +000091 // removeFromWorkList - remove all instances of I from the worklist.
92 void removeFromWorkList(Instruction *I);
Chris Lattner260ab202002-04-18 17:39:14 +000093 public:
Chris Lattner113f4f42002-06-25 16:13:24 +000094 virtual bool runOnFunction(Function &F);
Chris Lattner260ab202002-04-18 17:39:14 +000095
Chris Lattnerf12cc842002-04-28 21:27:06 +000096 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnerf4ad1652003-11-02 05:57:39 +000097 AU.addRequired<TargetData>();
Chris Lattner820d9712002-10-21 20:00:28 +000098 AU.setPreservesCFG();
Chris Lattnerf12cc842002-04-28 21:27:06 +000099 }
100
Chris Lattner69193f92004-04-05 01:30:19 +0000101 TargetData &getTargetData() const { return *TD; }
102
Chris Lattner260ab202002-04-18 17:39:14 +0000103 // Visitation implementation - Implement instruction combining for different
104 // instruction types. The semantics are as follows:
105 // Return Value:
106 // null - No change was made
Chris Lattnere6794492002-08-12 21:17:25 +0000107 // I - Change was made, I is still valid, I may be dead though
Chris Lattner260ab202002-04-18 17:39:14 +0000108 // otherwise - Change was made, replace I with returned instruction
Misha Brukmanb1c93172005-04-21 23:48:37 +0000109 //
Chris Lattner113f4f42002-06-25 16:13:24 +0000110 Instruction *visitAdd(BinaryOperator &I);
111 Instruction *visitSub(BinaryOperator &I);
112 Instruction *visitMul(BinaryOperator &I);
113 Instruction *visitDiv(BinaryOperator &I);
114 Instruction *visitRem(BinaryOperator &I);
115 Instruction *visitAnd(BinaryOperator &I);
116 Instruction *visitOr (BinaryOperator &I);
117 Instruction *visitXor(BinaryOperator &I);
Chris Lattnerd1f46d32005-04-24 06:59:08 +0000118 Instruction *visitSetCondInst(SetCondInst &I);
119 Instruction *visitSetCondInstWithCastAndCast(SetCondInst &SCI);
120
Chris Lattner0798af32005-01-13 20:14:25 +0000121 Instruction *FoldGEPSetCC(User *GEPLHS, Value *RHS,
122 Instruction::BinaryOps Cond, Instruction &I);
Chris Lattnere8d6c602003-03-10 19:16:08 +0000123 Instruction *visitShiftInst(ShiftInst &I);
Chris Lattner14553932006-01-06 07:12:35 +0000124 Instruction *FoldShiftByConstant(Value *Op0, ConstantUInt *Op1,
125 ShiftInst &I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000126 Instruction *visitCastInst(CastInst &CI);
Chris Lattner411336f2005-01-19 21:50:18 +0000127 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
128 Instruction *FI);
Chris Lattnerb909e8b2004-03-12 05:52:32 +0000129 Instruction *visitSelectInst(SelectInst &CI);
Chris Lattner970c33a2003-06-19 17:00:31 +0000130 Instruction *visitCallInst(CallInst &CI);
131 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner113f4f42002-06-25 16:13:24 +0000132 Instruction *visitPHINode(PHINode &PN);
133 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Chris Lattner1085bdf2002-11-04 16:18:53 +0000134 Instruction *visitAllocationInst(AllocationInst &AI);
Chris Lattner8427bff2003-12-07 01:24:23 +0000135 Instruction *visitFreeInst(FreeInst &FI);
Chris Lattner0f1d8a32003-06-26 05:06:25 +0000136 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattner31f486c2005-01-31 05:36:43 +0000137 Instruction *visitStoreInst(StoreInst &SI);
Chris Lattner9eef8a72003-06-04 04:46:00 +0000138 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner4c9c20a2004-07-03 00:26:11 +0000139 Instruction *visitSwitchInst(SwitchInst &SI);
Chris Lattner39fac442006-04-15 01:39:45 +0000140 Instruction *visitInsertElementInst(InsertElementInst &IE);
Robert Bocchinoa8352962006-01-13 22:48:06 +0000141 Instruction *visitExtractElementInst(ExtractElementInst &EI);
Chris Lattnerfbb77a42006-04-10 22:45:52 +0000142 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
Chris Lattner260ab202002-04-18 17:39:14 +0000143
144 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner113f4f42002-06-25 16:13:24 +0000145 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000146
Chris Lattner970c33a2003-06-19 17:00:31 +0000147 private:
Chris Lattneraec3d942003-10-07 22:32:43 +0000148 Instruction *visitCallSite(CallSite CS);
Chris Lattner970c33a2003-06-19 17:00:31 +0000149 bool transformConstExprCastCall(CallSite CS);
150
Chris Lattner69193f92004-04-05 01:30:19 +0000151 public:
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000152 // InsertNewInstBefore - insert an instruction New before instruction Old
153 // in the program. Add the new instruction to the worklist.
154 //
Chris Lattner623826c2004-09-28 21:48:02 +0000155 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattner65217ff2002-08-23 18:32:43 +0000156 assert(New && New->getParent() == 0 &&
157 "New instruction already inserted into a basic block!");
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000158 BasicBlock *BB = Old.getParent();
159 BB->getInstList().insert(&Old, New); // Insert inst
160 WorkList.push_back(New); // Add to worklist
Chris Lattnere79e8542004-02-23 06:38:22 +0000161 return New;
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000162 }
163
Chris Lattner7e794272004-09-24 15:21:34 +0000164 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
165 /// This also adds the cast to the worklist. Finally, this returns the
166 /// cast.
167 Value *InsertCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
168 if (V->getType() == Ty) return V;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000169
Chris Lattnere79d2492006-04-06 19:19:17 +0000170 if (Constant *CV = dyn_cast<Constant>(V))
171 return ConstantExpr::getCast(CV, Ty);
172
Chris Lattner7e794272004-09-24 15:21:34 +0000173 Instruction *C = new CastInst(V, Ty, V->getName(), &Pos);
174 WorkList.push_back(C);
175 return C;
176 }
177
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000178 // ReplaceInstUsesWith - This method is to be used when an instruction is
179 // found to be dead, replacable with another preexisting expression. Here
180 // we add all uses of I to the worklist, replace all uses of I with the new
181 // value, then return I, so that the inst combiner will know that I was
182 // modified.
183 //
184 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattner51ea1272004-02-28 05:22:00 +0000185 AddUsersToWorkList(I); // Add all modified instrs to worklist
Chris Lattner8953b902004-04-05 02:10:19 +0000186 if (&I != V) {
187 I.replaceAllUsesWith(V);
188 return &I;
189 } else {
190 // If we are replacing the instruction with itself, this must be in a
191 // segment of unreachable code, so just clobber the instruction.
Chris Lattner8ba9ec92004-10-18 02:59:09 +0000192 I.replaceAllUsesWith(UndefValue::get(I.getType()));
Chris Lattner8953b902004-04-05 02:10:19 +0000193 return &I;
194 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000195 }
Chris Lattner51ea1272004-02-28 05:22:00 +0000196
Chris Lattner2590e512006-02-07 06:56:34 +0000197 // UpdateValueUsesWith - This method is to be used when an value is
198 // found to be replacable with another preexisting expression or was
199 // updated. Here we add all uses of I to the worklist, replace all uses of
200 // I with the new value (unless the instruction was just updated), then
201 // return true, so that the inst combiner will know that I was modified.
202 //
203 bool UpdateValueUsesWith(Value *Old, Value *New) {
204 AddUsersToWorkList(*Old); // Add all modified instrs to worklist
205 if (Old != New)
206 Old->replaceAllUsesWith(New);
207 if (Instruction *I = dyn_cast<Instruction>(Old))
208 WorkList.push_back(I);
Chris Lattner5b2edb12006-02-12 08:02:11 +0000209 if (Instruction *I = dyn_cast<Instruction>(New))
210 WorkList.push_back(I);
Chris Lattner2590e512006-02-07 06:56:34 +0000211 return true;
212 }
213
Chris Lattner51ea1272004-02-28 05:22:00 +0000214 // EraseInstFromFunction - When dealing with an instruction that has side
215 // effects or produces a void value, we can't rely on DCE to delete the
216 // instruction. Instead, visit methods should return the value returned by
217 // this function.
218 Instruction *EraseInstFromFunction(Instruction &I) {
219 assert(I.use_empty() && "Cannot erase instruction that is used!");
220 AddUsesToWorkList(I);
221 removeFromWorkList(&I);
Chris Lattner95307542004-11-18 21:41:39 +0000222 I.eraseFromParent();
Chris Lattner51ea1272004-02-28 05:22:00 +0000223 return 0; // Don't do anything with FI
224 }
225
Chris Lattner3ac7c262003-08-13 20:16:26 +0000226 private:
Chris Lattnerdfae8be2003-07-24 17:35:25 +0000227 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
228 /// InsertBefore instruction. This is specialized a bit to avoid inserting
229 /// casts that are known to not do anything...
230 ///
231 Value *InsertOperandCastBefore(Value *V, const Type *DestTy,
232 Instruction *InsertBefore);
233
Chris Lattner7fb29e12003-03-11 00:12:48 +0000234 // SimplifyCommutative - This performs a few simplifications for commutative
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000235 // operators.
Chris Lattner7fb29e12003-03-11 00:12:48 +0000236 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerba1cb382003-09-19 17:17:26 +0000237
Chris Lattner0157e7f2006-02-11 09:31:47 +0000238 bool SimplifyDemandedBits(Value *V, uint64_t Mask,
239 uint64_t &KnownZero, uint64_t &KnownOne,
240 unsigned Depth = 0);
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000241
242 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
243 // PHI node as operand #0, see if we can fold the instruction into the PHI
244 // (which is only possible if all operands to the PHI are constants).
245 Instruction *FoldOpIntoPhi(Instruction &I);
246
Chris Lattner7515cab2004-11-14 19:13:23 +0000247 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
248 // operator and they all are only used by the PHI, PHI together their
249 // inputs, and do the operation once, to the result of the PHI.
250 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
251
Chris Lattnerba1cb382003-09-19 17:17:26 +0000252 Instruction *OptAndOp(Instruction *Op, ConstantIntegral *OpRHS,
253 ConstantIntegral *AndRHS, BinaryOperator &TheAnd);
Chris Lattneraf517572005-09-18 04:24:45 +0000254
255 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantIntegral *Mask,
256 bool isSub, Instruction &I);
Chris Lattner6862fbd2004-09-29 17:40:11 +0000257 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
258 bool Inside, Instruction &IB);
Chris Lattner216be912005-10-24 06:03:58 +0000259 Instruction *PromoteCastOfAllocation(CastInst &CI, AllocationInst &AI);
Chris Lattner260ab202002-04-18 17:39:14 +0000260 };
Chris Lattnerb28b6802002-07-23 18:06:35 +0000261
Chris Lattnerc8b70922002-07-26 21:12:46 +0000262 RegisterOpt<InstCombiner> X("instcombine", "Combine redundant instructions");
Chris Lattner260ab202002-04-18 17:39:14 +0000263}
264
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000265// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattner81a7a232004-10-16 18:11:37 +0000266// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000267static unsigned getComplexity(Value *V) {
268 if (isa<Instruction>(V)) {
269 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
Chris Lattner81a7a232004-10-16 18:11:37 +0000270 return 3;
271 return 4;
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000272 }
Chris Lattner81a7a232004-10-16 18:11:37 +0000273 if (isa<Argument>(V)) return 3;
274 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000275}
Chris Lattner260ab202002-04-18 17:39:14 +0000276
Chris Lattner7fb29e12003-03-11 00:12:48 +0000277// isOnlyUse - Return true if this instruction will be deleted if we stop using
278// it.
279static bool isOnlyUse(Value *V) {
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000280 return V->hasOneUse() || isa<Constant>(V);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000281}
282
Chris Lattnere79e8542004-02-23 06:38:22 +0000283// getPromotedType - Return the specified type promoted as it would be to pass
284// though a va_arg area...
285static const Type *getPromotedType(const Type *Ty) {
Chris Lattner97bfcea2004-06-17 18:16:02 +0000286 switch (Ty->getTypeID()) {
Chris Lattnere79e8542004-02-23 06:38:22 +0000287 case Type::SByteTyID:
288 case Type::ShortTyID: return Type::IntTy;
289 case Type::UByteTyID:
290 case Type::UShortTyID: return Type::UIntTy;
291 case Type::FloatTyID: return Type::DoubleTy;
292 default: return Ty;
293 }
294}
295
Chris Lattner567b81f2005-09-13 00:40:14 +0000296/// isCast - If the specified operand is a CastInst or a constant expr cast,
297/// return the operand value, otherwise return null.
298static Value *isCast(Value *V) {
299 if (CastInst *I = dyn_cast<CastInst>(V))
300 return I->getOperand(0);
301 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
302 if (CE->getOpcode() == Instruction::Cast)
303 return CE->getOperand(0);
304 return 0;
305}
306
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000307// SimplifyCommutative - This performs a few simplifications for commutative
308// operators:
Chris Lattner260ab202002-04-18 17:39:14 +0000309//
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000310// 1. Order operands such that they are listed from right (least complex) to
311// left (most complex). This puts constants before unary operators before
312// binary operators.
313//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000314// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
315// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000316//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000317bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000318 bool Changed = false;
319 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
320 Changed = !I.swapOperands();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000321
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000322 if (!I.isAssociative()) return Changed;
323 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattner7fb29e12003-03-11 00:12:48 +0000324 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
325 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
326 if (isa<Constant>(I.getOperand(1))) {
Chris Lattner34428442003-05-27 16:40:51 +0000327 Constant *Folded = ConstantExpr::get(I.getOpcode(),
328 cast<Constant>(I.getOperand(1)),
329 cast<Constant>(Op->getOperand(1)));
Chris Lattner7fb29e12003-03-11 00:12:48 +0000330 I.setOperand(0, Op->getOperand(0));
331 I.setOperand(1, Folded);
332 return true;
333 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
334 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
335 isOnlyUse(Op) && isOnlyUse(Op1)) {
336 Constant *C1 = cast<Constant>(Op->getOperand(1));
337 Constant *C2 = cast<Constant>(Op1->getOperand(1));
338
339 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner34428442003-05-27 16:40:51 +0000340 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000341 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
342 Op1->getOperand(0),
343 Op1->getName(), &I);
344 WorkList.push_back(New);
345 I.setOperand(0, New);
346 I.setOperand(1, Folded);
347 return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000348 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000349 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000350 return Changed;
Chris Lattner260ab202002-04-18 17:39:14 +0000351}
Chris Lattnerca081252001-12-14 16:52:21 +0000352
Chris Lattnerbb74e222003-03-10 23:06:50 +0000353// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
354// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattner9fa53de2002-05-06 16:49:18 +0000355//
Chris Lattnerbb74e222003-03-10 23:06:50 +0000356static inline Value *dyn_castNegVal(Value *V) {
357 if (BinaryOperator::isNeg(V))
Chris Lattnerd6f636a2005-04-24 07:30:14 +0000358 return BinaryOperator::getNegArgument(V);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000359
Chris Lattner9ad0d552004-12-14 20:08:06 +0000360 // Constants can be considered to be negated values if they can be folded.
361 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
362 return ConstantExpr::getNeg(C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000363 return 0;
Chris Lattner9fa53de2002-05-06 16:49:18 +0000364}
365
Chris Lattnerbb74e222003-03-10 23:06:50 +0000366static inline Value *dyn_castNotVal(Value *V) {
367 if (BinaryOperator::isNot(V))
Chris Lattnerd6f636a2005-04-24 07:30:14 +0000368 return BinaryOperator::getNotArgument(V);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000369
370 // Constants can be considered to be not'ed values...
Chris Lattnerdd65d862003-04-30 22:34:06 +0000371 if (ConstantIntegral *C = dyn_cast<ConstantIntegral>(V))
Chris Lattnerc8e7e292004-06-10 02:12:35 +0000372 return ConstantExpr::getNot(C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000373 return 0;
374}
375
Chris Lattner7fb29e12003-03-11 00:12:48 +0000376// dyn_castFoldableMul - If this value is a multiply that can be folded into
377// other computations (because it has a constant operand), return the
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000378// non-constant operand of the multiply, and set CST to point to the multiplier.
379// Otherwise, return null.
Chris Lattner7fb29e12003-03-11 00:12:48 +0000380//
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000381static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000382 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000383 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattner7fb29e12003-03-11 00:12:48 +0000384 if (I->getOpcode() == Instruction::Mul)
Chris Lattner970136362004-11-15 05:54:07 +0000385 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattner7fb29e12003-03-11 00:12:48 +0000386 return I->getOperand(0);
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000387 if (I->getOpcode() == Instruction::Shl)
Chris Lattner970136362004-11-15 05:54:07 +0000388 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000389 // The multiplier is really 1 << CST.
390 Constant *One = ConstantInt::get(V->getType(), 1);
391 CST = cast<ConstantInt>(ConstantExpr::getShl(One, CST));
392 return I->getOperand(0);
393 }
394 }
Chris Lattner7fb29e12003-03-11 00:12:48 +0000395 return 0;
Chris Lattner3082c5a2003-02-18 19:28:33 +0000396}
Chris Lattner31ae8632002-08-14 17:51:49 +0000397
Chris Lattner0798af32005-01-13 20:14:25 +0000398/// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
399/// expression, return it.
400static User *dyn_castGetElementPtr(Value *V) {
401 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
402 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
403 if (CE->getOpcode() == Instruction::GetElementPtr)
404 return cast<User>(V);
405 return false;
406}
407
Chris Lattner623826c2004-09-28 21:48:02 +0000408// AddOne, SubOne - Add or subtract a constant one from an integer constant...
Chris Lattner6862fbd2004-09-29 17:40:11 +0000409static ConstantInt *AddOne(ConstantInt *C) {
410 return cast<ConstantInt>(ConstantExpr::getAdd(C,
411 ConstantInt::get(C->getType(), 1)));
Chris Lattner623826c2004-09-28 21:48:02 +0000412}
Chris Lattner6862fbd2004-09-29 17:40:11 +0000413static ConstantInt *SubOne(ConstantInt *C) {
414 return cast<ConstantInt>(ConstantExpr::getSub(C,
415 ConstantInt::get(C->getType(), 1)));
Chris Lattner623826c2004-09-28 21:48:02 +0000416}
417
Chris Lattner0157e7f2006-02-11 09:31:47 +0000418/// GetConstantInType - Return a ConstantInt with the specified type and value.
419///
Chris Lattneree0f2802006-02-12 02:07:56 +0000420static ConstantIntegral *GetConstantInType(const Type *Ty, uint64_t Val) {
Chris Lattner0157e7f2006-02-11 09:31:47 +0000421 if (Ty->isUnsigned())
422 return ConstantUInt::get(Ty, Val);
Chris Lattneree0f2802006-02-12 02:07:56 +0000423 else if (Ty->getTypeID() == Type::BoolTyID)
424 return ConstantBool::get(Val);
Chris Lattner0157e7f2006-02-11 09:31:47 +0000425 int64_t SVal = Val;
426 SVal <<= 64-Ty->getPrimitiveSizeInBits();
427 SVal >>= 64-Ty->getPrimitiveSizeInBits();
428 return ConstantSInt::get(Ty, SVal);
429}
430
431
Chris Lattner4534dd592006-02-09 07:38:58 +0000432/// ComputeMaskedBits - Determine which of the bits specified in Mask are
433/// known to be either zero or one and return them in the KnownZero/KnownOne
434/// bitsets. This code only analyzes bits in Mask, in order to short-circuit
435/// processing.
436static void ComputeMaskedBits(Value *V, uint64_t Mask, uint64_t &KnownZero,
437 uint64_t &KnownOne, unsigned Depth = 0) {
Chris Lattner0b3557f2005-09-24 23:43:33 +0000438 // Note, we cannot consider 'undef' to be "IsZero" here. The problem is that
439 // we cannot optimize based on the assumption that it is zero without changing
Chris Lattnerc3ebf402006-02-07 07:27:52 +0000440 // it to be an explicit zero. If we don't change it to zero, other code could
Chris Lattner0b3557f2005-09-24 23:43:33 +0000441 // optimized based on the contradictory assumption that it is non-zero.
442 // Because instcombine aggressively folds operations with undef args anyway,
443 // this won't lose us code quality.
Chris Lattner4534dd592006-02-09 07:38:58 +0000444 if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(V)) {
445 // We know all of the bits for a constant!
Chris Lattner0157e7f2006-02-11 09:31:47 +0000446 KnownOne = CI->getZExtValue() & Mask;
Chris Lattner4534dd592006-02-09 07:38:58 +0000447 KnownZero = ~KnownOne & Mask;
448 return;
449 }
450
451 KnownZero = KnownOne = 0; // Don't know anything.
Chris Lattner92a68652006-02-07 08:05:22 +0000452 if (Depth == 6 || Mask == 0)
Chris Lattner4534dd592006-02-09 07:38:58 +0000453 return; // Limit search depth.
454
455 uint64_t KnownZero2, KnownOne2;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000456 Instruction *I = dyn_cast<Instruction>(V);
457 if (!I) return;
458
Chris Lattnerfb296922006-05-04 17:33:35 +0000459 Mask &= V->getType()->getIntegralTypeMask();
460
Chris Lattner0157e7f2006-02-11 09:31:47 +0000461 switch (I->getOpcode()) {
462 case Instruction::And:
463 // If either the LHS or the RHS are Zero, the result is zero.
464 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
465 Mask &= ~KnownZero;
466 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
467 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
468 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
469
470 // Output known-1 bits are only known if set in both the LHS & RHS.
471 KnownOne &= KnownOne2;
472 // Output known-0 are known to be clear if zero in either the LHS | RHS.
473 KnownZero |= KnownZero2;
474 return;
475 case Instruction::Or:
476 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
477 Mask &= ~KnownOne;
478 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
479 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
480 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
481
482 // Output known-0 bits are only known if clear in both the LHS & RHS.
483 KnownZero &= KnownZero2;
484 // Output known-1 are known to be set if set in either the LHS | RHS.
485 KnownOne |= KnownOne2;
486 return;
487 case Instruction::Xor: {
488 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
489 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
490 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
491 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
492
493 // Output known-0 bits are known if clear or set in both the LHS & RHS.
494 uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
495 // Output known-1 are known to be set if set in only one of the LHS, RHS.
496 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
497 KnownZero = KnownZeroOut;
498 return;
499 }
500 case Instruction::Select:
501 ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
502 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
503 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
504 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
505
506 // Only known if known in both the LHS and RHS.
507 KnownOne &= KnownOne2;
508 KnownZero &= KnownZero2;
509 return;
510 case Instruction::Cast: {
511 const Type *SrcTy = I->getOperand(0)->getType();
512 if (!SrcTy->isIntegral()) return;
513
514 // If this is an integer truncate or noop, just look in the input.
515 if (SrcTy->getPrimitiveSizeInBits() >=
516 I->getType()->getPrimitiveSizeInBits()) {
517 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
Chris Lattner4534dd592006-02-09 07:38:58 +0000518 return;
519 }
Chris Lattner4534dd592006-02-09 07:38:58 +0000520
Chris Lattner0157e7f2006-02-11 09:31:47 +0000521 // Sign or Zero extension. Compute the bits in the result that are not
522 // present in the input.
523 uint64_t NotIn = ~SrcTy->getIntegralTypeMask();
524 uint64_t NewBits = I->getType()->getIntegralTypeMask() & NotIn;
Chris Lattner62010c42005-10-09 06:36:35 +0000525
Chris Lattner0157e7f2006-02-11 09:31:47 +0000526 // Handle zero extension.
527 if (!SrcTy->isSigned()) {
528 Mask &= SrcTy->getIntegralTypeMask();
529 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
530 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
531 // The top bits are known to be zero.
532 KnownZero |= NewBits;
533 } else {
534 // Sign extension.
535 Mask &= SrcTy->getIntegralTypeMask();
536 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
537 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattner92a68652006-02-07 08:05:22 +0000538
Chris Lattner0157e7f2006-02-11 09:31:47 +0000539 // If the sign bit of the input is known set or clear, then we know the
540 // top bits of the result.
541 uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
542 if (KnownZero & InSignBit) { // Input sign bit known zero
Chris Lattner4534dd592006-02-09 07:38:58 +0000543 KnownZero |= NewBits;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000544 KnownOne &= ~NewBits;
545 } else if (KnownOne & InSignBit) { // Input sign bit known set
546 KnownOne |= NewBits;
547 KnownZero &= ~NewBits;
548 } else { // Input sign bit unknown
549 KnownZero &= ~NewBits;
550 KnownOne &= ~NewBits;
551 }
552 }
553 return;
554 }
555 case Instruction::Shl:
556 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
557 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1))) {
558 Mask >>= SA->getValue();
559 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
560 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
561 KnownZero <<= SA->getValue();
562 KnownOne <<= SA->getValue();
563 KnownZero |= (1ULL << SA->getValue())-1; // low bits known zero.
564 return;
565 }
566 break;
567 case Instruction::Shr:
568 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
569 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1))) {
570 // Compute the new bits that are at the top now.
571 uint64_t HighBits = (1ULL << SA->getValue())-1;
572 HighBits <<= I->getType()->getPrimitiveSizeInBits()-SA->getValue();
573
574 if (I->getType()->isUnsigned()) { // Unsigned shift right.
575 Mask <<= SA->getValue();
576 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
577 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
578 KnownZero >>= SA->getValue();
579 KnownOne >>= SA->getValue();
580 KnownZero |= HighBits; // high bits known zero.
Chris Lattner4534dd592006-02-09 07:38:58 +0000581 } else {
Chris Lattner0157e7f2006-02-11 09:31:47 +0000582 Mask <<= SA->getValue();
583 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
584 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
585 KnownZero >>= SA->getValue();
586 KnownOne >>= SA->getValue();
587
588 // Handle the sign bits.
589 uint64_t SignBit = 1ULL << (I->getType()->getPrimitiveSizeInBits()-1);
590 SignBit >>= SA->getValue(); // Adjust to where it is now in the mask.
591
592 if (KnownZero & SignBit) { // New bits are known zero.
593 KnownZero |= HighBits;
594 } else if (KnownOne & SignBit) { // New bits are known one.
595 KnownOne |= HighBits;
Chris Lattner4534dd592006-02-09 07:38:58 +0000596 }
597 }
598 return;
Chris Lattner62010c42005-10-09 06:36:35 +0000599 }
Chris Lattner0157e7f2006-02-11 09:31:47 +0000600 break;
Chris Lattner0b3557f2005-09-24 23:43:33 +0000601 }
Chris Lattner92a68652006-02-07 08:05:22 +0000602}
603
604/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
605/// this predicate to simplify operations downstream. Mask is known to be zero
606/// for bits that V cannot have.
607static bool MaskedValueIsZero(Value *V, uint64_t Mask, unsigned Depth = 0) {
Chris Lattner4534dd592006-02-09 07:38:58 +0000608 uint64_t KnownZero, KnownOne;
609 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
610 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
611 return (KnownZero & Mask) == Mask;
Chris Lattner0b3557f2005-09-24 23:43:33 +0000612}
613
Chris Lattner0157e7f2006-02-11 09:31:47 +0000614/// ShrinkDemandedConstant - Check to see if the specified operand of the
615/// specified instruction is a constant integer. If so, check to see if there
616/// are any bits set in the constant that are not demanded. If so, shrink the
617/// constant and return true.
618static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
619 uint64_t Demanded) {
620 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
621 if (!OpC) return false;
622
623 // If there are no bits set that aren't demanded, nothing to do.
624 if ((~Demanded & OpC->getZExtValue()) == 0)
625 return false;
626
627 // This is producing any bits that are not needed, shrink the RHS.
628 uint64_t Val = Demanded & OpC->getZExtValue();
629 I->setOperand(OpNo, GetConstantInType(OpC->getType(), Val));
630 return true;
631}
632
Chris Lattneree0f2802006-02-12 02:07:56 +0000633// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
634// set of known zero and one bits, compute the maximum and minimum values that
635// could have the specified known zero and known one bits, returning them in
636// min/max.
637static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
638 uint64_t KnownZero,
639 uint64_t KnownOne,
640 int64_t &Min, int64_t &Max) {
641 uint64_t TypeBits = Ty->getIntegralTypeMask();
642 uint64_t UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
643
644 uint64_t SignBit = 1ULL << (Ty->getPrimitiveSizeInBits()-1);
645
646 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
647 // bit if it is unknown.
648 Min = KnownOne;
649 Max = KnownOne|UnknownBits;
650
651 if (SignBit & UnknownBits) { // Sign bit is unknown
652 Min |= SignBit;
653 Max &= ~SignBit;
654 }
655
656 // Sign extend the min/max values.
657 int ShAmt = 64-Ty->getPrimitiveSizeInBits();
658 Min = (Min << ShAmt) >> ShAmt;
659 Max = (Max << ShAmt) >> ShAmt;
660}
661
662// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
663// a set of known zero and one bits, compute the maximum and minimum values that
664// could have the specified known zero and known one bits, returning them in
665// min/max.
666static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
667 uint64_t KnownZero,
668 uint64_t KnownOne,
669 uint64_t &Min,
670 uint64_t &Max) {
671 uint64_t TypeBits = Ty->getIntegralTypeMask();
672 uint64_t UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
673
674 // The minimum value is when the unknown bits are all zeros.
675 Min = KnownOne;
676 // The maximum value is when the unknown bits are all ones.
677 Max = KnownOne|UnknownBits;
678}
Chris Lattner0157e7f2006-02-11 09:31:47 +0000679
680
681/// SimplifyDemandedBits - Look at V. At this point, we know that only the
682/// DemandedMask bits of the result of V are ever used downstream. If we can
683/// use this information to simplify V, do so and return true. Otherwise,
684/// analyze the expression and return a mask of KnownOne and KnownZero bits for
685/// the expression (used to simplify the caller). The KnownZero/One bits may
686/// only be accurate for those bits in the DemandedMask.
687bool InstCombiner::SimplifyDemandedBits(Value *V, uint64_t DemandedMask,
688 uint64_t &KnownZero, uint64_t &KnownOne,
Chris Lattner2590e512006-02-07 06:56:34 +0000689 unsigned Depth) {
Chris Lattner0157e7f2006-02-11 09:31:47 +0000690 if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(V)) {
691 // We know all of the bits for a constant!
692 KnownOne = CI->getZExtValue() & DemandedMask;
693 KnownZero = ~KnownOne & DemandedMask;
694 return false;
695 }
696
697 KnownZero = KnownOne = 0;
Chris Lattner2590e512006-02-07 06:56:34 +0000698 if (!V->hasOneUse()) { // Other users may use these bits.
Chris Lattner0157e7f2006-02-11 09:31:47 +0000699 if (Depth != 0) { // Not at the root.
700 // Just compute the KnownZero/KnownOne bits to simplify things downstream.
701 ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
Chris Lattner2590e512006-02-07 06:56:34 +0000702 return false;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000703 }
Chris Lattner2590e512006-02-07 06:56:34 +0000704 // If this is the root being simplified, allow it to have multiple uses,
Chris Lattner0157e7f2006-02-11 09:31:47 +0000705 // just set the DemandedMask to all bits.
706 DemandedMask = V->getType()->getIntegralTypeMask();
707 } else if (DemandedMask == 0) { // Not demanding any bits from V.
Chris Lattner92a68652006-02-07 08:05:22 +0000708 if (V != UndefValue::get(V->getType()))
709 return UpdateValueUsesWith(V, UndefValue::get(V->getType()));
710 return false;
Chris Lattner2590e512006-02-07 06:56:34 +0000711 } else if (Depth == 6) { // Limit search depth.
712 return false;
713 }
714
715 Instruction *I = dyn_cast<Instruction>(V);
716 if (!I) return false; // Only analyze instructions.
717
Chris Lattnerfb296922006-05-04 17:33:35 +0000718 DemandedMask &= V->getType()->getIntegralTypeMask();
719
Chris Lattner0157e7f2006-02-11 09:31:47 +0000720 uint64_t KnownZero2, KnownOne2;
Chris Lattner2590e512006-02-07 06:56:34 +0000721 switch (I->getOpcode()) {
722 default: break;
723 case Instruction::And:
Chris Lattner0157e7f2006-02-11 09:31:47 +0000724 // If either the LHS or the RHS are Zero, the result is zero.
725 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
726 KnownZero, KnownOne, Depth+1))
727 return true;
728 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
729
730 // If something is known zero on the RHS, the bits aren't demanded on the
731 // LHS.
732 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownZero,
733 KnownZero2, KnownOne2, Depth+1))
734 return true;
735 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
736
737 // If all of the demanded bits are known one on one side, return the other.
738 // These bits cannot contribute to the result of the 'and'.
739 if ((DemandedMask & ~KnownZero2 & KnownOne) == (DemandedMask & ~KnownZero2))
740 return UpdateValueUsesWith(I, I->getOperand(0));
741 if ((DemandedMask & ~KnownZero & KnownOne2) == (DemandedMask & ~KnownZero))
742 return UpdateValueUsesWith(I, I->getOperand(1));
Chris Lattner5b2edb12006-02-12 08:02:11 +0000743
744 // If all of the demanded bits in the inputs are known zeros, return zero.
745 if ((DemandedMask & (KnownZero|KnownZero2)) == DemandedMask)
746 return UpdateValueUsesWith(I, Constant::getNullValue(I->getType()));
747
Chris Lattner0157e7f2006-02-11 09:31:47 +0000748 // If the RHS is a constant, see if we can simplify it.
Chris Lattner5b2edb12006-02-12 08:02:11 +0000749 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~KnownZero2))
Chris Lattner0157e7f2006-02-11 09:31:47 +0000750 return UpdateValueUsesWith(I, I);
751
752 // Output known-1 bits are only known if set in both the LHS & RHS.
753 KnownOne &= KnownOne2;
754 // Output known-0 are known to be clear if zero in either the LHS | RHS.
755 KnownZero |= KnownZero2;
756 break;
757 case Instruction::Or:
758 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
759 KnownZero, KnownOne, Depth+1))
760 return true;
761 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
762 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownOne,
763 KnownZero2, KnownOne2, Depth+1))
764 return true;
765 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
766
767 // If all of the demanded bits are known zero on one side, return the other.
768 // These bits cannot contribute to the result of the 'or'.
Jeff Cohen0add83e2006-02-18 03:20:33 +0000769 if ((DemandedMask & ~KnownOne2 & KnownZero) == (DemandedMask & ~KnownOne2))
Chris Lattner0157e7f2006-02-11 09:31:47 +0000770 return UpdateValueUsesWith(I, I->getOperand(0));
Jeff Cohen0add83e2006-02-18 03:20:33 +0000771 if ((DemandedMask & ~KnownOne & KnownZero2) == (DemandedMask & ~KnownOne))
Chris Lattner0157e7f2006-02-11 09:31:47 +0000772 return UpdateValueUsesWith(I, I->getOperand(1));
Chris Lattner5b2edb12006-02-12 08:02:11 +0000773
774 // If all of the potentially set bits on one side are known to be set on
775 // the other side, just use the 'other' side.
776 if ((DemandedMask & (~KnownZero) & KnownOne2) ==
777 (DemandedMask & (~KnownZero)))
778 return UpdateValueUsesWith(I, I->getOperand(0));
Nate Begeman8a77efe2006-02-16 21:11:51 +0000779 if ((DemandedMask & (~KnownZero2) & KnownOne) ==
780 (DemandedMask & (~KnownZero2)))
781 return UpdateValueUsesWith(I, I->getOperand(1));
Chris Lattner0157e7f2006-02-11 09:31:47 +0000782
783 // If the RHS is a constant, see if we can simplify it.
784 if (ShrinkDemandedConstant(I, 1, DemandedMask))
785 return UpdateValueUsesWith(I, I);
786
787 // Output known-0 bits are only known if clear in both the LHS & RHS.
788 KnownZero &= KnownZero2;
789 // Output known-1 are known to be set if set in either the LHS | RHS.
790 KnownOne |= KnownOne2;
791 break;
792 case Instruction::Xor: {
793 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
794 KnownZero, KnownOne, Depth+1))
795 return true;
796 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
797 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
798 KnownZero2, KnownOne2, Depth+1))
799 return true;
800 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
801
802 // If all of the demanded bits are known zero on one side, return the other.
803 // These bits cannot contribute to the result of the 'xor'.
804 if ((DemandedMask & KnownZero) == DemandedMask)
805 return UpdateValueUsesWith(I, I->getOperand(0));
806 if ((DemandedMask & KnownZero2) == DemandedMask)
807 return UpdateValueUsesWith(I, I->getOperand(1));
808
809 // Output known-0 bits are known if clear or set in both the LHS & RHS.
810 uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
811 // Output known-1 are known to be set if set in only one of the LHS, RHS.
812 uint64_t KnownOneOut = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
813
814 // If all of the unknown bits are known to be zero on one side or the other
815 // (but not both) turn this into an *inclusive* or.
Chris Lattner5b2edb12006-02-12 08:02:11 +0000816 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattner0157e7f2006-02-11 09:31:47 +0000817 if (uint64_t UnknownBits = DemandedMask & ~(KnownZeroOut|KnownOneOut)) {
818 if ((UnknownBits & (KnownZero|KnownZero2)) == UnknownBits) {
819 Instruction *Or =
820 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
821 I->getName());
822 InsertNewInstBefore(Or, *I);
823 return UpdateValueUsesWith(I, Or);
Chris Lattner2590e512006-02-07 06:56:34 +0000824 }
825 }
Chris Lattner0157e7f2006-02-11 09:31:47 +0000826
Chris Lattner5b2edb12006-02-12 08:02:11 +0000827 // If all of the demanded bits on one side are known, and all of the set
828 // bits on that side are also known to be set on the other side, turn this
829 // into an AND, as we know the bits will be cleared.
830 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
831 if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask) { // all known
832 if ((KnownOne & KnownOne2) == KnownOne) {
833 Constant *AndC = GetConstantInType(I->getType(),
834 ~KnownOne & DemandedMask);
835 Instruction *And =
836 BinaryOperator::createAnd(I->getOperand(0), AndC, "tmp");
837 InsertNewInstBefore(And, *I);
838 return UpdateValueUsesWith(I, And);
839 }
840 }
841
Chris Lattner0157e7f2006-02-11 09:31:47 +0000842 // If the RHS is a constant, see if we can simplify it.
843 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
844 if (ShrinkDemandedConstant(I, 1, DemandedMask))
845 return UpdateValueUsesWith(I, I);
846
847 KnownZero = KnownZeroOut;
848 KnownOne = KnownOneOut;
849 break;
850 }
851 case Instruction::Select:
852 if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
853 KnownZero, KnownOne, Depth+1))
854 return true;
855 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
856 KnownZero2, KnownOne2, Depth+1))
857 return true;
858 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
859 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
860
861 // If the operands are constants, see if we can simplify them.
862 if (ShrinkDemandedConstant(I, 1, DemandedMask))
863 return UpdateValueUsesWith(I, I);
864 if (ShrinkDemandedConstant(I, 2, DemandedMask))
865 return UpdateValueUsesWith(I, I);
866
867 // Only known if known in both the LHS and RHS.
868 KnownOne &= KnownOne2;
869 KnownZero &= KnownZero2;
870 break;
Chris Lattner2590e512006-02-07 06:56:34 +0000871 case Instruction::Cast: {
872 const Type *SrcTy = I->getOperand(0)->getType();
Chris Lattner0157e7f2006-02-11 09:31:47 +0000873 if (!SrcTy->isIntegral()) return false;
Chris Lattner2590e512006-02-07 06:56:34 +0000874
Chris Lattner0157e7f2006-02-11 09:31:47 +0000875 // If this is an integer truncate or noop, just look in the input.
876 if (SrcTy->getPrimitiveSizeInBits() >=
877 I->getType()->getPrimitiveSizeInBits()) {
878 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
879 KnownZero, KnownOne, Depth+1))
880 return true;
881 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
882 break;
883 }
884
885 // Sign or Zero extension. Compute the bits in the result that are not
886 // present in the input.
887 uint64_t NotIn = ~SrcTy->getIntegralTypeMask();
888 uint64_t NewBits = I->getType()->getIntegralTypeMask() & NotIn;
889
890 // Handle zero extension.
891 if (!SrcTy->isSigned()) {
892 DemandedMask &= SrcTy->getIntegralTypeMask();
893 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
894 KnownZero, KnownOne, Depth+1))
895 return true;
896 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
897 // The top bits are known to be zero.
898 KnownZero |= NewBits;
899 } else {
900 // Sign extension.
Chris Lattner7d852282006-02-13 22:41:07 +0000901 uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
902 int64_t InputDemandedBits = DemandedMask & SrcTy->getIntegralTypeMask();
903
904 // If any of the sign extended bits are demanded, we know that the sign
905 // bit is demanded.
906 if (NewBits & DemandedMask)
907 InputDemandedBits |= InSignBit;
908
909 if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
Chris Lattner0157e7f2006-02-11 09:31:47 +0000910 KnownZero, KnownOne, Depth+1))
911 return true;
912 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
913
914 // If the sign bit of the input is known set or clear, then we know the
915 // top bits of the result.
Chris Lattner2590e512006-02-07 06:56:34 +0000916
Chris Lattner0157e7f2006-02-11 09:31:47 +0000917 // If the input sign bit is known zero, or if the NewBits are not demanded
918 // convert this into a zero extension.
919 if ((KnownZero & InSignBit) || (NewBits & ~DemandedMask) == NewBits) {
Chris Lattner2590e512006-02-07 06:56:34 +0000920 // Convert to unsigned first.
Chris Lattner44314822006-02-07 19:07:40 +0000921 Instruction *NewVal;
Chris Lattner2590e512006-02-07 06:56:34 +0000922 NewVal = new CastInst(I->getOperand(0), SrcTy->getUnsignedVersion(),
Chris Lattner44314822006-02-07 19:07:40 +0000923 I->getOperand(0)->getName());
924 InsertNewInstBefore(NewVal, *I);
Chris Lattner0157e7f2006-02-11 09:31:47 +0000925 // Then cast that to the destination type.
Chris Lattner44314822006-02-07 19:07:40 +0000926 NewVal = new CastInst(NewVal, I->getType(), I->getName());
927 InsertNewInstBefore(NewVal, *I);
Chris Lattner2590e512006-02-07 06:56:34 +0000928 return UpdateValueUsesWith(I, NewVal);
Chris Lattner0157e7f2006-02-11 09:31:47 +0000929 } else if (KnownOne & InSignBit) { // Input sign bit known set
930 KnownOne |= NewBits;
931 KnownZero &= ~NewBits;
932 } else { // Input sign bit unknown
933 KnownZero &= ~NewBits;
934 KnownOne &= ~NewBits;
Chris Lattner2590e512006-02-07 06:56:34 +0000935 }
Chris Lattner2590e512006-02-07 06:56:34 +0000936 }
Chris Lattner0157e7f2006-02-11 09:31:47 +0000937 break;
Chris Lattner2590e512006-02-07 06:56:34 +0000938 }
Chris Lattner2590e512006-02-07 06:56:34 +0000939 case Instruction::Shl:
Chris Lattner0157e7f2006-02-11 09:31:47 +0000940 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1))) {
941 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask >> SA->getValue(),
942 KnownZero, KnownOne, Depth+1))
943 return true;
944 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
945 KnownZero <<= SA->getValue();
946 KnownOne <<= SA->getValue();
947 KnownZero |= (1ULL << SA->getValue())-1; // low bits known zero.
948 }
Chris Lattner2590e512006-02-07 06:56:34 +0000949 break;
950 case Instruction::Shr:
Chris Lattner0157e7f2006-02-11 09:31:47 +0000951 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1))) {
952 unsigned ShAmt = SA->getValue();
953
954 // Compute the new bits that are at the top now.
955 uint64_t HighBits = (1ULL << ShAmt)-1;
956 HighBits <<= I->getType()->getPrimitiveSizeInBits() - ShAmt;
Chris Lattner68e74752006-02-13 06:09:08 +0000957 uint64_t TypeMask = I->getType()->getIntegralTypeMask();
Chris Lattner0157e7f2006-02-11 09:31:47 +0000958 if (I->getType()->isUnsigned()) { // Unsigned shift right.
Chris Lattner68e74752006-02-13 06:09:08 +0000959 if (SimplifyDemandedBits(I->getOperand(0),
960 (DemandedMask << ShAmt) & TypeMask,
Chris Lattner0157e7f2006-02-11 09:31:47 +0000961 KnownZero, KnownOne, Depth+1))
962 return true;
963 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattner68e74752006-02-13 06:09:08 +0000964 KnownZero &= TypeMask;
965 KnownOne &= TypeMask;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000966 KnownZero >>= ShAmt;
967 KnownOne >>= ShAmt;
968 KnownZero |= HighBits; // high bits known zero.
969 } else { // Signed shift right.
Chris Lattner68e74752006-02-13 06:09:08 +0000970 if (SimplifyDemandedBits(I->getOperand(0),
971 (DemandedMask << ShAmt) & TypeMask,
Chris Lattner0157e7f2006-02-11 09:31:47 +0000972 KnownZero, KnownOne, Depth+1))
973 return true;
974 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattner68e74752006-02-13 06:09:08 +0000975 KnownZero &= TypeMask;
976 KnownOne &= TypeMask;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000977 KnownZero >>= SA->getValue();
978 KnownOne >>= SA->getValue();
979
980 // Handle the sign bits.
981 uint64_t SignBit = 1ULL << (I->getType()->getPrimitiveSizeInBits()-1);
982 SignBit >>= SA->getValue(); // Adjust to where it is now in the mask.
983
984 // If the input sign bit is known to be zero, or if none of the top bits
985 // are demanded, turn this into an unsigned shift right.
986 if ((KnownZero & SignBit) || (HighBits & ~DemandedMask) == HighBits) {
987 // Convert the input to unsigned.
988 Instruction *NewVal;
989 NewVal = new CastInst(I->getOperand(0),
990 I->getType()->getUnsignedVersion(),
991 I->getOperand(0)->getName());
992 InsertNewInstBefore(NewVal, *I);
993 // Perform the unsigned shift right.
994 NewVal = new ShiftInst(Instruction::Shr, NewVal, SA, I->getName());
995 InsertNewInstBefore(NewVal, *I);
996 // Then cast that to the destination type.
997 NewVal = new CastInst(NewVal, I->getType(), I->getName());
998 InsertNewInstBefore(NewVal, *I);
999 return UpdateValueUsesWith(I, NewVal);
1000 } else if (KnownOne & SignBit) { // New bits are known one.
1001 KnownOne |= HighBits;
1002 }
Chris Lattner2590e512006-02-07 06:56:34 +00001003 }
Chris Lattner0157e7f2006-02-11 09:31:47 +00001004 }
Chris Lattner2590e512006-02-07 06:56:34 +00001005 break;
1006 }
Chris Lattner0157e7f2006-02-11 09:31:47 +00001007
1008 // If the client is only demanding bits that we know, return the known
1009 // constant.
1010 if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask)
1011 return UpdateValueUsesWith(I, GetConstantInType(I->getType(), KnownOne));
Chris Lattner2590e512006-02-07 06:56:34 +00001012 return false;
1013}
1014
Chris Lattner623826c2004-09-28 21:48:02 +00001015// isTrueWhenEqual - Return true if the specified setcondinst instruction is
1016// true when both operands are equal...
1017//
1018static bool isTrueWhenEqual(Instruction &I) {
1019 return I.getOpcode() == Instruction::SetEQ ||
1020 I.getOpcode() == Instruction::SetGE ||
1021 I.getOpcode() == Instruction::SetLE;
1022}
Chris Lattnerb8b97502003-08-13 19:01:45 +00001023
1024/// AssociativeOpt - Perform an optimization on an associative operator. This
1025/// function is designed to check a chain of associative operators for a
1026/// potential to apply a certain optimization. Since the optimization may be
1027/// applicable if the expression was reassociated, this checks the chain, then
1028/// reassociates the expression as necessary to expose the optimization
1029/// opportunity. This makes use of a special Functor, which must define
1030/// 'shouldApply' and 'apply' methods.
1031///
1032template<typename Functor>
1033Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1034 unsigned Opcode = Root.getOpcode();
1035 Value *LHS = Root.getOperand(0);
1036
1037 // Quick check, see if the immediate LHS matches...
1038 if (F.shouldApply(LHS))
1039 return F.apply(Root);
1040
1041 // Otherwise, if the LHS is not of the same opcode as the root, return.
1042 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001043 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattnerb8b97502003-08-13 19:01:45 +00001044 // Should we apply this transform to the RHS?
1045 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1046
1047 // If not to the RHS, check to see if we should apply to the LHS...
1048 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1049 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1050 ShouldApply = true;
1051 }
1052
1053 // If the functor wants to apply the optimization to the RHS of LHSI,
1054 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1055 if (ShouldApply) {
1056 BasicBlock *BB = Root.getParent();
Misha Brukmanb1c93172005-04-21 23:48:37 +00001057
Chris Lattnerb8b97502003-08-13 19:01:45 +00001058 // Now all of the instructions are in the current basic block, go ahead
1059 // and perform the reassociation.
1060 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1061
1062 // First move the selected RHS to the LHS of the root...
1063 Root.setOperand(0, LHSI->getOperand(1));
1064
1065 // Make what used to be the LHS of the root be the user of the root...
1066 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner284d3b02004-04-16 18:08:07 +00001067 if (&Root == TmpLHSI) {
Chris Lattner8953b902004-04-05 02:10:19 +00001068 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1069 return 0;
1070 }
Chris Lattner284d3b02004-04-16 18:08:07 +00001071 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattnerb8b97502003-08-13 19:01:45 +00001072 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner284d3b02004-04-16 18:08:07 +00001073 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
1074 BasicBlock::iterator ARI = &Root; ++ARI;
1075 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
1076 ARI = Root;
Chris Lattnerb8b97502003-08-13 19:01:45 +00001077
1078 // Now propagate the ExtraOperand down the chain of instructions until we
1079 // get to LHSI.
1080 while (TmpLHSI != LHSI) {
1081 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner284d3b02004-04-16 18:08:07 +00001082 // Move the instruction to immediately before the chain we are
1083 // constructing to avoid breaking dominance properties.
1084 NextLHSI->getParent()->getInstList().remove(NextLHSI);
1085 BB->getInstList().insert(ARI, NextLHSI);
1086 ARI = NextLHSI;
1087
Chris Lattnerb8b97502003-08-13 19:01:45 +00001088 Value *NextOp = NextLHSI->getOperand(1);
1089 NextLHSI->setOperand(1, ExtraOperand);
1090 TmpLHSI = NextLHSI;
1091 ExtraOperand = NextOp;
1092 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001093
Chris Lattnerb8b97502003-08-13 19:01:45 +00001094 // Now that the instructions are reassociated, have the functor perform
1095 // the transformation...
1096 return F.apply(Root);
1097 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001098
Chris Lattnerb8b97502003-08-13 19:01:45 +00001099 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1100 }
1101 return 0;
1102}
1103
1104
1105// AddRHS - Implements: X + X --> X << 1
1106struct AddRHS {
1107 Value *RHS;
1108 AddRHS(Value *rhs) : RHS(rhs) {}
1109 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1110 Instruction *apply(BinaryOperator &Add) const {
1111 return new ShiftInst(Instruction::Shl, Add.getOperand(0),
1112 ConstantInt::get(Type::UByteTy, 1));
1113 }
1114};
1115
1116// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1117// iff C1&C2 == 0
1118struct AddMaskingAnd {
1119 Constant *C2;
1120 AddMaskingAnd(Constant *c) : C2(c) {}
1121 bool shouldApply(Value *LHS) const {
Chris Lattnerd4252a72004-07-30 07:50:03 +00001122 ConstantInt *C1;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001123 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Chris Lattnerd4252a72004-07-30 07:50:03 +00001124 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattnerb8b97502003-08-13 19:01:45 +00001125 }
1126 Instruction *apply(BinaryOperator &Add) const {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001127 return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattnerb8b97502003-08-13 19:01:45 +00001128 }
1129};
1130
Chris Lattner86102b82005-01-01 16:22:27 +00001131static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner183b3362004-04-09 19:05:30 +00001132 InstCombiner *IC) {
Chris Lattner86102b82005-01-01 16:22:27 +00001133 if (isa<CastInst>(I)) {
1134 if (Constant *SOC = dyn_cast<Constant>(SO))
1135 return ConstantExpr::getCast(SOC, I.getType());
Misha Brukmanb1c93172005-04-21 23:48:37 +00001136
Chris Lattner86102b82005-01-01 16:22:27 +00001137 return IC->InsertNewInstBefore(new CastInst(SO, I.getType(),
1138 SO->getName() + ".cast"), I);
1139 }
1140
Chris Lattner183b3362004-04-09 19:05:30 +00001141 // Figure out if the constant is the left or the right argument.
Chris Lattner86102b82005-01-01 16:22:27 +00001142 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1143 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattnerb8b97502003-08-13 19:01:45 +00001144
Chris Lattner183b3362004-04-09 19:05:30 +00001145 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1146 if (ConstIsRHS)
Chris Lattner86102b82005-01-01 16:22:27 +00001147 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1148 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner183b3362004-04-09 19:05:30 +00001149 }
1150
1151 Value *Op0 = SO, *Op1 = ConstOperand;
1152 if (!ConstIsRHS)
1153 std::swap(Op0, Op1);
1154 Instruction *New;
Chris Lattner86102b82005-01-01 16:22:27 +00001155 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1156 New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
1157 else if (ShiftInst *SI = dyn_cast<ShiftInst>(&I))
1158 New = new ShiftInst(SI->getOpcode(), Op0, Op1, SO->getName()+".sh");
Chris Lattnerf9d96652004-04-10 19:15:56 +00001159 else {
Chris Lattner183b3362004-04-09 19:05:30 +00001160 assert(0 && "Unknown binary instruction type!");
Chris Lattnerf9d96652004-04-10 19:15:56 +00001161 abort();
1162 }
Chris Lattner86102b82005-01-01 16:22:27 +00001163 return IC->InsertNewInstBefore(New, I);
1164}
1165
1166// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1167// constant as the other operand, try to fold the binary operator into the
1168// select arguments. This also works for Cast instructions, which obviously do
1169// not have a second operand.
1170static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1171 InstCombiner *IC) {
1172 // Don't modify shared select instructions
1173 if (!SI->hasOneUse()) return 0;
1174 Value *TV = SI->getOperand(1);
1175 Value *FV = SI->getOperand(2);
1176
1177 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner374e6592005-04-21 05:43:13 +00001178 // Bool selects with constant operands can be folded to logical ops.
1179 if (SI->getType() == Type::BoolTy) return 0;
1180
Chris Lattner86102b82005-01-01 16:22:27 +00001181 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1182 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1183
1184 return new SelectInst(SI->getCondition(), SelectTrueVal,
1185 SelectFalseVal);
1186 }
1187 return 0;
Chris Lattner183b3362004-04-09 19:05:30 +00001188}
1189
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001190
1191/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1192/// node as operand #0, see if we can fold the instruction into the PHI (which
1193/// is only possible if all operands to the PHI are constants).
1194Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1195 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattner7515cab2004-11-14 19:13:23 +00001196 unsigned NumPHIValues = PN->getNumIncomingValues();
1197 if (!PN->hasOneUse() || NumPHIValues == 0 ||
1198 !isa<Constant>(PN->getIncomingValue(0))) return 0;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001199
1200 // Check to see if all of the operands of the PHI are constants. If not, we
1201 // cannot do the transformation.
Chris Lattner7515cab2004-11-14 19:13:23 +00001202 for (unsigned i = 1; i != NumPHIValues; ++i)
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001203 if (!isa<Constant>(PN->getIncomingValue(i)))
1204 return 0;
1205
1206 // Okay, we can do the transformation: create the new PHI node.
1207 PHINode *NewPN = new PHINode(I.getType(), I.getName());
1208 I.setName("");
Chris Lattnerd8e20182005-01-29 00:39:08 +00001209 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001210 InsertNewInstBefore(NewPN, *PN);
1211
1212 // Next, add all of the operands to the PHI.
1213 if (I.getNumOperands() == 2) {
1214 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattner7515cab2004-11-14 19:13:23 +00001215 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001216 Constant *InV = cast<Constant>(PN->getIncomingValue(i));
1217 NewPN->addIncoming(ConstantExpr::get(I.getOpcode(), InV, C),
1218 PN->getIncomingBlock(i));
1219 }
1220 } else {
1221 assert(isa<CastInst>(I) && "Unary op should be a cast!");
1222 const Type *RetTy = I.getType();
Chris Lattner7515cab2004-11-14 19:13:23 +00001223 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001224 Constant *InV = cast<Constant>(PN->getIncomingValue(i));
1225 NewPN->addIncoming(ConstantExpr::getCast(InV, RetTy),
1226 PN->getIncomingBlock(i));
1227 }
1228 }
1229 return ReplaceInstUsesWith(I, NewPN);
1230}
1231
Chris Lattner113f4f42002-06-25 16:13:24 +00001232Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001233 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00001234 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattner9fa53de2002-05-06 16:49:18 +00001235
Chris Lattnercf4a9962004-04-10 22:01:55 +00001236 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattner81a7a232004-10-16 18:11:37 +00001237 // X + undef -> undef
1238 if (isa<UndefValue>(RHS))
1239 return ReplaceInstUsesWith(I, RHS);
1240
Chris Lattnercf4a9962004-04-10 22:01:55 +00001241 // X + 0 --> X
Chris Lattner7fde91e2005-10-17 17:56:38 +00001242 if (!I.getType()->isFloatingPoint()) { // NOTE: -0 + +0 = +0.
1243 if (RHSC->isNullValue())
1244 return ReplaceInstUsesWith(I, LHS);
Chris Lattnerda1b1522005-10-17 20:18:38 +00001245 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
1246 if (CFP->isExactlyValue(-0.0))
1247 return ReplaceInstUsesWith(I, LHS);
Chris Lattner7fde91e2005-10-17 17:56:38 +00001248 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001249
Chris Lattnercf4a9962004-04-10 22:01:55 +00001250 // X + (signbit) --> X ^ signbit
1251 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattner92a68652006-02-07 08:05:22 +00001252 uint64_t Val = CI->getZExtValue();
Chris Lattner77defba2006-02-07 07:00:41 +00001253 if (Val == (1ULL << (CI->getType()->getPrimitiveSizeInBits()-1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001254 return BinaryOperator::createXor(LHS, RHS);
Chris Lattnercf4a9962004-04-10 22:01:55 +00001255 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001256
1257 if (isa<PHINode>(LHS))
1258 if (Instruction *NV = FoldOpIntoPhi(I))
1259 return NV;
Chris Lattner0b3557f2005-09-24 23:43:33 +00001260
Chris Lattner330628a2006-01-06 17:59:59 +00001261 ConstantInt *XorRHS = 0;
1262 Value *XorLHS = 0;
Chris Lattner0b3557f2005-09-24 23:43:33 +00001263 if (match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
1264 unsigned TySizeBits = I.getType()->getPrimitiveSizeInBits();
1265 int64_t RHSSExt = cast<ConstantInt>(RHSC)->getSExtValue();
1266 uint64_t RHSZExt = cast<ConstantInt>(RHSC)->getZExtValue();
1267
1268 uint64_t C0080Val = 1ULL << 31;
1269 int64_t CFF80Val = -C0080Val;
1270 unsigned Size = 32;
1271 do {
1272 if (TySizeBits > Size) {
1273 bool Found = false;
1274 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
1275 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
1276 if (RHSSExt == CFF80Val) {
1277 if (XorRHS->getZExtValue() == C0080Val)
1278 Found = true;
1279 } else if (RHSZExt == C0080Val) {
1280 if (XorRHS->getSExtValue() == CFF80Val)
1281 Found = true;
1282 }
1283 if (Found) {
1284 // This is a sign extend if the top bits are known zero.
Chris Lattner4534dd592006-02-09 07:38:58 +00001285 uint64_t Mask = ~0ULL;
Chris Lattnerc3ebf402006-02-07 07:27:52 +00001286 Mask <<= 64-(TySizeBits-Size);
Chris Lattner4534dd592006-02-09 07:38:58 +00001287 Mask &= XorLHS->getType()->getIntegralTypeMask();
Chris Lattnerc3ebf402006-02-07 07:27:52 +00001288 if (!MaskedValueIsZero(XorLHS, Mask))
Chris Lattner0b3557f2005-09-24 23:43:33 +00001289 Size = 0; // Not a sign ext, but can't be any others either.
1290 goto FoundSExt;
1291 }
1292 }
1293 Size >>= 1;
1294 C0080Val >>= Size;
1295 CFF80Val >>= Size;
1296 } while (Size >= 8);
1297
1298FoundSExt:
1299 const Type *MiddleType = 0;
1300 switch (Size) {
1301 default: break;
1302 case 32: MiddleType = Type::IntTy; break;
1303 case 16: MiddleType = Type::ShortTy; break;
1304 case 8: MiddleType = Type::SByteTy; break;
1305 }
1306 if (MiddleType) {
1307 Instruction *NewTrunc = new CastInst(XorLHS, MiddleType, "sext");
1308 InsertNewInstBefore(NewTrunc, I);
1309 return new CastInst(NewTrunc, I.getType());
1310 }
1311 }
Chris Lattnercf4a9962004-04-10 22:01:55 +00001312 }
Chris Lattner9fa53de2002-05-06 16:49:18 +00001313
Chris Lattnerb8b97502003-08-13 19:01:45 +00001314 // X + X --> X << 1
Robert Bocchino7b5b86c2004-07-27 21:02:21 +00001315 if (I.getType()->isInteger()) {
Chris Lattnerb8b97502003-08-13 19:01:45 +00001316 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Chris Lattner47060462005-04-07 17:14:51 +00001317
1318 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
1319 if (RHSI->getOpcode() == Instruction::Sub)
1320 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
1321 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
1322 }
1323 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
1324 if (LHSI->getOpcode() == Instruction::Sub)
1325 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
1326 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
1327 }
Robert Bocchino7b5b86c2004-07-27 21:02:21 +00001328 }
Chris Lattnerede3fe02003-08-13 04:18:28 +00001329
Chris Lattner147e9752002-05-08 22:46:53 +00001330 // -A + B --> B - A
Chris Lattnerbb74e222003-03-10 23:06:50 +00001331 if (Value *V = dyn_castNegVal(LHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001332 return BinaryOperator::createSub(RHS, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +00001333
1334 // A + -B --> A - B
Chris Lattnerbb74e222003-03-10 23:06:50 +00001335 if (!isa<Constant>(RHS))
1336 if (Value *V = dyn_castNegVal(RHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001337 return BinaryOperator::createSub(LHS, V);
Chris Lattner260ab202002-04-18 17:39:14 +00001338
Misha Brukmanb1c93172005-04-21 23:48:37 +00001339
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001340 ConstantInt *C2;
1341 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
1342 if (X == RHS) // X*C + X --> X * (C+1)
1343 return BinaryOperator::createMul(RHS, AddOne(C2));
1344
1345 // X*C1 + X*C2 --> X * (C1+C2)
1346 ConstantInt *C1;
1347 if (X == dyn_castFoldableMul(RHS, C1))
1348 return BinaryOperator::createMul(X, ConstantExpr::getAdd(C1, C2));
Chris Lattner57c8d992003-02-18 19:57:07 +00001349 }
1350
1351 // X + X*C --> X * (C+1)
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001352 if (dyn_castFoldableMul(RHS, C2) == LHS)
1353 return BinaryOperator::createMul(LHS, AddOne(C2));
1354
Chris Lattner57c8d992003-02-18 19:57:07 +00001355
Chris Lattnerb8b97502003-08-13 19:01:45 +00001356 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattnerd4252a72004-07-30 07:50:03 +00001357 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattnerb8b97502003-08-13 19:01:45 +00001358 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2))) return R;
Chris Lattner7fb29e12003-03-11 00:12:48 +00001359
Chris Lattnerb9cde762003-10-02 15:11:26 +00001360 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner330628a2006-01-06 17:59:59 +00001361 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00001362 if (match(LHS, m_Not(m_Value(X)))) { // ~X + C --> (C-1) - X
1363 Constant *C= ConstantExpr::getSub(CRHS, ConstantInt::get(I.getType(), 1));
1364 return BinaryOperator::createSub(C, X);
Chris Lattnerb9cde762003-10-02 15:11:26 +00001365 }
Chris Lattnerd4252a72004-07-30 07:50:03 +00001366
Chris Lattnerbff91d92004-10-08 05:07:56 +00001367 // (X & FF00) + xx00 -> (X+xx00) & FF00
1368 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
1369 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
1370 if (Anded == CRHS) {
1371 // See if all bits from the first bit set in the Add RHS up are included
1372 // in the mask. First, get the rightmost bit.
1373 uint64_t AddRHSV = CRHS->getRawValue();
1374
1375 // Form a mask of all bits from the lowest bit added through the top.
1376 uint64_t AddRHSHighBits = ~((AddRHSV & -AddRHSV)-1);
Chris Lattner77defba2006-02-07 07:00:41 +00001377 AddRHSHighBits &= C2->getType()->getIntegralTypeMask();
Chris Lattnerbff91d92004-10-08 05:07:56 +00001378
1379 // See if the and mask includes all of these bits.
1380 uint64_t AddRHSHighBitsAnd = AddRHSHighBits & C2->getRawValue();
Misha Brukmanb1c93172005-04-21 23:48:37 +00001381
Chris Lattnerbff91d92004-10-08 05:07:56 +00001382 if (AddRHSHighBits == AddRHSHighBitsAnd) {
1383 // Okay, the xform is safe. Insert the new add pronto.
1384 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
1385 LHS->getName()), I);
1386 return BinaryOperator::createAnd(NewAdd, C2);
1387 }
1388 }
1389 }
1390
Chris Lattnerd4252a72004-07-30 07:50:03 +00001391 // Try to fold constant add into select arguments.
1392 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner86102b82005-01-01 16:22:27 +00001393 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattnerd4252a72004-07-30 07:50:03 +00001394 return R;
Chris Lattnerb9cde762003-10-02 15:11:26 +00001395 }
1396
Chris Lattner113f4f42002-06-25 16:13:24 +00001397 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +00001398}
1399
Chris Lattnerbdb0ce02003-07-22 21:46:59 +00001400// isSignBit - Return true if the value represented by the constant only has the
1401// highest order bit set.
1402static bool isSignBit(ConstantInt *CI) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001403 unsigned NumBits = CI->getType()->getPrimitiveSizeInBits();
Chris Lattner2f1457f2005-04-24 17:46:05 +00001404 return (CI->getRawValue() & (~0ULL >> (64-NumBits))) == (1ULL << (NumBits-1));
Chris Lattnerbdb0ce02003-07-22 21:46:59 +00001405}
1406
Chris Lattner022167f2004-03-13 00:11:49 +00001407/// RemoveNoopCast - Strip off nonconverting casts from the value.
1408///
1409static Value *RemoveNoopCast(Value *V) {
1410 if (CastInst *CI = dyn_cast<CastInst>(V)) {
1411 const Type *CTy = CI->getType();
1412 const Type *OpTy = CI->getOperand(0)->getType();
1413 if (CTy->isInteger() && OpTy->isInteger()) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001414 if (CTy->getPrimitiveSizeInBits() == OpTy->getPrimitiveSizeInBits())
Chris Lattner022167f2004-03-13 00:11:49 +00001415 return RemoveNoopCast(CI->getOperand(0));
1416 } else if (isa<PointerType>(CTy) && isa<PointerType>(OpTy))
1417 return RemoveNoopCast(CI->getOperand(0));
1418 }
1419 return V;
1420}
1421
Chris Lattner113f4f42002-06-25 16:13:24 +00001422Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +00001423 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001424
Chris Lattnere6794492002-08-12 21:17:25 +00001425 if (Op0 == Op1) // sub X, X -> 0
1426 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner260ab202002-04-18 17:39:14 +00001427
Chris Lattnere6794492002-08-12 21:17:25 +00001428 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattnerbb74e222003-03-10 23:06:50 +00001429 if (Value *V = dyn_castNegVal(Op1))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001430 return BinaryOperator::createAdd(Op0, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +00001431
Chris Lattner81a7a232004-10-16 18:11:37 +00001432 if (isa<UndefValue>(Op0))
1433 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
1434 if (isa<UndefValue>(Op1))
1435 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
1436
Chris Lattner8f2f5982003-11-05 01:06:05 +00001437 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
1438 // Replace (-1 - A) with (~A)...
Chris Lattner3082c5a2003-02-18 19:28:33 +00001439 if (C->isAllOnesValue())
1440 return BinaryOperator::createNot(Op1);
Chris Lattnerad3c4952002-05-09 01:29:19 +00001441
Chris Lattner8f2f5982003-11-05 01:06:05 +00001442 // C - ~X == X + (1+C)
Reid Spencer4fdd96c2005-06-18 17:37:34 +00001443 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00001444 if (match(Op1, m_Not(m_Value(X))))
1445 return BinaryOperator::createAdd(X,
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001446 ConstantExpr::getAdd(C, ConstantInt::get(I.getType(), 1)));
Chris Lattner92295c52004-03-12 23:53:13 +00001447 // -((uint)X >> 31) -> ((int)X >> 31)
1448 // -((int)X >> 31) -> ((uint)X >> 31)
Chris Lattner022167f2004-03-13 00:11:49 +00001449 if (C->isNullValue()) {
1450 Value *NoopCastedRHS = RemoveNoopCast(Op1);
1451 if (ShiftInst *SI = dyn_cast<ShiftInst>(NoopCastedRHS))
Chris Lattner92295c52004-03-12 23:53:13 +00001452 if (SI->getOpcode() == Instruction::Shr)
1453 if (ConstantUInt *CU = dyn_cast<ConstantUInt>(SI->getOperand(1))) {
1454 const Type *NewTy;
Chris Lattner022167f2004-03-13 00:11:49 +00001455 if (SI->getType()->isSigned())
Chris Lattner97bfcea2004-06-17 18:16:02 +00001456 NewTy = SI->getType()->getUnsignedVersion();
Chris Lattner92295c52004-03-12 23:53:13 +00001457 else
Chris Lattner97bfcea2004-06-17 18:16:02 +00001458 NewTy = SI->getType()->getSignedVersion();
Chris Lattner92295c52004-03-12 23:53:13 +00001459 // Check to see if we are shifting out everything but the sign bit.
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001460 if (CU->getValue() == SI->getType()->getPrimitiveSizeInBits()-1) {
Chris Lattner92295c52004-03-12 23:53:13 +00001461 // Ok, the transformation is safe. Insert a cast of the incoming
1462 // value, then the new shift, then the new cast.
1463 Instruction *FirstCast = new CastInst(SI->getOperand(0), NewTy,
1464 SI->getOperand(0)->getName());
1465 Value *InV = InsertNewInstBefore(FirstCast, I);
1466 Instruction *NewShift = new ShiftInst(Instruction::Shr, FirstCast,
1467 CU, SI->getName());
Chris Lattner022167f2004-03-13 00:11:49 +00001468 if (NewShift->getType() == I.getType())
1469 return NewShift;
1470 else {
1471 InV = InsertNewInstBefore(NewShift, I);
1472 return new CastInst(NewShift, I.getType());
1473 }
Chris Lattner92295c52004-03-12 23:53:13 +00001474 }
1475 }
Chris Lattner022167f2004-03-13 00:11:49 +00001476 }
Chris Lattner183b3362004-04-09 19:05:30 +00001477
1478 // Try to fold constant sub into select arguments.
1479 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner86102b82005-01-01 16:22:27 +00001480 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00001481 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001482
1483 if (isa<PHINode>(Op0))
1484 if (Instruction *NV = FoldOpIntoPhi(I))
1485 return NV;
Chris Lattner8f2f5982003-11-05 01:06:05 +00001486 }
1487
Chris Lattnera9be4492005-04-07 16:15:25 +00001488 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
1489 if (Op1I->getOpcode() == Instruction::Add &&
1490 !Op0->getType()->isFloatingPoint()) {
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00001491 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Chris Lattnera9be4492005-04-07 16:15:25 +00001492 return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00001493 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Chris Lattnera9be4492005-04-07 16:15:25 +00001494 return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00001495 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
1496 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
1497 // C1-(X+C2) --> (C1-C2)-X
1498 return BinaryOperator::createSub(ConstantExpr::getSub(CI1, CI2),
1499 Op1I->getOperand(0));
1500 }
Chris Lattnera9be4492005-04-07 16:15:25 +00001501 }
1502
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001503 if (Op1I->hasOneUse()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00001504 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
1505 // is not used by anyone else...
1506 //
Chris Lattnerc2f0aa52004-02-02 20:09:56 +00001507 if (Op1I->getOpcode() == Instruction::Sub &&
1508 !Op1I->getType()->isFloatingPoint()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00001509 // Swap the two operands of the subexpr...
1510 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
1511 Op1I->setOperand(0, IIOp1);
1512 Op1I->setOperand(1, IIOp0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001513
Chris Lattner3082c5a2003-02-18 19:28:33 +00001514 // Create the new top level add instruction...
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001515 return BinaryOperator::createAdd(Op0, Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001516 }
1517
1518 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
1519 //
1520 if (Op1I->getOpcode() == Instruction::And &&
1521 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
1522 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
1523
Chris Lattner396dbfe2004-06-09 05:08:07 +00001524 Value *NewNot =
1525 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001526 return BinaryOperator::createAnd(Op0, NewNot);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001527 }
Chris Lattner57c8d992003-02-18 19:57:07 +00001528
Chris Lattner0aee4b72004-10-06 15:08:25 +00001529 // -(X sdiv C) -> (X sdiv -C)
1530 if (Op1I->getOpcode() == Instruction::Div)
1531 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
Chris Lattnera9be4492005-04-07 16:15:25 +00001532 if (CSI->isNullValue())
Chris Lattner0aee4b72004-10-06 15:08:25 +00001533 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Misha Brukmanb1c93172005-04-21 23:48:37 +00001534 return BinaryOperator::createDiv(Op1I->getOperand(0),
Chris Lattner0aee4b72004-10-06 15:08:25 +00001535 ConstantExpr::getNeg(DivRHS));
1536
Chris Lattner57c8d992003-02-18 19:57:07 +00001537 // X - X*C --> X * (1-C)
Reid Spencer4fdd96c2005-06-18 17:37:34 +00001538 ConstantInt *C2 = 0;
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001539 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00001540 Constant *CP1 =
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001541 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1), C2);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001542 return BinaryOperator::createMul(Op0, CP1);
Chris Lattner57c8d992003-02-18 19:57:07 +00001543 }
Chris Lattnerad3c4952002-05-09 01:29:19 +00001544 }
Chris Lattnera9be4492005-04-07 16:15:25 +00001545 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00001546
Chris Lattner47060462005-04-07 17:14:51 +00001547 if (!Op0->getType()->isFloatingPoint())
1548 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
1549 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner411336f2005-01-19 21:50:18 +00001550 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
1551 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
1552 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
1553 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner47060462005-04-07 17:14:51 +00001554 } else if (Op0I->getOpcode() == Instruction::Sub) {
1555 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
1556 return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
Chris Lattner411336f2005-01-19 21:50:18 +00001557 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001558
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001559 ConstantInt *C1;
1560 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
1561 if (X == Op1) { // X*C - X --> X * (C-1)
1562 Constant *CP1 = ConstantExpr::getSub(C1, ConstantInt::get(I.getType(),1));
1563 return BinaryOperator::createMul(Op1, CP1);
1564 }
Chris Lattner57c8d992003-02-18 19:57:07 +00001565
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001566 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
1567 if (X == dyn_castFoldableMul(Op1, C2))
1568 return BinaryOperator::createMul(Op1, ConstantExpr::getSub(C1, C2));
1569 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001570 return 0;
Chris Lattner260ab202002-04-18 17:39:14 +00001571}
1572
Chris Lattnere79e8542004-02-23 06:38:22 +00001573/// isSignBitCheck - Given an exploded setcc instruction, return true if it is
1574/// really just returns true if the most significant (sign) bit is set.
1575static bool isSignBitCheck(unsigned Opcode, Value *LHS, ConstantInt *RHS) {
1576 if (RHS->getType()->isSigned()) {
1577 // True if source is LHS < 0 or LHS <= -1
1578 return Opcode == Instruction::SetLT && RHS->isNullValue() ||
1579 Opcode == Instruction::SetLE && RHS->isAllOnesValue();
1580 } else {
1581 ConstantUInt *RHSC = cast<ConstantUInt>(RHS);
1582 // True if source is LHS > 127 or LHS >= 128, where the constants depend on
1583 // the size of the integer type.
1584 if (Opcode == Instruction::SetGE)
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001585 return RHSC->getValue() ==
1586 1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1);
Chris Lattnere79e8542004-02-23 06:38:22 +00001587 if (Opcode == Instruction::SetGT)
1588 return RHSC->getValue() ==
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001589 (1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1))-1;
Chris Lattnere79e8542004-02-23 06:38:22 +00001590 }
1591 return false;
1592}
1593
Chris Lattner113f4f42002-06-25 16:13:24 +00001594Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001595 bool Changed = SimplifyCommutative(I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001596 Value *Op0 = I.getOperand(0);
Chris Lattner260ab202002-04-18 17:39:14 +00001597
Chris Lattner81a7a232004-10-16 18:11:37 +00001598 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
1599 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1600
Chris Lattnere6794492002-08-12 21:17:25 +00001601 // Simplify mul instructions with a constant RHS...
Chris Lattner3082c5a2003-02-18 19:28:33 +00001602 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
1603 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerede3fe02003-08-13 04:18:28 +00001604
1605 // ((X << C1)*C2) == (X * (C2 << C1))
1606 if (ShiftInst *SI = dyn_cast<ShiftInst>(Op0))
1607 if (SI->getOpcode() == Instruction::Shl)
1608 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001609 return BinaryOperator::createMul(SI->getOperand(0),
1610 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanb1c93172005-04-21 23:48:37 +00001611
Chris Lattnercce81be2003-09-11 22:24:54 +00001612 if (CI->isNullValue())
1613 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
1614 if (CI->equalsInt(1)) // X * 1 == X
1615 return ReplaceInstUsesWith(I, Op0);
1616 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Chris Lattner35236d82003-06-25 17:09:20 +00001617 return BinaryOperator::createNeg(Op0, I.getName());
Chris Lattner31ba1292002-04-29 22:24:47 +00001618
Chris Lattnercce81be2003-09-11 22:24:54 +00001619 int64_t Val = (int64_t)cast<ConstantInt>(CI)->getRawValue();
Chris Lattner22d00a82005-08-02 19:16:58 +00001620 if (isPowerOf2_64(Val)) { // Replace X*(2^C) with X << C
1621 uint64_t C = Log2_64(Val);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001622 return new ShiftInst(Instruction::Shl, Op0,
1623 ConstantUInt::get(Type::UByteTy, C));
Chris Lattner22d00a82005-08-02 19:16:58 +00001624 }
Robert Bocchino7b5b86c2004-07-27 21:02:21 +00001625 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00001626 if (Op1F->isNullValue())
1627 return ReplaceInstUsesWith(I, Op1);
Chris Lattner31ba1292002-04-29 22:24:47 +00001628
Chris Lattner3082c5a2003-02-18 19:28:33 +00001629 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
1630 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
1631 if (Op1F->getValue() == 1.0)
1632 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
1633 }
Chris Lattner32c01df2006-03-04 06:04:02 +00001634
1635 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
1636 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
1637 isa<ConstantInt>(Op0I->getOperand(1))) {
1638 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
1639 Instruction *Add = BinaryOperator::createMul(Op0I->getOperand(0),
1640 Op1, "tmp");
1641 InsertNewInstBefore(Add, I);
1642 Value *C1C2 = ConstantExpr::getMul(Op1,
1643 cast<Constant>(Op0I->getOperand(1)));
1644 return BinaryOperator::createAdd(Add, C1C2);
1645
1646 }
Chris Lattner183b3362004-04-09 19:05:30 +00001647
1648 // Try to fold constant mul into select arguments.
1649 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00001650 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00001651 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001652
1653 if (isa<PHINode>(Op0))
1654 if (Instruction *NV = FoldOpIntoPhi(I))
1655 return NV;
Chris Lattner260ab202002-04-18 17:39:14 +00001656 }
1657
Chris Lattner934a64cf2003-03-10 23:23:04 +00001658 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
1659 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001660 return BinaryOperator::createMul(Op0v, Op1v);
Chris Lattner934a64cf2003-03-10 23:23:04 +00001661
Chris Lattner2635b522004-02-23 05:39:21 +00001662 // If one of the operands of the multiply is a cast from a boolean value, then
1663 // we know the bool is either zero or one, so this is a 'masking' multiply.
1664 // See if we can simplify things based on how the boolean was originally
1665 // formed.
1666 CastInst *BoolCast = 0;
1667 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(0)))
1668 if (CI->getOperand(0)->getType() == Type::BoolTy)
1669 BoolCast = CI;
1670 if (!BoolCast)
1671 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(1)))
1672 if (CI->getOperand(0)->getType() == Type::BoolTy)
1673 BoolCast = CI;
1674 if (BoolCast) {
1675 if (SetCondInst *SCI = dyn_cast<SetCondInst>(BoolCast->getOperand(0))) {
1676 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
1677 const Type *SCOpTy = SCIOp0->getType();
1678
Chris Lattnere79e8542004-02-23 06:38:22 +00001679 // If the setcc is true iff the sign bit of X is set, then convert this
1680 // multiply into a shift/and combination.
1681 if (isa<ConstantInt>(SCIOp1) &&
1682 isSignBitCheck(SCI->getOpcode(), SCIOp0, cast<ConstantInt>(SCIOp1))) {
Chris Lattner2635b522004-02-23 05:39:21 +00001683 // Shift the X value right to turn it into "all signbits".
1684 Constant *Amt = ConstantUInt::get(Type::UByteTy,
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001685 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattnere79e8542004-02-23 06:38:22 +00001686 if (SCIOp0->getType()->isUnsigned()) {
Chris Lattner97bfcea2004-06-17 18:16:02 +00001687 const Type *NewTy = SCIOp0->getType()->getSignedVersion();
Chris Lattnere79e8542004-02-23 06:38:22 +00001688 SCIOp0 = InsertNewInstBefore(new CastInst(SCIOp0, NewTy,
1689 SCIOp0->getName()), I);
1690 }
1691
1692 Value *V =
1693 InsertNewInstBefore(new ShiftInst(Instruction::Shr, SCIOp0, Amt,
1694 BoolCast->getOperand(0)->getName()+
1695 ".mask"), I);
Chris Lattner2635b522004-02-23 05:39:21 +00001696
1697 // If the multiply type is not the same as the source type, sign extend
1698 // or truncate to the multiply type.
1699 if (I.getType() != V->getType())
Chris Lattnere79e8542004-02-23 06:38:22 +00001700 V = InsertNewInstBefore(new CastInst(V, I.getType(), V->getName()),I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001701
Chris Lattner2635b522004-02-23 05:39:21 +00001702 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001703 return BinaryOperator::createAnd(V, OtherOp);
Chris Lattner2635b522004-02-23 05:39:21 +00001704 }
1705 }
1706 }
1707
Chris Lattner113f4f42002-06-25 16:13:24 +00001708 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +00001709}
1710
Chris Lattner113f4f42002-06-25 16:13:24 +00001711Instruction *InstCombiner::visitDiv(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001712 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner81a7a232004-10-16 18:11:37 +00001713
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001714 if (isa<UndefValue>(Op0)) // undef / X -> 0
1715 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1716 if (isa<UndefValue>(Op1))
1717 return ReplaceInstUsesWith(I, Op1); // X / undef -> undef
1718
1719 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnere20c3342004-04-26 14:01:59 +00001720 // div X, 1 == X
Chris Lattnere6794492002-08-12 21:17:25 +00001721 if (RHS->equalsInt(1))
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001722 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001723
Chris Lattnere20c3342004-04-26 14:01:59 +00001724 // div X, -1 == -X
1725 if (RHS->isAllOnesValue())
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001726 return BinaryOperator::createNeg(Op0);
Chris Lattnere20c3342004-04-26 14:01:59 +00001727
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001728 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
Chris Lattner272d5ca2004-09-28 18:22:15 +00001729 if (LHS->getOpcode() == Instruction::Div)
1730 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Chris Lattner272d5ca2004-09-28 18:22:15 +00001731 // (X / C1) / C2 -> X / (C1*C2)
1732 return BinaryOperator::createDiv(LHS->getOperand(0),
1733 ConstantExpr::getMul(RHS, LHSRHS));
1734 }
1735
Chris Lattner3082c5a2003-02-18 19:28:33 +00001736 // Check to see if this is an unsigned division with an exact power of 2,
1737 // if so, convert to a right shift.
1738 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
1739 if (uint64_t Val = C->getValue()) // Don't break X / 0
Chris Lattner22d00a82005-08-02 19:16:58 +00001740 if (isPowerOf2_64(Val)) {
1741 uint64_t C = Log2_64(Val);
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001742 return new ShiftInst(Instruction::Shr, Op0,
Chris Lattner3082c5a2003-02-18 19:28:33 +00001743 ConstantUInt::get(Type::UByteTy, C));
Chris Lattner22d00a82005-08-02 19:16:58 +00001744 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001745
Chris Lattner4ad08352004-10-09 02:50:40 +00001746 // -X/C -> X/-C
1747 if (RHS->getType()->isSigned())
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001748 if (Value *LHSNeg = dyn_castNegVal(Op0))
Chris Lattner4ad08352004-10-09 02:50:40 +00001749 return BinaryOperator::createDiv(LHSNeg, ConstantExpr::getNeg(RHS));
1750
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001751 if (!RHS->isNullValue()) {
1752 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00001753 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001754 return R;
1755 if (isa<PHINode>(Op0))
1756 if (Instruction *NV = FoldOpIntoPhi(I))
1757 return NV;
1758 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00001759 }
1760
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001761 // If this is 'udiv X, (Cond ? C1, C2)' where C1&C2 are powers of two,
1762 // transform this into: '(Cond ? (udiv X, C1) : (udiv X, C2))'.
1763 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1764 if (ConstantUInt *STO = dyn_cast<ConstantUInt>(SI->getOperand(1)))
1765 if (ConstantUInt *SFO = dyn_cast<ConstantUInt>(SI->getOperand(2))) {
1766 if (STO->getValue() == 0) { // Couldn't be this argument.
1767 I.setOperand(1, SFO);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001768 return &I;
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001769 } else if (SFO->getValue() == 0) {
Chris Lattner89dc4f12005-06-16 04:55:52 +00001770 I.setOperand(1, STO);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001771 return &I;
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001772 }
1773
Chris Lattner42362612005-04-08 04:03:26 +00001774 uint64_t TVA = STO->getValue(), FVA = SFO->getValue();
Chris Lattner22d00a82005-08-02 19:16:58 +00001775 if (isPowerOf2_64(TVA) && isPowerOf2_64(FVA)) {
1776 unsigned TSA = Log2_64(TVA), FSA = Log2_64(FVA);
Chris Lattner42362612005-04-08 04:03:26 +00001777 Constant *TC = ConstantUInt::get(Type::UByteTy, TSA);
1778 Instruction *TSI = new ShiftInst(Instruction::Shr, Op0,
1779 TC, SI->getName()+".t");
1780 TSI = InsertNewInstBefore(TSI, I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001781
Chris Lattner42362612005-04-08 04:03:26 +00001782 Constant *FC = ConstantUInt::get(Type::UByteTy, FSA);
1783 Instruction *FSI = new ShiftInst(Instruction::Shr, Op0,
1784 FC, SI->getName()+".f");
1785 FSI = InsertNewInstBefore(FSI, I);
1786 return new SelectInst(SI->getOperand(0), TSI, FSI);
1787 }
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001788 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001789
Chris Lattner3082c5a2003-02-18 19:28:33 +00001790 // 0 / X == 0, we don't need to preserve faults!
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001791 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattner3082c5a2003-02-18 19:28:33 +00001792 if (LHS->equalsInt(0))
1793 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1794
Chris Lattnerdd0c1742005-11-05 07:40:31 +00001795 if (I.getType()->isSigned()) {
Chris Lattnerc3ebf402006-02-07 07:27:52 +00001796 // If the sign bits of both operands are zero (i.e. we can prove they are
Chris Lattnerdd0c1742005-11-05 07:40:31 +00001797 // unsigned inputs), turn this into a udiv.
Chris Lattnerc3ebf402006-02-07 07:27:52 +00001798 uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
1799 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
Chris Lattnerdd0c1742005-11-05 07:40:31 +00001800 const Type *NTy = Op0->getType()->getUnsignedVersion();
1801 Instruction *LHS = new CastInst(Op0, NTy, Op0->getName());
1802 InsertNewInstBefore(LHS, I);
1803 Value *RHS;
1804 if (Constant *R = dyn_cast<Constant>(Op1))
1805 RHS = ConstantExpr::getCast(R, NTy);
1806 else
1807 RHS = InsertNewInstBefore(new CastInst(Op1, NTy, Op1->getName()), I);
1808 Instruction *Div = BinaryOperator::createDiv(LHS, RHS, I.getName());
1809 InsertNewInstBefore(Div, I);
1810 return new CastInst(Div, I.getType());
1811 }
Chris Lattner2e90b732006-02-05 07:54:04 +00001812 } else {
1813 // Known to be an unsigned division.
1814 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
1815 // Turn A / (C1 << N), where C1 is "1<<C2" into A >> (N+C2) [udiv only].
1816 if (RHSI->getOpcode() == Instruction::Shl &&
1817 isa<ConstantUInt>(RHSI->getOperand(0))) {
1818 unsigned C1 = cast<ConstantUInt>(RHSI->getOperand(0))->getRawValue();
1819 if (isPowerOf2_64(C1)) {
1820 unsigned C2 = Log2_64(C1);
1821 Value *Add = RHSI->getOperand(1);
1822 if (C2) {
1823 Constant *C2V = ConstantUInt::get(Add->getType(), C2);
1824 Add = InsertNewInstBefore(BinaryOperator::createAdd(Add, C2V,
1825 "tmp"), I);
1826 }
1827 return new ShiftInst(Instruction::Shr, Op0, Add);
1828 }
1829 }
1830 }
Chris Lattnerdd0c1742005-11-05 07:40:31 +00001831 }
1832
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001833 return 0;
1834}
1835
1836
Chris Lattner85dda9a2006-03-02 06:50:58 +00001837/// GetFactor - If we can prove that the specified value is at least a multiple
1838/// of some factor, return that factor.
1839static Constant *GetFactor(Value *V) {
1840 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
1841 return CI;
1842
1843 // Unless we can be tricky, we know this is a multiple of 1.
1844 Constant *Result = ConstantInt::get(V->getType(), 1);
1845
1846 Instruction *I = dyn_cast<Instruction>(V);
1847 if (!I) return Result;
1848
1849 if (I->getOpcode() == Instruction::Mul) {
1850 // Handle multiplies by a constant, etc.
1851 return ConstantExpr::getMul(GetFactor(I->getOperand(0)),
1852 GetFactor(I->getOperand(1)));
1853 } else if (I->getOpcode() == Instruction::Shl) {
1854 // (X<<C) -> X * (1 << C)
1855 if (Constant *ShRHS = dyn_cast<Constant>(I->getOperand(1))) {
1856 ShRHS = ConstantExpr::getShl(Result, ShRHS);
1857 return ConstantExpr::getMul(GetFactor(I->getOperand(0)), ShRHS);
1858 }
1859 } else if (I->getOpcode() == Instruction::And) {
1860 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1861 // X & 0xFFF0 is known to be a multiple of 16.
1862 unsigned Zeros = CountTrailingZeros_64(RHS->getZExtValue());
1863 if (Zeros != V->getType()->getPrimitiveSizeInBits())
1864 return ConstantExpr::getShl(Result,
1865 ConstantUInt::get(Type::UByteTy, Zeros));
1866 }
1867 } else if (I->getOpcode() == Instruction::Cast) {
1868 Value *Op = I->getOperand(0);
1869 // Only handle int->int casts.
1870 if (!Op->getType()->isInteger()) return Result;
1871 return ConstantExpr::getCast(GetFactor(Op), V->getType());
1872 }
1873 return Result;
1874}
1875
Chris Lattner113f4f42002-06-25 16:13:24 +00001876Instruction *InstCombiner::visitRem(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001877 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner0de4a8d2006-02-28 05:30:45 +00001878
1879 // 0 % X == 0, we don't need to preserve faults!
1880 if (Constant *LHS = dyn_cast<Constant>(Op0))
1881 if (LHS->isNullValue())
1882 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1883
1884 if (isa<UndefValue>(Op0)) // undef % X -> 0
1885 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1886 if (isa<UndefValue>(Op1))
1887 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
1888
Chris Lattnere9ff0ea2005-11-05 07:28:37 +00001889 if (I.getType()->isSigned()) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001890 if (Value *RHSNeg = dyn_castNegVal(Op1))
Chris Lattner98c6bdf2004-07-06 07:11:42 +00001891 if (!isa<ConstantSInt>(RHSNeg) ||
Chris Lattner8e726062004-08-09 21:05:48 +00001892 cast<ConstantSInt>(RHSNeg)->getValue() > 0) {
Chris Lattner7fd5f072004-07-06 07:01:22 +00001893 // X % -Y -> X % Y
1894 AddUsesToWorkList(I);
1895 I.setOperand(1, RHSNeg);
1896 return &I;
1897 }
Chris Lattnere9ff0ea2005-11-05 07:28:37 +00001898
1899 // If the top bits of both operands are zero (i.e. we can prove they are
1900 // unsigned inputs), turn this into a urem.
Chris Lattnerc3ebf402006-02-07 07:27:52 +00001901 uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
1902 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
Chris Lattnere9ff0ea2005-11-05 07:28:37 +00001903 const Type *NTy = Op0->getType()->getUnsignedVersion();
1904 Instruction *LHS = new CastInst(Op0, NTy, Op0->getName());
1905 InsertNewInstBefore(LHS, I);
1906 Value *RHS;
1907 if (Constant *R = dyn_cast<Constant>(Op1))
1908 RHS = ConstantExpr::getCast(R, NTy);
1909 else
1910 RHS = InsertNewInstBefore(new CastInst(Op1, NTy, Op1->getName()), I);
1911 Instruction *Rem = BinaryOperator::createRem(LHS, RHS, I.getName());
1912 InsertNewInstBefore(Rem, I);
1913 return new CastInst(Rem, I.getType());
1914 }
1915 }
Chris Lattner7fd5f072004-07-06 07:01:22 +00001916
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001917 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner0de4a8d2006-02-28 05:30:45 +00001918 // X % 0 == undef, we don't need to preserve faults!
1919 if (RHS->equalsInt(0))
1920 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
1921
Chris Lattner3082c5a2003-02-18 19:28:33 +00001922 if (RHS->equalsInt(1)) // X % 1 == 0
1923 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1924
1925 // Check to see if this is an unsigned remainder with an exact power of 2,
1926 // if so, convert to a bitwise and.
1927 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
Chris Lattner0de4a8d2006-02-28 05:30:45 +00001928 if (isPowerOf2_64(C->getValue()))
1929 return BinaryOperator::createAnd(Op0, SubOne(C));
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001930
Chris Lattnerb70f1412006-02-28 05:49:21 +00001931 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
1932 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
1933 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
1934 return R;
1935 } else if (isa<PHINode>(Op0I)) {
1936 if (Instruction *NV = FoldOpIntoPhi(I))
1937 return NV;
Chris Lattnerb70f1412006-02-28 05:49:21 +00001938 }
Chris Lattner85dda9a2006-03-02 06:50:58 +00001939
1940 // X*C1%C2 --> 0 iff C1%C2 == 0
1941 if (ConstantExpr::getRem(GetFactor(Op0I), RHS)->isNullValue())
1942 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerb70f1412006-02-28 05:49:21 +00001943 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00001944 }
1945
Chris Lattner2e90b732006-02-05 07:54:04 +00001946 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
1947 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1) [urem only].
1948 if (I.getType()->isUnsigned() &&
1949 RHSI->getOpcode() == Instruction::Shl &&
1950 isa<ConstantUInt>(RHSI->getOperand(0))) {
1951 unsigned C1 = cast<ConstantUInt>(RHSI->getOperand(0))->getRawValue();
1952 if (isPowerOf2_64(C1)) {
1953 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
1954 Value *Add = InsertNewInstBefore(BinaryOperator::createAdd(RHSI, N1,
1955 "tmp"), I);
1956 return BinaryOperator::createAnd(Op0, Add);
1957 }
1958 }
Chris Lattner0de4a8d2006-02-28 05:30:45 +00001959
1960 // If this is 'urem X, (Cond ? C1, C2)' where C1&C2 are powers of two,
1961 // transform this into: '(Cond ? (urem X, C1) : (urem X, C2))'.
1962 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1963 if (ConstantUInt *STO = dyn_cast<ConstantUInt>(SI->getOperand(1)))
1964 if (ConstantUInt *SFO = dyn_cast<ConstantUInt>(SI->getOperand(2))) {
1965 if (STO->getValue() == 0) { // Couldn't be this argument.
1966 I.setOperand(1, SFO);
1967 return &I;
1968 } else if (SFO->getValue() == 0) {
1969 I.setOperand(1, STO);
1970 return &I;
1971 }
1972
1973 if (isPowerOf2_64(STO->getValue()) && isPowerOf2_64(SFO->getValue())){
1974 Value *TrueAnd = InsertNewInstBefore(BinaryOperator::createAnd(Op0,
1975 SubOne(STO), SI->getName()+".t"), I);
1976 Value *FalseAnd = InsertNewInstBefore(BinaryOperator::createAnd(Op0,
1977 SubOne(SFO), SI->getName()+".f"), I);
1978 return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
1979 }
1980 }
Chris Lattner2e90b732006-02-05 07:54:04 +00001981 }
1982
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001983 return 0;
1984}
1985
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001986// isMaxValueMinusOne - return true if this is Max-1
Chris Lattnere6794492002-08-12 21:17:25 +00001987static bool isMaxValueMinusOne(const ConstantInt *C) {
Chris Lattner77defba2006-02-07 07:00:41 +00001988 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
1989 return CU->getValue() == C->getType()->getIntegralTypeMask()-1;
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001990
1991 const ConstantSInt *CS = cast<ConstantSInt>(C);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001992
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001993 // Calculate 0111111111..11111
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001994 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001995 int64_t Val = INT64_MAX; // All ones
1996 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
1997 return CS->getValue() == Val-1;
1998}
1999
2000// isMinValuePlusOne - return true if this is Min+1
Chris Lattnere6794492002-08-12 21:17:25 +00002001static bool isMinValuePlusOne(const ConstantInt *C) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002002 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
2003 return CU->getValue() == 1;
2004
2005 const ConstantSInt *CS = cast<ConstantSInt>(C);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002006
2007 // Calculate 1111111111000000000000
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002008 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002009 int64_t Val = -1; // All ones
2010 Val <<= TypeBits-1; // Shift over to the right spot
2011 return CS->getValue() == Val+1;
2012}
2013
Chris Lattner35167c32004-06-09 07:59:58 +00002014// isOneBitSet - Return true if there is exactly one bit set in the specified
2015// constant.
2016static bool isOneBitSet(const ConstantInt *CI) {
2017 uint64_t V = CI->getRawValue();
2018 return V && (V & (V-1)) == 0;
2019}
2020
Chris Lattner8fc5af42004-09-23 21:46:38 +00002021#if 0 // Currently unused
2022// isLowOnes - Return true if the constant is of the form 0+1+.
2023static bool isLowOnes(const ConstantInt *CI) {
2024 uint64_t V = CI->getRawValue();
2025
2026 // There won't be bits set in parts that the type doesn't contain.
2027 V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
2028
2029 uint64_t U = V+1; // If it is low ones, this should be a power of two.
2030 return U && V && (U & V) == 0;
2031}
2032#endif
2033
2034// isHighOnes - Return true if the constant is of the form 1+0+.
2035// This is the same as lowones(~X).
2036static bool isHighOnes(const ConstantInt *CI) {
2037 uint64_t V = ~CI->getRawValue();
Chris Lattner2c14cf72005-08-07 07:03:10 +00002038 if (~V == 0) return false; // 0's does not match "1+"
Chris Lattner8fc5af42004-09-23 21:46:38 +00002039
2040 // There won't be bits set in parts that the type doesn't contain.
2041 V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
2042
2043 uint64_t U = V+1; // If it is low ones, this should be a power of two.
2044 return U && V && (U & V) == 0;
2045}
2046
2047
Chris Lattner3ac7c262003-08-13 20:16:26 +00002048/// getSetCondCode - Encode a setcc opcode into a three bit mask. These bits
2049/// are carefully arranged to allow folding of expressions such as:
2050///
2051/// (A < B) | (A > B) --> (A != B)
2052///
2053/// Bit value '4' represents that the comparison is true if A > B, bit value '2'
2054/// represents that the comparison is true if A == B, and bit value '1' is true
2055/// if A < B.
2056///
2057static unsigned getSetCondCode(const SetCondInst *SCI) {
2058 switch (SCI->getOpcode()) {
2059 // False -> 0
2060 case Instruction::SetGT: return 1;
2061 case Instruction::SetEQ: return 2;
2062 case Instruction::SetGE: return 3;
2063 case Instruction::SetLT: return 4;
2064 case Instruction::SetNE: return 5;
2065 case Instruction::SetLE: return 6;
2066 // True -> 7
2067 default:
2068 assert(0 && "Invalid SetCC opcode!");
2069 return 0;
2070 }
2071}
2072
2073/// getSetCCValue - This is the complement of getSetCondCode, which turns an
2074/// opcode and two operands into either a constant true or false, or a brand new
2075/// SetCC instruction.
2076static Value *getSetCCValue(unsigned Opcode, Value *LHS, Value *RHS) {
2077 switch (Opcode) {
2078 case 0: return ConstantBool::False;
2079 case 1: return new SetCondInst(Instruction::SetGT, LHS, RHS);
2080 case 2: return new SetCondInst(Instruction::SetEQ, LHS, RHS);
2081 case 3: return new SetCondInst(Instruction::SetGE, LHS, RHS);
2082 case 4: return new SetCondInst(Instruction::SetLT, LHS, RHS);
2083 case 5: return new SetCondInst(Instruction::SetNE, LHS, RHS);
2084 case 6: return new SetCondInst(Instruction::SetLE, LHS, RHS);
2085 case 7: return ConstantBool::True;
2086 default: assert(0 && "Illegal SetCCCode!"); return 0;
2087 }
2088}
2089
2090// FoldSetCCLogical - Implements (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
2091struct FoldSetCCLogical {
2092 InstCombiner &IC;
2093 Value *LHS, *RHS;
2094 FoldSetCCLogical(InstCombiner &ic, SetCondInst *SCI)
2095 : IC(ic), LHS(SCI->getOperand(0)), RHS(SCI->getOperand(1)) {}
2096 bool shouldApply(Value *V) const {
2097 if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
2098 return (SCI->getOperand(0) == LHS && SCI->getOperand(1) == RHS ||
2099 SCI->getOperand(0) == RHS && SCI->getOperand(1) == LHS);
2100 return false;
2101 }
2102 Instruction *apply(BinaryOperator &Log) const {
2103 SetCondInst *SCI = cast<SetCondInst>(Log.getOperand(0));
2104 if (SCI->getOperand(0) != LHS) {
2105 assert(SCI->getOperand(1) == LHS);
2106 SCI->swapOperands(); // Swap the LHS and RHS of the SetCC
2107 }
2108
2109 unsigned LHSCode = getSetCondCode(SCI);
2110 unsigned RHSCode = getSetCondCode(cast<SetCondInst>(Log.getOperand(1)));
2111 unsigned Code;
2112 switch (Log.getOpcode()) {
2113 case Instruction::And: Code = LHSCode & RHSCode; break;
2114 case Instruction::Or: Code = LHSCode | RHSCode; break;
2115 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner2caaaba2003-09-22 20:33:34 +00002116 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattner3ac7c262003-08-13 20:16:26 +00002117 }
2118
2119 Value *RV = getSetCCValue(Code, LHS, RHS);
2120 if (Instruction *I = dyn_cast<Instruction>(RV))
2121 return I;
2122 // Otherwise, it's a constant boolean value...
2123 return IC.ReplaceInstUsesWith(Log, RV);
2124 }
2125};
2126
Chris Lattnerba1cb382003-09-19 17:17:26 +00002127// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
2128// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
2129// guaranteed to be either a shift instruction or a binary operator.
2130Instruction *InstCombiner::OptAndOp(Instruction *Op,
2131 ConstantIntegral *OpRHS,
2132 ConstantIntegral *AndRHS,
2133 BinaryOperator &TheAnd) {
2134 Value *X = Op->getOperand(0);
Chris Lattnerfcf21a72004-01-12 19:47:05 +00002135 Constant *Together = 0;
2136 if (!isa<ShiftInst>(Op))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002137 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002138
Chris Lattnerba1cb382003-09-19 17:17:26 +00002139 switch (Op->getOpcode()) {
2140 case Instruction::Xor:
Chris Lattner86102b82005-01-01 16:22:27 +00002141 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00002142 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
2143 std::string OpName = Op->getName(); Op->setName("");
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002144 Instruction *And = BinaryOperator::createAnd(X, AndRHS, OpName);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002145 InsertNewInstBefore(And, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002146 return BinaryOperator::createXor(And, Together);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002147 }
2148 break;
2149 case Instruction::Or:
Chris Lattner86102b82005-01-01 16:22:27 +00002150 if (Together == AndRHS) // (X | C) & C --> C
2151 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002152
Chris Lattner86102b82005-01-01 16:22:27 +00002153 if (Op->hasOneUse() && Together != OpRHS) {
2154 // (X | C1) & C2 --> (X | (C1&C2)) & C2
2155 std::string Op0Name = Op->getName(); Op->setName("");
2156 Instruction *Or = BinaryOperator::createOr(X, Together, Op0Name);
2157 InsertNewInstBefore(Or, TheAnd);
2158 return BinaryOperator::createAnd(Or, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002159 }
2160 break;
2161 case Instruction::Add:
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002162 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00002163 // Adding a one to a single bit bit-field should be turned into an XOR
2164 // of the bit. First thing to check is to see if this AND is with a
2165 // single bit constant.
Chris Lattner35167c32004-06-09 07:59:58 +00002166 uint64_t AndRHSV = cast<ConstantInt>(AndRHS)->getRawValue();
Chris Lattnerba1cb382003-09-19 17:17:26 +00002167
2168 // Clear bits that are not part of the constant.
Chris Lattner77defba2006-02-07 07:00:41 +00002169 AndRHSV &= AndRHS->getType()->getIntegralTypeMask();
Chris Lattnerba1cb382003-09-19 17:17:26 +00002170
2171 // If there is only one bit set...
Chris Lattner35167c32004-06-09 07:59:58 +00002172 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00002173 // Ok, at this point, we know that we are masking the result of the
2174 // ADD down to exactly one bit. If the constant we are adding has
2175 // no bits set below this bit, then we can eliminate the ADD.
Chris Lattner35167c32004-06-09 07:59:58 +00002176 uint64_t AddRHS = cast<ConstantInt>(OpRHS)->getRawValue();
Misha Brukmanb1c93172005-04-21 23:48:37 +00002177
Chris Lattnerba1cb382003-09-19 17:17:26 +00002178 // Check to see if any bits below the one bit set in AndRHSV are set.
2179 if ((AddRHS & (AndRHSV-1)) == 0) {
2180 // If not, the only thing that can effect the output of the AND is
2181 // the bit specified by AndRHSV. If that bit is set, the effect of
2182 // the XOR is to toggle the bit. If it is clear, then the ADD has
2183 // no effect.
2184 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
2185 TheAnd.setOperand(0, X);
2186 return &TheAnd;
2187 } else {
2188 std::string Name = Op->getName(); Op->setName("");
2189 // Pull the XOR out of the AND.
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002190 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS, Name);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002191 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002192 return BinaryOperator::createXor(NewAnd, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002193 }
2194 }
2195 }
2196 }
2197 break;
Chris Lattner2da29172003-09-19 19:05:02 +00002198
2199 case Instruction::Shl: {
2200 // We know that the AND will not produce any of the bits shifted in, so if
2201 // the anded constant includes them, clear them now!
2202 //
2203 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner7e794272004-09-24 15:21:34 +00002204 Constant *ShlMask = ConstantExpr::getShl(AllOne, OpRHS);
2205 Constant *CI = ConstantExpr::getAnd(AndRHS, ShlMask);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002206
Chris Lattner7e794272004-09-24 15:21:34 +00002207 if (CI == ShlMask) { // Masking out bits that the shift already masks
2208 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
2209 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner2da29172003-09-19 19:05:02 +00002210 TheAnd.setOperand(1, CI);
2211 return &TheAnd;
2212 }
2213 break;
Misha Brukmanb1c93172005-04-21 23:48:37 +00002214 }
Chris Lattner2da29172003-09-19 19:05:02 +00002215 case Instruction::Shr:
2216 // We know that the AND will not produce any of the bits shifted in, so if
2217 // the anded constant includes them, clear them now! This only applies to
2218 // unsigned shifts, because a signed shr may bring in set bits!
2219 //
2220 if (AndRHS->getType()->isUnsigned()) {
2221 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner7e794272004-09-24 15:21:34 +00002222 Constant *ShrMask = ConstantExpr::getShr(AllOne, OpRHS);
2223 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
2224
2225 if (CI == ShrMask) { // Masking out bits that the shift already masks.
2226 return ReplaceInstUsesWith(TheAnd, Op);
2227 } else if (CI != AndRHS) {
2228 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
Chris Lattner2da29172003-09-19 19:05:02 +00002229 return &TheAnd;
2230 }
Chris Lattner7e794272004-09-24 15:21:34 +00002231 } else { // Signed shr.
2232 // See if this is shifting in some sign extension, then masking it out
2233 // with an and.
2234 if (Op->hasOneUse()) {
2235 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
2236 Constant *ShrMask = ConstantExpr::getUShr(AllOne, OpRHS);
2237 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
Chris Lattner5c3c21e2004-10-22 04:53:16 +00002238 if (CI == AndRHS) { // Masking out bits shifted in.
Chris Lattner7e794272004-09-24 15:21:34 +00002239 // Make the argument unsigned.
2240 Value *ShVal = Op->getOperand(0);
2241 ShVal = InsertCastBefore(ShVal,
2242 ShVal->getType()->getUnsignedVersion(),
2243 TheAnd);
2244 ShVal = InsertNewInstBefore(new ShiftInst(Instruction::Shr, ShVal,
2245 OpRHS, Op->getName()),
2246 TheAnd);
Chris Lattner70c20392004-10-27 05:57:15 +00002247 Value *AndRHS2 = ConstantExpr::getCast(AndRHS, ShVal->getType());
2248 ShVal = InsertNewInstBefore(BinaryOperator::createAnd(ShVal, AndRHS2,
2249 TheAnd.getName()),
2250 TheAnd);
Chris Lattner7e794272004-09-24 15:21:34 +00002251 return new CastInst(ShVal, Op->getType());
2252 }
2253 }
Chris Lattner2da29172003-09-19 19:05:02 +00002254 }
2255 break;
Chris Lattnerba1cb382003-09-19 17:17:26 +00002256 }
2257 return 0;
2258}
2259
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002260
Chris Lattner6862fbd2004-09-29 17:40:11 +00002261/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
2262/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
2263/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. IB is the location to
2264/// insert new instructions.
2265Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
2266 bool Inside, Instruction &IB) {
2267 assert(cast<ConstantBool>(ConstantExpr::getSetLE(Lo, Hi))->getValue() &&
2268 "Lo is not <= Hi in range emission code!");
2269 if (Inside) {
2270 if (Lo == Hi) // Trivially false.
2271 return new SetCondInst(Instruction::SetNE, V, V);
2272 if (cast<ConstantIntegral>(Lo)->isMinValue())
2273 return new SetCondInst(Instruction::SetLT, V, Hi);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002274
Chris Lattner6862fbd2004-09-29 17:40:11 +00002275 Constant *AddCST = ConstantExpr::getNeg(Lo);
2276 Instruction *Add = BinaryOperator::createAdd(V, AddCST,V->getName()+".off");
2277 InsertNewInstBefore(Add, IB);
2278 // Convert to unsigned for the comparison.
2279 const Type *UnsType = Add->getType()->getUnsignedVersion();
2280 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
2281 AddCST = ConstantExpr::getAdd(AddCST, Hi);
2282 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2283 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
2284 }
2285
2286 if (Lo == Hi) // Trivially true.
2287 return new SetCondInst(Instruction::SetEQ, V, V);
2288
2289 Hi = SubOne(cast<ConstantInt>(Hi));
2290 if (cast<ConstantIntegral>(Lo)->isMinValue()) // V < 0 || V >= Hi ->'V > Hi-1'
2291 return new SetCondInst(Instruction::SetGT, V, Hi);
2292
2293 // Emit X-Lo > Hi-Lo-1
2294 Constant *AddCST = ConstantExpr::getNeg(Lo);
2295 Instruction *Add = BinaryOperator::createAdd(V, AddCST, V->getName()+".off");
2296 InsertNewInstBefore(Add, IB);
2297 // Convert to unsigned for the comparison.
2298 const Type *UnsType = Add->getType()->getUnsignedVersion();
2299 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
2300 AddCST = ConstantExpr::getAdd(AddCST, Hi);
2301 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2302 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
2303}
2304
Chris Lattnerb4b25302005-09-18 07:22:02 +00002305// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
2306// any number of 0s on either side. The 1s are allowed to wrap from LSB to
2307// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
2308// not, since all 1s are not contiguous.
2309static bool isRunOfOnes(ConstantIntegral *Val, unsigned &MB, unsigned &ME) {
2310 uint64_t V = Val->getRawValue();
2311 if (!isShiftedMask_64(V)) return false;
2312
2313 // look for the first zero bit after the run of ones
2314 MB = 64-CountLeadingZeros_64((V - 1) ^ V);
2315 // look for the first non-zero bit
2316 ME = 64-CountLeadingZeros_64(V);
2317 return true;
2318}
2319
2320
2321
2322/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
2323/// where isSub determines whether the operator is a sub. If we can fold one of
2324/// the following xforms:
Chris Lattneraf517572005-09-18 04:24:45 +00002325///
2326/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
2327/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
2328/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
2329///
2330/// return (A +/- B).
2331///
2332Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
2333 ConstantIntegral *Mask, bool isSub,
2334 Instruction &I) {
2335 Instruction *LHSI = dyn_cast<Instruction>(LHS);
2336 if (!LHSI || LHSI->getNumOperands() != 2 ||
2337 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
2338
2339 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
2340
2341 switch (LHSI->getOpcode()) {
2342 default: return 0;
2343 case Instruction::And:
Chris Lattnerb4b25302005-09-18 07:22:02 +00002344 if (ConstantExpr::getAnd(N, Mask) == Mask) {
2345 // If the AndRHS is a power of two minus one (0+1+), this is simple.
2346 if ((Mask->getRawValue() & Mask->getRawValue()+1) == 0)
2347 break;
2348
2349 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
2350 // part, we don't need any explicit masks to take them out of A. If that
2351 // is all N is, ignore it.
2352 unsigned MB, ME;
2353 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Chris Lattnerc3ebf402006-02-07 07:27:52 +00002354 uint64_t Mask = RHS->getType()->getIntegralTypeMask();
2355 Mask >>= 64-MB+1;
2356 if (MaskedValueIsZero(RHS, Mask))
Chris Lattnerb4b25302005-09-18 07:22:02 +00002357 break;
2358 }
2359 }
Chris Lattneraf517572005-09-18 04:24:45 +00002360 return 0;
2361 case Instruction::Or:
2362 case Instruction::Xor:
Chris Lattnerb4b25302005-09-18 07:22:02 +00002363 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
2364 if ((Mask->getRawValue() & Mask->getRawValue()+1) == 0 &&
2365 ConstantExpr::getAnd(N, Mask)->isNullValue())
Chris Lattneraf517572005-09-18 04:24:45 +00002366 break;
2367 return 0;
2368 }
2369
2370 Instruction *New;
2371 if (isSub)
2372 New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
2373 else
2374 New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
2375 return InsertNewInstBefore(New, I);
2376}
2377
Chris Lattner113f4f42002-06-25 16:13:24 +00002378Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00002379 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00002380 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002381
Chris Lattner81a7a232004-10-16 18:11:37 +00002382 if (isa<UndefValue>(Op1)) // X & undef -> 0
2383 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2384
Chris Lattner86102b82005-01-01 16:22:27 +00002385 // and X, X = X
2386 if (Op0 == Op1)
Chris Lattnere6794492002-08-12 21:17:25 +00002387 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002388
Chris Lattner5b2edb12006-02-12 08:02:11 +00002389 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner5997cf92006-02-08 03:25:32 +00002390 // purpose is to compute bits we don't care about.
Chris Lattner0157e7f2006-02-11 09:31:47 +00002391 uint64_t KnownZero, KnownOne;
Chris Lattnerd70d9f52006-03-25 21:58:26 +00002392 if (!isa<PackedType>(I.getType()) &&
2393 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
Chris Lattner0157e7f2006-02-11 09:31:47 +00002394 KnownZero, KnownOne))
Chris Lattner5997cf92006-02-08 03:25:32 +00002395 return &I;
2396
Chris Lattner86102b82005-01-01 16:22:27 +00002397 if (ConstantIntegral *AndRHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00002398 uint64_t AndRHSMask = AndRHS->getZExtValue();
2399 uint64_t TypeMask = Op0->getType()->getIntegralTypeMask();
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00002400 uint64_t NotAndRHS = AndRHSMask^TypeMask;
Chris Lattner86102b82005-01-01 16:22:27 +00002401
Chris Lattnerba1cb382003-09-19 17:17:26 +00002402 // Optimize a variety of ((val OP C1) & C2) combinations...
2403 if (isa<BinaryOperator>(Op0) || isa<ShiftInst>(Op0)) {
2404 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner86102b82005-01-01 16:22:27 +00002405 Value *Op0LHS = Op0I->getOperand(0);
2406 Value *Op0RHS = Op0I->getOperand(1);
2407 switch (Op0I->getOpcode()) {
2408 case Instruction::Xor:
2409 case Instruction::Or:
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00002410 // If the mask is only needed on one incoming arm, push it up.
2411 if (Op0I->hasOneUse()) {
2412 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
2413 // Not masking anything out for the LHS, move to RHS.
2414 Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
2415 Op0RHS->getName()+".masked");
2416 InsertNewInstBefore(NewRHS, I);
2417 return BinaryOperator::create(
2418 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002419 }
Chris Lattnerc3ebf402006-02-07 07:27:52 +00002420 if (!isa<Constant>(Op0RHS) &&
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00002421 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
2422 // Not masking anything out for the RHS, move to LHS.
2423 Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
2424 Op0LHS->getName()+".masked");
2425 InsertNewInstBefore(NewLHS, I);
2426 return BinaryOperator::create(
2427 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
2428 }
2429 }
2430
Chris Lattner86102b82005-01-01 16:22:27 +00002431 break;
Chris Lattneraf517572005-09-18 04:24:45 +00002432 case Instruction::Add:
Chris Lattnerb4b25302005-09-18 07:22:02 +00002433 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
2434 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
2435 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
2436 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
2437 return BinaryOperator::createAnd(V, AndRHS);
2438 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
2439 return BinaryOperator::createAnd(V, AndRHS); // Add commutes
Chris Lattneraf517572005-09-18 04:24:45 +00002440 break;
2441
2442 case Instruction::Sub:
Chris Lattnerb4b25302005-09-18 07:22:02 +00002443 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
2444 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
2445 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
2446 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
2447 return BinaryOperator::createAnd(V, AndRHS);
Chris Lattneraf517572005-09-18 04:24:45 +00002448 break;
Chris Lattner86102b82005-01-01 16:22:27 +00002449 }
2450
Chris Lattner16464b32003-07-23 19:25:52 +00002451 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner86102b82005-01-01 16:22:27 +00002452 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerba1cb382003-09-19 17:17:26 +00002453 return Res;
Chris Lattner86102b82005-01-01 16:22:27 +00002454 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
2455 const Type *SrcTy = CI->getOperand(0)->getType();
2456
Chris Lattner2c14cf72005-08-07 07:03:10 +00002457 // If this is an integer truncation or change from signed-to-unsigned, and
2458 // if the source is an and/or with immediate, transform it. This
2459 // frequently occurs for bitfield accesses.
2460 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
2461 if (SrcTy->getPrimitiveSizeInBits() >=
2462 I.getType()->getPrimitiveSizeInBits() &&
2463 CastOp->getNumOperands() == 2)
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00002464 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1)))
Chris Lattner2c14cf72005-08-07 07:03:10 +00002465 if (CastOp->getOpcode() == Instruction::And) {
2466 // Change: and (cast (and X, C1) to T), C2
2467 // into : and (cast X to T), trunc(C1)&C2
2468 // This will folds the two ands together, which may allow other
2469 // simplifications.
2470 Instruction *NewCast =
2471 new CastInst(CastOp->getOperand(0), I.getType(),
2472 CastOp->getName()+".shrunk");
2473 NewCast = InsertNewInstBefore(NewCast, I);
2474
2475 Constant *C3=ConstantExpr::getCast(AndCI, I.getType());//trunc(C1)
2476 C3 = ConstantExpr::getAnd(C3, AndRHS); // trunc(C1)&C2
2477 return BinaryOperator::createAnd(NewCast, C3);
2478 } else if (CastOp->getOpcode() == Instruction::Or) {
2479 // Change: and (cast (or X, C1) to T), C2
2480 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
2481 Constant *C3=ConstantExpr::getCast(AndCI, I.getType());//trunc(C1)
2482 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
2483 return ReplaceInstUsesWith(I, AndRHS);
2484 }
2485 }
Chris Lattner33217db2003-07-23 19:36:21 +00002486 }
Chris Lattner183b3362004-04-09 19:05:30 +00002487
2488 // Try to fold constant and into select arguments.
2489 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00002490 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00002491 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002492 if (isa<PHINode>(Op0))
2493 if (Instruction *NV = FoldOpIntoPhi(I))
2494 return NV;
Chris Lattner49b47ae2003-07-23 17:57:01 +00002495 }
2496
Chris Lattnerbb74e222003-03-10 23:06:50 +00002497 Value *Op0NotVal = dyn_castNotVal(Op0);
2498 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002499
Chris Lattner023a4832004-06-18 06:07:51 +00002500 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
2501 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2502
Misha Brukman9c003d82004-07-30 12:50:08 +00002503 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattnerbb74e222003-03-10 23:06:50 +00002504 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002505 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
2506 I.getName()+".demorgan");
Chris Lattner49b47ae2003-07-23 17:57:01 +00002507 InsertNewInstBefore(Or, I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002508 return BinaryOperator::createNot(Or);
2509 }
Chris Lattner8b10ab32006-02-13 23:07:23 +00002510
2511 {
2512 Value *A = 0, *B = 0;
2513 ConstantInt *C1 = 0, *C2 = 0;
2514 if (match(Op0, m_Or(m_Value(A), m_Value(B))))
2515 if (A == Op1 || B == Op1) // (A | ?) & A --> A
2516 return ReplaceInstUsesWith(I, Op1);
2517 if (match(Op1, m_Or(m_Value(A), m_Value(B))))
2518 if (A == Op0 || B == Op0) // A & (A | ?) --> A
2519 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerdcd07922006-04-01 08:03:55 +00002520
2521 if (Op0->hasOneUse() &&
2522 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
2523 if (A == Op1) { // (A^B)&A -> A&(A^B)
2524 I.swapOperands(); // Simplify below
2525 std::swap(Op0, Op1);
2526 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
2527 cast<BinaryOperator>(Op0)->swapOperands();
2528 I.swapOperands(); // Simplify below
2529 std::swap(Op0, Op1);
2530 }
2531 }
2532 if (Op1->hasOneUse() &&
2533 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
2534 if (B == Op0) { // B&(A^B) -> B&(B^A)
2535 cast<BinaryOperator>(Op1)->swapOperands();
2536 std::swap(A, B);
2537 }
2538 if (A == Op0) { // A&(A^B) -> A & ~B
2539 Instruction *NotB = BinaryOperator::createNot(B, "tmp");
2540 InsertNewInstBefore(NotB, I);
2541 return BinaryOperator::createAnd(A, NotB);
2542 }
2543 }
Chris Lattner8b10ab32006-02-13 23:07:23 +00002544 }
2545
Chris Lattner3082c5a2003-02-18 19:28:33 +00002546
Chris Lattner623826c2004-09-28 21:48:02 +00002547 if (SetCondInst *RHS = dyn_cast<SetCondInst>(Op1)) {
2548 // (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
Chris Lattner3ac7c262003-08-13 20:16:26 +00002549 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
2550 return R;
2551
Chris Lattner623826c2004-09-28 21:48:02 +00002552 Value *LHSVal, *RHSVal;
2553 ConstantInt *LHSCst, *RHSCst;
2554 Instruction::BinaryOps LHSCC, RHSCC;
2555 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
2556 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
2557 if (LHSVal == RHSVal && // Found (X setcc C1) & (X setcc C2)
2558 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
Misha Brukmanb1c93172005-04-21 23:48:37 +00002559 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
Chris Lattner623826c2004-09-28 21:48:02 +00002560 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
2561 // Ensure that the larger constant is on the RHS.
2562 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
2563 SetCondInst *LHS = cast<SetCondInst>(Op0);
2564 if (cast<ConstantBool>(Cmp)->getValue()) {
2565 std::swap(LHS, RHS);
2566 std::swap(LHSCst, RHSCst);
2567 std::swap(LHSCC, RHSCC);
2568 }
2569
2570 // At this point, we know we have have two setcc instructions
2571 // comparing a value against two constants and and'ing the result
2572 // together. Because of the above check, we know that we only have
2573 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
2574 // FoldSetCCLogical check above), that the two constants are not
2575 // equal.
2576 assert(LHSCst != RHSCst && "Compares not folded above?");
2577
2578 switch (LHSCC) {
2579 default: assert(0 && "Unknown integer condition code!");
2580 case Instruction::SetEQ:
2581 switch (RHSCC) {
2582 default: assert(0 && "Unknown integer condition code!");
2583 case Instruction::SetEQ: // (X == 13 & X == 15) -> false
2584 case Instruction::SetGT: // (X == 13 & X > 15) -> false
2585 return ReplaceInstUsesWith(I, ConstantBool::False);
2586 case Instruction::SetNE: // (X == 13 & X != 15) -> X == 13
2587 case Instruction::SetLT: // (X == 13 & X < 15) -> X == 13
2588 return ReplaceInstUsesWith(I, LHS);
2589 }
2590 case Instruction::SetNE:
2591 switch (RHSCC) {
2592 default: assert(0 && "Unknown integer condition code!");
2593 case Instruction::SetLT:
2594 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X < 14) -> X < 13
2595 return new SetCondInst(Instruction::SetLT, LHSVal, LHSCst);
2596 break; // (X != 13 & X < 15) -> no change
2597 case Instruction::SetEQ: // (X != 13 & X == 15) -> X == 15
2598 case Instruction::SetGT: // (X != 13 & X > 15) -> X > 15
2599 return ReplaceInstUsesWith(I, RHS);
2600 case Instruction::SetNE:
2601 if (LHSCst == SubOne(RHSCst)) {// (X != 13 & X != 14) -> X-13 >u 1
2602 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
2603 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
2604 LHSVal->getName()+".off");
2605 InsertNewInstBefore(Add, I);
2606 const Type *UnsType = Add->getType()->getUnsignedVersion();
2607 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
2608 AddCST = ConstantExpr::getSub(RHSCst, LHSCst);
2609 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2610 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
2611 }
2612 break; // (X != 13 & X != 15) -> no change
2613 }
2614 break;
2615 case Instruction::SetLT:
2616 switch (RHSCC) {
2617 default: assert(0 && "Unknown integer condition code!");
2618 case Instruction::SetEQ: // (X < 13 & X == 15) -> false
2619 case Instruction::SetGT: // (X < 13 & X > 15) -> false
2620 return ReplaceInstUsesWith(I, ConstantBool::False);
2621 case Instruction::SetNE: // (X < 13 & X != 15) -> X < 13
2622 case Instruction::SetLT: // (X < 13 & X < 15) -> X < 13
2623 return ReplaceInstUsesWith(I, LHS);
2624 }
2625 case Instruction::SetGT:
2626 switch (RHSCC) {
2627 default: assert(0 && "Unknown integer condition code!");
2628 case Instruction::SetEQ: // (X > 13 & X == 15) -> X > 13
2629 return ReplaceInstUsesWith(I, LHS);
2630 case Instruction::SetGT: // (X > 13 & X > 15) -> X > 15
2631 return ReplaceInstUsesWith(I, RHS);
2632 case Instruction::SetNE:
2633 if (RHSCst == AddOne(LHSCst)) // (X > 13 & X != 14) -> X > 14
2634 return new SetCondInst(Instruction::SetGT, LHSVal, RHSCst);
2635 break; // (X > 13 & X != 15) -> no change
Chris Lattner6862fbd2004-09-29 17:40:11 +00002636 case Instruction::SetLT: // (X > 13 & X < 15) -> (X-14) <u 1
2637 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true, I);
Chris Lattner623826c2004-09-28 21:48:02 +00002638 }
2639 }
2640 }
2641 }
2642
Chris Lattner3af10532006-05-05 06:39:07 +00002643 // fold (and (cast A), (cast B)) -> (cast (and A, B))
2644 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
2645 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
2646 if (Op0C->getOperand(0)->getType() == Op1C->getOperand(0)->getType() &&
2647 Op0C->getOperand(0)->getType()->isIntegral()) {
2648 Instruction *NewOp = BinaryOperator::createAnd(Op0C->getOperand(0),
2649 Op1C->getOperand(0),
2650 I.getName());
2651 InsertNewInstBefore(NewOp, I);
2652 return new CastInst(NewOp, I.getType());
2653 }
2654 }
2655
Chris Lattner113f4f42002-06-25 16:13:24 +00002656 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002657}
2658
Chris Lattner113f4f42002-06-25 16:13:24 +00002659Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00002660 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00002661 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002662
Chris Lattner81a7a232004-10-16 18:11:37 +00002663 if (isa<UndefValue>(Op1))
2664 return ReplaceInstUsesWith(I, // X | undef -> -1
2665 ConstantIntegral::getAllOnesValue(I.getType()));
2666
Chris Lattner5b2edb12006-02-12 08:02:11 +00002667 // or X, X = X
2668 if (Op0 == Op1)
Chris Lattnere6794492002-08-12 21:17:25 +00002669 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002670
Chris Lattner5b2edb12006-02-12 08:02:11 +00002671 // See if we can simplify any instructions used by the instruction whose sole
2672 // purpose is to compute bits we don't care about.
2673 uint64_t KnownZero, KnownOne;
Chris Lattnerd70d9f52006-03-25 21:58:26 +00002674 if (!isa<PackedType>(I.getType()) &&
2675 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
Chris Lattner5b2edb12006-02-12 08:02:11 +00002676 KnownZero, KnownOne))
2677 return &I;
2678
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002679 // or X, -1 == -1
Chris Lattner8f0d1562003-07-23 18:29:44 +00002680 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner330628a2006-01-06 17:59:59 +00002681 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00002682 // (X & C1) | C2 --> (X | C2) & (C1|C2)
2683 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Chris Lattnerb62f5082005-05-09 04:58:36 +00002684 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0->getName());
2685 Op0->setName("");
Chris Lattnerd4252a72004-07-30 07:50:03 +00002686 InsertNewInstBefore(Or, I);
2687 return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, C1));
2688 }
Chris Lattner8f0d1562003-07-23 18:29:44 +00002689
Chris Lattnerd4252a72004-07-30 07:50:03 +00002690 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
2691 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
2692 std::string Op0Name = Op0->getName(); Op0->setName("");
2693 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
2694 InsertNewInstBefore(Or, I);
2695 return BinaryOperator::createXor(Or,
2696 ConstantExpr::getAnd(C1, ConstantExpr::getNot(RHS)));
Chris Lattner8f0d1562003-07-23 18:29:44 +00002697 }
Chris Lattner183b3362004-04-09 19:05:30 +00002698
2699 // Try to fold constant and into select arguments.
2700 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00002701 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00002702 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002703 if (isa<PHINode>(Op0))
2704 if (Instruction *NV = FoldOpIntoPhi(I))
2705 return NV;
Chris Lattner8f0d1562003-07-23 18:29:44 +00002706 }
2707
Chris Lattner330628a2006-01-06 17:59:59 +00002708 Value *A = 0, *B = 0;
2709 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattner4294cec2005-05-07 23:49:08 +00002710
2711 if (match(Op0, m_And(m_Value(A), m_Value(B))))
2712 if (A == Op1 || B == Op1) // (A & ?) | A --> A
2713 return ReplaceInstUsesWith(I, Op1);
2714 if (match(Op1, m_And(m_Value(A), m_Value(B))))
2715 if (A == Op0 || B == Op0) // A | (A & ?) --> A
2716 return ReplaceInstUsesWith(I, Op0);
2717
Chris Lattnerb62f5082005-05-09 04:58:36 +00002718 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
2719 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattnerc3ebf402006-02-07 07:27:52 +00002720 MaskedValueIsZero(Op1, C1->getZExtValue())) {
Chris Lattnerb62f5082005-05-09 04:58:36 +00002721 Instruction *NOr = BinaryOperator::createOr(A, Op1, Op0->getName());
2722 Op0->setName("");
2723 return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
2724 }
2725
2726 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
2727 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattnerc3ebf402006-02-07 07:27:52 +00002728 MaskedValueIsZero(Op0, C1->getZExtValue())) {
Chris Lattnerb62f5082005-05-09 04:58:36 +00002729 Instruction *NOr = BinaryOperator::createOr(A, Op0, Op1->getName());
2730 Op0->setName("");
2731 return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
2732 }
2733
Chris Lattner15212982005-09-18 03:42:07 +00002734 // (A & C1)|(B & C2)
Chris Lattnerd4252a72004-07-30 07:50:03 +00002735 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattner15212982005-09-18 03:42:07 +00002736 match(Op1, m_And(m_Value(B), m_ConstantInt(C2)))) {
2737
2738 if (A == B) // (A & C1)|(A & C2) == A & (C1|C2)
2739 return BinaryOperator::createAnd(A, ConstantExpr::getOr(C1, C2));
2740
2741
Chris Lattner01f56c62005-09-18 06:02:59 +00002742 // If we have: ((V + N) & C1) | (V & C2)
2743 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
2744 // replace with V+N.
2745 if (C1 == ConstantExpr::getNot(C2)) {
Chris Lattner330628a2006-01-06 17:59:59 +00002746 Value *V1 = 0, *V2 = 0;
Chris Lattner01f56c62005-09-18 06:02:59 +00002747 if ((C2->getRawValue() & (C2->getRawValue()+1)) == 0 && // C2 == 0+1+
2748 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
2749 // Add commutes, try both ways.
Chris Lattnerc3ebf402006-02-07 07:27:52 +00002750 if (V1 == B && MaskedValueIsZero(V2, C2->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00002751 return ReplaceInstUsesWith(I, A);
Chris Lattnerc3ebf402006-02-07 07:27:52 +00002752 if (V2 == B && MaskedValueIsZero(V1, C2->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00002753 return ReplaceInstUsesWith(I, A);
2754 }
2755 // Or commutes, try both ways.
2756 if ((C1->getRawValue() & (C1->getRawValue()+1)) == 0 &&
2757 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
2758 // Add commutes, try both ways.
Chris Lattnerc3ebf402006-02-07 07:27:52 +00002759 if (V1 == A && MaskedValueIsZero(V2, C1->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00002760 return ReplaceInstUsesWith(I, B);
Chris Lattnerc3ebf402006-02-07 07:27:52 +00002761 if (V2 == A && MaskedValueIsZero(V1, C1->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00002762 return ReplaceInstUsesWith(I, B);
Chris Lattner15212982005-09-18 03:42:07 +00002763 }
2764 }
2765 }
Chris Lattner812aab72003-08-12 19:11:07 +00002766
Chris Lattnerd4252a72004-07-30 07:50:03 +00002767 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
2768 if (A == Op1) // ~A | A == -1
Misha Brukmanb1c93172005-04-21 23:48:37 +00002769 return ReplaceInstUsesWith(I,
Chris Lattnerd4252a72004-07-30 07:50:03 +00002770 ConstantIntegral::getAllOnesValue(I.getType()));
2771 } else {
2772 A = 0;
2773 }
Chris Lattner4294cec2005-05-07 23:49:08 +00002774 // Note, A is still live here!
Chris Lattnerd4252a72004-07-30 07:50:03 +00002775 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
2776 if (Op0 == B)
Misha Brukmanb1c93172005-04-21 23:48:37 +00002777 return ReplaceInstUsesWith(I,
Chris Lattnerd4252a72004-07-30 07:50:03 +00002778 ConstantIntegral::getAllOnesValue(I.getType()));
Chris Lattner3e327a42003-03-10 23:13:59 +00002779
Misha Brukman9c003d82004-07-30 12:50:08 +00002780 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattnerd4252a72004-07-30 07:50:03 +00002781 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
2782 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
2783 I.getName()+".demorgan"), I);
2784 return BinaryOperator::createNot(And);
2785 }
Chris Lattner3e327a42003-03-10 23:13:59 +00002786 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00002787
Chris Lattner3ac7c262003-08-13 20:16:26 +00002788 // (setcc1 A, B) | (setcc2 A, B) --> (setcc3 A, B)
Chris Lattnerdcf756e2004-09-28 22:33:08 +00002789 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1))) {
Chris Lattner3ac7c262003-08-13 20:16:26 +00002790 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
2791 return R;
2792
Chris Lattnerdcf756e2004-09-28 22:33:08 +00002793 Value *LHSVal, *RHSVal;
2794 ConstantInt *LHSCst, *RHSCst;
2795 Instruction::BinaryOps LHSCC, RHSCC;
2796 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
2797 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
2798 if (LHSVal == RHSVal && // Found (X setcc C1) | (X setcc C2)
2799 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
Misha Brukmanb1c93172005-04-21 23:48:37 +00002800 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
Chris Lattnerdcf756e2004-09-28 22:33:08 +00002801 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
2802 // Ensure that the larger constant is on the RHS.
2803 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
2804 SetCondInst *LHS = cast<SetCondInst>(Op0);
2805 if (cast<ConstantBool>(Cmp)->getValue()) {
2806 std::swap(LHS, RHS);
2807 std::swap(LHSCst, RHSCst);
2808 std::swap(LHSCC, RHSCC);
2809 }
2810
2811 // At this point, we know we have have two setcc instructions
2812 // comparing a value against two constants and or'ing the result
2813 // together. Because of the above check, we know that we only have
2814 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
2815 // FoldSetCCLogical check above), that the two constants are not
2816 // equal.
2817 assert(LHSCst != RHSCst && "Compares not folded above?");
2818
2819 switch (LHSCC) {
2820 default: assert(0 && "Unknown integer condition code!");
2821 case Instruction::SetEQ:
2822 switch (RHSCC) {
2823 default: assert(0 && "Unknown integer condition code!");
2824 case Instruction::SetEQ:
2825 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
2826 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
2827 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
2828 LHSVal->getName()+".off");
2829 InsertNewInstBefore(Add, I);
2830 const Type *UnsType = Add->getType()->getUnsignedVersion();
2831 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
2832 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
2833 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2834 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
2835 }
2836 break; // (X == 13 | X == 15) -> no change
2837
Chris Lattner5c219462005-04-19 06:04:18 +00002838 case Instruction::SetGT: // (X == 13 | X > 14) -> no change
2839 break;
Chris Lattnerdcf756e2004-09-28 22:33:08 +00002840 case Instruction::SetNE: // (X == 13 | X != 15) -> X != 15
2841 case Instruction::SetLT: // (X == 13 | X < 15) -> X < 15
2842 return ReplaceInstUsesWith(I, RHS);
2843 }
2844 break;
2845 case Instruction::SetNE:
2846 switch (RHSCC) {
2847 default: assert(0 && "Unknown integer condition code!");
Chris Lattnerdcf756e2004-09-28 22:33:08 +00002848 case Instruction::SetEQ: // (X != 13 | X == 15) -> X != 13
2849 case Instruction::SetGT: // (X != 13 | X > 15) -> X != 13
2850 return ReplaceInstUsesWith(I, LHS);
2851 case Instruction::SetNE: // (X != 13 | X != 15) -> true
Chris Lattner2ceb6ee2005-06-17 03:59:17 +00002852 case Instruction::SetLT: // (X != 13 | X < 15) -> true
Chris Lattnerdcf756e2004-09-28 22:33:08 +00002853 return ReplaceInstUsesWith(I, ConstantBool::True);
2854 }
2855 break;
2856 case Instruction::SetLT:
2857 switch (RHSCC) {
2858 default: assert(0 && "Unknown integer condition code!");
2859 case Instruction::SetEQ: // (X < 13 | X == 14) -> no change
2860 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00002861 case Instruction::SetGT: // (X < 13 | X > 15) -> (X-13) > 2
2862 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false, I);
Chris Lattnerdcf756e2004-09-28 22:33:08 +00002863 case Instruction::SetNE: // (X < 13 | X != 15) -> X != 15
2864 case Instruction::SetLT: // (X < 13 | X < 15) -> X < 15
2865 return ReplaceInstUsesWith(I, RHS);
2866 }
2867 break;
2868 case Instruction::SetGT:
2869 switch (RHSCC) {
2870 default: assert(0 && "Unknown integer condition code!");
2871 case Instruction::SetEQ: // (X > 13 | X == 15) -> X > 13
2872 case Instruction::SetGT: // (X > 13 | X > 15) -> X > 13
2873 return ReplaceInstUsesWith(I, LHS);
2874 case Instruction::SetNE: // (X > 13 | X != 15) -> true
2875 case Instruction::SetLT: // (X > 13 | X < 15) -> true
2876 return ReplaceInstUsesWith(I, ConstantBool::True);
2877 }
2878 }
2879 }
2880 }
Chris Lattner3af10532006-05-05 06:39:07 +00002881
2882 // fold (or (cast A), (cast B)) -> (cast (or A, B))
2883 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
2884 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
2885 if (Op0C->getOperand(0)->getType() == Op1C->getOperand(0)->getType() &&
2886 Op0C->getOperand(0)->getType()->isIntegral()) {
2887 Instruction *NewOp = BinaryOperator::createOr(Op0C->getOperand(0),
2888 Op1C->getOperand(0),
2889 I.getName());
2890 InsertNewInstBefore(NewOp, I);
2891 return new CastInst(NewOp, I.getType());
2892 }
2893 }
2894
Chris Lattner15212982005-09-18 03:42:07 +00002895
Chris Lattner113f4f42002-06-25 16:13:24 +00002896 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002897}
2898
Chris Lattnerc2076352004-02-16 01:20:27 +00002899// XorSelf - Implements: X ^ X --> 0
2900struct XorSelf {
2901 Value *RHS;
2902 XorSelf(Value *rhs) : RHS(rhs) {}
2903 bool shouldApply(Value *LHS) const { return LHS == RHS; }
2904 Instruction *apply(BinaryOperator &Xor) const {
2905 return &Xor;
2906 }
2907};
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002908
2909
Chris Lattner113f4f42002-06-25 16:13:24 +00002910Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00002911 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00002912 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002913
Chris Lattner81a7a232004-10-16 18:11:37 +00002914 if (isa<UndefValue>(Op1))
2915 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
2916
Chris Lattnerc2076352004-02-16 01:20:27 +00002917 // xor X, X = 0, even if X is nested in a sequence of Xor's.
2918 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
2919 assert(Result == &I && "AssociativeOpt didn't work?");
Chris Lattnere6794492002-08-12 21:17:25 +00002920 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc2076352004-02-16 01:20:27 +00002921 }
Chris Lattner5b2edb12006-02-12 08:02:11 +00002922
2923 // See if we can simplify any instructions used by the instruction whose sole
2924 // purpose is to compute bits we don't care about.
2925 uint64_t KnownZero, KnownOne;
Chris Lattnerd70d9f52006-03-25 21:58:26 +00002926 if (!isa<PackedType>(I.getType()) &&
2927 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
Chris Lattner5b2edb12006-02-12 08:02:11 +00002928 KnownZero, KnownOne))
2929 return &I;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002930
Chris Lattner97638592003-07-23 21:37:07 +00002931 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner97638592003-07-23 21:37:07 +00002932 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerb8d6e402002-08-20 18:24:26 +00002933 // xor (setcc A, B), true = not (setcc A, B) = setncc A, B
Chris Lattner97638592003-07-23 21:37:07 +00002934 if (SetCondInst *SCI = dyn_cast<SetCondInst>(Op0I))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002935 if (RHS == ConstantBool::True && SCI->hasOneUse())
Chris Lattnerb8d6e402002-08-20 18:24:26 +00002936 return new SetCondInst(SCI->getInverseCondition(),
2937 SCI->getOperand(0), SCI->getOperand(1));
Chris Lattnere5806662003-11-04 23:50:51 +00002938
Chris Lattner8f2f5982003-11-05 01:06:05 +00002939 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002940 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
2941 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002942 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
2943 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002944 ConstantInt::get(I.getType(), 1));
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002945 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002946 }
Chris Lattner023a4832004-06-18 06:07:51 +00002947
2948 // ~(~X & Y) --> (X | ~Y)
2949 if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
2950 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
2951 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
2952 Instruction *NotY =
Misha Brukmanb1c93172005-04-21 23:48:37 +00002953 BinaryOperator::createNot(Op0I->getOperand(1),
Chris Lattner023a4832004-06-18 06:07:51 +00002954 Op0I->getOperand(1)->getName()+".not");
2955 InsertNewInstBefore(NotY, I);
2956 return BinaryOperator::createOr(Op0NotVal, NotY);
2957 }
2958 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002959
Chris Lattner97638592003-07-23 21:37:07 +00002960 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner5b2edb12006-02-12 08:02:11 +00002961 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner0f68fa62003-11-04 23:37:10 +00002962 // ~(X-c) --> (-c-1)-X
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002963 if (RHS->isAllOnesValue()) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002964 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
2965 return BinaryOperator::createSub(
2966 ConstantExpr::getSub(NegOp0CI,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002967 ConstantInt::get(I.getType(), 1)),
Chris Lattner0f68fa62003-11-04 23:37:10 +00002968 Op0I->getOperand(0));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002969 }
Chris Lattnerf78df7c2006-02-26 19:57:54 +00002970 } else if (Op0I->getOpcode() == Instruction::Or) {
2971 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
2972 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getZExtValue())) {
2973 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
2974 // Anything in both C1 and C2 is known to be zero, remove it from
2975 // NewRHS.
2976 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
2977 NewRHS = ConstantExpr::getAnd(NewRHS,
2978 ConstantExpr::getNot(CommonBits));
2979 WorkList.push_back(Op0I);
2980 I.setOperand(0, Op0I->getOperand(0));
2981 I.setOperand(1, NewRHS);
2982 return &I;
2983 }
Chris Lattner97638592003-07-23 21:37:07 +00002984 }
Chris Lattnerb8d6e402002-08-20 18:24:26 +00002985 }
Chris Lattner183b3362004-04-09 19:05:30 +00002986
2987 // Try to fold constant and into select arguments.
2988 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00002989 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00002990 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002991 if (isa<PHINode>(Op0))
2992 if (Instruction *NV = FoldOpIntoPhi(I))
2993 return NV;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002994 }
2995
Chris Lattnerbb74e222003-03-10 23:06:50 +00002996 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00002997 if (X == Op1)
2998 return ReplaceInstUsesWith(I,
2999 ConstantIntegral::getAllOnesValue(I.getType()));
3000
Chris Lattnerbb74e222003-03-10 23:06:50 +00003001 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00003002 if (X == Op0)
3003 return ReplaceInstUsesWith(I,
3004 ConstantIntegral::getAllOnesValue(I.getType()));
3005
Chris Lattnerdcd07922006-04-01 08:03:55 +00003006 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1))
Chris Lattnerb36d9082004-02-16 03:54:20 +00003007 if (Op1I->getOpcode() == Instruction::Or) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003008 if (Op1I->getOperand(0) == Op0) { // B^(B|A) == (A|B)^B
Chris Lattnerdcd07922006-04-01 08:03:55 +00003009 Op1I->swapOperands();
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003010 I.swapOperands();
3011 std::swap(Op0, Op1);
3012 } else if (Op1I->getOperand(1) == Op0) { // B^(A|B) == (A|B)^B
Chris Lattnerdcd07922006-04-01 08:03:55 +00003013 I.swapOperands(); // Simplified below.
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003014 std::swap(Op0, Op1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003015 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00003016 } else if (Op1I->getOpcode() == Instruction::Xor) {
3017 if (Op0 == Op1I->getOperand(0)) // A^(A^B) == B
3018 return ReplaceInstUsesWith(I, Op1I->getOperand(1));
3019 else if (Op0 == Op1I->getOperand(1)) // A^(B^A) == B
3020 return ReplaceInstUsesWith(I, Op1I->getOperand(0));
Chris Lattnerdcd07922006-04-01 08:03:55 +00003021 } else if (Op1I->getOpcode() == Instruction::And && Op1I->hasOneUse()) {
3022 if (Op1I->getOperand(0) == Op0) // A^(A&B) -> A^(B&A)
3023 Op1I->swapOperands();
3024 if (Op0 == Op1I->getOperand(1)) { // A^(B&A) -> (B&A)^A
3025 I.swapOperands(); // Simplified below.
3026 std::swap(Op0, Op1);
3027 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00003028 }
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003029
Chris Lattnerdcd07922006-04-01 08:03:55 +00003030 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00003031 if (Op0I->getOpcode() == Instruction::Or && Op0I->hasOneUse()) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003032 if (Op0I->getOperand(0) == Op1) // (B|A)^B == (A|B)^B
Chris Lattnerdcd07922006-04-01 08:03:55 +00003033 Op0I->swapOperands();
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003034 if (Op0I->getOperand(1) == Op1) { // (A|B)^B == A & ~B
Chris Lattnerdcd07922006-04-01 08:03:55 +00003035 Instruction *NotB = BinaryOperator::createNot(Op1, "tmp");
3036 InsertNewInstBefore(NotB, I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003037 return BinaryOperator::createAnd(Op0I->getOperand(0), NotB);
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003038 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00003039 } else if (Op0I->getOpcode() == Instruction::Xor) {
3040 if (Op1 == Op0I->getOperand(0)) // (A^B)^A == B
3041 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
3042 else if (Op1 == Op0I->getOperand(1)) // (B^A)^A == B
3043 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattnerdcd07922006-04-01 08:03:55 +00003044 } else if (Op0I->getOpcode() == Instruction::And && Op0I->hasOneUse()) {
3045 if (Op0I->getOperand(0) == Op1) // (A&B)^A -> (B&A)^A
3046 Op0I->swapOperands();
Chris Lattner6cf49142006-04-01 22:05:01 +00003047 if (Op0I->getOperand(1) == Op1 && // (B&A)^A == ~B & A
3048 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattnerdcd07922006-04-01 08:03:55 +00003049 Instruction *N = BinaryOperator::createNot(Op0I->getOperand(0), "tmp");
3050 InsertNewInstBefore(N, I);
3051 return BinaryOperator::createAnd(N, Op1);
3052 }
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003053 }
3054
Chris Lattner3ac7c262003-08-13 20:16:26 +00003055 // (setcc1 A, B) ^ (setcc2 A, B) --> (setcc3 A, B)
3056 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
3057 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
3058 return R;
3059
Chris Lattner3af10532006-05-05 06:39:07 +00003060 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
3061 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
3062 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3063 if (Op0C->getOperand(0)->getType() == Op1C->getOperand(0)->getType() &&
3064 Op0C->getOperand(0)->getType()->isIntegral()) {
3065 Instruction *NewOp = BinaryOperator::createXor(Op0C->getOperand(0),
3066 Op1C->getOperand(0),
3067 I.getName());
3068 InsertNewInstBefore(NewOp, I);
3069 return new CastInst(NewOp, I.getType());
3070 }
3071 }
3072
Chris Lattner113f4f42002-06-25 16:13:24 +00003073 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003074}
3075
Chris Lattner6862fbd2004-09-29 17:40:11 +00003076/// MulWithOverflow - Compute Result = In1*In2, returning true if the result
3077/// overflowed for this type.
3078static bool MulWithOverflow(ConstantInt *&Result, ConstantInt *In1,
3079 ConstantInt *In2) {
3080 Result = cast<ConstantInt>(ConstantExpr::getMul(In1, In2));
3081 return !In2->isNullValue() && ConstantExpr::getDiv(Result, In2) != In1;
3082}
3083
3084static bool isPositive(ConstantInt *C) {
3085 return cast<ConstantSInt>(C)->getValue() >= 0;
3086}
3087
3088/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
3089/// overflowed for this type.
3090static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
3091 ConstantInt *In2) {
3092 Result = cast<ConstantInt>(ConstantExpr::getAdd(In1, In2));
3093
3094 if (In1->getType()->isUnsigned())
3095 return cast<ConstantUInt>(Result)->getValue() <
3096 cast<ConstantUInt>(In1)->getValue();
3097 if (isPositive(In1) != isPositive(In2))
3098 return false;
3099 if (isPositive(In1))
3100 return cast<ConstantSInt>(Result)->getValue() <
3101 cast<ConstantSInt>(In1)->getValue();
3102 return cast<ConstantSInt>(Result)->getValue() >
3103 cast<ConstantSInt>(In1)->getValue();
3104}
3105
Chris Lattner0798af32005-01-13 20:14:25 +00003106/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
3107/// code necessary to compute the offset from the base pointer (without adding
3108/// in the base pointer). Return the result as a signed integer of intptr size.
3109static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
3110 TargetData &TD = IC.getTargetData();
3111 gep_type_iterator GTI = gep_type_begin(GEP);
3112 const Type *UIntPtrTy = TD.getIntPtrType();
3113 const Type *SIntPtrTy = UIntPtrTy->getSignedVersion();
3114 Value *Result = Constant::getNullValue(SIntPtrTy);
3115
3116 // Build a mask for high order bits.
Chris Lattner77defba2006-02-07 07:00:41 +00003117 uint64_t PtrSizeMask = ~0ULL >> (64-TD.getPointerSize()*8);
Chris Lattner0798af32005-01-13 20:14:25 +00003118
Chris Lattner0798af32005-01-13 20:14:25 +00003119 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
3120 Value *Op = GEP->getOperand(i);
Chris Lattnerd35d2102005-01-13 23:26:48 +00003121 uint64_t Size = TD.getTypeSize(GTI.getIndexedType()) & PtrSizeMask;
Chris Lattner0798af32005-01-13 20:14:25 +00003122 Constant *Scale = ConstantExpr::getCast(ConstantUInt::get(UIntPtrTy, Size),
3123 SIntPtrTy);
3124 if (Constant *OpC = dyn_cast<Constant>(Op)) {
3125 if (!OpC->isNullValue()) {
Chris Lattner4cb9fa32005-01-13 20:40:58 +00003126 OpC = ConstantExpr::getCast(OpC, SIntPtrTy);
Chris Lattner0798af32005-01-13 20:14:25 +00003127 Scale = ConstantExpr::getMul(OpC, Scale);
3128 if (Constant *RC = dyn_cast<Constant>(Result))
3129 Result = ConstantExpr::getAdd(RC, Scale);
3130 else {
3131 // Emit an add instruction.
3132 Result = IC.InsertNewInstBefore(
3133 BinaryOperator::createAdd(Result, Scale,
3134 GEP->getName()+".offs"), I);
3135 }
3136 }
3137 } else {
Chris Lattner7aa41cf2005-01-14 17:17:59 +00003138 // Convert to correct type.
3139 Op = IC.InsertNewInstBefore(new CastInst(Op, SIntPtrTy,
3140 Op->getName()+".c"), I);
3141 if (Size != 1)
Chris Lattner4cb9fa32005-01-13 20:40:58 +00003142 // We'll let instcombine(mul) convert this to a shl if possible.
3143 Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
3144 GEP->getName()+".idx"), I);
Chris Lattner0798af32005-01-13 20:14:25 +00003145
3146 // Emit an add instruction.
Chris Lattner4cb9fa32005-01-13 20:40:58 +00003147 Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
Chris Lattner0798af32005-01-13 20:14:25 +00003148 GEP->getName()+".offs"), I);
3149 }
3150 }
3151 return Result;
3152}
3153
3154/// FoldGEPSetCC - Fold comparisons between a GEP instruction and something
3155/// else. At this point we know that the GEP is on the LHS of the comparison.
3156Instruction *InstCombiner::FoldGEPSetCC(User *GEPLHS, Value *RHS,
3157 Instruction::BinaryOps Cond,
3158 Instruction &I) {
3159 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattner81e84172005-01-13 22:25:21 +00003160
3161 if (CastInst *CI = dyn_cast<CastInst>(RHS))
3162 if (isa<PointerType>(CI->getOperand(0)->getType()))
3163 RHS = CI->getOperand(0);
3164
Chris Lattner0798af32005-01-13 20:14:25 +00003165 Value *PtrBase = GEPLHS->getOperand(0);
3166 if (PtrBase == RHS) {
3167 // As an optimization, we don't actually have to compute the actual value of
3168 // OFFSET if this is a seteq or setne comparison, just return whether each
3169 // index is zero or not.
Chris Lattner81e84172005-01-13 22:25:21 +00003170 if (Cond == Instruction::SetEQ || Cond == Instruction::SetNE) {
3171 Instruction *InVal = 0;
Chris Lattnercd517ff2005-01-28 19:32:01 +00003172 gep_type_iterator GTI = gep_type_begin(GEPLHS);
3173 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i, ++GTI) {
Chris Lattner81e84172005-01-13 22:25:21 +00003174 bool EmitIt = true;
3175 if (Constant *C = dyn_cast<Constant>(GEPLHS->getOperand(i))) {
3176 if (isa<UndefValue>(C)) // undef index -> undef.
3177 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
3178 if (C->isNullValue())
3179 EmitIt = false;
Chris Lattnercd517ff2005-01-28 19:32:01 +00003180 else if (TD->getTypeSize(GTI.getIndexedType()) == 0) {
3181 EmitIt = false; // This is indexing into a zero sized array?
Misha Brukmanb1c93172005-04-21 23:48:37 +00003182 } else if (isa<ConstantInt>(C))
Chris Lattner81e84172005-01-13 22:25:21 +00003183 return ReplaceInstUsesWith(I, // No comparison is needed here.
3184 ConstantBool::get(Cond == Instruction::SetNE));
3185 }
3186
3187 if (EmitIt) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00003188 Instruction *Comp =
Chris Lattner81e84172005-01-13 22:25:21 +00003189 new SetCondInst(Cond, GEPLHS->getOperand(i),
3190 Constant::getNullValue(GEPLHS->getOperand(i)->getType()));
3191 if (InVal == 0)
3192 InVal = Comp;
3193 else {
3194 InVal = InsertNewInstBefore(InVal, I);
3195 InsertNewInstBefore(Comp, I);
3196 if (Cond == Instruction::SetNE) // True if any are unequal
3197 InVal = BinaryOperator::createOr(InVal, Comp);
3198 else // True if all are equal
3199 InVal = BinaryOperator::createAnd(InVal, Comp);
3200 }
3201 }
3202 }
3203
3204 if (InVal)
3205 return InVal;
3206 else
3207 ReplaceInstUsesWith(I, // No comparison is needed here, all indexes = 0
3208 ConstantBool::get(Cond == Instruction::SetEQ));
3209 }
Chris Lattner0798af32005-01-13 20:14:25 +00003210
3211 // Only lower this if the setcc is the only user of the GEP or if we expect
3212 // the result to fold to a constant!
3213 if (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) {
3214 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
3215 Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
3216 return new SetCondInst(Cond, Offset,
3217 Constant::getNullValue(Offset->getType()));
3218 }
3219 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
Chris Lattnera21bf8d2005-04-25 20:17:30 +00003220 // If the base pointers are different, but the indices are the same, just
3221 // compare the base pointer.
3222 if (PtrBase != GEPRHS->getOperand(0)) {
3223 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00003224 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattnerbd43b9d2005-04-26 14:40:41 +00003225 GEPRHS->getOperand(0)->getType();
Chris Lattnera21bf8d2005-04-25 20:17:30 +00003226 if (IndicesTheSame)
3227 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
3228 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
3229 IndicesTheSame = false;
3230 break;
3231 }
3232
3233 // If all indices are the same, just compare the base pointers.
3234 if (IndicesTheSame)
3235 return new SetCondInst(Cond, GEPLHS->getOperand(0),
3236 GEPRHS->getOperand(0));
3237
3238 // Otherwise, the base pointers are different and the indices are
3239 // different, bail out.
Chris Lattner0798af32005-01-13 20:14:25 +00003240 return 0;
Chris Lattnera21bf8d2005-04-25 20:17:30 +00003241 }
Chris Lattner0798af32005-01-13 20:14:25 +00003242
Chris Lattner81e84172005-01-13 22:25:21 +00003243 // If one of the GEPs has all zero indices, recurse.
3244 bool AllZeros = true;
3245 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
3246 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
3247 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
3248 AllZeros = false;
3249 break;
3250 }
3251 if (AllZeros)
3252 return FoldGEPSetCC(GEPRHS, GEPLHS->getOperand(0),
3253 SetCondInst::getSwappedCondition(Cond), I);
Chris Lattner4fa89822005-01-14 00:20:05 +00003254
3255 // If the other GEP has all zero indices, recurse.
Chris Lattner81e84172005-01-13 22:25:21 +00003256 AllZeros = true;
3257 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
3258 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
3259 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
3260 AllZeros = false;
3261 break;
3262 }
3263 if (AllZeros)
3264 return FoldGEPSetCC(GEPLHS, GEPRHS->getOperand(0), Cond, I);
3265
Chris Lattner4fa89822005-01-14 00:20:05 +00003266 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
3267 // If the GEPs only differ by one index, compare it.
3268 unsigned NumDifferences = 0; // Keep track of # differences.
3269 unsigned DiffOperand = 0; // The operand that differs.
3270 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
3271 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003272 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
3273 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattnerfc4429e2005-01-21 23:06:49 +00003274 // Irreconcilable differences.
Chris Lattner4fa89822005-01-14 00:20:05 +00003275 NumDifferences = 2;
3276 break;
3277 } else {
3278 if (NumDifferences++) break;
3279 DiffOperand = i;
3280 }
3281 }
3282
3283 if (NumDifferences == 0) // SAME GEP?
3284 return ReplaceInstUsesWith(I, // No comparison is needed here.
3285 ConstantBool::get(Cond == Instruction::SetEQ));
3286 else if (NumDifferences == 1) {
Chris Lattnerfc4429e2005-01-21 23:06:49 +00003287 Value *LHSV = GEPLHS->getOperand(DiffOperand);
3288 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Chris Lattner247aef82005-07-18 23:07:33 +00003289
3290 // Convert the operands to signed values to make sure to perform a
3291 // signed comparison.
3292 const Type *NewTy = LHSV->getType()->getSignedVersion();
3293 if (LHSV->getType() != NewTy)
3294 LHSV = InsertNewInstBefore(new CastInst(LHSV, NewTy,
3295 LHSV->getName()), I);
3296 if (RHSV->getType() != NewTy)
3297 RHSV = InsertNewInstBefore(new CastInst(RHSV, NewTy,
3298 RHSV->getName()), I);
3299 return new SetCondInst(Cond, LHSV, RHSV);
Chris Lattner4fa89822005-01-14 00:20:05 +00003300 }
3301 }
3302
Chris Lattner0798af32005-01-13 20:14:25 +00003303 // Only lower this if the setcc is the only user of the GEP or if we expect
3304 // the result to fold to a constant!
3305 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
3306 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
3307 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
3308 Value *L = EmitGEPOffset(GEPLHS, I, *this);
3309 Value *R = EmitGEPOffset(GEPRHS, I, *this);
3310 return new SetCondInst(Cond, L, R);
3311 }
3312 }
3313 return 0;
3314}
3315
3316
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003317Instruction *InstCombiner::visitSetCondInst(SetCondInst &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003318 bool Changed = SimplifyCommutative(I);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003319 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3320 const Type *Ty = Op0->getType();
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003321
3322 // setcc X, X
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003323 if (Op0 == Op1)
3324 return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
Chris Lattner1fc23f32002-05-09 20:11:54 +00003325
Chris Lattner81a7a232004-10-16 18:11:37 +00003326 if (isa<UndefValue>(Op1)) // X setcc undef -> undef
3327 return ReplaceInstUsesWith(I, UndefValue::get(Type::BoolTy));
3328
Chris Lattner15ff1e12004-11-14 07:33:16 +00003329 // setcc <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
3330 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanb1c93172005-04-21 23:48:37 +00003331 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
3332 isa<ConstantPointerNull>(Op0)) &&
3333 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner15ff1e12004-11-14 07:33:16 +00003334 isa<ConstantPointerNull>(Op1)))
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003335 return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
3336
3337 // setcc's with boolean values can always be turned into bitwise operations
3338 if (Ty == Type::BoolTy) {
Chris Lattner4456da62004-08-11 00:50:51 +00003339 switch (I.getOpcode()) {
3340 default: assert(0 && "Invalid setcc instruction!");
3341 case Instruction::SetEQ: { // seteq bool %A, %B -> ~(A^B)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003342 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003343 InsertNewInstBefore(Xor, I);
Chris Lattner16930792003-11-03 04:25:02 +00003344 return BinaryOperator::createNot(Xor);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003345 }
Chris Lattner4456da62004-08-11 00:50:51 +00003346 case Instruction::SetNE:
3347 return BinaryOperator::createXor(Op0, Op1);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003348
Chris Lattner4456da62004-08-11 00:50:51 +00003349 case Instruction::SetGT:
3350 std::swap(Op0, Op1); // Change setgt -> setlt
3351 // FALL THROUGH
3352 case Instruction::SetLT: { // setlt bool A, B -> ~X & Y
3353 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
3354 InsertNewInstBefore(Not, I);
3355 return BinaryOperator::createAnd(Not, Op1);
3356 }
3357 case Instruction::SetGE:
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003358 std::swap(Op0, Op1); // Change setge -> setle
Chris Lattner4456da62004-08-11 00:50:51 +00003359 // FALL THROUGH
3360 case Instruction::SetLE: { // setle bool %A, %B -> ~A | B
3361 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
3362 InsertNewInstBefore(Not, I);
3363 return BinaryOperator::createOr(Not, Op1);
3364 }
3365 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003366 }
3367
Chris Lattner2dd01742004-06-09 04:24:29 +00003368 // See if we are doing a comparison between a constant and an instruction that
3369 // can be folded into the comparison.
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003370 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner6862fbd2004-09-29 17:40:11 +00003371 // Check to see if we are comparing against the minimum or maximum value...
3372 if (CI->isMinValue()) {
3373 if (I.getOpcode() == Instruction::SetLT) // A < MIN -> FALSE
3374 return ReplaceInstUsesWith(I, ConstantBool::False);
3375 if (I.getOpcode() == Instruction::SetGE) // A >= MIN -> TRUE
3376 return ReplaceInstUsesWith(I, ConstantBool::True);
3377 if (I.getOpcode() == Instruction::SetLE) // A <= MIN -> A == MIN
3378 return BinaryOperator::createSetEQ(Op0, Op1);
3379 if (I.getOpcode() == Instruction::SetGT) // A > MIN -> A != MIN
3380 return BinaryOperator::createSetNE(Op0, Op1);
3381
3382 } else if (CI->isMaxValue()) {
3383 if (I.getOpcode() == Instruction::SetGT) // A > MAX -> FALSE
3384 return ReplaceInstUsesWith(I, ConstantBool::False);
3385 if (I.getOpcode() == Instruction::SetLE) // A <= MAX -> TRUE
3386 return ReplaceInstUsesWith(I, ConstantBool::True);
3387 if (I.getOpcode() == Instruction::SetGE) // A >= MAX -> A == MAX
3388 return BinaryOperator::createSetEQ(Op0, Op1);
3389 if (I.getOpcode() == Instruction::SetLT) // A < MAX -> A != MAX
3390 return BinaryOperator::createSetNE(Op0, Op1);
3391
3392 // Comparing against a value really close to min or max?
3393 } else if (isMinValuePlusOne(CI)) {
3394 if (I.getOpcode() == Instruction::SetLT) // A < MIN+1 -> A == MIN
3395 return BinaryOperator::createSetEQ(Op0, SubOne(CI));
3396 if (I.getOpcode() == Instruction::SetGE) // A >= MIN-1 -> A != MIN
3397 return BinaryOperator::createSetNE(Op0, SubOne(CI));
3398
3399 } else if (isMaxValueMinusOne(CI)) {
3400 if (I.getOpcode() == Instruction::SetGT) // A > MAX-1 -> A == MAX
3401 return BinaryOperator::createSetEQ(Op0, AddOne(CI));
3402 if (I.getOpcode() == Instruction::SetLE) // A <= MAX-1 -> A != MAX
3403 return BinaryOperator::createSetNE(Op0, AddOne(CI));
3404 }
3405
3406 // If we still have a setle or setge instruction, turn it into the
3407 // appropriate setlt or setgt instruction. Since the border cases have
3408 // already been handled above, this requires little checking.
3409 //
3410 if (I.getOpcode() == Instruction::SetLE)
3411 return BinaryOperator::createSetLT(Op0, AddOne(CI));
3412 if (I.getOpcode() == Instruction::SetGE)
3413 return BinaryOperator::createSetGT(Op0, SubOne(CI));
3414
Chris Lattneree0f2802006-02-12 02:07:56 +00003415
3416 // See if we can fold the comparison based on bits known to be zero or one
3417 // in the input.
3418 uint64_t KnownZero, KnownOne;
3419 if (SimplifyDemandedBits(Op0, Ty->getIntegralTypeMask(),
3420 KnownZero, KnownOne, 0))
3421 return &I;
3422
3423 // Given the known and unknown bits, compute a range that the LHS could be
3424 // in.
3425 if (KnownOne | KnownZero) {
3426 if (Ty->isUnsigned()) { // Unsigned comparison.
3427 uint64_t Min, Max;
3428 uint64_t RHSVal = CI->getZExtValue();
3429 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne,
3430 Min, Max);
3431 switch (I.getOpcode()) { // LE/GE have been folded already.
3432 default: assert(0 && "Unknown setcc opcode!");
3433 case Instruction::SetEQ:
3434 if (Max < RHSVal || Min > RHSVal)
3435 return ReplaceInstUsesWith(I, ConstantBool::False);
3436 break;
3437 case Instruction::SetNE:
3438 if (Max < RHSVal || Min > RHSVal)
3439 return ReplaceInstUsesWith(I, ConstantBool::True);
3440 break;
3441 case Instruction::SetLT:
3442 if (Max < RHSVal) return ReplaceInstUsesWith(I, ConstantBool::True);
3443 if (Min > RHSVal) return ReplaceInstUsesWith(I, ConstantBool::False);
3444 break;
3445 case Instruction::SetGT:
3446 if (Min > RHSVal) return ReplaceInstUsesWith(I, ConstantBool::True);
3447 if (Max < RHSVal) return ReplaceInstUsesWith(I, ConstantBool::False);
3448 break;
3449 }
3450 } else { // Signed comparison.
3451 int64_t Min, Max;
3452 int64_t RHSVal = CI->getSExtValue();
3453 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne,
3454 Min, Max);
3455 switch (I.getOpcode()) { // LE/GE have been folded already.
3456 default: assert(0 && "Unknown setcc opcode!");
3457 case Instruction::SetEQ:
3458 if (Max < RHSVal || Min > RHSVal)
3459 return ReplaceInstUsesWith(I, ConstantBool::False);
3460 break;
3461 case Instruction::SetNE:
3462 if (Max < RHSVal || Min > RHSVal)
3463 return ReplaceInstUsesWith(I, ConstantBool::True);
3464 break;
3465 case Instruction::SetLT:
3466 if (Max < RHSVal) return ReplaceInstUsesWith(I, ConstantBool::True);
3467 if (Min > RHSVal) return ReplaceInstUsesWith(I, ConstantBool::False);
3468 break;
3469 case Instruction::SetGT:
3470 if (Min > RHSVal) return ReplaceInstUsesWith(I, ConstantBool::True);
3471 if (Max < RHSVal) return ReplaceInstUsesWith(I, ConstantBool::False);
3472 break;
3473 }
3474 }
3475 }
3476
3477
Chris Lattnere1e10e12004-05-25 06:32:08 +00003478 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00003479 switch (LHSI->getOpcode()) {
3480 case Instruction::And:
3481 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
3482 LHSI->getOperand(0)->hasOneUse()) {
3483 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
3484 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
3485 // happens a LOT in code produced by the C front-end, for bitfield
3486 // access.
3487 ShiftInst *Shift = dyn_cast<ShiftInst>(LHSI->getOperand(0));
Chris Lattneree0f2802006-02-12 02:07:56 +00003488 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
3489
3490 // Check to see if there is a noop-cast between the shift and the and.
3491 if (!Shift) {
3492 if (CastInst *CI = dyn_cast<CastInst>(LHSI->getOperand(0)))
3493 if (CI->getOperand(0)->getType()->isIntegral() &&
3494 CI->getOperand(0)->getType()->getPrimitiveSizeInBits() ==
3495 CI->getType()->getPrimitiveSizeInBits())
3496 Shift = dyn_cast<ShiftInst>(CI->getOperand(0));
3497 }
3498
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00003499 ConstantUInt *ShAmt;
3500 ShAmt = Shift ? dyn_cast<ConstantUInt>(Shift->getOperand(1)) : 0;
Chris Lattneree0f2802006-02-12 02:07:56 +00003501 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
3502 const Type *AndTy = AndCST->getType(); // Type of the and.
Misha Brukmanb1c93172005-04-21 23:48:37 +00003503
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00003504 // We can fold this as long as we can't shift unknown bits
3505 // into the mask. This can only happen with signed shift
3506 // rights, as they sign-extend.
3507 if (ShAmt) {
3508 bool CanFold = Shift->getOpcode() != Instruction::Shr ||
Chris Lattneree0f2802006-02-12 02:07:56 +00003509 Ty->isUnsigned();
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00003510 if (!CanFold) {
3511 // To test for the bad case of the signed shr, see if any
3512 // of the bits shifted in could be tested after the mask.
Chris Lattnerc53cb9d2005-06-17 01:29:28 +00003513 int ShAmtVal = Ty->getPrimitiveSizeInBits()-ShAmt->getValue();
3514 if (ShAmtVal < 0) ShAmtVal = 0; // Out of range shift.
3515
3516 Constant *OShAmt = ConstantUInt::get(Type::UByteTy, ShAmtVal);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003517 Constant *ShVal =
Chris Lattneree0f2802006-02-12 02:07:56 +00003518 ConstantExpr::getShl(ConstantInt::getAllOnesValue(AndTy),
3519 OShAmt);
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00003520 if (ConstantExpr::getAnd(ShVal, AndCST)->isNullValue())
3521 CanFold = true;
3522 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003523
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00003524 if (CanFold) {
Chris Lattner6afc02f2004-09-28 17:54:07 +00003525 Constant *NewCst;
3526 if (Shift->getOpcode() == Instruction::Shl)
3527 NewCst = ConstantExpr::getUShr(CI, ShAmt);
3528 else
3529 NewCst = ConstantExpr::getShl(CI, ShAmt);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00003530
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00003531 // Check to see if we are shifting out any of the bits being
3532 // compared.
3533 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != CI){
3534 // If we shifted bits out, the fold is not going to work out.
3535 // As a special case, check to see if this means that the
3536 // result is always true or false now.
3537 if (I.getOpcode() == Instruction::SetEQ)
3538 return ReplaceInstUsesWith(I, ConstantBool::False);
3539 if (I.getOpcode() == Instruction::SetNE)
3540 return ReplaceInstUsesWith(I, ConstantBool::True);
3541 } else {
3542 I.setOperand(1, NewCst);
Chris Lattner6afc02f2004-09-28 17:54:07 +00003543 Constant *NewAndCST;
3544 if (Shift->getOpcode() == Instruction::Shl)
3545 NewAndCST = ConstantExpr::getUShr(AndCST, ShAmt);
3546 else
3547 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
3548 LHSI->setOperand(1, NewAndCST);
Chris Lattneree0f2802006-02-12 02:07:56 +00003549 if (AndTy == Ty)
3550 LHSI->setOperand(0, Shift->getOperand(0));
3551 else {
3552 Value *NewCast = InsertCastBefore(Shift->getOperand(0), AndTy,
3553 *Shift);
3554 LHSI->setOperand(0, NewCast);
3555 }
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00003556 WorkList.push_back(Shift); // Shift is dead.
3557 AddUsesToWorkList(I);
3558 return &I;
Chris Lattner1638de42004-07-21 19:50:44 +00003559 }
3560 }
Chris Lattner35167c32004-06-09 07:59:58 +00003561 }
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00003562 }
3563 break;
Chris Lattnerbfff18a2004-09-27 19:29:18 +00003564
Chris Lattner272d5ca2004-09-28 18:22:15 +00003565 case Instruction::Shl: // (setcc (shl X, ShAmt), CI)
3566 if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
3567 switch (I.getOpcode()) {
3568 default: break;
3569 case Instruction::SetEQ:
3570 case Instruction::SetNE: {
Chris Lattner19b57f52005-06-15 20:53:31 +00003571 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
3572
3573 // Check that the shift amount is in range. If not, don't perform
3574 // undefined shifts. When the shift is visited it will be
3575 // simplified.
3576 if (ShAmt->getValue() >= TypeBits)
3577 break;
3578
Chris Lattner272d5ca2004-09-28 18:22:15 +00003579 // If we are comparing against bits always shifted out, the
3580 // comparison cannot succeed.
Misha Brukmanb1c93172005-04-21 23:48:37 +00003581 Constant *Comp =
Chris Lattner272d5ca2004-09-28 18:22:15 +00003582 ConstantExpr::getShl(ConstantExpr::getShr(CI, ShAmt), ShAmt);
3583 if (Comp != CI) {// Comparing against a bit that we know is zero.
3584 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
3585 Constant *Cst = ConstantBool::get(IsSetNE);
3586 return ReplaceInstUsesWith(I, Cst);
3587 }
3588
3589 if (LHSI->hasOneUse()) {
3590 // Otherwise strength reduce the shift into an and.
Chris Lattnerfdfe3e492005-01-08 19:42:22 +00003591 unsigned ShAmtVal = (unsigned)ShAmt->getValue();
Chris Lattner272d5ca2004-09-28 18:22:15 +00003592 uint64_t Val = (1ULL << (TypeBits-ShAmtVal))-1;
3593
3594 Constant *Mask;
3595 if (CI->getType()->isUnsigned()) {
3596 Mask = ConstantUInt::get(CI->getType(), Val);
3597 } else if (ShAmtVal != 0) {
3598 Mask = ConstantSInt::get(CI->getType(), Val);
3599 } else {
3600 Mask = ConstantInt::getAllOnesValue(CI->getType());
3601 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003602
Chris Lattner272d5ca2004-09-28 18:22:15 +00003603 Instruction *AndI =
3604 BinaryOperator::createAnd(LHSI->getOperand(0),
3605 Mask, LHSI->getName()+".mask");
3606 Value *And = InsertNewInstBefore(AndI, I);
3607 return new SetCondInst(I.getOpcode(), And,
3608 ConstantExpr::getUShr(CI, ShAmt));
3609 }
3610 }
3611 }
3612 }
3613 break;
3614
Chris Lattnerbfff18a2004-09-27 19:29:18 +00003615 case Instruction::Shr: // (setcc (shr X, ShAmt), CI)
Chris Lattner1023b872004-09-27 16:18:50 +00003616 if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
Chris Lattner1023b872004-09-27 16:18:50 +00003617 switch (I.getOpcode()) {
3618 default: break;
3619 case Instruction::SetEQ:
3620 case Instruction::SetNE: {
Chris Lattner19b57f52005-06-15 20:53:31 +00003621
3622 // Check that the shift amount is in range. If not, don't perform
3623 // undefined shifts. When the shift is visited it will be
3624 // simplified.
Chris Lattner104002b2005-06-16 01:52:07 +00003625 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
Chris Lattner19b57f52005-06-15 20:53:31 +00003626 if (ShAmt->getValue() >= TypeBits)
3627 break;
3628
Chris Lattner1023b872004-09-27 16:18:50 +00003629 // If we are comparing against bits always shifted out, the
3630 // comparison cannot succeed.
Misha Brukmanb1c93172005-04-21 23:48:37 +00003631 Constant *Comp =
Chris Lattner1023b872004-09-27 16:18:50 +00003632 ConstantExpr::getShr(ConstantExpr::getShl(CI, ShAmt), ShAmt);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003633
Chris Lattner1023b872004-09-27 16:18:50 +00003634 if (Comp != CI) {// Comparing against a bit that we know is zero.
3635 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
3636 Constant *Cst = ConstantBool::get(IsSetNE);
3637 return ReplaceInstUsesWith(I, Cst);
3638 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003639
Chris Lattner1023b872004-09-27 16:18:50 +00003640 if (LHSI->hasOneUse() || CI->isNullValue()) {
Chris Lattnerfdfe3e492005-01-08 19:42:22 +00003641 unsigned ShAmtVal = (unsigned)ShAmt->getValue();
Chris Lattner272d5ca2004-09-28 18:22:15 +00003642
Chris Lattner1023b872004-09-27 16:18:50 +00003643 // Otherwise strength reduce the shift into an and.
3644 uint64_t Val = ~0ULL; // All ones.
3645 Val <<= ShAmtVal; // Shift over to the right spot.
3646
3647 Constant *Mask;
3648 if (CI->getType()->isUnsigned()) {
Chris Lattner2f1457f2005-04-24 17:46:05 +00003649 Val &= ~0ULL >> (64-TypeBits);
Chris Lattner1023b872004-09-27 16:18:50 +00003650 Mask = ConstantUInt::get(CI->getType(), Val);
3651 } else {
3652 Mask = ConstantSInt::get(CI->getType(), Val);
3653 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003654
Chris Lattner1023b872004-09-27 16:18:50 +00003655 Instruction *AndI =
3656 BinaryOperator::createAnd(LHSI->getOperand(0),
3657 Mask, LHSI->getName()+".mask");
3658 Value *And = InsertNewInstBefore(AndI, I);
3659 return new SetCondInst(I.getOpcode(), And,
3660 ConstantExpr::getShl(CI, ShAmt));
3661 }
3662 break;
3663 }
3664 }
3665 }
3666 break;
Chris Lattner7e794272004-09-24 15:21:34 +00003667
Chris Lattner6862fbd2004-09-29 17:40:11 +00003668 case Instruction::Div:
3669 // Fold: (div X, C1) op C2 -> range check
3670 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
3671 // Fold this div into the comparison, producing a range check.
3672 // Determine, based on the divide type, what the range is being
3673 // checked. If there is an overflow on the low or high side, remember
3674 // it, otherwise compute the range [low, hi) bounding the new value.
3675 bool LoOverflow = false, HiOverflow = 0;
3676 ConstantInt *LoBound = 0, *HiBound = 0;
3677
3678 ConstantInt *Prod;
3679 bool ProdOV = MulWithOverflow(Prod, CI, DivRHS);
3680
Chris Lattnera92af962004-10-11 19:40:04 +00003681 Instruction::BinaryOps Opcode = I.getOpcode();
3682
Chris Lattner6862fbd2004-09-29 17:40:11 +00003683 if (DivRHS->isNullValue()) { // Don't hack on divide by zeros.
3684 } else if (LHSI->getType()->isUnsigned()) { // udiv
3685 LoBound = Prod;
3686 LoOverflow = ProdOV;
3687 HiOverflow = ProdOV || AddWithOverflow(HiBound, LoBound, DivRHS);
3688 } else if (isPositive(DivRHS)) { // Divisor is > 0.
3689 if (CI->isNullValue()) { // (X / pos) op 0
3690 // Can't overflow.
3691 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
3692 HiBound = DivRHS;
3693 } else if (isPositive(CI)) { // (X / pos) op pos
3694 LoBound = Prod;
3695 LoOverflow = ProdOV;
3696 HiOverflow = ProdOV || AddWithOverflow(HiBound, Prod, DivRHS);
3697 } else { // (X / pos) op neg
3698 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
3699 LoOverflow = AddWithOverflow(LoBound, Prod,
3700 cast<ConstantInt>(DivRHSH));
3701 HiBound = Prod;
3702 HiOverflow = ProdOV;
3703 }
3704 } else { // Divisor is < 0.
3705 if (CI->isNullValue()) { // (X / neg) op 0
3706 LoBound = AddOne(DivRHS);
3707 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner73bcba52005-06-17 02:05:55 +00003708 if (HiBound == DivRHS)
3709 LoBound = 0; // - INTMIN = INTMIN
Chris Lattner6862fbd2004-09-29 17:40:11 +00003710 } else if (isPositive(CI)) { // (X / neg) op pos
3711 HiOverflow = LoOverflow = ProdOV;
3712 if (!LoOverflow)
3713 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS));
3714 HiBound = AddOne(Prod);
3715 } else { // (X / neg) op neg
3716 LoBound = Prod;
3717 LoOverflow = HiOverflow = ProdOV;
3718 HiBound = cast<ConstantInt>(ConstantExpr::getSub(Prod, DivRHS));
3719 }
Chris Lattner0b41e862004-10-08 19:15:44 +00003720
Chris Lattnera92af962004-10-11 19:40:04 +00003721 // Dividing by a negate swaps the condition.
3722 Opcode = SetCondInst::getSwappedCondition(Opcode);
Chris Lattner6862fbd2004-09-29 17:40:11 +00003723 }
3724
3725 if (LoBound) {
3726 Value *X = LHSI->getOperand(0);
Chris Lattnera92af962004-10-11 19:40:04 +00003727 switch (Opcode) {
Chris Lattner6862fbd2004-09-29 17:40:11 +00003728 default: assert(0 && "Unhandled setcc opcode!");
3729 case Instruction::SetEQ:
3730 if (LoOverflow && HiOverflow)
3731 return ReplaceInstUsesWith(I, ConstantBool::False);
3732 else if (HiOverflow)
3733 return new SetCondInst(Instruction::SetGE, X, LoBound);
3734 else if (LoOverflow)
3735 return new SetCondInst(Instruction::SetLT, X, HiBound);
3736 else
3737 return InsertRangeTest(X, LoBound, HiBound, true, I);
3738 case Instruction::SetNE:
3739 if (LoOverflow && HiOverflow)
3740 return ReplaceInstUsesWith(I, ConstantBool::True);
3741 else if (HiOverflow)
3742 return new SetCondInst(Instruction::SetLT, X, LoBound);
3743 else if (LoOverflow)
3744 return new SetCondInst(Instruction::SetGE, X, HiBound);
3745 else
3746 return InsertRangeTest(X, LoBound, HiBound, false, I);
3747 case Instruction::SetLT:
3748 if (LoOverflow)
3749 return ReplaceInstUsesWith(I, ConstantBool::False);
3750 return new SetCondInst(Instruction::SetLT, X, LoBound);
3751 case Instruction::SetGT:
3752 if (HiOverflow)
3753 return ReplaceInstUsesWith(I, ConstantBool::False);
3754 return new SetCondInst(Instruction::SetGE, X, HiBound);
3755 }
3756 }
3757 }
3758 break;
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00003759 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003760
Chris Lattnerd492a0b2003-07-23 17:02:11 +00003761 // Simplify seteq and setne instructions...
3762 if (I.getOpcode() == Instruction::SetEQ ||
3763 I.getOpcode() == Instruction::SetNE) {
3764 bool isSetNE = I.getOpcode() == Instruction::SetNE;
3765
Chris Lattnercfbce7c2003-07-23 17:26:36 +00003766 // If the first operand is (and|or|xor) with a constant, and the second
Chris Lattnerd492a0b2003-07-23 17:02:11 +00003767 // operand is a constant, simplify a bit.
Chris Lattnerc992add2003-08-13 05:33:12 +00003768 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
3769 switch (BO->getOpcode()) {
Chris Lattner23b47b62004-07-06 07:38:18 +00003770 case Instruction::Rem:
3771 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
3772 if (CI->isNullValue() && isa<ConstantSInt>(BO->getOperand(1)) &&
3773 BO->hasOneUse() &&
Chris Lattner22d00a82005-08-02 19:16:58 +00003774 cast<ConstantSInt>(BO->getOperand(1))->getValue() > 1) {
3775 int64_t V = cast<ConstantSInt>(BO->getOperand(1))->getValue();
3776 if (isPowerOf2_64(V)) {
3777 unsigned L2 = Log2_64(V);
Chris Lattner23b47b62004-07-06 07:38:18 +00003778 const Type *UTy = BO->getType()->getUnsignedVersion();
3779 Value *NewX = InsertNewInstBefore(new CastInst(BO->getOperand(0),
3780 UTy, "tmp"), I);
3781 Constant *RHSCst = ConstantUInt::get(UTy, 1ULL << L2);
3782 Value *NewRem =InsertNewInstBefore(BinaryOperator::createRem(NewX,
3783 RHSCst, BO->getName()), I);
3784 return BinaryOperator::create(I.getOpcode(), NewRem,
3785 Constant::getNullValue(UTy));
3786 }
Chris Lattner22d00a82005-08-02 19:16:58 +00003787 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003788 break;
Chris Lattner23b47b62004-07-06 07:38:18 +00003789
Chris Lattnerc992add2003-08-13 05:33:12 +00003790 case Instruction::Add:
Chris Lattner6e079362004-06-27 22:51:36 +00003791 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
3792 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerb121ae12004-09-21 21:35:23 +00003793 if (BO->hasOneUse())
3794 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
3795 ConstantExpr::getSub(CI, BOp1C));
Chris Lattner6e079362004-06-27 22:51:36 +00003796 } else if (CI->isNullValue()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00003797 // Replace ((add A, B) != 0) with (A != -B) if A or B is
3798 // efficiently invertible, or if the add has just this one use.
3799 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003800
Chris Lattnerc992add2003-08-13 05:33:12 +00003801 if (Value *NegVal = dyn_castNegVal(BOp1))
3802 return new SetCondInst(I.getOpcode(), BOp0, NegVal);
3803 else if (Value *NegVal = dyn_castNegVal(BOp0))
3804 return new SetCondInst(I.getOpcode(), NegVal, BOp1);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00003805 else if (BO->hasOneUse()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00003806 Instruction *Neg = BinaryOperator::createNeg(BOp1, BO->getName());
3807 BO->setName("");
3808 InsertNewInstBefore(Neg, I);
3809 return new SetCondInst(I.getOpcode(), BOp0, Neg);
3810 }
3811 }
3812 break;
3813 case Instruction::Xor:
3814 // For the xor case, we can xor two constants together, eliminating
3815 // the explicit xor.
3816 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
3817 return BinaryOperator::create(I.getOpcode(), BO->getOperand(0),
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003818 ConstantExpr::getXor(CI, BOC));
Chris Lattnerc992add2003-08-13 05:33:12 +00003819
3820 // FALLTHROUGH
3821 case Instruction::Sub:
3822 // Replace (([sub|xor] A, B) != 0) with (A != B)
3823 if (CI->isNullValue())
3824 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
3825 BO->getOperand(1));
3826 break;
3827
3828 case Instruction::Or:
3829 // If bits are being or'd in that are not present in the constant we
3830 // are comparing against, then the comparison could never succeed!
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003831 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Chris Lattnerc8e7e292004-06-10 02:12:35 +00003832 Constant *NotCI = ConstantExpr::getNot(CI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003833 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Chris Lattnerd492a0b2003-07-23 17:02:11 +00003834 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003835 }
Chris Lattnerc992add2003-08-13 05:33:12 +00003836 break;
3837
3838 case Instruction::And:
3839 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerd492a0b2003-07-23 17:02:11 +00003840 // If bits are being compared against that are and'd out, then the
3841 // comparison can never succeed!
Chris Lattnerc8e7e292004-06-10 02:12:35 +00003842 if (!ConstantExpr::getAnd(CI,
3843 ConstantExpr::getNot(BOC))->isNullValue())
Chris Lattnerd492a0b2003-07-23 17:02:11 +00003844 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattnerc992add2003-08-13 05:33:12 +00003845
Chris Lattner35167c32004-06-09 07:59:58 +00003846 // If we have ((X & C) == C), turn it into ((X & C) != 0).
Chris Lattneree59d4b2004-06-10 02:33:20 +00003847 if (CI == BOC && isOneBitSet(CI))
Chris Lattner35167c32004-06-09 07:59:58 +00003848 return new SetCondInst(isSetNE ? Instruction::SetEQ :
3849 Instruction::SetNE, Op0,
3850 Constant::getNullValue(CI->getType()));
Chris Lattner35167c32004-06-09 07:59:58 +00003851
Chris Lattnerc992add2003-08-13 05:33:12 +00003852 // Replace (and X, (1 << size(X)-1) != 0) with x < 0, converting X
3853 // to be a signed value as appropriate.
3854 if (isSignBit(BOC)) {
3855 Value *X = BO->getOperand(0);
3856 // If 'X' is not signed, insert a cast now...
3857 if (!BOC->getType()->isSigned()) {
Chris Lattner97bfcea2004-06-17 18:16:02 +00003858 const Type *DestTy = BOC->getType()->getSignedVersion();
Chris Lattnerbfff18a2004-09-27 19:29:18 +00003859 X = InsertCastBefore(X, DestTy, I);
Chris Lattnerc992add2003-08-13 05:33:12 +00003860 }
3861 return new SetCondInst(isSetNE ? Instruction::SetLT :
3862 Instruction::SetGE, X,
3863 Constant::getNullValue(X->getType()));
3864 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003865
Chris Lattnerbfff18a2004-09-27 19:29:18 +00003866 // ((X & ~7) == 0) --> X < 8
Chris Lattner8fc5af42004-09-23 21:46:38 +00003867 if (CI->isNullValue() && isHighOnes(BOC)) {
3868 Value *X = BO->getOperand(0);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00003869 Constant *NegX = ConstantExpr::getNeg(BOC);
Chris Lattner8fc5af42004-09-23 21:46:38 +00003870
3871 // If 'X' is signed, insert a cast now.
Chris Lattnerbfff18a2004-09-27 19:29:18 +00003872 if (NegX->getType()->isSigned()) {
3873 const Type *DestTy = NegX->getType()->getUnsignedVersion();
3874 X = InsertCastBefore(X, DestTy, I);
3875 NegX = ConstantExpr::getCast(NegX, DestTy);
Chris Lattner8fc5af42004-09-23 21:46:38 +00003876 }
3877
3878 return new SetCondInst(isSetNE ? Instruction::SetGE :
Chris Lattnerbfff18a2004-09-27 19:29:18 +00003879 Instruction::SetLT, X, NegX);
Chris Lattner8fc5af42004-09-23 21:46:38 +00003880 }
3881
Chris Lattnerd492a0b2003-07-23 17:02:11 +00003882 }
Chris Lattnerc992add2003-08-13 05:33:12 +00003883 default: break;
3884 }
3885 }
Chris Lattner2b55ea32004-02-23 07:16:20 +00003886 } else { // Not a SetEQ/SetNE
Misha Brukmanb1c93172005-04-21 23:48:37 +00003887 // If the LHS is a cast from an integral value of the same size,
Chris Lattner2b55ea32004-02-23 07:16:20 +00003888 if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
3889 Value *CastOp = Cast->getOperand(0);
3890 const Type *SrcTy = CastOp->getType();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003891 unsigned SrcTySize = SrcTy->getPrimitiveSizeInBits();
Chris Lattner2b55ea32004-02-23 07:16:20 +00003892 if (SrcTy != Cast->getType() && SrcTy->isInteger() &&
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003893 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00003894 assert((SrcTy->isSigned() ^ Cast->getType()->isSigned()) &&
Chris Lattner2b55ea32004-02-23 07:16:20 +00003895 "Source and destination signednesses should differ!");
3896 if (Cast->getType()->isSigned()) {
3897 // If this is a signed comparison, check for comparisons in the
3898 // vicinity of zero.
3899 if (I.getOpcode() == Instruction::SetLT && CI->isNullValue())
3900 // X < 0 => x > 127
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003901 return BinaryOperator::createSetGT(CastOp,
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003902 ConstantUInt::get(SrcTy, (1ULL << (SrcTySize-1))-1));
Chris Lattner2b55ea32004-02-23 07:16:20 +00003903 else if (I.getOpcode() == Instruction::SetGT &&
3904 cast<ConstantSInt>(CI)->getValue() == -1)
3905 // X > -1 => x < 128
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003906 return BinaryOperator::createSetLT(CastOp,
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003907 ConstantUInt::get(SrcTy, 1ULL << (SrcTySize-1)));
Chris Lattner2b55ea32004-02-23 07:16:20 +00003908 } else {
3909 ConstantUInt *CUI = cast<ConstantUInt>(CI);
3910 if (I.getOpcode() == Instruction::SetLT &&
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003911 CUI->getValue() == 1ULL << (SrcTySize-1))
Chris Lattner2b55ea32004-02-23 07:16:20 +00003912 // X < 128 => X > -1
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003913 return BinaryOperator::createSetGT(CastOp,
3914 ConstantSInt::get(SrcTy, -1));
Chris Lattner2b55ea32004-02-23 07:16:20 +00003915 else if (I.getOpcode() == Instruction::SetGT &&
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003916 CUI->getValue() == (1ULL << (SrcTySize-1))-1)
Chris Lattner2b55ea32004-02-23 07:16:20 +00003917 // X > 127 => X < 0
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003918 return BinaryOperator::createSetLT(CastOp,
3919 Constant::getNullValue(SrcTy));
Chris Lattner2b55ea32004-02-23 07:16:20 +00003920 }
3921 }
3922 }
Chris Lattnere967b342003-06-04 05:10:11 +00003923 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003924 }
3925
Chris Lattner77c32c32005-04-23 15:31:55 +00003926 // Handle setcc with constant RHS's that can be integer, FP or pointer.
3927 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
3928 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
3929 switch (LHSI->getOpcode()) {
Chris Lattnera816eee2005-05-01 04:42:15 +00003930 case Instruction::GetElementPtr:
3931 if (RHSC->isNullValue()) {
3932 // Transform setcc GEP P, int 0, int 0, int 0, null -> setcc P, null
3933 bool isAllZeros = true;
3934 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
3935 if (!isa<Constant>(LHSI->getOperand(i)) ||
3936 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
3937 isAllZeros = false;
3938 break;
3939 }
3940 if (isAllZeros)
3941 return new SetCondInst(I.getOpcode(), LHSI->getOperand(0),
3942 Constant::getNullValue(LHSI->getOperand(0)->getType()));
3943 }
3944 break;
3945
Chris Lattner77c32c32005-04-23 15:31:55 +00003946 case Instruction::PHI:
3947 if (Instruction *NV = FoldOpIntoPhi(I))
3948 return NV;
3949 break;
3950 case Instruction::Select:
3951 // If either operand of the select is a constant, we can fold the
3952 // comparison into the select arms, which will cause one to be
3953 // constant folded and the select turned into a bitwise or.
3954 Value *Op1 = 0, *Op2 = 0;
3955 if (LHSI->hasOneUse()) {
3956 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
3957 // Fold the known value into the constant operand.
3958 Op1 = ConstantExpr::get(I.getOpcode(), C, RHSC);
3959 // Insert a new SetCC of the other select operand.
3960 Op2 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
3961 LHSI->getOperand(2), RHSC,
3962 I.getName()), I);
3963 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
3964 // Fold the known value into the constant operand.
3965 Op2 = ConstantExpr::get(I.getOpcode(), C, RHSC);
3966 // Insert a new SetCC of the other select operand.
3967 Op1 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
3968 LHSI->getOperand(1), RHSC,
3969 I.getName()), I);
3970 }
3971 }
Jeff Cohen82639852005-04-23 21:38:35 +00003972
Chris Lattner77c32c32005-04-23 15:31:55 +00003973 if (Op1)
3974 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
3975 break;
3976 }
3977 }
3978
Chris Lattner0798af32005-01-13 20:14:25 +00003979 // If we can optimize a 'setcc GEP, P' or 'setcc P, GEP', do so now.
3980 if (User *GEP = dyn_castGetElementPtr(Op0))
3981 if (Instruction *NI = FoldGEPSetCC(GEP, Op1, I.getOpcode(), I))
3982 return NI;
3983 if (User *GEP = dyn_castGetElementPtr(Op1))
3984 if (Instruction *NI = FoldGEPSetCC(GEP, Op0,
3985 SetCondInst::getSwappedCondition(I.getOpcode()), I))
3986 return NI;
3987
Chris Lattner16930792003-11-03 04:25:02 +00003988 // Test to see if the operands of the setcc are casted versions of other
3989 // values. If the cast can be stripped off both arguments, we do so now.
Chris Lattner6444c372003-11-03 05:17:03 +00003990 if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3991 Value *CastOp0 = CI->getOperand(0);
3992 if (CastOp0->getType()->isLosslesslyConvertibleTo(CI->getType()) &&
Chris Lattner7d2a5392004-03-13 23:54:27 +00003993 (isa<Constant>(Op1) || isa<CastInst>(Op1)) &&
Chris Lattner16930792003-11-03 04:25:02 +00003994 (I.getOpcode() == Instruction::SetEQ ||
3995 I.getOpcode() == Instruction::SetNE)) {
3996 // We keep moving the cast from the left operand over to the right
3997 // operand, where it can often be eliminated completely.
Chris Lattner6444c372003-11-03 05:17:03 +00003998 Op0 = CastOp0;
Misha Brukmanb1c93172005-04-21 23:48:37 +00003999
Chris Lattner16930792003-11-03 04:25:02 +00004000 // If operand #1 is a cast instruction, see if we can eliminate it as
4001 // well.
Chris Lattner6444c372003-11-03 05:17:03 +00004002 if (CastInst *CI2 = dyn_cast<CastInst>(Op1))
4003 if (CI2->getOperand(0)->getType()->isLosslesslyConvertibleTo(
Chris Lattner16930792003-11-03 04:25:02 +00004004 Op0->getType()))
Chris Lattner6444c372003-11-03 05:17:03 +00004005 Op1 = CI2->getOperand(0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004006
Chris Lattner16930792003-11-03 04:25:02 +00004007 // If Op1 is a constant, we can fold the cast into the constant.
4008 if (Op1->getType() != Op0->getType())
4009 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
4010 Op1 = ConstantExpr::getCast(Op1C, Op0->getType());
4011 } else {
4012 // Otherwise, cast the RHS right before the setcc
4013 Op1 = new CastInst(Op1, Op0->getType(), Op1->getName());
4014 InsertNewInstBefore(cast<Instruction>(Op1), I);
4015 }
4016 return BinaryOperator::create(I.getOpcode(), Op0, Op1);
4017 }
4018
Chris Lattner6444c372003-11-03 05:17:03 +00004019 // Handle the special case of: setcc (cast bool to X), <cst>
4020 // This comes up when you have code like
4021 // int X = A < B;
4022 // if (X) ...
4023 // For generality, we handle any zero-extension of any operand comparison
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004024 // with a constant or another cast from the same type.
4025 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
4026 if (Instruction *R = visitSetCondInstWithCastAndCast(I))
4027 return R;
Chris Lattner6444c372003-11-03 05:17:03 +00004028 }
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00004029
4030 if (I.getOpcode() == Instruction::SetNE ||
4031 I.getOpcode() == Instruction::SetEQ) {
4032 Value *A, *B;
4033 if (match(Op0, m_Xor(m_Value(A), m_Value(B))) &&
4034 (A == Op1 || B == Op1)) {
4035 // (A^B) == A -> B == 0
4036 Value *OtherVal = A == Op1 ? B : A;
4037 return BinaryOperator::create(I.getOpcode(), OtherVal,
4038 Constant::getNullValue(A->getType()));
4039 } else if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
4040 (A == Op0 || B == Op0)) {
4041 // A == (A^B) -> B == 0
4042 Value *OtherVal = A == Op0 ? B : A;
4043 return BinaryOperator::create(I.getOpcode(), OtherVal,
4044 Constant::getNullValue(A->getType()));
4045 } else if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
4046 // (A-B) == A -> B == 0
4047 return BinaryOperator::create(I.getOpcode(), B,
4048 Constant::getNullValue(B->getType()));
4049 } else if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
4050 // A == (A-B) -> B == 0
4051 return BinaryOperator::create(I.getOpcode(), B,
4052 Constant::getNullValue(B->getType()));
4053 }
4054 }
Chris Lattner113f4f42002-06-25 16:13:24 +00004055 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004056}
4057
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004058// visitSetCondInstWithCastAndCast - Handle setcond (cast x to y), (cast/cst).
4059// We only handle extending casts so far.
4060//
4061Instruction *InstCombiner::visitSetCondInstWithCastAndCast(SetCondInst &SCI) {
4062 Value *LHSCIOp = cast<CastInst>(SCI.getOperand(0))->getOperand(0);
4063 const Type *SrcTy = LHSCIOp->getType();
4064 const Type *DestTy = SCI.getOperand(0)->getType();
4065 Value *RHSCIOp;
4066
4067 if (!DestTy->isIntegral() || !SrcTy->isIntegral())
Chris Lattner03f06f12005-01-17 03:20:02 +00004068 return 0;
4069
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004070 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
4071 unsigned DestBits = DestTy->getPrimitiveSizeInBits();
4072 if (SrcBits >= DestBits) return 0; // Only handle extending cast.
4073
4074 // Is this a sign or zero extension?
4075 bool isSignSrc = SrcTy->isSigned();
4076 bool isSignDest = DestTy->isSigned();
4077
4078 if (CastInst *CI = dyn_cast<CastInst>(SCI.getOperand(1))) {
4079 // Not an extension from the same type?
4080 RHSCIOp = CI->getOperand(0);
4081 if (RHSCIOp->getType() != LHSCIOp->getType()) return 0;
4082 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(SCI.getOperand(1))) {
4083 // Compute the constant that would happen if we truncated to SrcTy then
4084 // reextended to DestTy.
4085 Constant *Res = ConstantExpr::getCast(CI, SrcTy);
4086
4087 if (ConstantExpr::getCast(Res, DestTy) == CI) {
4088 RHSCIOp = Res;
4089 } else {
4090 // If the value cannot be represented in the shorter type, we cannot emit
4091 // a simple comparison.
4092 if (SCI.getOpcode() == Instruction::SetEQ)
4093 return ReplaceInstUsesWith(SCI, ConstantBool::False);
4094 if (SCI.getOpcode() == Instruction::SetNE)
4095 return ReplaceInstUsesWith(SCI, ConstantBool::True);
4096
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004097 // Evaluate the comparison for LT.
4098 Value *Result;
4099 if (DestTy->isSigned()) {
4100 // We're performing a signed comparison.
4101 if (isSignSrc) {
4102 // Signed extend and signed comparison.
4103 if (cast<ConstantSInt>(CI)->getValue() < 0) // X < (small) --> false
4104 Result = ConstantBool::False;
4105 else
4106 Result = ConstantBool::True; // X < (large) --> true
4107 } else {
4108 // Unsigned extend and signed comparison.
4109 if (cast<ConstantSInt>(CI)->getValue() < 0)
4110 Result = ConstantBool::False;
4111 else
4112 Result = ConstantBool::True;
4113 }
4114 } else {
4115 // We're performing an unsigned comparison.
4116 if (!isSignSrc) {
4117 // Unsigned extend & compare -> always true.
4118 Result = ConstantBool::True;
4119 } else {
4120 // We're performing an unsigned comp with a sign extended value.
4121 // This is true if the input is >= 0. [aka >s -1]
4122 Constant *NegOne = ConstantIntegral::getAllOnesValue(SrcTy);
4123 Result = InsertNewInstBefore(BinaryOperator::createSetGT(LHSCIOp,
4124 NegOne, SCI.getName()), SCI);
4125 }
Reid Spencer279fa252004-11-28 21:31:15 +00004126 }
Chris Lattner03f06f12005-01-17 03:20:02 +00004127
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00004128 // Finally, return the value computed.
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004129 if (SCI.getOpcode() == Instruction::SetLT) {
4130 return ReplaceInstUsesWith(SCI, Result);
4131 } else {
4132 assert(SCI.getOpcode()==Instruction::SetGT &&"SetCC should be folded!");
4133 if (Constant *CI = dyn_cast<Constant>(Result))
4134 return ReplaceInstUsesWith(SCI, ConstantExpr::getNot(CI));
4135 else
4136 return BinaryOperator::createNot(Result);
4137 }
Chris Lattner03f06f12005-01-17 03:20:02 +00004138 }
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004139 } else {
4140 return 0;
Reid Spencer279fa252004-11-28 21:31:15 +00004141 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004142
Chris Lattner252a8452005-06-16 03:00:08 +00004143 // Okay, just insert a compare of the reduced operands now!
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004144 return BinaryOperator::create(SCI.getOpcode(), LHSCIOp, RHSCIOp);
4145}
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004146
Chris Lattnere8d6c602003-03-10 19:16:08 +00004147Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +00004148 assert(I.getOperand(1)->getType() == Type::UByteTy);
4149 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00004150 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004151
4152 // shl X, 0 == X and shr X, 0 == X
4153 // shl 0, X == 0 and shr 0, X == 0
4154 if (Op1 == Constant::getNullValue(Type::UByteTy) ||
Chris Lattnere6794492002-08-12 21:17:25 +00004155 Op0 == Constant::getNullValue(Op0->getType()))
4156 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf5b4ef72006-02-12 08:07:37 +00004157
Chris Lattner81a7a232004-10-16 18:11:37 +00004158 if (isa<UndefValue>(Op0)) { // undef >>s X -> undef
4159 if (!isLeftShift && I.getType()->isSigned())
Chris Lattner67f05452004-10-16 23:28:04 +00004160 return ReplaceInstUsesWith(I, Op0);
Chris Lattner81a7a232004-10-16 18:11:37 +00004161 else // undef << X -> 0 AND undef >>u X -> 0
4162 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4163 }
4164 if (isa<UndefValue>(Op1)) {
Chris Lattner18aa4d82005-07-20 18:49:28 +00004165 if (isLeftShift || I.getType()->isUnsigned())// X << undef, X >>u undef -> 0
Chris Lattner81a7a232004-10-16 18:11:37 +00004166 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4167 else
4168 return ReplaceInstUsesWith(I, Op0); // X >>s undef -> X
4169 }
4170
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00004171 // shr int -1, X = -1 (for any arithmetic shift rights of ~0)
4172 if (!isLeftShift)
4173 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
4174 if (CSI->isAllOnesValue())
4175 return ReplaceInstUsesWith(I, CSI);
4176
Chris Lattner183b3362004-04-09 19:05:30 +00004177 // Try to fold constant and into select arguments.
4178 if (isa<Constant>(Op0))
4179 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner86102b82005-01-01 16:22:27 +00004180 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00004181 return R;
4182
Chris Lattnerb18dbbf2005-05-08 17:34:56 +00004183 // See if we can turn a signed shr into an unsigned shr.
4184 if (!isLeftShift && I.getType()->isSigned()) {
Chris Lattnerc3ebf402006-02-07 07:27:52 +00004185 if (MaskedValueIsZero(Op0,
4186 1ULL << (I.getType()->getPrimitiveSizeInBits()-1))) {
Chris Lattnerb18dbbf2005-05-08 17:34:56 +00004187 Value *V = InsertCastBefore(Op0, I.getType()->getUnsignedVersion(), I);
4188 V = InsertNewInstBefore(new ShiftInst(Instruction::Shr, V, Op1,
4189 I.getName()), I);
4190 return new CastInst(V, I.getType());
4191 }
4192 }
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00004193
Chris Lattner14553932006-01-06 07:12:35 +00004194 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op1))
4195 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
4196 return Res;
4197 return 0;
4198}
4199
4200Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantUInt *Op1,
4201 ShiftInst &I) {
4202 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattnerb3309392006-01-06 07:22:22 +00004203 bool isSignedShift = Op0->getType()->isSigned();
4204 bool isUnsignedShift = !isSignedShift;
Chris Lattner14553932006-01-06 07:12:35 +00004205
Chris Lattnerf5b4ef72006-02-12 08:07:37 +00004206 // See if we can simplify any instructions used by the instruction whose sole
4207 // purpose is to compute bits we don't care about.
4208 uint64_t KnownZero, KnownOne;
4209 if (SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
4210 KnownZero, KnownOne))
4211 return &I;
4212
Chris Lattner14553932006-01-06 07:12:35 +00004213 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
4214 // of a signed value.
4215 //
4216 unsigned TypeBits = Op0->getType()->getPrimitiveSizeInBits();
4217 if (Op1->getValue() >= TypeBits) {
Chris Lattnerb3309392006-01-06 07:22:22 +00004218 if (isUnsignedShift || isLeftShift)
Chris Lattner14553932006-01-06 07:12:35 +00004219 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
4220 else {
4221 I.setOperand(1, ConstantUInt::get(Type::UByteTy, TypeBits-1));
4222 return &I;
Chris Lattnerf5ce2542004-02-23 20:30:06 +00004223 }
Chris Lattner14553932006-01-06 07:12:35 +00004224 }
4225
4226 // ((X*C1) << C2) == (X * (C1 << C2))
4227 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
4228 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
4229 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
4230 return BinaryOperator::createMul(BO->getOperand(0),
4231 ConstantExpr::getShl(BOOp, Op1));
4232
4233 // Try to fold constant and into select arguments.
4234 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4235 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4236 return R;
4237 if (isa<PHINode>(Op0))
4238 if (Instruction *NV = FoldOpIntoPhi(I))
4239 return NV;
4240
4241 if (Op0->hasOneUse()) {
Chris Lattner14553932006-01-06 07:12:35 +00004242 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
4243 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
4244 Value *V1, *V2;
4245 ConstantInt *CC;
4246 switch (Op0BO->getOpcode()) {
Chris Lattner27cb9db2005-09-18 05:12:10 +00004247 default: break;
4248 case Instruction::Add:
4249 case Instruction::And:
4250 case Instruction::Or:
4251 case Instruction::Xor:
4252 // These operators commute.
4253 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner797dee72005-09-18 06:30:59 +00004254 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
4255 match(Op0BO->getOperand(1),
Chris Lattner14553932006-01-06 07:12:35 +00004256 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Chris Lattner797dee72005-09-18 06:30:59 +00004257 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00004258 Op0BO->getOperand(0), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00004259 Op0BO->getName());
4260 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner24cd2fa2006-02-09 07:41:14 +00004261 Instruction *X =
4262 BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
4263 Op0BO->getOperand(1)->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00004264 InsertNewInstBefore(X, I); // (X + (Y << C))
4265 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
Chris Lattner14553932006-01-06 07:12:35 +00004266 C2 = ConstantExpr::getShl(C2, Op1);
Chris Lattner797dee72005-09-18 06:30:59 +00004267 return BinaryOperator::createAnd(X, C2);
4268 }
Chris Lattner14553932006-01-06 07:12:35 +00004269
Chris Lattner797dee72005-09-18 06:30:59 +00004270 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
4271 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
4272 match(Op0BO->getOperand(1),
4273 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner14553932006-01-06 07:12:35 +00004274 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner24cd2fa2006-02-09 07:41:14 +00004275 cast<BinaryOperator>(Op0BO->getOperand(1))->getOperand(0)->hasOneUse()) {
Chris Lattner797dee72005-09-18 06:30:59 +00004276 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00004277 Op0BO->getOperand(0), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00004278 Op0BO->getName());
4279 InsertNewInstBefore(YS, I); // (Y << C)
4280 Instruction *XM =
Chris Lattner14553932006-01-06 07:12:35 +00004281 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner797dee72005-09-18 06:30:59 +00004282 V1->getName()+".mask");
4283 InsertNewInstBefore(XM, I); // X & (CC << C)
4284
4285 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
4286 }
Chris Lattner14553932006-01-06 07:12:35 +00004287
Chris Lattner797dee72005-09-18 06:30:59 +00004288 // FALL THROUGH.
Chris Lattner27cb9db2005-09-18 05:12:10 +00004289 case Instruction::Sub:
4290 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner797dee72005-09-18 06:30:59 +00004291 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
4292 match(Op0BO->getOperand(0),
Chris Lattner14553932006-01-06 07:12:35 +00004293 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Chris Lattner797dee72005-09-18 06:30:59 +00004294 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00004295 Op0BO->getOperand(1), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00004296 Op0BO->getName());
4297 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner24cd2fa2006-02-09 07:41:14 +00004298 Instruction *X =
4299 BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
4300 Op0BO->getOperand(0)->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00004301 InsertNewInstBefore(X, I); // (X + (Y << C))
4302 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
Chris Lattner14553932006-01-06 07:12:35 +00004303 C2 = ConstantExpr::getShl(C2, Op1);
Chris Lattner797dee72005-09-18 06:30:59 +00004304 return BinaryOperator::createAnd(X, C2);
4305 }
Chris Lattner14553932006-01-06 07:12:35 +00004306
Chris Lattner797dee72005-09-18 06:30:59 +00004307 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
4308 match(Op0BO->getOperand(0),
4309 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner14553932006-01-06 07:12:35 +00004310 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner24cd2fa2006-02-09 07:41:14 +00004311 cast<BinaryOperator>(Op0BO->getOperand(0))
4312 ->getOperand(0)->hasOneUse()) {
Chris Lattner797dee72005-09-18 06:30:59 +00004313 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00004314 Op0BO->getOperand(1), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00004315 Op0BO->getName());
4316 InsertNewInstBefore(YS, I); // (Y << C)
4317 Instruction *XM =
Chris Lattner14553932006-01-06 07:12:35 +00004318 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner797dee72005-09-18 06:30:59 +00004319 V1->getName()+".mask");
4320 InsertNewInstBefore(XM, I); // X & (CC << C)
4321
4322 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
4323 }
Chris Lattner14553932006-01-06 07:12:35 +00004324
Chris Lattner27cb9db2005-09-18 05:12:10 +00004325 break;
Chris Lattner14553932006-01-06 07:12:35 +00004326 }
4327
4328
4329 // If the operand is an bitwise operator with a constant RHS, and the
4330 // shift is the only use, we can pull it out of the shift.
4331 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
4332 bool isValid = true; // Valid only for And, Or, Xor
4333 bool highBitSet = false; // Transform if high bit of constant set?
4334
4335 switch (Op0BO->getOpcode()) {
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00004336 default: isValid = false; break; // Do not perform transform!
Chris Lattner44bd3922004-10-08 03:46:20 +00004337 case Instruction::Add:
4338 isValid = isLeftShift;
4339 break;
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00004340 case Instruction::Or:
4341 case Instruction::Xor:
4342 highBitSet = false;
4343 break;
4344 case Instruction::And:
4345 highBitSet = true;
4346 break;
Chris Lattner14553932006-01-06 07:12:35 +00004347 }
4348
4349 // If this is a signed shift right, and the high bit is modified
4350 // by the logical operation, do not perform the transformation.
4351 // The highBitSet boolean indicates the value of the high bit of
4352 // the constant which would cause it to be modified for this
4353 // operation.
4354 //
Chris Lattnerb3309392006-01-06 07:22:22 +00004355 if (isValid && !isLeftShift && isSignedShift) {
Chris Lattner14553932006-01-06 07:12:35 +00004356 uint64_t Val = Op0C->getRawValue();
4357 isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
4358 }
4359
4360 if (isValid) {
4361 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
4362
4363 Instruction *NewShift =
4364 new ShiftInst(I.getOpcode(), Op0BO->getOperand(0), Op1,
4365 Op0BO->getName());
4366 Op0BO->setName("");
4367 InsertNewInstBefore(NewShift, I);
4368
4369 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
4370 NewRHS);
4371 }
4372 }
4373 }
4374 }
4375
Chris Lattnereb372a02006-01-06 07:52:12 +00004376 // Find out if this is a shift of a shift by a constant.
4377 ShiftInst *ShiftOp = 0;
Chris Lattner14553932006-01-06 07:12:35 +00004378 if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0))
Chris Lattnereb372a02006-01-06 07:52:12 +00004379 ShiftOp = Op0SI;
4380 else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
4381 // If this is a noop-integer case of a shift instruction, use the shift.
4382 if (CI->getOperand(0)->getType()->isInteger() &&
4383 CI->getOperand(0)->getType()->getPrimitiveSizeInBits() ==
4384 CI->getType()->getPrimitiveSizeInBits() &&
4385 isa<ShiftInst>(CI->getOperand(0))) {
4386 ShiftOp = cast<ShiftInst>(CI->getOperand(0));
4387 }
4388 }
4389
4390 if (ShiftOp && isa<ConstantUInt>(ShiftOp->getOperand(1))) {
4391 // Find the operands and properties of the input shift. Note that the
4392 // signedness of the input shift may differ from the current shift if there
4393 // is a noop cast between the two.
4394 bool isShiftOfLeftShift = ShiftOp->getOpcode() == Instruction::Shl;
4395 bool isShiftOfSignedShift = ShiftOp->getType()->isSigned();
Chris Lattner9cbfbc22006-01-07 01:32:28 +00004396 bool isShiftOfUnsignedShift = !isShiftOfSignedShift;
Chris Lattnereb372a02006-01-06 07:52:12 +00004397
4398 ConstantUInt *ShiftAmt1C = cast<ConstantUInt>(ShiftOp->getOperand(1));
4399
4400 unsigned ShiftAmt1 = (unsigned)ShiftAmt1C->getValue();
4401 unsigned ShiftAmt2 = (unsigned)Op1->getValue();
4402
4403 // Check for (A << c1) << c2 and (A >> c1) >> c2.
4404 if (isLeftShift == isShiftOfLeftShift) {
4405 // Do not fold these shifts if the first one is signed and the second one
4406 // is unsigned and this is a right shift. Further, don't do any folding
4407 // on them.
4408 if (isShiftOfSignedShift && isUnsignedShift && !isLeftShift)
4409 return 0;
Chris Lattner14553932006-01-06 07:12:35 +00004410
Chris Lattnereb372a02006-01-06 07:52:12 +00004411 unsigned Amt = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
4412 if (Amt > Op0->getType()->getPrimitiveSizeInBits())
4413 Amt = Op0->getType()->getPrimitiveSizeInBits();
Chris Lattner14553932006-01-06 07:12:35 +00004414
Chris Lattnereb372a02006-01-06 07:52:12 +00004415 Value *Op = ShiftOp->getOperand(0);
4416 if (isShiftOfSignedShift != isSignedShift)
4417 Op = InsertNewInstBefore(new CastInst(Op, I.getType(), "tmp"), I);
4418 return new ShiftInst(I.getOpcode(), Op,
4419 ConstantUInt::get(Type::UByteTy, Amt));
4420 }
4421
4422 // Check for (A << c1) >> c2 or (A >> c1) << c2. If we are dealing with
4423 // signed types, we can only support the (A >> c1) << c2 configuration,
4424 // because it can not turn an arbitrary bit of A into a sign bit.
4425 if (isUnsignedShift || isLeftShift) {
4426 // Calculate bitmask for what gets shifted off the edge.
4427 Constant *C = ConstantIntegral::getAllOnesValue(I.getType());
4428 if (isLeftShift)
4429 C = ConstantExpr::getShl(C, ShiftAmt1C);
4430 else
Chris Lattner9cbfbc22006-01-07 01:32:28 +00004431 C = ConstantExpr::getUShr(C, ShiftAmt1C);
Chris Lattnereb372a02006-01-06 07:52:12 +00004432
4433 Value *Op = ShiftOp->getOperand(0);
4434 if (isShiftOfSignedShift != isSignedShift)
4435 Op = InsertNewInstBefore(new CastInst(Op, I.getType(),Op->getName()),I);
4436
4437 Instruction *Mask =
4438 BinaryOperator::createAnd(Op, C, Op->getName()+".mask");
4439 InsertNewInstBefore(Mask, I);
4440
4441 // Figure out what flavor of shift we should use...
Chris Lattner9cbfbc22006-01-07 01:32:28 +00004442 if (ShiftAmt1 == ShiftAmt2) {
Chris Lattnereb372a02006-01-06 07:52:12 +00004443 return ReplaceInstUsesWith(I, Mask); // (A << c) >> c === A & c2
Chris Lattner9cbfbc22006-01-07 01:32:28 +00004444 } else if (ShiftAmt1 < ShiftAmt2) {
Chris Lattnereb372a02006-01-06 07:52:12 +00004445 return new ShiftInst(I.getOpcode(), Mask,
4446 ConstantUInt::get(Type::UByteTy, ShiftAmt2-ShiftAmt1));
Chris Lattner9cbfbc22006-01-07 01:32:28 +00004447 } else if (isShiftOfUnsignedShift || isShiftOfLeftShift) {
4448 if (isShiftOfUnsignedShift && !isShiftOfLeftShift && isSignedShift) {
4449 // Make sure to emit an unsigned shift right, not a signed one.
4450 Mask = InsertNewInstBefore(new CastInst(Mask,
4451 Mask->getType()->getUnsignedVersion(),
4452 Op->getName()), I);
4453 Mask = new ShiftInst(Instruction::Shr, Mask,
Chris Lattnereb372a02006-01-06 07:52:12 +00004454 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
Chris Lattner9cbfbc22006-01-07 01:32:28 +00004455 InsertNewInstBefore(Mask, I);
4456 return new CastInst(Mask, I.getType());
4457 } else {
4458 return new ShiftInst(ShiftOp->getOpcode(), Mask,
4459 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
4460 }
4461 } else {
4462 // (X >>s C1) << C2 where C1 > C2 === (X >>s (C1-C2)) & mask
4463 Op = InsertNewInstBefore(new CastInst(Mask,
4464 I.getType()->getSignedVersion(),
4465 Mask->getName()), I);
4466 Instruction *Shift =
4467 new ShiftInst(ShiftOp->getOpcode(), Op,
4468 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
4469 InsertNewInstBefore(Shift, I);
4470
4471 C = ConstantIntegral::getAllOnesValue(Shift->getType());
4472 C = ConstantExpr::getShl(C, Op1);
4473 Mask = BinaryOperator::createAnd(Shift, C, Op->getName()+".mask");
4474 InsertNewInstBefore(Mask, I);
4475 return new CastInst(Mask, I.getType());
Chris Lattnereb372a02006-01-06 07:52:12 +00004476 }
4477 } else {
Chris Lattner9cbfbc22006-01-07 01:32:28 +00004478 // We can handle signed (X << C1) >>s C2 if it's a sign extend. In
Chris Lattnereb372a02006-01-06 07:52:12 +00004479 // this case, C1 == C2 and C1 is 8, 16, or 32.
4480 if (ShiftAmt1 == ShiftAmt2) {
4481 const Type *SExtType = 0;
Chris Lattner655d08f2006-04-28 22:21:41 +00004482 switch (Op0->getType()->getPrimitiveSizeInBits() - ShiftAmt1) {
Chris Lattnereb372a02006-01-06 07:52:12 +00004483 case 8 : SExtType = Type::SByteTy; break;
4484 case 16: SExtType = Type::ShortTy; break;
4485 case 32: SExtType = Type::IntTy; break;
4486 }
4487
4488 if (SExtType) {
4489 Instruction *NewTrunc = new CastInst(ShiftOp->getOperand(0),
4490 SExtType, "sext");
4491 InsertNewInstBefore(NewTrunc, I);
4492 return new CastInst(NewTrunc, I.getType());
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00004493 }
Chris Lattner27cb9db2005-09-18 05:12:10 +00004494 }
Chris Lattner86102b82005-01-01 16:22:27 +00004495 }
Chris Lattnereb372a02006-01-06 07:52:12 +00004496 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004497 return 0;
4498}
4499
Chris Lattner4e2dbc62004-07-20 00:59:32 +00004500enum CastType {
4501 Noop = 0,
4502 Truncate = 1,
4503 Signext = 2,
4504 Zeroext = 3
4505};
4506
4507/// getCastType - In the future, we will split the cast instruction into these
4508/// various types. Until then, we have to do the analysis here.
4509static CastType getCastType(const Type *Src, const Type *Dest) {
4510 assert(Src->isIntegral() && Dest->isIntegral() &&
4511 "Only works on integral types!");
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004512 unsigned SrcSize = Src->getPrimitiveSizeInBits();
4513 unsigned DestSize = Dest->getPrimitiveSizeInBits();
Chris Lattner4e2dbc62004-07-20 00:59:32 +00004514
4515 if (SrcSize == DestSize) return Noop;
4516 if (SrcSize > DestSize) return Truncate;
4517 if (Src->isSigned()) return Signext;
4518 return Zeroext;
4519}
4520
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004521
Chris Lattner48a44f72002-05-02 17:06:02 +00004522// isEliminableCastOfCast - Return true if it is valid to eliminate the CI
4523// instruction.
4524//
Chris Lattnere154abf2006-01-19 07:40:22 +00004525static bool isEliminableCastOfCast(const Type *SrcTy, const Type *MidTy,
4526 const Type *DstTy, TargetData *TD) {
Chris Lattner48a44f72002-05-02 17:06:02 +00004527
Chris Lattner650b6da2002-08-02 20:00:25 +00004528 // It is legal to eliminate the instruction if casting A->B->A if the sizes
Misha Brukmanb1c93172005-04-21 23:48:37 +00004529 // are identical and the bits don't get reinterpreted (for example
Chris Lattner1638de42004-07-21 19:50:44 +00004530 // int->float->int would not be allowed).
Misha Brukmane5838c42003-05-20 18:45:36 +00004531 if (SrcTy == DstTy && SrcTy->isLosslesslyConvertibleTo(MidTy))
Chris Lattner650b6da2002-08-02 20:00:25 +00004532 return true;
Chris Lattner48a44f72002-05-02 17:06:02 +00004533
Chris Lattner4fbad962004-07-21 04:27:24 +00004534 // If we are casting between pointer and integer types, treat pointers as
4535 // integers of the appropriate size for the code below.
4536 if (isa<PointerType>(SrcTy)) SrcTy = TD->getIntPtrType();
4537 if (isa<PointerType>(MidTy)) MidTy = TD->getIntPtrType();
4538 if (isa<PointerType>(DstTy)) DstTy = TD->getIntPtrType();
Chris Lattner11ffd592004-07-20 05:21:00 +00004539
Chris Lattner48a44f72002-05-02 17:06:02 +00004540 // Allow free casting and conversion of sizes as long as the sign doesn't
4541 // change...
Chris Lattnerb0b412e2002-09-03 01:08:28 +00004542 if (SrcTy->isIntegral() && MidTy->isIntegral() && DstTy->isIntegral()) {
Chris Lattner4e2dbc62004-07-20 00:59:32 +00004543 CastType FirstCast = getCastType(SrcTy, MidTy);
4544 CastType SecondCast = getCastType(MidTy, DstTy);
Chris Lattner650b6da2002-08-02 20:00:25 +00004545
Chris Lattner4e2dbc62004-07-20 00:59:32 +00004546 // Capture the effect of these two casts. If the result is a legal cast,
4547 // the CastType is stored here, otherwise a special code is used.
4548 static const unsigned CastResult[] = {
4549 // First cast is noop
4550 0, 1, 2, 3,
4551 // First cast is a truncate
4552 1, 1, 4, 4, // trunc->extend is not safe to eliminate
4553 // First cast is a sign ext
Chris Lattner1638de42004-07-21 19:50:44 +00004554 2, 5, 2, 4, // signext->zeroext never ok
Chris Lattner4e2dbc62004-07-20 00:59:32 +00004555 // First cast is a zero ext
Chris Lattner1638de42004-07-21 19:50:44 +00004556 3, 5, 3, 3,
Chris Lattner4e2dbc62004-07-20 00:59:32 +00004557 };
4558
4559 unsigned Result = CastResult[FirstCast*4+SecondCast];
4560 switch (Result) {
4561 default: assert(0 && "Illegal table value!");
4562 case 0:
4563 case 1:
4564 case 2:
4565 case 3:
4566 // FIXME: in the future, when LLVM has explicit sign/zeroextends and
4567 // truncates, we could eliminate more casts.
4568 return (unsigned)getCastType(SrcTy, DstTy) == Result;
4569 case 4:
4570 return false; // Not possible to eliminate this here.
4571 case 5:
Chris Lattner1638de42004-07-21 19:50:44 +00004572 // Sign or zero extend followed by truncate is always ok if the result
4573 // is a truncate or noop.
4574 CastType ResultCast = getCastType(SrcTy, DstTy);
4575 if (ResultCast == Noop || ResultCast == Truncate)
4576 return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +00004577 // Otherwise we are still growing the value, we are only safe if the
Chris Lattner1638de42004-07-21 19:50:44 +00004578 // result will match the sign/zeroextendness of the result.
4579 return ResultCast == FirstCast;
Chris Lattner3732aca2002-08-15 16:15:25 +00004580 }
Chris Lattner650b6da2002-08-02 20:00:25 +00004581 }
Chris Lattnere154abf2006-01-19 07:40:22 +00004582
4583 // If this is a cast from 'float -> double -> integer', cast from
4584 // 'float -> integer' directly, as the value isn't changed by the
4585 // float->double conversion.
4586 if (SrcTy->isFloatingPoint() && MidTy->isFloatingPoint() &&
4587 DstTy->isIntegral() &&
4588 SrcTy->getPrimitiveSize() < MidTy->getPrimitiveSize())
4589 return true;
4590
Chris Lattnercaba72b2006-04-02 05:43:13 +00004591 // Packed type conversions don't modify bits.
4592 if (isa<PackedType>(SrcTy) && isa<PackedType>(MidTy) &&isa<PackedType>(DstTy))
4593 return true;
4594
Chris Lattner48a44f72002-05-02 17:06:02 +00004595 return false;
4596}
4597
Chris Lattner11ffd592004-07-20 05:21:00 +00004598static bool ValueRequiresCast(const Value *V, const Type *Ty, TargetData *TD) {
Chris Lattnerdfae8be2003-07-24 17:35:25 +00004599 if (V->getType() == Ty || isa<Constant>(V)) return false;
4600 if (const CastInst *CI = dyn_cast<CastInst>(V))
Chris Lattner11ffd592004-07-20 05:21:00 +00004601 if (isEliminableCastOfCast(CI->getOperand(0)->getType(), CI->getType(), Ty,
4602 TD))
Chris Lattnerdfae8be2003-07-24 17:35:25 +00004603 return false;
4604 return true;
4605}
4606
4607/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
4608/// InsertBefore instruction. This is specialized a bit to avoid inserting
4609/// casts that are known to not do anything...
4610///
4611Value *InstCombiner::InsertOperandCastBefore(Value *V, const Type *DestTy,
4612 Instruction *InsertBefore) {
4613 if (V->getType() == DestTy) return V;
4614 if (Constant *C = dyn_cast<Constant>(V))
4615 return ConstantExpr::getCast(C, DestTy);
4616
4617 CastInst *CI = new CastInst(V, DestTy, V->getName());
4618 InsertNewInstBefore(CI, *InsertBefore);
4619 return CI;
4620}
Chris Lattner48a44f72002-05-02 17:06:02 +00004621
Chris Lattner8f663e82005-10-29 04:36:15 +00004622/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
4623/// expression. If so, decompose it, returning some value X, such that Val is
4624/// X*Scale+Offset.
4625///
4626static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
4627 unsigned &Offset) {
4628 assert(Val->getType() == Type::UIntTy && "Unexpected allocation size type!");
4629 if (ConstantUInt *CI = dyn_cast<ConstantUInt>(Val)) {
4630 Offset = CI->getValue();
4631 Scale = 1;
4632 return ConstantUInt::get(Type::UIntTy, 0);
4633 } else if (Instruction *I = dyn_cast<Instruction>(Val)) {
4634 if (I->getNumOperands() == 2) {
4635 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(I->getOperand(1))) {
4636 if (I->getOpcode() == Instruction::Shl) {
4637 // This is a value scaled by '1 << the shift amt'.
4638 Scale = 1U << CUI->getValue();
4639 Offset = 0;
4640 return I->getOperand(0);
4641 } else if (I->getOpcode() == Instruction::Mul) {
4642 // This value is scaled by 'CUI'.
4643 Scale = CUI->getValue();
4644 Offset = 0;
4645 return I->getOperand(0);
4646 } else if (I->getOpcode() == Instruction::Add) {
4647 // We have X+C. Check to see if we really have (X*C2)+C1, where C1 is
4648 // divisible by C2.
4649 unsigned SubScale;
4650 Value *SubVal = DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
4651 Offset);
4652 Offset += CUI->getValue();
4653 if (SubScale > 1 && (Offset % SubScale == 0)) {
4654 Scale = SubScale;
4655 return SubVal;
4656 }
4657 }
4658 }
4659 }
4660 }
4661
4662 // Otherwise, we can't look past this.
4663 Scale = 1;
4664 Offset = 0;
4665 return Val;
4666}
4667
4668
Chris Lattner216be912005-10-24 06:03:58 +00004669/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
4670/// try to eliminate the cast by moving the type information into the alloc.
4671Instruction *InstCombiner::PromoteCastOfAllocation(CastInst &CI,
4672 AllocationInst &AI) {
4673 const PointerType *PTy = dyn_cast<PointerType>(CI.getType());
Chris Lattnerbb171802005-10-27 05:53:56 +00004674 if (!PTy) return 0; // Not casting the allocation to a pointer type.
Chris Lattner216be912005-10-24 06:03:58 +00004675
Chris Lattnerac87beb2005-10-24 06:22:12 +00004676 // Remove any uses of AI that are dead.
4677 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
4678 std::vector<Instruction*> DeadUsers;
4679 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
4680 Instruction *User = cast<Instruction>(*UI++);
4681 if (isInstructionTriviallyDead(User)) {
4682 while (UI != E && *UI == User)
4683 ++UI; // If this instruction uses AI more than once, don't break UI.
4684
4685 // Add operands to the worklist.
4686 AddUsesToWorkList(*User);
4687 ++NumDeadInst;
4688 DEBUG(std::cerr << "IC: DCE: " << *User);
4689
4690 User->eraseFromParent();
4691 removeFromWorkList(User);
4692 }
4693 }
4694
Chris Lattner216be912005-10-24 06:03:58 +00004695 // Get the type really allocated and the type casted to.
4696 const Type *AllocElTy = AI.getAllocatedType();
4697 const Type *CastElTy = PTy->getElementType();
4698 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner355ecc02005-10-24 06:26:18 +00004699
4700 unsigned AllocElTyAlign = TD->getTypeSize(AllocElTy);
4701 unsigned CastElTyAlign = TD->getTypeSize(CastElTy);
4702 if (CastElTyAlign < AllocElTyAlign) return 0;
4703
Chris Lattner46705b22005-10-24 06:35:18 +00004704 // If the allocation has multiple uses, only promote it if we are strictly
4705 // increasing the alignment of the resultant allocation. If we keep it the
4706 // same, we open the door to infinite loops of various kinds.
4707 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
4708
Chris Lattner216be912005-10-24 06:03:58 +00004709 uint64_t AllocElTySize = TD->getTypeSize(AllocElTy);
4710 uint64_t CastElTySize = TD->getTypeSize(CastElTy);
Chris Lattnerbb171802005-10-27 05:53:56 +00004711 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner355ecc02005-10-24 06:26:18 +00004712
Chris Lattner8270c332005-10-29 03:19:53 +00004713 // See if we can satisfy the modulus by pulling a scale out of the array
4714 // size argument.
Chris Lattner8f663e82005-10-29 04:36:15 +00004715 unsigned ArraySizeScale, ArrayOffset;
4716 Value *NumElements = // See if the array size is a decomposable linear expr.
4717 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
4718
Chris Lattner8270c332005-10-29 03:19:53 +00004719 // If we can now satisfy the modulus, by using a non-1 scale, we really can
4720 // do the xform.
Chris Lattner8f663e82005-10-29 04:36:15 +00004721 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
4722 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattnerb3ecf962005-10-27 06:12:00 +00004723
Chris Lattner8270c332005-10-29 03:19:53 +00004724 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
4725 Value *Amt = 0;
4726 if (Scale == 1) {
4727 Amt = NumElements;
4728 } else {
4729 Amt = ConstantUInt::get(Type::UIntTy, Scale);
4730 if (ConstantUInt *CI = dyn_cast<ConstantUInt>(NumElements))
4731 Amt = ConstantExpr::getMul(CI, cast<ConstantUInt>(Amt));
4732 else if (Scale != 1) {
4733 Instruction *Tmp = BinaryOperator::createMul(Amt, NumElements, "tmp");
4734 Amt = InsertNewInstBefore(Tmp, AI);
Chris Lattnerb3ecf962005-10-27 06:12:00 +00004735 }
Chris Lattnerbb171802005-10-27 05:53:56 +00004736 }
4737
Chris Lattner8f663e82005-10-29 04:36:15 +00004738 if (unsigned Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
4739 Value *Off = ConstantUInt::get(Type::UIntTy, Offset);
4740 Instruction *Tmp = BinaryOperator::createAdd(Amt, Off, "tmp");
4741 Amt = InsertNewInstBefore(Tmp, AI);
4742 }
4743
Chris Lattner216be912005-10-24 06:03:58 +00004744 std::string Name = AI.getName(); AI.setName("");
4745 AllocationInst *New;
4746 if (isa<MallocInst>(AI))
Nate Begeman848622f2005-11-05 09:21:28 +00004747 New = new MallocInst(CastElTy, Amt, AI.getAlignment(), Name);
Chris Lattner216be912005-10-24 06:03:58 +00004748 else
Nate Begeman848622f2005-11-05 09:21:28 +00004749 New = new AllocaInst(CastElTy, Amt, AI.getAlignment(), Name);
Chris Lattner216be912005-10-24 06:03:58 +00004750 InsertNewInstBefore(New, AI);
Chris Lattner46705b22005-10-24 06:35:18 +00004751
4752 // If the allocation has multiple uses, insert a cast and change all things
4753 // that used it to use the new cast. This will also hack on CI, but it will
4754 // die soon.
4755 if (!AI.hasOneUse()) {
4756 AddUsesToWorkList(AI);
4757 CastInst *NewCast = new CastInst(New, AI.getType(), "tmpcast");
4758 InsertNewInstBefore(NewCast, AI);
4759 AI.replaceAllUsesWith(NewCast);
4760 }
Chris Lattner216be912005-10-24 06:03:58 +00004761 return ReplaceInstUsesWith(CI, New);
4762}
4763
4764
Chris Lattner48a44f72002-05-02 17:06:02 +00004765// CastInst simplification
Chris Lattner260ab202002-04-18 17:39:14 +00004766//
Chris Lattner113f4f42002-06-25 16:13:24 +00004767Instruction *InstCombiner::visitCastInst(CastInst &CI) {
Chris Lattner55d4bda2003-06-23 21:59:52 +00004768 Value *Src = CI.getOperand(0);
4769
Chris Lattner48a44f72002-05-02 17:06:02 +00004770 // If the user is casting a value to the same type, eliminate this cast
4771 // instruction...
Chris Lattner55d4bda2003-06-23 21:59:52 +00004772 if (CI.getType() == Src->getType())
4773 return ReplaceInstUsesWith(CI, Src);
Chris Lattner48a44f72002-05-02 17:06:02 +00004774
Chris Lattner81a7a232004-10-16 18:11:37 +00004775 if (isa<UndefValue>(Src)) // cast undef -> undef
4776 return ReplaceInstUsesWith(CI, UndefValue::get(CI.getType()));
4777
Chris Lattner48a44f72002-05-02 17:06:02 +00004778 // If casting the result of another cast instruction, try to eliminate this
4779 // one!
4780 //
Chris Lattner86102b82005-01-01 16:22:27 +00004781 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
4782 Value *A = CSrc->getOperand(0);
4783 if (isEliminableCastOfCast(A->getType(), CSrc->getType(),
4784 CI.getType(), TD)) {
Chris Lattner48a44f72002-05-02 17:06:02 +00004785 // This instruction now refers directly to the cast's src operand. This
4786 // has a good chance of making CSrc dead.
Chris Lattner113f4f42002-06-25 16:13:24 +00004787 CI.setOperand(0, CSrc->getOperand(0));
4788 return &CI;
Chris Lattner48a44f72002-05-02 17:06:02 +00004789 }
4790
Chris Lattner650b6da2002-08-02 20:00:25 +00004791 // If this is an A->B->A cast, and we are dealing with integral types, try
4792 // to convert this into a logical 'and' instruction.
4793 //
Misha Brukmanb1c93172005-04-21 23:48:37 +00004794 if (A->getType()->isInteger() &&
Chris Lattnerb0b412e2002-09-03 01:08:28 +00004795 CI.getType()->isInteger() && CSrc->getType()->isInteger() &&
Chris Lattner86102b82005-01-01 16:22:27 +00004796 CSrc->getType()->isUnsigned() && // B->A cast must zero extend
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004797 CSrc->getType()->getPrimitiveSizeInBits() <
4798 CI.getType()->getPrimitiveSizeInBits()&&
4799 A->getType()->getPrimitiveSizeInBits() ==
4800 CI.getType()->getPrimitiveSizeInBits()) {
Chris Lattner650b6da2002-08-02 20:00:25 +00004801 assert(CSrc->getType() != Type::ULongTy &&
4802 "Cannot have type bigger than ulong!");
Chris Lattner77defba2006-02-07 07:00:41 +00004803 uint64_t AndValue = CSrc->getType()->getIntegralTypeMask();
Chris Lattner86102b82005-01-01 16:22:27 +00004804 Constant *AndOp = ConstantUInt::get(A->getType()->getUnsignedVersion(),
4805 AndValue);
4806 AndOp = ConstantExpr::getCast(AndOp, A->getType());
4807 Instruction *And = BinaryOperator::createAnd(CSrc->getOperand(0), AndOp);
4808 if (And->getType() != CI.getType()) {
4809 And->setName(CSrc->getName()+".mask");
4810 InsertNewInstBefore(And, CI);
4811 And = new CastInst(And, CI.getType());
4812 }
4813 return And;
Chris Lattner650b6da2002-08-02 20:00:25 +00004814 }
4815 }
Chris Lattner2590e512006-02-07 06:56:34 +00004816
Chris Lattner03841652004-05-25 04:29:21 +00004817 // If this is a cast to bool, turn it into the appropriate setne instruction.
4818 if (CI.getType() == Type::BoolTy)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004819 return BinaryOperator::createSetNE(CI.getOperand(0),
Chris Lattner03841652004-05-25 04:29:21 +00004820 Constant::getNullValue(CI.getOperand(0)->getType()));
4821
Chris Lattner2590e512006-02-07 06:56:34 +00004822 // See if we can simplify any instructions used by the LHS whose sole
4823 // purpose is to compute bits we don't care about.
Chris Lattner0157e7f2006-02-11 09:31:47 +00004824 if (CI.getType()->isInteger() && CI.getOperand(0)->getType()->isIntegral()) {
4825 uint64_t KnownZero, KnownOne;
4826 if (SimplifyDemandedBits(&CI, CI.getType()->getIntegralTypeMask(),
4827 KnownZero, KnownOne))
4828 return &CI;
4829 }
Chris Lattner2590e512006-02-07 06:56:34 +00004830
Chris Lattnerd0d51602003-06-21 23:12:02 +00004831 // If casting the result of a getelementptr instruction with no offset, turn
4832 // this into a cast of the original pointer!
4833 //
Chris Lattner55d4bda2003-06-23 21:59:52 +00004834 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattnerd0d51602003-06-21 23:12:02 +00004835 bool AllZeroOperands = true;
4836 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
4837 if (!isa<Constant>(GEP->getOperand(i)) ||
4838 !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
4839 AllZeroOperands = false;
4840 break;
4841 }
4842 if (AllZeroOperands) {
4843 CI.setOperand(0, GEP->getOperand(0));
4844 return &CI;
4845 }
4846 }
4847
Chris Lattnerf4ad1652003-11-02 05:57:39 +00004848 // If we are casting a malloc or alloca to a pointer to a type of the same
4849 // size, rewrite the allocation instruction to allocate the "right" type.
4850 //
4851 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
Chris Lattner216be912005-10-24 06:03:58 +00004852 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
4853 return V;
Chris Lattnerf4ad1652003-11-02 05:57:39 +00004854
Chris Lattner86102b82005-01-01 16:22:27 +00004855 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
4856 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
4857 return NV;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00004858 if (isa<PHINode>(Src))
4859 if (Instruction *NV = FoldOpIntoPhi(CI))
4860 return NV;
Chris Lattnerb19a5c62006-04-12 18:09:35 +00004861
4862 // If the source and destination are pointers, and this cast is equivalent to
4863 // a getelementptr X, 0, 0, 0... turn it into the appropriate getelementptr.
4864 // This can enhance SROA and other transforms that want type-safe pointers.
4865 if (const PointerType *DstPTy = dyn_cast<PointerType>(CI.getType()))
4866 if (const PointerType *SrcPTy = dyn_cast<PointerType>(Src->getType())) {
4867 const Type *DstTy = DstPTy->getElementType();
4868 const Type *SrcTy = SrcPTy->getElementType();
4869
4870 Constant *ZeroUInt = Constant::getNullValue(Type::UIntTy);
4871 unsigned NumZeros = 0;
4872 while (SrcTy != DstTy &&
4873 isa<CompositeType>(SrcTy) && !isa<PointerType>(SrcTy)) {
4874 SrcTy = cast<CompositeType>(SrcTy)->getTypeAtIndex(ZeroUInt);
4875 ++NumZeros;
4876 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00004877
Chris Lattnerb19a5c62006-04-12 18:09:35 +00004878 // If we found a path from the src to dest, create the getelementptr now.
4879 if (SrcTy == DstTy) {
4880 std::vector<Value*> Idxs(NumZeros+1, ZeroUInt);
4881 return new GetElementPtrInst(Src, Idxs);
4882 }
4883 }
4884
Chris Lattnerdfae8be2003-07-24 17:35:25 +00004885 // If the source value is an instruction with only this use, we can attempt to
4886 // propagate the cast into the instruction. Also, only handle integral types
4887 // for now.
4888 if (Instruction *SrcI = dyn_cast<Instruction>(Src))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00004889 if (SrcI->hasOneUse() && Src->getType()->isIntegral() &&
Chris Lattnerdfae8be2003-07-24 17:35:25 +00004890 CI.getType()->isInteger()) { // Don't mess with casts to bool here
4891 const Type *DestTy = CI.getType();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004892 unsigned SrcBitSize = Src->getType()->getPrimitiveSizeInBits();
4893 unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
Chris Lattnerdfae8be2003-07-24 17:35:25 +00004894
4895 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
4896 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
4897
4898 switch (SrcI->getOpcode()) {
4899 case Instruction::Add:
4900 case Instruction::Mul:
4901 case Instruction::And:
4902 case Instruction::Or:
4903 case Instruction::Xor:
4904 // If we are discarding information, or just changing the sign, rewrite.
4905 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
4906 // Don't insert two casts if they cannot be eliminated. We allow two
4907 // casts to be inserted if the sizes are the same. This could only be
4908 // converting signedness, which is a noop.
Chris Lattner11ffd592004-07-20 05:21:00 +00004909 if (DestBitSize == SrcBitSize || !ValueRequiresCast(Op1, DestTy,TD) ||
4910 !ValueRequiresCast(Op0, DestTy, TD)) {
Chris Lattnerdfae8be2003-07-24 17:35:25 +00004911 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
4912 Value *Op1c = InsertOperandCastBefore(Op1, DestTy, SrcI);
4913 return BinaryOperator::create(cast<BinaryOperator>(SrcI)
4914 ->getOpcode(), Op0c, Op1c);
4915 }
4916 }
Chris Lattner72086162005-05-06 02:07:39 +00004917
4918 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
4919 if (SrcBitSize == 1 && SrcI->getOpcode() == Instruction::Xor &&
4920 Op1 == ConstantBool::True &&
4921 (!Op0->hasOneUse() || !isa<SetCondInst>(Op0))) {
4922 Value *New = InsertOperandCastBefore(Op0, DestTy, &CI);
4923 return BinaryOperator::createXor(New,
4924 ConstantInt::get(CI.getType(), 1));
4925 }
Chris Lattnerdfae8be2003-07-24 17:35:25 +00004926 break;
4927 case Instruction::Shl:
4928 // Allow changing the sign of the source operand. Do not allow changing
4929 // the size of the shift, UNLESS the shift amount is a constant. We
4930 // mush not change variable sized shifts to a smaller size, because it
4931 // is undefined to shift more bits out than exist in the value.
4932 if (DestBitSize == SrcBitSize ||
4933 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
4934 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
4935 return new ShiftInst(Instruction::Shl, Op0c, Op1);
4936 }
4937 break;
Chris Lattner87380412005-05-06 04:18:52 +00004938 case Instruction::Shr:
4939 // If this is a signed shr, and if all bits shifted in are about to be
4940 // truncated off, turn it into an unsigned shr to allow greater
4941 // simplifications.
4942 if (DestBitSize < SrcBitSize && Src->getType()->isSigned() &&
4943 isa<ConstantInt>(Op1)) {
4944 unsigned ShiftAmt = cast<ConstantUInt>(Op1)->getValue();
4945 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
4946 // Convert to unsigned.
4947 Value *N1 = InsertOperandCastBefore(Op0,
4948 Op0->getType()->getUnsignedVersion(), &CI);
4949 // Insert the new shift, which is now unsigned.
4950 N1 = InsertNewInstBefore(new ShiftInst(Instruction::Shr, N1,
4951 Op1, Src->getName()), CI);
4952 return new CastInst(N1, CI.getType());
4953 }
4954 }
4955 break;
4956
Chris Lattnerc7bfed02006-02-27 02:38:23 +00004957 case Instruction::SetEQ:
Chris Lattner809dfac2005-05-04 19:10:26 +00004958 case Instruction::SetNE:
Chris Lattnerc7bfed02006-02-27 02:38:23 +00004959 // We if we are just checking for a seteq of a single bit and casting it
4960 // to an integer. If so, shift the bit to the appropriate place then
4961 // cast to integer to avoid the comparison.
Chris Lattner809dfac2005-05-04 19:10:26 +00004962 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerc7bfed02006-02-27 02:38:23 +00004963 uint64_t Op1CV = Op1C->getZExtValue();
4964 // cast (X == 0) to int --> X^1 iff X has only the low bit set.
4965 // cast (X == 0) to int --> (X>>1)^1 iff X has only the 2nd bit set.
4966 // cast (X == 1) to int --> X iff X has only the low bit set.
4967 // cast (X == 2) to int --> X>>1 iff X has only the 2nd bit set.
4968 // cast (X != 0) to int --> X iff X has only the low bit set.
4969 // cast (X != 0) to int --> X>>1 iff X has only the 2nd bit set.
4970 // cast (X != 1) to int --> X^1 iff X has only the low bit set.
4971 // cast (X != 2) to int --> (X>>1)^1 iff X has only the 2nd bit set.
4972 if (Op1CV == 0 || isPowerOf2_64(Op1CV)) {
4973 // If Op1C some other power of two, convert:
4974 uint64_t KnownZero, KnownOne;
4975 uint64_t TypeMask = Op1->getType()->getIntegralTypeMask();
4976 ComputeMaskedBits(Op0, TypeMask, KnownZero, KnownOne);
4977
4978 if (isPowerOf2_64(KnownZero^TypeMask)) { // Exactly one possible 1?
4979 bool isSetNE = SrcI->getOpcode() == Instruction::SetNE;
4980 if (Op1CV && (Op1CV != (KnownZero^TypeMask))) {
4981 // (X&4) == 2 --> false
4982 // (X&4) != 2 --> true
Chris Lattnerc5b6c9a2006-02-28 19:47:20 +00004983 Constant *Res = ConstantBool::get(isSetNE);
4984 Res = ConstantExpr::getCast(Res, CI.getType());
4985 return ReplaceInstUsesWith(CI, Res);
Chris Lattnerc7bfed02006-02-27 02:38:23 +00004986 }
4987
4988 unsigned ShiftAmt = Log2_64(KnownZero^TypeMask);
4989 Value *In = Op0;
4990 if (ShiftAmt) {
Chris Lattner4c2d3782005-05-06 01:53:19 +00004991 // Perform an unsigned shr by shiftamt. Convert input to
4992 // unsigned if it is signed.
Chris Lattner4c2d3782005-05-06 01:53:19 +00004993 if (In->getType()->isSigned())
4994 In = InsertNewInstBefore(new CastInst(In,
4995 In->getType()->getUnsignedVersion(), In->getName()),CI);
4996 // Insert the shift to put the result in the low bit.
4997 In = InsertNewInstBefore(new ShiftInst(Instruction::Shr, In,
Chris Lattnerc7bfed02006-02-27 02:38:23 +00004998 ConstantInt::get(Type::UByteTy, ShiftAmt),
4999 In->getName()+".lobit"), CI);
Chris Lattner4c2d3782005-05-06 01:53:19 +00005000 }
Chris Lattnerc7bfed02006-02-27 02:38:23 +00005001
5002 if ((Op1CV != 0) == isSetNE) { // Toggle the low bit.
5003 Constant *One = ConstantInt::get(In->getType(), 1);
5004 In = BinaryOperator::createXor(In, One, "tmp");
5005 InsertNewInstBefore(cast<Instruction>(In), CI);
Chris Lattner4c2d3782005-05-06 01:53:19 +00005006 }
Chris Lattnerc7bfed02006-02-27 02:38:23 +00005007
5008 if (CI.getType() == In->getType())
5009 return ReplaceInstUsesWith(CI, In);
5010 else
5011 return new CastInst(In, CI.getType());
Chris Lattner4c2d3782005-05-06 01:53:19 +00005012 }
Chris Lattner809dfac2005-05-04 19:10:26 +00005013 }
5014 }
5015 break;
Chris Lattnerdfae8be2003-07-24 17:35:25 +00005016 }
5017 }
Chris Lattnerbb171802005-10-27 05:53:56 +00005018
Chris Lattner260ab202002-04-18 17:39:14 +00005019 return 0;
Chris Lattnerca081252001-12-14 16:52:21 +00005020}
5021
Chris Lattner56e4d3d2004-04-09 23:46:01 +00005022/// GetSelectFoldableOperands - We want to turn code that looks like this:
5023/// %C = or %A, %B
5024/// %D = select %cond, %C, %A
5025/// into:
5026/// %C = select %cond, %B, 0
5027/// %D = or %A, %C
5028///
5029/// Assuming that the specified instruction is an operand to the select, return
5030/// a bitmask indicating which operands of this instruction are foldable if they
5031/// equal the other incoming value of the select.
5032///
5033static unsigned GetSelectFoldableOperands(Instruction *I) {
5034 switch (I->getOpcode()) {
5035 case Instruction::Add:
5036 case Instruction::Mul:
5037 case Instruction::And:
5038 case Instruction::Or:
5039 case Instruction::Xor:
5040 return 3; // Can fold through either operand.
5041 case Instruction::Sub: // Can only fold on the amount subtracted.
5042 case Instruction::Shl: // Can only fold on the shift amount.
5043 case Instruction::Shr:
Misha Brukmanb1c93172005-04-21 23:48:37 +00005044 return 1;
Chris Lattner56e4d3d2004-04-09 23:46:01 +00005045 default:
5046 return 0; // Cannot fold
5047 }
5048}
5049
5050/// GetSelectFoldableConstant - For the same transformation as the previous
5051/// function, return the identity constant that goes into the select.
5052static Constant *GetSelectFoldableConstant(Instruction *I) {
5053 switch (I->getOpcode()) {
5054 default: assert(0 && "This cannot happen!"); abort();
5055 case Instruction::Add:
5056 case Instruction::Sub:
5057 case Instruction::Or:
5058 case Instruction::Xor:
5059 return Constant::getNullValue(I->getType());
5060 case Instruction::Shl:
5061 case Instruction::Shr:
5062 return Constant::getNullValue(Type::UByteTy);
5063 case Instruction::And:
5064 return ConstantInt::getAllOnesValue(I->getType());
5065 case Instruction::Mul:
5066 return ConstantInt::get(I->getType(), 1);
5067 }
5068}
5069
Chris Lattner411336f2005-01-19 21:50:18 +00005070/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
5071/// have the same opcode and only one use each. Try to simplify this.
5072Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
5073 Instruction *FI) {
5074 if (TI->getNumOperands() == 1) {
5075 // If this is a non-volatile load or a cast from the same type,
5076 // merge.
5077 if (TI->getOpcode() == Instruction::Cast) {
5078 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
5079 return 0;
5080 } else {
5081 return 0; // unknown unary op.
5082 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00005083
Chris Lattner411336f2005-01-19 21:50:18 +00005084 // Fold this by inserting a select from the input values.
5085 SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
5086 FI->getOperand(0), SI.getName()+".v");
5087 InsertNewInstBefore(NewSI, SI);
5088 return new CastInst(NewSI, TI->getType());
5089 }
5090
5091 // Only handle binary operators here.
5092 if (!isa<ShiftInst>(TI) && !isa<BinaryOperator>(TI))
5093 return 0;
5094
5095 // Figure out if the operations have any operands in common.
5096 Value *MatchOp, *OtherOpT, *OtherOpF;
5097 bool MatchIsOpZero;
5098 if (TI->getOperand(0) == FI->getOperand(0)) {
5099 MatchOp = TI->getOperand(0);
5100 OtherOpT = TI->getOperand(1);
5101 OtherOpF = FI->getOperand(1);
5102 MatchIsOpZero = true;
5103 } else if (TI->getOperand(1) == FI->getOperand(1)) {
5104 MatchOp = TI->getOperand(1);
5105 OtherOpT = TI->getOperand(0);
5106 OtherOpF = FI->getOperand(0);
5107 MatchIsOpZero = false;
5108 } else if (!TI->isCommutative()) {
5109 return 0;
5110 } else if (TI->getOperand(0) == FI->getOperand(1)) {
5111 MatchOp = TI->getOperand(0);
5112 OtherOpT = TI->getOperand(1);
5113 OtherOpF = FI->getOperand(0);
5114 MatchIsOpZero = true;
5115 } else if (TI->getOperand(1) == FI->getOperand(0)) {
5116 MatchOp = TI->getOperand(1);
5117 OtherOpT = TI->getOperand(0);
5118 OtherOpF = FI->getOperand(1);
5119 MatchIsOpZero = true;
5120 } else {
5121 return 0;
5122 }
5123
5124 // If we reach here, they do have operations in common.
5125 SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
5126 OtherOpF, SI.getName()+".v");
5127 InsertNewInstBefore(NewSI, SI);
5128
5129 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
5130 if (MatchIsOpZero)
5131 return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
5132 else
5133 return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
5134 } else {
5135 if (MatchIsOpZero)
5136 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), MatchOp, NewSI);
5137 else
5138 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), NewSI, MatchOp);
5139 }
5140}
5141
Chris Lattnerb909e8b2004-03-12 05:52:32 +00005142Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattner533bc492004-03-30 19:37:13 +00005143 Value *CondVal = SI.getCondition();
5144 Value *TrueVal = SI.getTrueValue();
5145 Value *FalseVal = SI.getFalseValue();
5146
5147 // select true, X, Y -> X
5148 // select false, X, Y -> Y
5149 if (ConstantBool *C = dyn_cast<ConstantBool>(CondVal))
Chris Lattnerb909e8b2004-03-12 05:52:32 +00005150 if (C == ConstantBool::True)
Chris Lattner533bc492004-03-30 19:37:13 +00005151 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattnerb909e8b2004-03-12 05:52:32 +00005152 else {
5153 assert(C == ConstantBool::False);
Chris Lattner533bc492004-03-30 19:37:13 +00005154 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattnerb909e8b2004-03-12 05:52:32 +00005155 }
Chris Lattner533bc492004-03-30 19:37:13 +00005156
5157 // select C, X, X -> X
5158 if (TrueVal == FalseVal)
5159 return ReplaceInstUsesWith(SI, TrueVal);
5160
Chris Lattner81a7a232004-10-16 18:11:37 +00005161 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
5162 return ReplaceInstUsesWith(SI, FalseVal);
5163 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
5164 return ReplaceInstUsesWith(SI, TrueVal);
5165 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
5166 if (isa<Constant>(TrueVal))
5167 return ReplaceInstUsesWith(SI, TrueVal);
5168 else
5169 return ReplaceInstUsesWith(SI, FalseVal);
5170 }
5171
Chris Lattner1c631e82004-04-08 04:43:23 +00005172 if (SI.getType() == Type::BoolTy)
5173 if (ConstantBool *C = dyn_cast<ConstantBool>(TrueVal)) {
5174 if (C == ConstantBool::True) {
5175 // Change: A = select B, true, C --> A = or B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00005176 return BinaryOperator::createOr(CondVal, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00005177 } else {
5178 // Change: A = select B, false, C --> A = and !B, C
5179 Value *NotCond =
5180 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
5181 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00005182 return BinaryOperator::createAnd(NotCond, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00005183 }
5184 } else if (ConstantBool *C = dyn_cast<ConstantBool>(FalseVal)) {
5185 if (C == ConstantBool::False) {
5186 // Change: A = select B, C, false --> A = and B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00005187 return BinaryOperator::createAnd(CondVal, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00005188 } else {
5189 // Change: A = select B, C, true --> A = or !B, C
5190 Value *NotCond =
5191 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
5192 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00005193 return BinaryOperator::createOr(NotCond, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00005194 }
5195 }
5196
Chris Lattner183b3362004-04-09 19:05:30 +00005197 // Selecting between two integer constants?
5198 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
5199 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
5200 // select C, 1, 0 -> cast C to int
5201 if (FalseValC->isNullValue() && TrueValC->getRawValue() == 1) {
5202 return new CastInst(CondVal, SI.getType());
5203 } else if (TrueValC->isNullValue() && FalseValC->getRawValue() == 1) {
5204 // select C, 0, 1 -> cast !C to int
5205 Value *NotCond =
5206 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
Chris Lattnercf7baf32004-04-09 18:19:44 +00005207 "not."+CondVal->getName()), SI);
Chris Lattner183b3362004-04-09 19:05:30 +00005208 return new CastInst(NotCond, SI.getType());
Chris Lattnercf7baf32004-04-09 18:19:44 +00005209 }
Chris Lattner35167c32004-06-09 07:59:58 +00005210
5211 // If one of the constants is zero (we know they can't both be) and we
5212 // have a setcc instruction with zero, and we have an 'and' with the
5213 // non-constant value, eliminate this whole mess. This corresponds to
5214 // cases like this: ((X & 27) ? 27 : 0)
5215 if (TrueValC->isNullValue() || FalseValC->isNullValue())
5216 if (Instruction *IC = dyn_cast<Instruction>(SI.getCondition()))
5217 if ((IC->getOpcode() == Instruction::SetEQ ||
5218 IC->getOpcode() == Instruction::SetNE) &&
5219 isa<ConstantInt>(IC->getOperand(1)) &&
5220 cast<Constant>(IC->getOperand(1))->isNullValue())
5221 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
5222 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00005223 isa<ConstantInt>(ICA->getOperand(1)) &&
5224 (ICA->getOperand(1) == TrueValC ||
5225 ICA->getOperand(1) == FalseValC) &&
Chris Lattner35167c32004-06-09 07:59:58 +00005226 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
5227 // Okay, now we know that everything is set up, we just don't
5228 // know whether we have a setne or seteq and whether the true or
5229 // false val is the zero.
5230 bool ShouldNotVal = !TrueValC->isNullValue();
5231 ShouldNotVal ^= IC->getOpcode() == Instruction::SetNE;
5232 Value *V = ICA;
5233 if (ShouldNotVal)
5234 V = InsertNewInstBefore(BinaryOperator::create(
5235 Instruction::Xor, V, ICA->getOperand(1)), SI);
5236 return ReplaceInstUsesWith(SI, V);
5237 }
Chris Lattner533bc492004-03-30 19:37:13 +00005238 }
Chris Lattner623fba12004-04-10 22:21:27 +00005239
5240 // See if we are selecting two values based on a comparison of the two values.
5241 if (SetCondInst *SCI = dyn_cast<SetCondInst>(CondVal)) {
5242 if (SCI->getOperand(0) == TrueVal && SCI->getOperand(1) == FalseVal) {
5243 // Transform (X == Y) ? X : Y -> Y
5244 if (SCI->getOpcode() == Instruction::SetEQ)
5245 return ReplaceInstUsesWith(SI, FalseVal);
5246 // Transform (X != Y) ? X : Y -> X
5247 if (SCI->getOpcode() == Instruction::SetNE)
5248 return ReplaceInstUsesWith(SI, TrueVal);
5249 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
5250
5251 } else if (SCI->getOperand(0) == FalseVal && SCI->getOperand(1) == TrueVal){
5252 // Transform (X == Y) ? Y : X -> X
5253 if (SCI->getOpcode() == Instruction::SetEQ)
Chris Lattner24cf0202004-04-11 01:39:19 +00005254 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattner623fba12004-04-10 22:21:27 +00005255 // Transform (X != Y) ? Y : X -> Y
5256 if (SCI->getOpcode() == Instruction::SetNE)
Chris Lattner24cf0202004-04-11 01:39:19 +00005257 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattner623fba12004-04-10 22:21:27 +00005258 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
5259 }
5260 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00005261
Chris Lattnera04c9042005-01-13 22:52:24 +00005262 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
5263 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
5264 if (TI->hasOneUse() && FI->hasOneUse()) {
5265 bool isInverse = false;
5266 Instruction *AddOp = 0, *SubOp = 0;
5267
Chris Lattner411336f2005-01-19 21:50:18 +00005268 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
5269 if (TI->getOpcode() == FI->getOpcode())
5270 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
5271 return IV;
5272
5273 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
5274 // even legal for FP.
Chris Lattnera04c9042005-01-13 22:52:24 +00005275 if (TI->getOpcode() == Instruction::Sub &&
5276 FI->getOpcode() == Instruction::Add) {
5277 AddOp = FI; SubOp = TI;
5278 } else if (FI->getOpcode() == Instruction::Sub &&
5279 TI->getOpcode() == Instruction::Add) {
5280 AddOp = TI; SubOp = FI;
5281 }
5282
5283 if (AddOp) {
5284 Value *OtherAddOp = 0;
5285 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
5286 OtherAddOp = AddOp->getOperand(1);
5287 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
5288 OtherAddOp = AddOp->getOperand(0);
5289 }
5290
5291 if (OtherAddOp) {
Chris Lattnerb580d262006-02-24 18:05:58 +00005292 // So at this point we know we have (Y -> OtherAddOp):
5293 // select C, (add X, Y), (sub X, Z)
5294 Value *NegVal; // Compute -Z
5295 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
5296 NegVal = ConstantExpr::getNeg(C);
5297 } else {
5298 NegVal = InsertNewInstBefore(
5299 BinaryOperator::createNeg(SubOp->getOperand(1), "tmp"), SI);
Chris Lattnera04c9042005-01-13 22:52:24 +00005300 }
Chris Lattnerb580d262006-02-24 18:05:58 +00005301
5302 Value *NewTrueOp = OtherAddOp;
5303 Value *NewFalseOp = NegVal;
5304 if (AddOp != TI)
5305 std::swap(NewTrueOp, NewFalseOp);
5306 Instruction *NewSel =
5307 new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
5308
5309 NewSel = InsertNewInstBefore(NewSel, SI);
5310 return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
Chris Lattnera04c9042005-01-13 22:52:24 +00005311 }
5312 }
5313 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00005314
Chris Lattner56e4d3d2004-04-09 23:46:01 +00005315 // See if we can fold the select into one of our operands.
5316 if (SI.getType()->isInteger()) {
5317 // See the comment above GetSelectFoldableOperands for a description of the
5318 // transformation we are doing here.
5319 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
5320 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
5321 !isa<Constant>(FalseVal))
5322 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
5323 unsigned OpToFold = 0;
5324 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
5325 OpToFold = 1;
5326 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
5327 OpToFold = 2;
5328 }
5329
5330 if (OpToFold) {
5331 Constant *C = GetSelectFoldableConstant(TVI);
5332 std::string Name = TVI->getName(); TVI->setName("");
5333 Instruction *NewSel =
5334 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C,
5335 Name);
5336 InsertNewInstBefore(NewSel, SI);
5337 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
5338 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
5339 else if (ShiftInst *SI = dyn_cast<ShiftInst>(TVI))
5340 return new ShiftInst(SI->getOpcode(), FalseVal, NewSel);
5341 else {
5342 assert(0 && "Unknown instruction!!");
5343 }
5344 }
5345 }
Chris Lattner6862fbd2004-09-29 17:40:11 +00005346
Chris Lattner56e4d3d2004-04-09 23:46:01 +00005347 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
5348 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
5349 !isa<Constant>(TrueVal))
5350 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
5351 unsigned OpToFold = 0;
5352 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
5353 OpToFold = 1;
5354 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
5355 OpToFold = 2;
5356 }
5357
5358 if (OpToFold) {
5359 Constant *C = GetSelectFoldableConstant(FVI);
5360 std::string Name = FVI->getName(); FVI->setName("");
5361 Instruction *NewSel =
5362 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold),
5363 Name);
5364 InsertNewInstBefore(NewSel, SI);
5365 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
5366 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
5367 else if (ShiftInst *SI = dyn_cast<ShiftInst>(FVI))
5368 return new ShiftInst(SI->getOpcode(), TrueVal, NewSel);
5369 else {
5370 assert(0 && "Unknown instruction!!");
5371 }
5372 }
5373 }
5374 }
Chris Lattnerd6f636a2005-04-24 07:30:14 +00005375
5376 if (BinaryOperator::isNot(CondVal)) {
5377 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
5378 SI.setOperand(1, FalseVal);
5379 SI.setOperand(2, TrueVal);
5380 return &SI;
5381 }
5382
Chris Lattnerb909e8b2004-03-12 05:52:32 +00005383 return 0;
5384}
5385
Chris Lattner82f2ef22006-03-06 20:18:44 +00005386/// GetKnownAlignment - If the specified pointer has an alignment that we can
5387/// determine, return it, otherwise return 0.
5388static unsigned GetKnownAlignment(Value *V, TargetData *TD) {
5389 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
5390 unsigned Align = GV->getAlignment();
5391 if (Align == 0 && TD)
5392 Align = TD->getTypeAlignment(GV->getType()->getElementType());
5393 return Align;
5394 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
5395 unsigned Align = AI->getAlignment();
5396 if (Align == 0 && TD) {
5397 if (isa<AllocaInst>(AI))
5398 Align = TD->getTypeAlignment(AI->getType()->getElementType());
5399 else if (isa<MallocInst>(AI)) {
5400 // Malloc returns maximally aligned memory.
5401 Align = TD->getTypeAlignment(AI->getType()->getElementType());
5402 Align = std::max(Align, (unsigned)TD->getTypeAlignment(Type::DoubleTy));
5403 Align = std::max(Align, (unsigned)TD->getTypeAlignment(Type::LongTy));
5404 }
5405 }
5406 return Align;
Chris Lattner53ef5a02006-03-07 01:28:57 +00005407 } else if (isa<CastInst>(V) ||
5408 (isa<ConstantExpr>(V) &&
5409 cast<ConstantExpr>(V)->getOpcode() == Instruction::Cast)) {
5410 User *CI = cast<User>(V);
Chris Lattner82f2ef22006-03-06 20:18:44 +00005411 if (isa<PointerType>(CI->getOperand(0)->getType()))
5412 return GetKnownAlignment(CI->getOperand(0), TD);
5413 return 0;
Chris Lattner53ef5a02006-03-07 01:28:57 +00005414 } else if (isa<GetElementPtrInst>(V) ||
5415 (isa<ConstantExpr>(V) &&
5416 cast<ConstantExpr>(V)->getOpcode()==Instruction::GetElementPtr)) {
5417 User *GEPI = cast<User>(V);
Chris Lattner82f2ef22006-03-06 20:18:44 +00005418 unsigned BaseAlignment = GetKnownAlignment(GEPI->getOperand(0), TD);
5419 if (BaseAlignment == 0) return 0;
5420
5421 // If all indexes are zero, it is just the alignment of the base pointer.
5422 bool AllZeroOperands = true;
5423 for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
5424 if (!isa<Constant>(GEPI->getOperand(i)) ||
5425 !cast<Constant>(GEPI->getOperand(i))->isNullValue()) {
5426 AllZeroOperands = false;
5427 break;
5428 }
5429 if (AllZeroOperands)
5430 return BaseAlignment;
5431
5432 // Otherwise, if the base alignment is >= the alignment we expect for the
5433 // base pointer type, then we know that the resultant pointer is aligned at
5434 // least as much as its type requires.
5435 if (!TD) return 0;
5436
5437 const Type *BasePtrTy = GEPI->getOperand(0)->getType();
5438 if (TD->getTypeAlignment(cast<PointerType>(BasePtrTy)->getElementType())
Chris Lattner53ef5a02006-03-07 01:28:57 +00005439 <= BaseAlignment) {
5440 const Type *GEPTy = GEPI->getType();
5441 return TD->getTypeAlignment(cast<PointerType>(GEPTy)->getElementType());
5442 }
Chris Lattner82f2ef22006-03-06 20:18:44 +00005443 return 0;
5444 }
5445 return 0;
5446}
5447
Chris Lattnerb909e8b2004-03-12 05:52:32 +00005448
Chris Lattnerc66b2232006-01-13 20:11:04 +00005449/// visitCallInst - CallInst simplification. This mostly only handles folding
5450/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
5451/// the heavy lifting.
5452///
Chris Lattner970c33a2003-06-19 17:00:31 +00005453Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattnerc66b2232006-01-13 20:11:04 +00005454 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
5455 if (!II) return visitCallSite(&CI);
5456
Chris Lattner51ea1272004-02-28 05:22:00 +00005457 // Intrinsics cannot occur in an invoke, so handle them here instead of in
5458 // visitCallSite.
Chris Lattnerc66b2232006-01-13 20:11:04 +00005459 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner00648e12004-10-12 04:52:52 +00005460 bool Changed = false;
5461
5462 // memmove/cpy/set of zero bytes is a noop.
5463 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
5464 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
5465
Chris Lattner00648e12004-10-12 04:52:52 +00005466 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
5467 if (CI->getRawValue() == 1) {
5468 // Replace the instruction with just byte operations. We would
5469 // transform other cases to loads/stores, but we don't know if
5470 // alignment is sufficient.
5471 }
Chris Lattner51ea1272004-02-28 05:22:00 +00005472 }
5473
Chris Lattner00648e12004-10-12 04:52:52 +00005474 // If we have a memmove and the source operation is a constant global,
5475 // then the source and dest pointers can't alias, so we can change this
5476 // into a call to memcpy.
Chris Lattner82f2ef22006-03-06 20:18:44 +00005477 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(II)) {
Chris Lattner00648e12004-10-12 04:52:52 +00005478 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
5479 if (GVSrc->isConstant()) {
5480 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner681ef2f2006-03-03 01:34:17 +00005481 const char *Name;
5482 if (CI.getCalledFunction()->getFunctionType()->getParamType(3) ==
5483 Type::UIntTy)
5484 Name = "llvm.memcpy.i32";
5485 else
5486 Name = "llvm.memcpy.i64";
5487 Function *MemCpy = M->getOrInsertFunction(Name,
Chris Lattner00648e12004-10-12 04:52:52 +00005488 CI.getCalledFunction()->getFunctionType());
5489 CI.setOperand(0, MemCpy);
5490 Changed = true;
5491 }
Chris Lattner82f2ef22006-03-06 20:18:44 +00005492 }
Chris Lattner00648e12004-10-12 04:52:52 +00005493
Chris Lattner82f2ef22006-03-06 20:18:44 +00005494 // If we can determine a pointer alignment that is bigger than currently
5495 // set, update the alignment.
5496 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
5497 unsigned Alignment1 = GetKnownAlignment(MI->getOperand(1), TD);
5498 unsigned Alignment2 = GetKnownAlignment(MI->getOperand(2), TD);
5499 unsigned Align = std::min(Alignment1, Alignment2);
5500 if (MI->getAlignment()->getRawValue() < Align) {
5501 MI->setAlignment(ConstantUInt::get(Type::UIntTy, Align));
5502 Changed = true;
5503 }
5504 } else if (isa<MemSetInst>(MI)) {
5505 unsigned Alignment = GetKnownAlignment(MI->getDest(), TD);
5506 if (MI->getAlignment()->getRawValue() < Alignment) {
5507 MI->setAlignment(ConstantUInt::get(Type::UIntTy, Alignment));
5508 Changed = true;
5509 }
5510 }
5511
Chris Lattnerc66b2232006-01-13 20:11:04 +00005512 if (Changed) return II;
Chris Lattner503221f2006-01-13 21:28:09 +00005513 } else {
5514 switch (II->getIntrinsicID()) {
5515 default: break;
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00005516 case Intrinsic::ppc_altivec_lvx:
5517 case Intrinsic::ppc_altivec_lvxl:
Chris Lattner36dd7c92006-04-17 22:26:56 +00005518 case Intrinsic::x86_sse_loadu_ps:
5519 case Intrinsic::x86_sse2_loadu_pd:
5520 case Intrinsic::x86_sse2_loadu_dq:
5521 // Turn PPC lvx -> load if the pointer is known aligned.
5522 // Turn X86 loadups -> load if the pointer is known aligned.
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00005523 if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
Chris Lattnere79d2492006-04-06 19:19:17 +00005524 Value *Ptr = InsertCastBefore(II->getOperand(1),
5525 PointerType::get(II->getType()), CI);
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00005526 return new LoadInst(Ptr);
5527 }
5528 break;
5529 case Intrinsic::ppc_altivec_stvx:
5530 case Intrinsic::ppc_altivec_stvxl:
5531 // Turn stvx -> store if the pointer is known aligned.
5532 if (GetKnownAlignment(II->getOperand(2), TD) >= 16) {
Chris Lattnere79d2492006-04-06 19:19:17 +00005533 const Type *OpPtrTy = PointerType::get(II->getOperand(1)->getType());
5534 Value *Ptr = InsertCastBefore(II->getOperand(2), OpPtrTy, CI);
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00005535 return new StoreInst(II->getOperand(1), Ptr);
5536 }
5537 break;
Chris Lattner36dd7c92006-04-17 22:26:56 +00005538 case Intrinsic::x86_sse_storeu_ps:
5539 case Intrinsic::x86_sse2_storeu_pd:
5540 case Intrinsic::x86_sse2_storeu_dq:
5541 case Intrinsic::x86_sse2_storel_dq:
5542 // Turn X86 storeu -> store if the pointer is known aligned.
5543 if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
5544 const Type *OpPtrTy = PointerType::get(II->getOperand(2)->getType());
5545 Value *Ptr = InsertCastBefore(II->getOperand(1), OpPtrTy, CI);
5546 return new StoreInst(II->getOperand(2), Ptr);
5547 }
5548 break;
Chris Lattnere79d2492006-04-06 19:19:17 +00005549 case Intrinsic::ppc_altivec_vperm:
5550 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
5551 if (ConstantPacked *Mask = dyn_cast<ConstantPacked>(II->getOperand(3))) {
5552 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
5553
5554 // Check that all of the elements are integer constants or undefs.
5555 bool AllEltsOk = true;
5556 for (unsigned i = 0; i != 16; ++i) {
5557 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
5558 !isa<UndefValue>(Mask->getOperand(i))) {
5559 AllEltsOk = false;
5560 break;
5561 }
5562 }
5563
5564 if (AllEltsOk) {
5565 // Cast the input vectors to byte vectors.
5566 Value *Op0 = InsertCastBefore(II->getOperand(1), Mask->getType(), CI);
5567 Value *Op1 = InsertCastBefore(II->getOperand(2), Mask->getType(), CI);
5568 Value *Result = UndefValue::get(Op0->getType());
5569
5570 // Only extract each element once.
5571 Value *ExtractedElts[32];
5572 memset(ExtractedElts, 0, sizeof(ExtractedElts));
5573
5574 for (unsigned i = 0; i != 16; ++i) {
5575 if (isa<UndefValue>(Mask->getOperand(i)))
5576 continue;
5577 unsigned Idx =cast<ConstantInt>(Mask->getOperand(i))->getRawValue();
5578 Idx &= 31; // Match the hardware behavior.
5579
5580 if (ExtractedElts[Idx] == 0) {
5581 Instruction *Elt =
5582 new ExtractElementInst(Idx < 16 ? Op0 : Op1,
5583 ConstantUInt::get(Type::UIntTy, Idx&15),
5584 "tmp");
5585 InsertNewInstBefore(Elt, CI);
5586 ExtractedElts[Idx] = Elt;
5587 }
5588
5589 // Insert this value into the result vector.
5590 Result = new InsertElementInst(Result, ExtractedElts[Idx],
5591 ConstantUInt::get(Type::UIntTy, i),
5592 "tmp");
5593 InsertNewInstBefore(cast<Instruction>(Result), CI);
5594 }
5595 return new CastInst(Result, CI.getType());
5596 }
5597 }
5598 break;
5599
Chris Lattner503221f2006-01-13 21:28:09 +00005600 case Intrinsic::stackrestore: {
5601 // If the save is right next to the restore, remove the restore. This can
5602 // happen when variable allocas are DCE'd.
5603 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
5604 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
5605 BasicBlock::iterator BI = SS;
5606 if (&*++BI == II)
5607 return EraseInstFromFunction(CI);
5608 }
5609 }
5610
5611 // If the stack restore is in a return/unwind block and if there are no
5612 // allocas or calls between the restore and the return, nuke the restore.
5613 TerminatorInst *TI = II->getParent()->getTerminator();
5614 if (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)) {
5615 BasicBlock::iterator BI = II;
5616 bool CannotRemove = false;
5617 for (++BI; &*BI != TI; ++BI) {
5618 if (isa<AllocaInst>(BI) ||
5619 (isa<CallInst>(BI) && !isa<IntrinsicInst>(BI))) {
5620 CannotRemove = true;
5621 break;
5622 }
5623 }
5624 if (!CannotRemove)
5625 return EraseInstFromFunction(CI);
5626 }
5627 break;
5628 }
5629 }
Chris Lattner00648e12004-10-12 04:52:52 +00005630 }
5631
Chris Lattnerc66b2232006-01-13 20:11:04 +00005632 return visitCallSite(II);
Chris Lattner970c33a2003-06-19 17:00:31 +00005633}
5634
5635// InvokeInst simplification
5636//
5637Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattneraec3d942003-10-07 22:32:43 +00005638 return visitCallSite(&II);
Chris Lattner970c33a2003-06-19 17:00:31 +00005639}
5640
Chris Lattneraec3d942003-10-07 22:32:43 +00005641// visitCallSite - Improvements for call and invoke instructions.
5642//
5643Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner75b4d1d2003-10-07 22:54:13 +00005644 bool Changed = false;
5645
5646 // If the callee is a constexpr cast of a function, attempt to move the cast
5647 // to the arguments of the call/invoke.
Chris Lattneraec3d942003-10-07 22:32:43 +00005648 if (transformConstExprCastCall(CS)) return 0;
5649
Chris Lattner75b4d1d2003-10-07 22:54:13 +00005650 Value *Callee = CS.getCalledValue();
Chris Lattner81a7a232004-10-16 18:11:37 +00005651
Chris Lattner61d9d812005-05-13 07:09:09 +00005652 if (Function *CalleeF = dyn_cast<Function>(Callee))
5653 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
5654 Instruction *OldCall = CS.getInstruction();
5655 // If the call and callee calling conventions don't match, this call must
5656 // be unreachable, as the call is undefined.
5657 new StoreInst(ConstantBool::True,
5658 UndefValue::get(PointerType::get(Type::BoolTy)), OldCall);
5659 if (!OldCall->use_empty())
5660 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
5661 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
5662 return EraseInstFromFunction(*OldCall);
5663 return 0;
5664 }
5665
Chris Lattner8ba9ec92004-10-18 02:59:09 +00005666 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
5667 // This instruction is not reachable, just remove it. We insert a store to
5668 // undef so that we know that this code is not reachable, despite the fact
5669 // that we can't modify the CFG here.
5670 new StoreInst(ConstantBool::True,
5671 UndefValue::get(PointerType::get(Type::BoolTy)),
5672 CS.getInstruction());
5673
5674 if (!CS.getInstruction()->use_empty())
5675 CS.getInstruction()->
5676 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
5677
5678 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
5679 // Don't break the CFG, insert a dummy cond branch.
5680 new BranchInst(II->getNormalDest(), II->getUnwindDest(),
5681 ConstantBool::True, II);
Chris Lattner81a7a232004-10-16 18:11:37 +00005682 }
Chris Lattner8ba9ec92004-10-18 02:59:09 +00005683 return EraseInstFromFunction(*CS.getInstruction());
5684 }
Chris Lattner81a7a232004-10-16 18:11:37 +00005685
Chris Lattner75b4d1d2003-10-07 22:54:13 +00005686 const PointerType *PTy = cast<PointerType>(Callee->getType());
5687 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
5688 if (FTy->isVarArg()) {
5689 // See if we can optimize any arguments passed through the varargs area of
5690 // the call.
5691 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
5692 E = CS.arg_end(); I != E; ++I)
5693 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
5694 // If this cast does not effect the value passed through the varargs
5695 // area, we can eliminate the use of the cast.
5696 Value *Op = CI->getOperand(0);
5697 if (CI->getType()->isLosslesslyConvertibleTo(Op->getType())) {
5698 *I = Op;
5699 Changed = true;
5700 }
5701 }
5702 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00005703
Chris Lattner75b4d1d2003-10-07 22:54:13 +00005704 return Changed ? CS.getInstruction() : 0;
Chris Lattneraec3d942003-10-07 22:32:43 +00005705}
5706
Chris Lattner970c33a2003-06-19 17:00:31 +00005707// transformConstExprCastCall - If the callee is a constexpr cast of a function,
5708// attempt to move the cast to the arguments of the call/invoke.
5709//
5710bool InstCombiner::transformConstExprCastCall(CallSite CS) {
5711 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
5712 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Chris Lattnerf3edc492004-07-18 18:59:44 +00005713 if (CE->getOpcode() != Instruction::Cast || !isa<Function>(CE->getOperand(0)))
Chris Lattner970c33a2003-06-19 17:00:31 +00005714 return false;
Reid Spencer87436872004-07-18 00:38:32 +00005715 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner970c33a2003-06-19 17:00:31 +00005716 Instruction *Caller = CS.getInstruction();
5717
5718 // Okay, this is a cast from a function to a different type. Unless doing so
5719 // would cause a type conversion of one of our arguments, change this call to
5720 // be a direct call with arguments casted to the appropriate types.
5721 //
5722 const FunctionType *FT = Callee->getFunctionType();
5723 const Type *OldRetTy = Caller->getType();
5724
Chris Lattner1f7942f2004-01-14 06:06:08 +00005725 // Check to see if we are changing the return type...
5726 if (OldRetTy != FT->getReturnType()) {
5727 if (Callee->isExternal() &&
Andrew Lenharth61eae292006-04-20 14:56:47 +00005728 !(OldRetTy->isLosslesslyConvertibleTo(FT->getReturnType()) ||
5729 (isa<PointerType>(FT->getReturnType()) &&
Andrew Lenharthf89e6302006-04-20 15:41:37 +00005730 TD->getIntPtrType()->isLosslesslyConvertibleTo(OldRetTy)))
Andrew Lenharth61eae292006-04-20 14:56:47 +00005731 && !Caller->use_empty())
Chris Lattner1f7942f2004-01-14 06:06:08 +00005732 return false; // Cannot transform this return value...
5733
5734 // If the callsite is an invoke instruction, and the return value is used by
5735 // a PHI node in a successor, we cannot change the return type of the call
5736 // because there is no place to put the cast instruction (without breaking
5737 // the critical edge). Bail out in this case.
5738 if (!Caller->use_empty())
5739 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
5740 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
5741 UI != E; ++UI)
5742 if (PHINode *PN = dyn_cast<PHINode>(*UI))
5743 if (PN->getParent() == II->getNormalDest() ||
Chris Lattnerfae8ab32004-02-08 21:44:31 +00005744 PN->getParent() == II->getUnwindDest())
Chris Lattner1f7942f2004-01-14 06:06:08 +00005745 return false;
5746 }
Chris Lattner970c33a2003-06-19 17:00:31 +00005747
5748 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
5749 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanb1c93172005-04-21 23:48:37 +00005750
Chris Lattner970c33a2003-06-19 17:00:31 +00005751 CallSite::arg_iterator AI = CS.arg_begin();
5752 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
5753 const Type *ParamTy = FT->getParamType(i);
5754 bool isConvertible = (*AI)->getType()->isLosslesslyConvertibleTo(ParamTy);
Misha Brukmanb1c93172005-04-21 23:48:37 +00005755 if (Callee->isExternal() && !isConvertible) return false;
Chris Lattner970c33a2003-06-19 17:00:31 +00005756 }
5757
5758 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
5759 Callee->isExternal())
5760 return false; // Do not delete arguments unless we have a function body...
5761
5762 // Okay, we decided that this is a safe thing to do: go ahead and start
5763 // inserting cast instructions as necessary...
5764 std::vector<Value*> Args;
5765 Args.reserve(NumActualArgs);
5766
5767 AI = CS.arg_begin();
5768 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
5769 const Type *ParamTy = FT->getParamType(i);
5770 if ((*AI)->getType() == ParamTy) {
5771 Args.push_back(*AI);
5772 } else {
Chris Lattner1c631e82004-04-08 04:43:23 +00005773 Args.push_back(InsertNewInstBefore(new CastInst(*AI, ParamTy, "tmp"),
5774 *Caller));
Chris Lattner970c33a2003-06-19 17:00:31 +00005775 }
5776 }
5777
5778 // If the function takes more arguments than the call was taking, add them
5779 // now...
5780 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
5781 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
5782
5783 // If we are removing arguments to the function, emit an obnoxious warning...
5784 if (FT->getNumParams() < NumActualArgs)
5785 if (!FT->isVarArg()) {
5786 std::cerr << "WARNING: While resolving call to function '"
5787 << Callee->getName() << "' arguments were dropped!\n";
5788 } else {
5789 // Add all of the arguments in their promoted form to the arg list...
5790 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
5791 const Type *PTy = getPromotedType((*AI)->getType());
5792 if (PTy != (*AI)->getType()) {
5793 // Must promote to pass through va_arg area!
5794 Instruction *Cast = new CastInst(*AI, PTy, "tmp");
5795 InsertNewInstBefore(Cast, *Caller);
5796 Args.push_back(Cast);
5797 } else {
5798 Args.push_back(*AI);
5799 }
5800 }
5801 }
5802
5803 if (FT->getReturnType() == Type::VoidTy)
5804 Caller->setName(""); // Void type should not have a name...
5805
5806 Instruction *NC;
5807 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Chris Lattnerfae8ab32004-02-08 21:44:31 +00005808 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
Chris Lattner970c33a2003-06-19 17:00:31 +00005809 Args, Caller->getName(), Caller);
Chris Lattner05c703e2005-05-14 12:25:32 +00005810 cast<InvokeInst>(II)->setCallingConv(II->getCallingConv());
Chris Lattner970c33a2003-06-19 17:00:31 +00005811 } else {
5812 NC = new CallInst(Callee, Args, Caller->getName(), Caller);
Chris Lattner6aacb0f2005-05-06 06:48:21 +00005813 if (cast<CallInst>(Caller)->isTailCall())
5814 cast<CallInst>(NC)->setTailCall();
Chris Lattner05c703e2005-05-14 12:25:32 +00005815 cast<CallInst>(NC)->setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Chris Lattner970c33a2003-06-19 17:00:31 +00005816 }
5817
5818 // Insert a cast of the return type as necessary...
5819 Value *NV = NC;
5820 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
5821 if (NV->getType() != Type::VoidTy) {
5822 NV = NC = new CastInst(NC, Caller->getType(), "tmp");
Chris Lattner686767f2003-10-30 00:46:41 +00005823
5824 // If this is an invoke instruction, we should insert it after the first
5825 // non-phi, instruction in the normal successor block.
5826 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
5827 BasicBlock::iterator I = II->getNormalDest()->begin();
5828 while (isa<PHINode>(I)) ++I;
5829 InsertNewInstBefore(NC, *I);
5830 } else {
5831 // Otherwise, it's a call, just insert cast right after the call instr
5832 InsertNewInstBefore(NC, *Caller);
5833 }
Chris Lattner51ea1272004-02-28 05:22:00 +00005834 AddUsersToWorkList(*Caller);
Chris Lattner970c33a2003-06-19 17:00:31 +00005835 } else {
Chris Lattnere29d6342004-10-17 21:22:38 +00005836 NV = UndefValue::get(Caller->getType());
Chris Lattner970c33a2003-06-19 17:00:31 +00005837 }
5838 }
5839
5840 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
5841 Caller->replaceAllUsesWith(NV);
5842 Caller->getParent()->getInstList().erase(Caller);
5843 removeFromWorkList(Caller);
5844 return true;
5845}
5846
5847
Chris Lattner7515cab2004-11-14 19:13:23 +00005848// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
5849// operator and they all are only used by the PHI, PHI together their
5850// inputs, and do the operation once, to the result of the PHI.
5851Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
5852 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
5853
5854 // Scan the instruction, looking for input operations that can be folded away.
5855 // If all input operands to the phi are the same instruction (e.g. a cast from
5856 // the same type or "+42") we can pull the operation through the PHI, reducing
5857 // code size and simplifying code.
5858 Constant *ConstantOp = 0;
5859 const Type *CastSrcTy = 0;
5860 if (isa<CastInst>(FirstInst)) {
5861 CastSrcTy = FirstInst->getOperand(0)->getType();
5862 } else if (isa<BinaryOperator>(FirstInst) || isa<ShiftInst>(FirstInst)) {
5863 // Can fold binop or shift if the RHS is a constant.
5864 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
5865 if (ConstantOp == 0) return 0;
5866 } else {
5867 return 0; // Cannot fold this operation.
5868 }
5869
5870 // Check to see if all arguments are the same operation.
5871 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
5872 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
5873 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
5874 if (!I->hasOneUse() || I->getOpcode() != FirstInst->getOpcode())
5875 return 0;
5876 if (CastSrcTy) {
5877 if (I->getOperand(0)->getType() != CastSrcTy)
5878 return 0; // Cast operation must match.
5879 } else if (I->getOperand(1) != ConstantOp) {
5880 return 0;
5881 }
5882 }
5883
5884 // Okay, they are all the same operation. Create a new PHI node of the
5885 // correct type, and PHI together all of the LHS's of the instructions.
5886 PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
5887 PN.getName()+".in");
Chris Lattnerd8e20182005-01-29 00:39:08 +00005888 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattner46dd5a62004-11-14 19:29:34 +00005889
5890 Value *InVal = FirstInst->getOperand(0);
5891 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattner7515cab2004-11-14 19:13:23 +00005892
5893 // Add all operands to the new PHI.
Chris Lattner46dd5a62004-11-14 19:29:34 +00005894 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
5895 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
5896 if (NewInVal != InVal)
5897 InVal = 0;
5898 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
5899 }
5900
5901 Value *PhiVal;
5902 if (InVal) {
5903 // The new PHI unions all of the same values together. This is really
5904 // common, so we handle it intelligently here for compile-time speed.
5905 PhiVal = InVal;
5906 delete NewPN;
5907 } else {
5908 InsertNewInstBefore(NewPN, PN);
5909 PhiVal = NewPN;
5910 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00005911
Chris Lattner7515cab2004-11-14 19:13:23 +00005912 // Insert and return the new operation.
5913 if (isa<CastInst>(FirstInst))
Chris Lattner46dd5a62004-11-14 19:29:34 +00005914 return new CastInst(PhiVal, PN.getType());
Chris Lattner7515cab2004-11-14 19:13:23 +00005915 else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattner46dd5a62004-11-14 19:29:34 +00005916 return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattner7515cab2004-11-14 19:13:23 +00005917 else
5918 return new ShiftInst(cast<ShiftInst>(FirstInst)->getOpcode(),
Chris Lattner46dd5a62004-11-14 19:29:34 +00005919 PhiVal, ConstantOp);
Chris Lattner7515cab2004-11-14 19:13:23 +00005920}
Chris Lattner48a44f72002-05-02 17:06:02 +00005921
Chris Lattner71536432005-01-17 05:10:15 +00005922/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
5923/// that is dead.
5924static bool DeadPHICycle(PHINode *PN, std::set<PHINode*> &PotentiallyDeadPHIs) {
5925 if (PN->use_empty()) return true;
5926 if (!PN->hasOneUse()) return false;
5927
5928 // Remember this node, and if we find the cycle, return.
5929 if (!PotentiallyDeadPHIs.insert(PN).second)
5930 return true;
5931
5932 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
5933 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanb1c93172005-04-21 23:48:37 +00005934
Chris Lattner71536432005-01-17 05:10:15 +00005935 return false;
5936}
5937
Chris Lattnerbbbdd852002-05-06 18:06:38 +00005938// PHINode simplification
5939//
Chris Lattner113f4f42002-06-25 16:13:24 +00005940Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Chris Lattner9f9c2602005-08-05 01:04:30 +00005941 if (Value *V = PN.hasConstantValue())
5942 return ReplaceInstUsesWith(PN, V);
Chris Lattner4db2d222004-02-16 05:07:08 +00005943
5944 // If the only user of this instruction is a cast instruction, and all of the
5945 // incoming values are constants, change this PHI to merge together the casted
5946 // constants.
5947 if (PN.hasOneUse())
5948 if (CastInst *CI = dyn_cast<CastInst>(PN.use_back()))
5949 if (CI->getType() != PN.getType()) { // noop casts will be folded
5950 bool AllConstant = true;
5951 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
5952 if (!isa<Constant>(PN.getIncomingValue(i))) {
5953 AllConstant = false;
5954 break;
5955 }
5956 if (AllConstant) {
5957 // Make a new PHI with all casted values.
5958 PHINode *New = new PHINode(CI->getType(), PN.getName(), &PN);
5959 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
5960 Constant *OldArg = cast<Constant>(PN.getIncomingValue(i));
5961 New->addIncoming(ConstantExpr::getCast(OldArg, New->getType()),
5962 PN.getIncomingBlock(i));
5963 }
5964
5965 // Update the cast instruction.
5966 CI->setOperand(0, New);
5967 WorkList.push_back(CI); // revisit the cast instruction to fold.
5968 WorkList.push_back(New); // Make sure to revisit the new Phi
5969 return &PN; // PN is now dead!
5970 }
5971 }
Chris Lattner7515cab2004-11-14 19:13:23 +00005972
5973 // If all PHI operands are the same operation, pull them through the PHI,
5974 // reducing code size.
5975 if (isa<Instruction>(PN.getIncomingValue(0)) &&
5976 PN.getIncomingValue(0)->hasOneUse())
5977 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
5978 return Result;
5979
Chris Lattner71536432005-01-17 05:10:15 +00005980 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
5981 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
5982 // PHI)... break the cycle.
5983 if (PN.hasOneUse())
5984 if (PHINode *PU = dyn_cast<PHINode>(PN.use_back())) {
5985 std::set<PHINode*> PotentiallyDeadPHIs;
5986 PotentiallyDeadPHIs.insert(&PN);
5987 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
5988 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
5989 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00005990
Chris Lattner91daeb52003-12-19 05:58:40 +00005991 return 0;
Chris Lattnerbbbdd852002-05-06 18:06:38 +00005992}
5993
Chris Lattner69193f92004-04-05 01:30:19 +00005994static Value *InsertSignExtendToPtrTy(Value *V, const Type *DTy,
5995 Instruction *InsertPoint,
5996 InstCombiner *IC) {
5997 unsigned PS = IC->getTargetData().getPointerSize();
5998 const Type *VTy = V->getType();
Chris Lattner69193f92004-04-05 01:30:19 +00005999 if (!VTy->isSigned() && VTy->getPrimitiveSize() < PS)
6000 // We must insert a cast to ensure we sign-extend.
6001 V = IC->InsertNewInstBefore(new CastInst(V, VTy->getSignedVersion(),
6002 V->getName()), *InsertPoint);
6003 return IC->InsertNewInstBefore(new CastInst(V, DTy, V->getName()),
6004 *InsertPoint);
6005}
6006
Chris Lattner48a44f72002-05-02 17:06:02 +00006007
Chris Lattner113f4f42002-06-25 16:13:24 +00006008Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner5f667a62004-05-07 22:09:22 +00006009 Value *PtrOp = GEP.getOperand(0);
Chris Lattner471bd762003-05-22 19:07:21 +00006010 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
Chris Lattner113f4f42002-06-25 16:13:24 +00006011 // If so, eliminate the noop.
Chris Lattner8d0bacb2004-02-22 05:25:17 +00006012 if (GEP.getNumOperands() == 1)
Chris Lattner5f667a62004-05-07 22:09:22 +00006013 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner8d0bacb2004-02-22 05:25:17 +00006014
Chris Lattner81a7a232004-10-16 18:11:37 +00006015 if (isa<UndefValue>(GEP.getOperand(0)))
6016 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
6017
Chris Lattner8d0bacb2004-02-22 05:25:17 +00006018 bool HasZeroPointerIndex = false;
6019 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
6020 HasZeroPointerIndex = C->isNullValue();
6021
6022 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner5f667a62004-05-07 22:09:22 +00006023 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner48a44f72002-05-02 17:06:02 +00006024
Chris Lattner69193f92004-04-05 01:30:19 +00006025 // Eliminate unneeded casts for indices.
6026 bool MadeChange = false;
Chris Lattner2b2412d2004-04-07 18:38:20 +00006027 gep_type_iterator GTI = gep_type_begin(GEP);
6028 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI)
6029 if (isa<SequentialType>(*GTI)) {
6030 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
6031 Value *Src = CI->getOperand(0);
6032 const Type *SrcTy = Src->getType();
6033 const Type *DestTy = CI->getType();
6034 if (Src->getType()->isInteger()) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00006035 if (SrcTy->getPrimitiveSizeInBits() ==
6036 DestTy->getPrimitiveSizeInBits()) {
Chris Lattner2b2412d2004-04-07 18:38:20 +00006037 // We can always eliminate a cast from ulong or long to the other.
6038 // We can always eliminate a cast from uint to int or the other on
6039 // 32-bit pointer platforms.
Chris Lattnerd1f46d32005-04-24 06:59:08 +00006040 if (DestTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()){
Chris Lattner2b2412d2004-04-07 18:38:20 +00006041 MadeChange = true;
6042 GEP.setOperand(i, Src);
6043 }
6044 } else if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
6045 SrcTy->getPrimitiveSize() == 4) {
6046 // We can always eliminate a cast from int to [u]long. We can
6047 // eliminate a cast from uint to [u]long iff the target is a 32-bit
6048 // pointer target.
Misha Brukmanb1c93172005-04-21 23:48:37 +00006049 if (SrcTy->isSigned() ||
Chris Lattnerd1f46d32005-04-24 06:59:08 +00006050 SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
Chris Lattner2b2412d2004-04-07 18:38:20 +00006051 MadeChange = true;
6052 GEP.setOperand(i, Src);
6053 }
Chris Lattner69193f92004-04-05 01:30:19 +00006054 }
6055 }
6056 }
Chris Lattner2b2412d2004-04-07 18:38:20 +00006057 // If we are using a wider index than needed for this platform, shrink it
6058 // to what we need. If the incoming value needs a cast instruction,
6059 // insert it. This explicit cast can make subsequent optimizations more
6060 // obvious.
6061 Value *Op = GEP.getOperand(i);
6062 if (Op->getType()->getPrimitiveSize() > TD->getPointerSize())
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00006063 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner44d0b952004-07-20 01:48:15 +00006064 GEP.setOperand(i, ConstantExpr::getCast(C,
6065 TD->getIntPtrType()->getSignedVersion()));
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00006066 MadeChange = true;
6067 } else {
Chris Lattner2b2412d2004-04-07 18:38:20 +00006068 Op = InsertNewInstBefore(new CastInst(Op, TD->getIntPtrType(),
6069 Op->getName()), GEP);
6070 GEP.setOperand(i, Op);
6071 MadeChange = true;
6072 }
Chris Lattner44d0b952004-07-20 01:48:15 +00006073
6074 // If this is a constant idx, make sure to canonicalize it to be a signed
6075 // operand, otherwise CSE and other optimizations are pessimized.
6076 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op)) {
6077 GEP.setOperand(i, ConstantExpr::getCast(CUI,
6078 CUI->getType()->getSignedVersion()));
6079 MadeChange = true;
6080 }
Chris Lattner69193f92004-04-05 01:30:19 +00006081 }
6082 if (MadeChange) return &GEP;
6083
Chris Lattnerae7a0d32002-08-02 19:29:35 +00006084 // Combine Indices - If the source pointer to this getelementptr instruction
6085 // is a getelementptr instruction, combine the indices of the two
6086 // getelementptr instructions into a single instruction.
6087 //
Chris Lattner57c67b02004-03-25 22:59:29 +00006088 std::vector<Value*> SrcGEPOperands;
Chris Lattner0798af32005-01-13 20:14:25 +00006089 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattner57c67b02004-03-25 22:59:29 +00006090 SrcGEPOperands.assign(Src->op_begin(), Src->op_end());
Chris Lattner57c67b02004-03-25 22:59:29 +00006091
6092 if (!SrcGEPOperands.empty()) {
Chris Lattner5f667a62004-05-07 22:09:22 +00006093 // Note that if our source is a gep chain itself that we wait for that
6094 // chain to be resolved before we perform this transformation. This
6095 // avoids us creating a TON of code in some cases.
6096 //
6097 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
6098 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
6099 return 0; // Wait until our source is folded to completion.
6100
Chris Lattnerae7a0d32002-08-02 19:29:35 +00006101 std::vector<Value *> Indices;
Chris Lattner5f667a62004-05-07 22:09:22 +00006102
6103 // Find out whether the last index in the source GEP is a sequential idx.
6104 bool EndsWithSequential = false;
6105 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
6106 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattner8ec5f882004-05-08 22:41:42 +00006107 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00006108
Chris Lattnerae7a0d32002-08-02 19:29:35 +00006109 // Can we combine the two pointer arithmetics offsets?
Chris Lattner5f667a62004-05-07 22:09:22 +00006110 if (EndsWithSequential) {
Chris Lattner235af562003-03-05 22:33:14 +00006111 // Replace: gep (gep %P, long B), long A, ...
6112 // With: T = long A+B; gep %P, T, ...
6113 //
Chris Lattner5f667a62004-05-07 22:09:22 +00006114 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner69193f92004-04-05 01:30:19 +00006115 if (SO1 == Constant::getNullValue(SO1->getType())) {
6116 Sum = GO1;
6117 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
6118 Sum = SO1;
6119 } else {
6120 // If they aren't the same type, convert both to an integer of the
6121 // target's pointer size.
6122 if (SO1->getType() != GO1->getType()) {
6123 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
6124 SO1 = ConstantExpr::getCast(SO1C, GO1->getType());
6125 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
6126 GO1 = ConstantExpr::getCast(GO1C, SO1->getType());
6127 } else {
6128 unsigned PS = TD->getPointerSize();
Chris Lattner69193f92004-04-05 01:30:19 +00006129 if (SO1->getType()->getPrimitiveSize() == PS) {
6130 // Convert GO1 to SO1's type.
6131 GO1 = InsertSignExtendToPtrTy(GO1, SO1->getType(), &GEP, this);
6132
6133 } else if (GO1->getType()->getPrimitiveSize() == PS) {
6134 // Convert SO1 to GO1's type.
6135 SO1 = InsertSignExtendToPtrTy(SO1, GO1->getType(), &GEP, this);
6136 } else {
6137 const Type *PT = TD->getIntPtrType();
6138 SO1 = InsertSignExtendToPtrTy(SO1, PT, &GEP, this);
6139 GO1 = InsertSignExtendToPtrTy(GO1, PT, &GEP, this);
6140 }
6141 }
6142 }
Chris Lattner5f667a62004-05-07 22:09:22 +00006143 if (isa<Constant>(SO1) && isa<Constant>(GO1))
6144 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
6145 else {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00006146 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
6147 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner5f667a62004-05-07 22:09:22 +00006148 }
Chris Lattner69193f92004-04-05 01:30:19 +00006149 }
Chris Lattner5f667a62004-05-07 22:09:22 +00006150
6151 // Recycle the GEP we already have if possible.
6152 if (SrcGEPOperands.size() == 2) {
6153 GEP.setOperand(0, SrcGEPOperands[0]);
6154 GEP.setOperand(1, Sum);
6155 return &GEP;
6156 } else {
6157 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
6158 SrcGEPOperands.end()-1);
6159 Indices.push_back(Sum);
6160 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
6161 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00006162 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner69193f92004-04-05 01:30:19 +00006163 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00006164 SrcGEPOperands.size() != 1) {
Chris Lattnerae7a0d32002-08-02 19:29:35 +00006165 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattner57c67b02004-03-25 22:59:29 +00006166 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
6167 SrcGEPOperands.end());
Chris Lattnerae7a0d32002-08-02 19:29:35 +00006168 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
6169 }
6170
6171 if (!Indices.empty())
Chris Lattner57c67b02004-03-25 22:59:29 +00006172 return new GetElementPtrInst(SrcGEPOperands[0], Indices, GEP.getName());
Chris Lattnerc59af1d2002-08-17 22:21:59 +00006173
Chris Lattner5f667a62004-05-07 22:09:22 +00006174 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattnerc59af1d2002-08-17 22:21:59 +00006175 // GEP of global variable. If all of the indices for this GEP are
6176 // constants, we can promote this to a constexpr instead of an instruction.
6177
6178 // Scan for nonconstants...
6179 std::vector<Constant*> Indices;
6180 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
6181 for (; I != E && isa<Constant>(*I); ++I)
6182 Indices.push_back(cast<Constant>(*I));
6183
6184 if (I == E) { // If they are all constants...
Chris Lattnerf3edc492004-07-18 18:59:44 +00006185 Constant *CE = ConstantExpr::getGetElementPtr(GV, Indices);
Chris Lattnerc59af1d2002-08-17 22:21:59 +00006186
6187 // Replace all uses of the GEP with the new constexpr...
6188 return ReplaceInstUsesWith(GEP, CE);
6189 }
Chris Lattner567b81f2005-09-13 00:40:14 +00006190 } else if (Value *X = isCast(PtrOp)) { // Is the operand a cast?
6191 if (!isa<PointerType>(X->getType())) {
6192 // Not interesting. Source pointer must be a cast from pointer.
6193 } else if (HasZeroPointerIndex) {
6194 // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
6195 // into : GEP [10 x ubyte]* X, long 0, ...
6196 //
6197 // This occurs when the program declares an array extern like "int X[];"
6198 //
6199 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
6200 const PointerType *XTy = cast<PointerType>(X->getType());
6201 if (const ArrayType *XATy =
6202 dyn_cast<ArrayType>(XTy->getElementType()))
6203 if (const ArrayType *CATy =
6204 dyn_cast<ArrayType>(CPTy->getElementType()))
6205 if (CATy->getElementType() == XATy->getElementType()) {
6206 // At this point, we know that the cast source type is a pointer
6207 // to an array of the same type as the destination pointer
6208 // array. Because the array type is never stepped over (there
6209 // is a leading zero) we can fold the cast into this GEP.
6210 GEP.setOperand(0, X);
6211 return &GEP;
6212 }
6213 } else if (GEP.getNumOperands() == 2) {
6214 // Transform things like:
Chris Lattner2a893292005-09-13 18:36:04 +00006215 // %t = getelementptr ubyte* cast ([2 x int]* %str to uint*), uint %V
6216 // into: %t1 = getelementptr [2 x int*]* %str, int 0, uint %V; cast
Chris Lattner567b81f2005-09-13 00:40:14 +00006217 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
6218 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
6219 if (isa<ArrayType>(SrcElTy) &&
6220 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
6221 TD->getTypeSize(ResElTy)) {
6222 Value *V = InsertNewInstBefore(
6223 new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
6224 GEP.getOperand(1), GEP.getName()), GEP);
6225 return new CastInst(V, GEP.getType());
Chris Lattner8d0bacb2004-02-22 05:25:17 +00006226 }
Chris Lattner2a893292005-09-13 18:36:04 +00006227
6228 // Transform things like:
6229 // getelementptr sbyte* cast ([100 x double]* X to sbyte*), int %tmp
6230 // (where tmp = 8*tmp2) into:
6231 // getelementptr [100 x double]* %arr, int 0, int %tmp.2
6232
6233 if (isa<ArrayType>(SrcElTy) &&
6234 (ResElTy == Type::SByteTy || ResElTy == Type::UByteTy)) {
6235 uint64_t ArrayEltSize =
6236 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType());
6237
6238 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
6239 // allow either a mul, shift, or constant here.
6240 Value *NewIdx = 0;
6241 ConstantInt *Scale = 0;
6242 if (ArrayEltSize == 1) {
6243 NewIdx = GEP.getOperand(1);
6244 Scale = ConstantInt::get(NewIdx->getType(), 1);
6245 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Chris Lattnera393e4d2005-09-14 17:32:56 +00006246 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner2a893292005-09-13 18:36:04 +00006247 Scale = CI;
6248 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
6249 if (Inst->getOpcode() == Instruction::Shl &&
6250 isa<ConstantInt>(Inst->getOperand(1))) {
6251 unsigned ShAmt =cast<ConstantUInt>(Inst->getOperand(1))->getValue();
6252 if (Inst->getType()->isSigned())
6253 Scale = ConstantSInt::get(Inst->getType(), 1ULL << ShAmt);
6254 else
6255 Scale = ConstantUInt::get(Inst->getType(), 1ULL << ShAmt);
6256 NewIdx = Inst->getOperand(0);
6257 } else if (Inst->getOpcode() == Instruction::Mul &&
6258 isa<ConstantInt>(Inst->getOperand(1))) {
6259 Scale = cast<ConstantInt>(Inst->getOperand(1));
6260 NewIdx = Inst->getOperand(0);
6261 }
6262 }
6263
6264 // If the index will be to exactly the right offset with the scale taken
6265 // out, perform the transformation.
6266 if (Scale && Scale->getRawValue() % ArrayEltSize == 0) {
6267 if (ConstantSInt *C = dyn_cast<ConstantSInt>(Scale))
6268 Scale = ConstantSInt::get(C->getType(),
Chris Lattnera393e4d2005-09-14 17:32:56 +00006269 (int64_t)C->getRawValue() /
6270 (int64_t)ArrayEltSize);
Chris Lattner2a893292005-09-13 18:36:04 +00006271 else
6272 Scale = ConstantUInt::get(Scale->getType(),
6273 Scale->getRawValue() / ArrayEltSize);
6274 if (Scale->getRawValue() != 1) {
6275 Constant *C = ConstantExpr::getCast(Scale, NewIdx->getType());
6276 Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
6277 NewIdx = InsertNewInstBefore(Sc, GEP);
6278 }
6279
6280 // Insert the new GEP instruction.
6281 Instruction *Idx =
6282 new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
6283 NewIdx, GEP.getName());
6284 Idx = InsertNewInstBefore(Idx, GEP);
6285 return new CastInst(Idx, GEP.getType());
6286 }
6287 }
Chris Lattner8d0bacb2004-02-22 05:25:17 +00006288 }
Chris Lattnerca081252001-12-14 16:52:21 +00006289 }
6290
Chris Lattnerca081252001-12-14 16:52:21 +00006291 return 0;
6292}
6293
Chris Lattner1085bdf2002-11-04 16:18:53 +00006294Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
6295 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
6296 if (AI.isArrayAllocation()) // Check C != 1
6297 if (const ConstantUInt *C = dyn_cast<ConstantUInt>(AI.getArraySize())) {
6298 const Type *NewTy = ArrayType::get(AI.getAllocatedType(), C->getValue());
Chris Lattnera2620ac2002-11-09 00:49:43 +00006299 AllocationInst *New = 0;
Chris Lattner1085bdf2002-11-04 16:18:53 +00006300
6301 // Create and insert the replacement instruction...
6302 if (isa<MallocInst>(AI))
Nate Begeman848622f2005-11-05 09:21:28 +00006303 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00006304 else {
6305 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Nate Begeman848622f2005-11-05 09:21:28 +00006306 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00006307 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00006308
6309 InsertNewInstBefore(New, AI);
Misha Brukmanb1c93172005-04-21 23:48:37 +00006310
Chris Lattner1085bdf2002-11-04 16:18:53 +00006311 // Scan to the end of the allocation instructions, to skip over a block of
6312 // allocas if possible...
6313 //
6314 BasicBlock::iterator It = New;
6315 while (isa<AllocationInst>(*It)) ++It;
6316
6317 // Now that I is pointing to the first non-allocation-inst in the block,
6318 // insert our getelementptr instruction...
6319 //
Chris Lattner809dfac2005-05-04 19:10:26 +00006320 Value *NullIdx = Constant::getNullValue(Type::IntTy);
6321 Value *V = new GetElementPtrInst(New, NullIdx, NullIdx,
6322 New->getName()+".sub", It);
Chris Lattner1085bdf2002-11-04 16:18:53 +00006323
6324 // Now make everything use the getelementptr instead of the original
6325 // allocation.
Chris Lattnerabb77c92004-03-19 06:08:10 +00006326 return ReplaceInstUsesWith(AI, V);
Chris Lattner81a7a232004-10-16 18:11:37 +00006327 } else if (isa<UndefValue>(AI.getArraySize())) {
6328 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner1085bdf2002-11-04 16:18:53 +00006329 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00006330
6331 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
6332 // Note that we only do this for alloca's, because malloc should allocate and
6333 // return a unique pointer, even for a zero byte allocation.
Misha Brukmanb1c93172005-04-21 23:48:37 +00006334 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
Chris Lattner49df6ce2004-07-02 22:55:47 +00006335 TD->getTypeSize(AI.getAllocatedType()) == 0)
Chris Lattnerabb77c92004-03-19 06:08:10 +00006336 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
6337
Chris Lattner1085bdf2002-11-04 16:18:53 +00006338 return 0;
6339}
6340
Chris Lattner8427bff2003-12-07 01:24:23 +00006341Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
6342 Value *Op = FI.getOperand(0);
6343
6344 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
6345 if (CastInst *CI = dyn_cast<CastInst>(Op))
6346 if (isa<PointerType>(CI->getOperand(0)->getType())) {
6347 FI.setOperand(0, CI->getOperand(0));
6348 return &FI;
6349 }
6350
Chris Lattner8ba9ec92004-10-18 02:59:09 +00006351 // free undef -> unreachable.
6352 if (isa<UndefValue>(Op)) {
6353 // Insert a new store to null because we cannot modify the CFG here.
6354 new StoreInst(ConstantBool::True,
6355 UndefValue::get(PointerType::get(Type::BoolTy)), &FI);
6356 return EraseInstFromFunction(FI);
6357 }
6358
Chris Lattnerf3a36602004-02-28 04:57:37 +00006359 // If we have 'free null' delete the instruction. This can happen in stl code
6360 // when lots of inlining happens.
Chris Lattner8ba9ec92004-10-18 02:59:09 +00006361 if (isa<ConstantPointerNull>(Op))
Chris Lattner51ea1272004-02-28 05:22:00 +00006362 return EraseInstFromFunction(FI);
Chris Lattnerf3a36602004-02-28 04:57:37 +00006363
Chris Lattner8427bff2003-12-07 01:24:23 +00006364 return 0;
6365}
6366
6367
Chris Lattner72684fe2005-01-31 05:51:45 +00006368/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Chris Lattner35e24772004-07-13 01:49:43 +00006369static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
6370 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00006371 Value *CastOp = CI->getOperand(0);
Chris Lattner35e24772004-07-13 01:49:43 +00006372
6373 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00006374 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Chris Lattner35e24772004-07-13 01:49:43 +00006375 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00006376
Chris Lattnerebca4762006-04-02 05:37:12 +00006377 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
6378 isa<PackedType>(DestPTy)) {
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00006379 // If the source is an array, the code below will not succeed. Check to
6380 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
6381 // constants.
6382 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
6383 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
6384 if (ASrcTy->getNumElements() != 0) {
6385 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
6386 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
6387 SrcTy = cast<PointerType>(CastOp->getType());
6388 SrcPTy = SrcTy->getElementType();
6389 }
6390
Chris Lattnerebca4762006-04-02 05:37:12 +00006391 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
6392 isa<PackedType>(SrcPTy)) &&
Chris Lattnerecfa9b52005-03-29 06:37:47 +00006393 // Do not allow turning this into a load of an integer, which is then
6394 // casted to a pointer, this pessimizes pointer analysis a lot.
6395 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00006396 IC.getTargetData().getTypeSize(SrcPTy) ==
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00006397 IC.getTargetData().getTypeSize(DestPTy)) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00006398
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00006399 // Okay, we are casting from one integer or pointer type to another of
6400 // the same size. Instead of casting the pointer before the load, cast
6401 // the result of the loaded value.
6402 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
6403 CI->getName(),
6404 LI.isVolatile()),LI);
6405 // Now cast the result of the load.
6406 return new CastInst(NewLoad, LI.getType());
6407 }
Chris Lattner35e24772004-07-13 01:49:43 +00006408 }
6409 }
6410 return 0;
6411}
6412
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00006413/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattnere6f13092004-09-19 19:18:10 +00006414/// from this value cannot trap. If it is not obviously safe to load from the
6415/// specified pointer, we do a quick local scan of the basic block containing
6416/// ScanFrom, to determine if the address is already accessed.
6417static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
6418 // If it is an alloca or global variable, it is always safe to load from.
6419 if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
6420
6421 // Otherwise, be a little bit agressive by scanning the local block where we
6422 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00006423 // from/to. If so, the previous load or store would have already trapped,
6424 // so there is no harm doing an extra load (also, CSE will later eliminate
6425 // the load entirely).
Chris Lattnere6f13092004-09-19 19:18:10 +00006426 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
6427
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00006428 while (BBI != E) {
Chris Lattnere6f13092004-09-19 19:18:10 +00006429 --BBI;
6430
6431 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
6432 if (LI->getOperand(0) == V) return true;
6433 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
6434 if (SI->getOperand(1) == V) return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +00006435
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00006436 }
Chris Lattnere6f13092004-09-19 19:18:10 +00006437 return false;
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00006438}
6439
Chris Lattner0f1d8a32003-06-26 05:06:25 +00006440Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
6441 Value *Op = LI.getOperand(0);
Chris Lattner7e8af382004-01-12 04:13:56 +00006442
Chris Lattnera9d84e32005-05-01 04:24:53 +00006443 // load (cast X) --> cast (load X) iff safe
6444 if (CastInst *CI = dyn_cast<CastInst>(Op))
6445 if (Instruction *Res = InstCombineLoadCast(*this, LI))
6446 return Res;
6447
6448 // None of the following transforms are legal for volatile loads.
6449 if (LI.isVolatile()) return 0;
Chris Lattnerb990f7d2005-09-12 22:00:15 +00006450
Chris Lattnerb990f7d2005-09-12 22:00:15 +00006451 if (&LI.getParent()->front() != &LI) {
6452 BasicBlock::iterator BBI = &LI; --BBI;
Chris Lattnere0bfdf12005-09-12 22:21:03 +00006453 // If the instruction immediately before this is a store to the same
6454 // address, do a simple form of store->load forwarding.
Chris Lattnerb990f7d2005-09-12 22:00:15 +00006455 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
6456 if (SI->getOperand(1) == LI.getOperand(0))
6457 return ReplaceInstUsesWith(LI, SI->getOperand(0));
Chris Lattnere0bfdf12005-09-12 22:21:03 +00006458 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
6459 if (LIB->getOperand(0) == LI.getOperand(0))
6460 return ReplaceInstUsesWith(LI, LIB);
Chris Lattnerb990f7d2005-09-12 22:00:15 +00006461 }
Chris Lattnera9d84e32005-05-01 04:24:53 +00006462
6463 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op))
6464 if (isa<ConstantPointerNull>(GEPI->getOperand(0)) ||
6465 isa<UndefValue>(GEPI->getOperand(0))) {
6466 // Insert a new store to null instruction before the load to indicate
6467 // that this code is not reachable. We do this instead of inserting
6468 // an unreachable instruction directly because we cannot modify the
6469 // CFG.
6470 new StoreInst(UndefValue::get(LI.getType()),
6471 Constant::getNullValue(Op->getType()), &LI);
6472 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
6473 }
6474
Chris Lattner81a7a232004-10-16 18:11:37 +00006475 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattnera9d84e32005-05-01 04:24:53 +00006476 // load null/undef -> undef
6477 if ((C->isNullValue() || isa<UndefValue>(C))) {
Chris Lattner8ba9ec92004-10-18 02:59:09 +00006478 // Insert a new store to null instruction before the load to indicate that
6479 // this code is not reachable. We do this instead of inserting an
6480 // unreachable instruction directly because we cannot modify the CFG.
Chris Lattnera9d84e32005-05-01 04:24:53 +00006481 new StoreInst(UndefValue::get(LI.getType()),
6482 Constant::getNullValue(Op->getType()), &LI);
Chris Lattner81a7a232004-10-16 18:11:37 +00006483 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner8ba9ec92004-10-18 02:59:09 +00006484 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00006485
Chris Lattner81a7a232004-10-16 18:11:37 +00006486 // Instcombine load (constant global) into the value loaded.
6487 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
6488 if (GV->isConstant() && !GV->isExternal())
6489 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanb1c93172005-04-21 23:48:37 +00006490
Chris Lattner81a7a232004-10-16 18:11:37 +00006491 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
6492 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
6493 if (CE->getOpcode() == Instruction::GetElementPtr) {
6494 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
6495 if (GV->isConstant() && !GV->isExternal())
Chris Lattner0b011ec2005-09-26 05:28:06 +00006496 if (Constant *V =
6497 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
Chris Lattner81a7a232004-10-16 18:11:37 +00006498 return ReplaceInstUsesWith(LI, V);
Chris Lattnera9d84e32005-05-01 04:24:53 +00006499 if (CE->getOperand(0)->isNullValue()) {
6500 // Insert a new store to null instruction before the load to indicate
6501 // that this code is not reachable. We do this instead of inserting
6502 // an unreachable instruction directly because we cannot modify the
6503 // CFG.
6504 new StoreInst(UndefValue::get(LI.getType()),
6505 Constant::getNullValue(Op->getType()), &LI);
6506 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
6507 }
6508
Chris Lattner81a7a232004-10-16 18:11:37 +00006509 } else if (CE->getOpcode() == Instruction::Cast) {
6510 if (Instruction *Res = InstCombineLoadCast(*this, LI))
6511 return Res;
6512 }
6513 }
Chris Lattnere228ee52004-04-08 20:39:49 +00006514
Chris Lattnera9d84e32005-05-01 04:24:53 +00006515 if (Op->hasOneUse()) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00006516 // Change select and PHI nodes to select values instead of addresses: this
6517 // helps alias analysis out a lot, allows many others simplifications, and
6518 // exposes redundancy in the code.
6519 //
6520 // Note that we cannot do the transformation unless we know that the
6521 // introduced loads cannot trap! Something like this is valid as long as
6522 // the condition is always false: load (select bool %C, int* null, int* %G),
6523 // but it would not be valid if we transformed it to load from null
6524 // unconditionally.
6525 //
6526 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
6527 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattnere6f13092004-09-19 19:18:10 +00006528 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
6529 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00006530 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner42618552004-09-20 10:15:10 +00006531 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00006532 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner42618552004-09-20 10:15:10 +00006533 SI->getOperand(2)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00006534 return new SelectInst(SI->getCondition(), V1, V2);
6535 }
6536
Chris Lattnerbdcf41a2004-09-23 15:46:00 +00006537 // load (select (cond, null, P)) -> load P
6538 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
6539 if (C->isNullValue()) {
6540 LI.setOperand(0, SI->getOperand(2));
6541 return &LI;
6542 }
6543
6544 // load (select (cond, P, null)) -> load P
6545 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
6546 if (C->isNullValue()) {
6547 LI.setOperand(0, SI->getOperand(1));
6548 return &LI;
6549 }
6550
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00006551 } else if (PHINode *PN = dyn_cast<PHINode>(Op)) {
6552 // load (phi (&V1, &V2, &V3)) --> phi(load &V1, load &V2, load &V3)
Chris Lattner42618552004-09-20 10:15:10 +00006553 bool Safe = PN->getParent() == LI.getParent();
6554
6555 // Scan all of the instructions between the PHI and the load to make
6556 // sure there are no instructions that might possibly alter the value
6557 // loaded from the PHI.
6558 if (Safe) {
6559 BasicBlock::iterator I = &LI;
6560 for (--I; !isa<PHINode>(I); --I)
6561 if (isa<StoreInst>(I) || isa<CallInst>(I)) {
6562 Safe = false;
6563 break;
6564 }
6565 }
6566
6567 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e && Safe; ++i)
Chris Lattnere6f13092004-09-19 19:18:10 +00006568 if (!isSafeToLoadUnconditionally(PN->getIncomingValue(i),
Chris Lattner42618552004-09-20 10:15:10 +00006569 PN->getIncomingBlock(i)->getTerminator()))
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00006570 Safe = false;
Chris Lattner42618552004-09-20 10:15:10 +00006571
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00006572 if (Safe) {
6573 // Create the PHI.
6574 PHINode *NewPN = new PHINode(LI.getType(), PN->getName());
6575 InsertNewInstBefore(NewPN, *PN);
6576 std::map<BasicBlock*,Value*> LoadMap; // Don't insert duplicate loads
6577
6578 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
6579 BasicBlock *BB = PN->getIncomingBlock(i);
6580 Value *&TheLoad = LoadMap[BB];
6581 if (TheLoad == 0) {
6582 Value *InVal = PN->getIncomingValue(i);
6583 TheLoad = InsertNewInstBefore(new LoadInst(InVal,
6584 InVal->getName()+".val"),
6585 *BB->getTerminator());
6586 }
6587 NewPN->addIncoming(TheLoad, BB);
6588 }
6589 return ReplaceInstUsesWith(LI, NewPN);
6590 }
6591 }
6592 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00006593 return 0;
6594}
6595
Chris Lattner72684fe2005-01-31 05:51:45 +00006596/// InstCombineStoreToCast - Fold 'store V, (cast P)' -> store (cast V), P'
6597/// when possible.
6598static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
6599 User *CI = cast<User>(SI.getOperand(1));
6600 Value *CastOp = CI->getOperand(0);
6601
6602 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
6603 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
6604 const Type *SrcPTy = SrcTy->getElementType();
6605
6606 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
6607 // If the source is an array, the code below will not succeed. Check to
6608 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
6609 // constants.
6610 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
6611 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
6612 if (ASrcTy->getNumElements() != 0) {
6613 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
6614 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
6615 SrcTy = cast<PointerType>(CastOp->getType());
6616 SrcPTy = SrcTy->getElementType();
6617 }
6618
6619 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00006620 IC.getTargetData().getTypeSize(SrcPTy) ==
Chris Lattner72684fe2005-01-31 05:51:45 +00006621 IC.getTargetData().getTypeSize(DestPTy)) {
6622
6623 // Okay, we are casting from one integer or pointer type to another of
6624 // the same size. Instead of casting the pointer before the store, cast
6625 // the value to be stored.
6626 Value *NewCast;
6627 if (Constant *C = dyn_cast<Constant>(SI.getOperand(0)))
6628 NewCast = ConstantExpr::getCast(C, SrcPTy);
6629 else
6630 NewCast = IC.InsertNewInstBefore(new CastInst(SI.getOperand(0),
6631 SrcPTy,
6632 SI.getOperand(0)->getName()+".c"), SI);
6633
6634 return new StoreInst(NewCast, CastOp);
6635 }
6636 }
6637 }
6638 return 0;
6639}
6640
Chris Lattner31f486c2005-01-31 05:36:43 +00006641Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
6642 Value *Val = SI.getOperand(0);
6643 Value *Ptr = SI.getOperand(1);
6644
6645 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner5997cf92006-02-08 03:25:32 +00006646 EraseInstFromFunction(SI);
Chris Lattner31f486c2005-01-31 05:36:43 +00006647 ++NumCombined;
6648 return 0;
6649 }
6650
Chris Lattner5997cf92006-02-08 03:25:32 +00006651 // Do really simple DSE, to catch cases where there are several consequtive
6652 // stores to the same location, separated by a few arithmetic operations. This
6653 // situation often occurs with bitfield accesses.
6654 BasicBlock::iterator BBI = &SI;
6655 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
6656 --ScanInsts) {
6657 --BBI;
6658
6659 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
6660 // Prev store isn't volatile, and stores to the same location?
6661 if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
6662 ++NumDeadStore;
6663 ++BBI;
6664 EraseInstFromFunction(*PrevSI);
6665 continue;
6666 }
6667 break;
6668 }
6669
6670 // Don't skip over loads or things that can modify memory.
6671 if (BBI->mayWriteToMemory() || isa<LoadInst>(BBI))
6672 break;
6673 }
6674
6675
6676 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner31f486c2005-01-31 05:36:43 +00006677
6678 // store X, null -> turns into 'unreachable' in SimplifyCFG
6679 if (isa<ConstantPointerNull>(Ptr)) {
6680 if (!isa<UndefValue>(Val)) {
6681 SI.setOperand(0, UndefValue::get(Val->getType()));
6682 if (Instruction *U = dyn_cast<Instruction>(Val))
6683 WorkList.push_back(U); // Dropped a use.
6684 ++NumCombined;
6685 }
6686 return 0; // Do not modify these!
6687 }
6688
6689 // store undef, Ptr -> noop
6690 if (isa<UndefValue>(Val)) {
Chris Lattner5997cf92006-02-08 03:25:32 +00006691 EraseInstFromFunction(SI);
Chris Lattner31f486c2005-01-31 05:36:43 +00006692 ++NumCombined;
6693 return 0;
6694 }
6695
Chris Lattner72684fe2005-01-31 05:51:45 +00006696 // If the pointer destination is a cast, see if we can fold the cast into the
6697 // source instead.
6698 if (CastInst *CI = dyn_cast<CastInst>(Ptr))
6699 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
6700 return Res;
6701 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
6702 if (CE->getOpcode() == Instruction::Cast)
6703 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
6704 return Res;
6705
Chris Lattner219175c2005-09-12 23:23:25 +00006706
6707 // If this store is the last instruction in the basic block, and if the block
6708 // ends with an unconditional branch, try to move it to the successor block.
Chris Lattner5997cf92006-02-08 03:25:32 +00006709 BBI = &SI; ++BBI;
Chris Lattner219175c2005-09-12 23:23:25 +00006710 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
6711 if (BI->isUnconditional()) {
6712 // Check to see if the successor block has exactly two incoming edges. If
6713 // so, see if the other predecessor contains a store to the same location.
6714 // if so, insert a PHI node (if needed) and move the stores down.
6715 BasicBlock *Dest = BI->getSuccessor(0);
6716
6717 pred_iterator PI = pred_begin(Dest);
6718 BasicBlock *Other = 0;
6719 if (*PI != BI->getParent())
6720 Other = *PI;
6721 ++PI;
6722 if (PI != pred_end(Dest)) {
6723 if (*PI != BI->getParent())
6724 if (Other)
6725 Other = 0;
6726 else
6727 Other = *PI;
6728 if (++PI != pred_end(Dest))
6729 Other = 0;
6730 }
6731 if (Other) { // If only one other pred...
6732 BBI = Other->getTerminator();
6733 // Make sure this other block ends in an unconditional branch and that
6734 // there is an instruction before the branch.
6735 if (isa<BranchInst>(BBI) && cast<BranchInst>(BBI)->isUnconditional() &&
6736 BBI != Other->begin()) {
6737 --BBI;
6738 StoreInst *OtherStore = dyn_cast<StoreInst>(BBI);
6739
6740 // If this instruction is a store to the same location.
6741 if (OtherStore && OtherStore->getOperand(1) == SI.getOperand(1)) {
6742 // Okay, we know we can perform this transformation. Insert a PHI
6743 // node now if we need it.
6744 Value *MergedVal = OtherStore->getOperand(0);
6745 if (MergedVal != SI.getOperand(0)) {
6746 PHINode *PN = new PHINode(MergedVal->getType(), "storemerge");
6747 PN->reserveOperandSpace(2);
6748 PN->addIncoming(SI.getOperand(0), SI.getParent());
6749 PN->addIncoming(OtherStore->getOperand(0), Other);
6750 MergedVal = InsertNewInstBefore(PN, Dest->front());
6751 }
6752
6753 // Advance to a place where it is safe to insert the new store and
6754 // insert it.
6755 BBI = Dest->begin();
6756 while (isa<PHINode>(BBI)) ++BBI;
6757 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
6758 OtherStore->isVolatile()), *BBI);
6759
6760 // Nuke the old stores.
Chris Lattner5997cf92006-02-08 03:25:32 +00006761 EraseInstFromFunction(SI);
6762 EraseInstFromFunction(*OtherStore);
Chris Lattner219175c2005-09-12 23:23:25 +00006763 ++NumCombined;
6764 return 0;
6765 }
6766 }
6767 }
6768 }
6769
Chris Lattner31f486c2005-01-31 05:36:43 +00006770 return 0;
6771}
6772
6773
Chris Lattner9eef8a72003-06-04 04:46:00 +00006774Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
6775 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4fdd96c2005-06-18 17:37:34 +00006776 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00006777 BasicBlock *TrueDest;
6778 BasicBlock *FalseDest;
6779 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
6780 !isa<Constant>(X)) {
6781 // Swap Destinations and condition...
6782 BI.setCondition(X);
6783 BI.setSuccessor(0, FalseDest);
6784 BI.setSuccessor(1, TrueDest);
6785 return &BI;
6786 }
6787
6788 // Cannonicalize setne -> seteq
6789 Instruction::BinaryOps Op; Value *Y;
6790 if (match(&BI, m_Br(m_SetCond(Op, m_Value(X), m_Value(Y)),
6791 TrueDest, FalseDest)))
6792 if ((Op == Instruction::SetNE || Op == Instruction::SetLE ||
6793 Op == Instruction::SetGE) && BI.getCondition()->hasOneUse()) {
6794 SetCondInst *I = cast<SetCondInst>(BI.getCondition());
6795 std::string Name = I->getName(); I->setName("");
6796 Instruction::BinaryOps NewOpcode = SetCondInst::getInverseCondition(Op);
6797 Value *NewSCC = BinaryOperator::create(NewOpcode, X, Y, Name, I);
Chris Lattnere967b342003-06-04 05:10:11 +00006798 // Swap Destinations and condition...
Chris Lattnerd4252a72004-07-30 07:50:03 +00006799 BI.setCondition(NewSCC);
Chris Lattnere967b342003-06-04 05:10:11 +00006800 BI.setSuccessor(0, FalseDest);
6801 BI.setSuccessor(1, TrueDest);
Chris Lattnerd4252a72004-07-30 07:50:03 +00006802 removeFromWorkList(I);
6803 I->getParent()->getInstList().erase(I);
6804 WorkList.push_back(cast<Instruction>(NewSCC));
Chris Lattnere967b342003-06-04 05:10:11 +00006805 return &BI;
6806 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00006807
Chris Lattner9eef8a72003-06-04 04:46:00 +00006808 return 0;
6809}
Chris Lattner1085bdf2002-11-04 16:18:53 +00006810
Chris Lattner4c9c20a2004-07-03 00:26:11 +00006811Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
6812 Value *Cond = SI.getCondition();
6813 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
6814 if (I->getOpcode() == Instruction::Add)
6815 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
6816 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
6817 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattner81a7a232004-10-16 18:11:37 +00006818 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner4c9c20a2004-07-03 00:26:11 +00006819 AddRHS));
6820 SI.setOperand(0, I->getOperand(0));
6821 WorkList.push_back(I);
6822 return &SI;
6823 }
6824 }
6825 return 0;
6826}
6827
Chris Lattner6bc98652006-03-05 00:22:33 +00006828/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
6829/// is to leave as a vector operation.
6830static bool CheapToScalarize(Value *V, bool isConstant) {
6831 if (isa<ConstantAggregateZero>(V))
6832 return true;
6833 if (ConstantPacked *C = dyn_cast<ConstantPacked>(V)) {
6834 if (isConstant) return true;
6835 // If all elts are the same, we can extract.
6836 Constant *Op0 = C->getOperand(0);
6837 for (unsigned i = 1; i < C->getNumOperands(); ++i)
6838 if (C->getOperand(i) != Op0)
6839 return false;
6840 return true;
6841 }
6842 Instruction *I = dyn_cast<Instruction>(V);
6843 if (!I) return false;
6844
6845 // Insert element gets simplified to the inserted element or is deleted if
6846 // this is constant idx extract element and its a constant idx insertelt.
6847 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
6848 isa<ConstantInt>(I->getOperand(2)))
6849 return true;
6850 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
6851 return true;
6852 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
6853 if (BO->hasOneUse() &&
6854 (CheapToScalarize(BO->getOperand(0), isConstant) ||
6855 CheapToScalarize(BO->getOperand(1), isConstant)))
6856 return true;
6857
6858 return false;
6859}
6860
Chris Lattner8d1d8d32006-03-31 23:01:56 +00006861/// FindScalarElement - Given a vector and an element number, see if the scalar
6862/// value is already around as a register, for example if it were inserted then
6863/// extracted from the vector.
6864static Value *FindScalarElement(Value *V, unsigned EltNo) {
6865 assert(isa<PackedType>(V->getType()) && "Not looking at a vector?");
6866 const PackedType *PTy = cast<PackedType>(V->getType());
Chris Lattner2d37f922006-04-10 23:06:36 +00006867 unsigned Width = PTy->getNumElements();
6868 if (EltNo >= Width) // Out of range access.
Chris Lattner8d1d8d32006-03-31 23:01:56 +00006869 return UndefValue::get(PTy->getElementType());
6870
6871 if (isa<UndefValue>(V))
6872 return UndefValue::get(PTy->getElementType());
6873 else if (isa<ConstantAggregateZero>(V))
6874 return Constant::getNullValue(PTy->getElementType());
6875 else if (ConstantPacked *CP = dyn_cast<ConstantPacked>(V))
6876 return CP->getOperand(EltNo);
6877 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
6878 // If this is an insert to a variable element, we don't know what it is.
6879 if (!isa<ConstantUInt>(III->getOperand(2))) return 0;
6880 unsigned IIElt = cast<ConstantUInt>(III->getOperand(2))->getValue();
6881
6882 // If this is an insert to the element we are looking for, return the
6883 // inserted value.
6884 if (EltNo == IIElt) return III->getOperand(1);
6885
6886 // Otherwise, the insertelement doesn't modify the value, recurse on its
6887 // vector input.
6888 return FindScalarElement(III->getOperand(0), EltNo);
Chris Lattner2d37f922006-04-10 23:06:36 +00006889 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
6890 if (isa<ConstantAggregateZero>(SVI->getOperand(2))) {
6891 return FindScalarElement(SVI->getOperand(0), 0);
6892 } else if (ConstantPacked *CP =
6893 dyn_cast<ConstantPacked>(SVI->getOperand(2))) {
6894 if (isa<UndefValue>(CP->getOperand(EltNo)))
6895 return UndefValue::get(PTy->getElementType());
6896 unsigned InEl = cast<ConstantUInt>(CP->getOperand(EltNo))->getValue();
6897 if (InEl < Width)
6898 return FindScalarElement(SVI->getOperand(0), InEl);
6899 else
6900 return FindScalarElement(SVI->getOperand(1), InEl - Width);
6901 }
Chris Lattner8d1d8d32006-03-31 23:01:56 +00006902 }
6903
6904 // Otherwise, we don't know.
6905 return 0;
6906}
6907
Robert Bocchinoa8352962006-01-13 22:48:06 +00006908Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Chris Lattner8d1d8d32006-03-31 23:01:56 +00006909
Chris Lattner92346c32006-03-31 18:25:14 +00006910 // If packed val is undef, replace extract with scalar undef.
6911 if (isa<UndefValue>(EI.getOperand(0)))
6912 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
6913
6914 // If packed val is constant 0, replace extract with scalar 0.
6915 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
6916 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
6917
Robert Bocchinoa8352962006-01-13 22:48:06 +00006918 if (ConstantPacked *C = dyn_cast<ConstantPacked>(EI.getOperand(0))) {
6919 // If packed val is constant with uniform operands, replace EI
6920 // with that operand
Chris Lattner6bc98652006-03-05 00:22:33 +00006921 Constant *op0 = C->getOperand(0);
Robert Bocchinoa8352962006-01-13 22:48:06 +00006922 for (unsigned i = 1; i < C->getNumOperands(); ++i)
Chris Lattner6bc98652006-03-05 00:22:33 +00006923 if (C->getOperand(i) != op0) {
6924 op0 = 0;
6925 break;
6926 }
6927 if (op0)
6928 return ReplaceInstUsesWith(EI, op0);
Robert Bocchinoa8352962006-01-13 22:48:06 +00006929 }
Chris Lattner6bc98652006-03-05 00:22:33 +00006930
Chris Lattner8d1d8d32006-03-31 23:01:56 +00006931 // If extracting a specified index from the vector, see if we can recursively
6932 // find a previously computed scalar that was inserted into the vector.
Chris Lattner2d37f922006-04-10 23:06:36 +00006933 if (ConstantUInt *IdxC = dyn_cast<ConstantUInt>(EI.getOperand(1))) {
Chris Lattner8d1d8d32006-03-31 23:01:56 +00006934 if (Value *Elt = FindScalarElement(EI.getOperand(0), IdxC->getValue()))
6935 return ReplaceInstUsesWith(EI, Elt);
Chris Lattner2d37f922006-04-10 23:06:36 +00006936 }
Chris Lattner8d1d8d32006-03-31 23:01:56 +00006937
Robert Bocchinoa8352962006-01-13 22:48:06 +00006938 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0)))
6939 if (I->hasOneUse()) {
6940 // Push extractelement into predecessor operation if legal and
6941 // profitable to do so
6942 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Chris Lattner6bc98652006-03-05 00:22:33 +00006943 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
6944 if (CheapToScalarize(BO, isConstantElt)) {
6945 ExtractElementInst *newEI0 =
6946 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
6947 EI.getName()+".lhs");
6948 ExtractElementInst *newEI1 =
6949 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
6950 EI.getName()+".rhs");
6951 InsertNewInstBefore(newEI0, EI);
6952 InsertNewInstBefore(newEI1, EI);
6953 return BinaryOperator::create(BO->getOpcode(), newEI0, newEI1);
6954 }
6955 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Robert Bocchinoa8352962006-01-13 22:48:06 +00006956 Value *Ptr = InsertCastBefore(I->getOperand(0),
6957 PointerType::get(EI.getType()), EI);
6958 GetElementPtrInst *GEP =
6959 new GetElementPtrInst(Ptr, EI.getOperand(1),
6960 I->getName() + ".gep");
6961 InsertNewInstBefore(GEP, EI);
6962 return new LoadInst(GEP);
Chris Lattner6bc98652006-03-05 00:22:33 +00006963 } else if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
6964 // Extracting the inserted element?
6965 if (IE->getOperand(2) == EI.getOperand(1))
6966 return ReplaceInstUsesWith(EI, IE->getOperand(1));
6967 // If the inserted and extracted elements are constants, they must not
Chris Lattner612fa8e2006-03-30 22:02:40 +00006968 // be the same value, extract from the pre-inserted value instead.
6969 if (isa<Constant>(IE->getOperand(2)) &&
6970 isa<Constant>(EI.getOperand(1))) {
6971 AddUsesToWorkList(EI);
6972 EI.setOperand(0, IE->getOperand(0));
6973 return &EI;
6974 }
Robert Bocchinoa8352962006-01-13 22:48:06 +00006975 }
6976 }
6977 return 0;
6978}
6979
Chris Lattner90951862006-04-16 00:51:47 +00006980/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
6981/// elements from either LHS or RHS, return the shuffle mask and true.
6982/// Otherwise, return false.
6983static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
6984 std::vector<Constant*> &Mask) {
6985 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
6986 "Invalid CollectSingleShuffleElements");
6987 unsigned NumElts = cast<PackedType>(V->getType())->getNumElements();
6988
6989 if (isa<UndefValue>(V)) {
6990 Mask.assign(NumElts, UndefValue::get(Type::UIntTy));
6991 return true;
6992 } else if (V == LHS) {
6993 for (unsigned i = 0; i != NumElts; ++i)
6994 Mask.push_back(ConstantUInt::get(Type::UIntTy, i));
6995 return true;
6996 } else if (V == RHS) {
6997 for (unsigned i = 0; i != NumElts; ++i)
6998 Mask.push_back(ConstantUInt::get(Type::UIntTy, i+NumElts));
6999 return true;
7000 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
7001 // If this is an insert of an extract from some other vector, include it.
7002 Value *VecOp = IEI->getOperand(0);
7003 Value *ScalarOp = IEI->getOperand(1);
7004 Value *IdxOp = IEI->getOperand(2);
7005
Chris Lattnerb6cb64b2006-04-27 21:14:21 +00007006 if (!isa<ConstantInt>(IdxOp))
7007 return false;
7008 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getRawValue();
7009
7010 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
7011 // Okay, we can handle this if the vector we are insertinting into is
7012 // transitively ok.
7013 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
7014 // If so, update the mask to reflect the inserted undef.
7015 Mask[InsertedIdx] = UndefValue::get(Type::UIntTy);
7016 return true;
7017 }
7018 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
7019 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner90951862006-04-16 00:51:47 +00007020 EI->getOperand(0)->getType() == V->getType()) {
7021 unsigned ExtractedIdx =
7022 cast<ConstantInt>(EI->getOperand(1))->getRawValue();
Chris Lattner90951862006-04-16 00:51:47 +00007023
7024 // This must be extracting from either LHS or RHS.
7025 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
7026 // Okay, we can handle this if the vector we are insertinting into is
7027 // transitively ok.
7028 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
7029 // If so, update the mask to reflect the inserted value.
7030 if (EI->getOperand(0) == LHS) {
7031 Mask[InsertedIdx & (NumElts-1)] =
7032 ConstantUInt::get(Type::UIntTy, ExtractedIdx);
7033 } else {
7034 assert(EI->getOperand(0) == RHS);
7035 Mask[InsertedIdx & (NumElts-1)] =
7036 ConstantUInt::get(Type::UIntTy, ExtractedIdx+NumElts);
7037
7038 }
7039 return true;
7040 }
7041 }
7042 }
7043 }
7044 }
7045 // TODO: Handle shufflevector here!
7046
7047 return false;
7048}
7049
7050/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
7051/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
7052/// that computes V and the LHS value of the shuffle.
Chris Lattner39fac442006-04-15 01:39:45 +00007053static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Chris Lattner90951862006-04-16 00:51:47 +00007054 Value *&RHS) {
7055 assert(isa<PackedType>(V->getType()) &&
7056 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattner39fac442006-04-15 01:39:45 +00007057 "Invalid shuffle!");
7058 unsigned NumElts = cast<PackedType>(V->getType())->getNumElements();
7059
7060 if (isa<UndefValue>(V)) {
7061 Mask.assign(NumElts, UndefValue::get(Type::UIntTy));
7062 return V;
7063 } else if (isa<ConstantAggregateZero>(V)) {
7064 Mask.assign(NumElts, ConstantUInt::get(Type::UIntTy, 0));
7065 return V;
7066 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
7067 // If this is an insert of an extract from some other vector, include it.
7068 Value *VecOp = IEI->getOperand(0);
7069 Value *ScalarOp = IEI->getOperand(1);
7070 Value *IdxOp = IEI->getOperand(2);
7071
7072 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
7073 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
7074 EI->getOperand(0)->getType() == V->getType()) {
7075 unsigned ExtractedIdx =
7076 cast<ConstantInt>(EI->getOperand(1))->getRawValue();
7077 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getRawValue();
7078
7079 // Either the extracted from or inserted into vector must be RHSVec,
7080 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner90951862006-04-16 00:51:47 +00007081 if (EI->getOperand(0) == RHS || RHS == 0) {
7082 RHS = EI->getOperand(0);
7083 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
Chris Lattner39fac442006-04-15 01:39:45 +00007084 Mask[InsertedIdx & (NumElts-1)] =
7085 ConstantUInt::get(Type::UIntTy, NumElts+ExtractedIdx);
7086 return V;
7087 }
7088
Chris Lattner90951862006-04-16 00:51:47 +00007089 if (VecOp == RHS) {
7090 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
Chris Lattner39fac442006-04-15 01:39:45 +00007091 // Everything but the extracted element is replaced with the RHS.
7092 for (unsigned i = 0; i != NumElts; ++i) {
7093 if (i != InsertedIdx)
7094 Mask[i] = ConstantUInt::get(Type::UIntTy, NumElts+i);
7095 }
7096 return V;
7097 }
Chris Lattner90951862006-04-16 00:51:47 +00007098
7099 // If this insertelement is a chain that comes from exactly these two
7100 // vectors, return the vector and the effective shuffle.
7101 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
7102 return EI->getOperand(0);
7103
Chris Lattner39fac442006-04-15 01:39:45 +00007104 }
7105 }
7106 }
Chris Lattner90951862006-04-16 00:51:47 +00007107 // TODO: Handle shufflevector here!
Chris Lattner39fac442006-04-15 01:39:45 +00007108
7109 // Otherwise, can't do anything fancy. Return an identity vector.
7110 for (unsigned i = 0; i != NumElts; ++i)
7111 Mask.push_back(ConstantUInt::get(Type::UIntTy, i));
7112 return V;
7113}
7114
7115Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
7116 Value *VecOp = IE.getOperand(0);
7117 Value *ScalarOp = IE.getOperand(1);
7118 Value *IdxOp = IE.getOperand(2);
7119
7120 // If the inserted element was extracted from some other vector, and if the
7121 // indexes are constant, try to turn this into a shufflevector operation.
7122 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
7123 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
7124 EI->getOperand(0)->getType() == IE.getType()) {
7125 unsigned NumVectorElts = IE.getType()->getNumElements();
7126 unsigned ExtractedIdx=cast<ConstantInt>(EI->getOperand(1))->getRawValue();
7127 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getRawValue();
7128
7129 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
7130 return ReplaceInstUsesWith(IE, VecOp);
7131
7132 if (InsertedIdx >= NumVectorElts) // Out of range insert.
7133 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
7134
7135 // If we are extracting a value from a vector, then inserting it right
7136 // back into the same place, just use the input vector.
7137 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
7138 return ReplaceInstUsesWith(IE, VecOp);
7139
7140 // We could theoretically do this for ANY input. However, doing so could
7141 // turn chains of insertelement instructions into a chain of shufflevector
7142 // instructions, and right now we do not merge shufflevectors. As such,
7143 // only do this in a situation where it is clear that there is benefit.
7144 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
7145 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
7146 // the values of VecOp, except then one read from EIOp0.
7147 // Build a new shuffle mask.
7148 std::vector<Constant*> Mask;
7149 if (isa<UndefValue>(VecOp))
7150 Mask.assign(NumVectorElts, UndefValue::get(Type::UIntTy));
7151 else {
7152 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
7153 Mask.assign(NumVectorElts, ConstantUInt::get(Type::UIntTy,
7154 NumVectorElts));
7155 }
7156 Mask[InsertedIdx] = ConstantUInt::get(Type::UIntTy, ExtractedIdx);
7157 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
7158 ConstantPacked::get(Mask));
7159 }
7160
7161 // If this insertelement isn't used by some other insertelement, turn it
7162 // (and any insertelements it points to), into one big shuffle.
7163 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
7164 std::vector<Constant*> Mask;
Chris Lattner90951862006-04-16 00:51:47 +00007165 Value *RHS = 0;
7166 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
7167 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
7168 // We now have a shuffle of LHS, RHS, Mask.
7169 return new ShuffleVectorInst(LHS, RHS, ConstantPacked::get(Mask));
Chris Lattner39fac442006-04-15 01:39:45 +00007170 }
7171 }
7172 }
7173
7174 return 0;
7175}
7176
7177
Chris Lattnerfbb77a42006-04-10 22:45:52 +00007178Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
7179 Value *LHS = SVI.getOperand(0);
7180 Value *RHS = SVI.getOperand(1);
7181 Constant *Mask = cast<Constant>(SVI.getOperand(2));
7182
7183 bool MadeChange = false;
7184
7185 if (isa<UndefValue>(Mask))
7186 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
7187
Chris Lattner39fac442006-04-15 01:39:45 +00007188 // TODO: If we have shuffle(x, undef, mask) and any elements of mask refer to
7189 // the undef, change them to undefs.
7190
Chris Lattnerfbb77a42006-04-10 22:45:52 +00007191 // Canonicalize shuffle(x,x) -> shuffle(x,undef)
7192 if (LHS == RHS) {
7193 if (isa<UndefValue>(LHS)) {
7194 // shuffle(undef,undef,mask) -> undef.
7195 return ReplaceInstUsesWith(SVI, LHS);
7196 }
7197
7198 if (!isa<ConstantAggregateZero>(Mask)) {
7199 // Remap any references to RHS to use LHS.
7200 ConstantPacked *CP = cast<ConstantPacked>(Mask);
7201 std::vector<Constant*> Elts;
7202 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i) {
7203 Elts.push_back(CP->getOperand(i));
7204 if (isa<UndefValue>(CP->getOperand(i)))
7205 continue;
7206 unsigned MV = cast<ConstantInt>(CP->getOperand(i))->getRawValue();
7207 if (MV >= e)
7208 Elts.back() = ConstantUInt::get(Type::UIntTy, MV & (e-1));
7209 }
7210 Mask = ConstantPacked::get(Elts);
7211 }
7212 SVI.setOperand(1, UndefValue::get(RHS->getType()));
7213 SVI.setOperand(2, Mask);
7214 MadeChange = true;
7215 }
7216
Chris Lattner34cebe72006-04-16 00:03:56 +00007217 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
7218 if (isa<UndefValue>(LHS)) {
7219 // shuffle(undef,x,<0,0,0,0>) -> undef.
7220 if (isa<ConstantAggregateZero>(Mask))
7221 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
7222
7223 ConstantPacked *CPM = cast<ConstantPacked>(Mask);
7224 std::vector<Constant*> Elts;
7225 for (unsigned i = 0, e = CPM->getNumOperands(); i != e; ++i) {
7226 if (isa<UndefValue>(CPM->getOperand(i)))
7227 Elts.push_back(CPM->getOperand(i));
7228 else {
7229 unsigned EltNo = cast<ConstantUInt>(CPM->getOperand(i))->getRawValue();
Chris Lattner90951862006-04-16 00:51:47 +00007230 if (EltNo >= e)
7231 Elts.push_back(ConstantUInt::get(Type::UIntTy, EltNo-e));
Chris Lattner34cebe72006-04-16 00:03:56 +00007232 else // Referring to the undef.
7233 Elts.push_back(UndefValue::get(Type::UIntTy));
7234 }
7235 }
7236 return new ShuffleVectorInst(RHS, LHS, ConstantPacked::get(Elts));
7237 }
7238
Chris Lattnerfbb77a42006-04-10 22:45:52 +00007239 if (ConstantPacked *CP = dyn_cast<ConstantPacked>(Mask)) {
7240 bool isLHSID = true, isRHSID = true;
7241
7242 // Analyze the shuffle.
7243 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i) {
7244 if (isa<UndefValue>(CP->getOperand(i)))
7245 continue;
7246 unsigned MV = cast<ConstantInt>(CP->getOperand(i))->getRawValue();
7247
7248 // Is this an identity shuffle of the LHS value?
7249 isLHSID &= (MV == i);
7250
7251 // Is this an identity shuffle of the RHS value?
7252 isRHSID &= (MV-e == i);
7253 }
7254
7255 // Eliminate identity shuffles.
7256 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
7257 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
7258 }
7259
7260 return MadeChange ? &SVI : 0;
7261}
7262
7263
Robert Bocchinoa8352962006-01-13 22:48:06 +00007264
Chris Lattner99f48c62002-09-02 04:59:56 +00007265void InstCombiner::removeFromWorkList(Instruction *I) {
7266 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
7267 WorkList.end());
7268}
7269
Chris Lattner39c98bb2004-12-08 23:43:58 +00007270
7271/// TryToSinkInstruction - Try to move the specified instruction from its
7272/// current block into the beginning of DestBlock, which can only happen if it's
7273/// safe to move the instruction past all of the instructions between it and the
7274/// end of its block.
7275static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
7276 assert(I->hasOneUse() && "Invariants didn't hold!");
7277
Chris Lattnerc4f67e62005-10-27 17:13:11 +00007278 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
7279 if (isa<PHINode>(I) || I->mayWriteToMemory()) return false;
Misha Brukmanb1c93172005-04-21 23:48:37 +00007280
Chris Lattner39c98bb2004-12-08 23:43:58 +00007281 // Do not sink alloca instructions out of the entry block.
7282 if (isa<AllocaInst>(I) && I->getParent() == &DestBlock->getParent()->front())
7283 return false;
7284
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00007285 // We can only sink load instructions if there is nothing between the load and
7286 // the end of block that could change the value.
7287 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00007288 for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
7289 Scan != E; ++Scan)
7290 if (Scan->mayWriteToMemory())
7291 return false;
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00007292 }
Chris Lattner39c98bb2004-12-08 23:43:58 +00007293
7294 BasicBlock::iterator InsertPos = DestBlock->begin();
7295 while (isa<PHINode>(InsertPos)) ++InsertPos;
7296
Chris Lattner9f269e42005-08-08 19:11:57 +00007297 I->moveBefore(InsertPos);
Chris Lattner39c98bb2004-12-08 23:43:58 +00007298 ++NumSunkInst;
7299 return true;
7300}
7301
Chris Lattner113f4f42002-06-25 16:13:24 +00007302bool InstCombiner::runOnFunction(Function &F) {
Chris Lattner260ab202002-04-18 17:39:14 +00007303 bool Changed = false;
Chris Lattnerf4ad1652003-11-02 05:57:39 +00007304 TD = &getAnalysis<TargetData>();
Chris Lattnerca081252001-12-14 16:52:21 +00007305
Chris Lattner4ed40f72005-07-07 20:40:38 +00007306 {
7307 // Populate the worklist with the reachable instructions.
7308 std::set<BasicBlock*> Visited;
7309 for (df_ext_iterator<BasicBlock*> BB = df_ext_begin(&F.front(), Visited),
7310 E = df_ext_end(&F.front(), Visited); BB != E; ++BB)
7311 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
7312 WorkList.push_back(I);
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00007313
Chris Lattner4ed40f72005-07-07 20:40:38 +00007314 // Do a quick scan over the function. If we find any blocks that are
7315 // unreachable, remove any instructions inside of them. This prevents
7316 // the instcombine code from having to deal with some bad special cases.
7317 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
7318 if (!Visited.count(BB)) {
7319 Instruction *Term = BB->getTerminator();
7320 while (Term != BB->begin()) { // Remove instrs bottom-up
7321 BasicBlock::iterator I = Term; --I;
Chris Lattner2d3a7a62004-04-27 15:13:33 +00007322
Chris Lattner4ed40f72005-07-07 20:40:38 +00007323 DEBUG(std::cerr << "IC: DCE: " << *I);
7324 ++NumDeadInst;
7325
7326 if (!I->use_empty())
7327 I->replaceAllUsesWith(UndefValue::get(I->getType()));
7328 I->eraseFromParent();
7329 }
7330 }
7331 }
Chris Lattnerca081252001-12-14 16:52:21 +00007332
7333 while (!WorkList.empty()) {
7334 Instruction *I = WorkList.back(); // Get an instruction from the worklist
7335 WorkList.pop_back();
7336
Misha Brukman632df282002-10-29 23:06:16 +00007337 // Check to see if we can DCE or ConstantPropagate the instruction...
Chris Lattner99f48c62002-09-02 04:59:56 +00007338 // Check to see if we can DIE the instruction...
7339 if (isInstructionTriviallyDead(I)) {
7340 // Add operands to the worklist...
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00007341 if (I->getNumOperands() < 4)
Chris Lattner51ea1272004-02-28 05:22:00 +00007342 AddUsesToWorkList(*I);
Chris Lattner99f48c62002-09-02 04:59:56 +00007343 ++NumDeadInst;
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00007344
Chris Lattnercd517ff2005-01-28 19:32:01 +00007345 DEBUG(std::cerr << "IC: DCE: " << *I);
7346
7347 I->eraseFromParent();
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00007348 removeFromWorkList(I);
7349 continue;
7350 }
Chris Lattner99f48c62002-09-02 04:59:56 +00007351
Misha Brukman632df282002-10-29 23:06:16 +00007352 // Instruction isn't dead, see if we can constant propagate it...
Chris Lattner99f48c62002-09-02 04:59:56 +00007353 if (Constant *C = ConstantFoldInstruction(I)) {
Alkis Evlogimenosa1291a02004-12-08 23:10:30 +00007354 Value* Ptr = I->getOperand(0);
Chris Lattner6580e092004-10-16 19:44:59 +00007355 if (isa<GetElementPtrInst>(I) &&
Alkis Evlogimenosa1291a02004-12-08 23:10:30 +00007356 cast<Constant>(Ptr)->isNullValue() &&
7357 !isa<ConstantPointerNull>(C) &&
7358 cast<PointerType>(Ptr->getType())->getElementType()->isSized()) {
Chris Lattner6580e092004-10-16 19:44:59 +00007359 // If this is a constant expr gep that is effectively computing an
7360 // "offsetof", fold it into 'cast int X to T*' instead of 'gep 0, 0, 12'
7361 bool isFoldableGEP = true;
7362 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i)
7363 if (!isa<ConstantInt>(I->getOperand(i)))
7364 isFoldableGEP = false;
7365 if (isFoldableGEP) {
Alkis Evlogimenosa1291a02004-12-08 23:10:30 +00007366 uint64_t Offset = TD->getIndexedOffset(Ptr->getType(),
Chris Lattner6580e092004-10-16 19:44:59 +00007367 std::vector<Value*>(I->op_begin()+1, I->op_end()));
7368 C = ConstantUInt::get(Type::ULongTy, Offset);
Chris Lattner684c5c62004-10-16 19:46:33 +00007369 C = ConstantExpr::getCast(C, TD->getIntPtrType());
Chris Lattner6580e092004-10-16 19:44:59 +00007370 C = ConstantExpr::getCast(C, I->getType());
7371 }
7372 }
7373
Chris Lattnercd517ff2005-01-28 19:32:01 +00007374 DEBUG(std::cerr << "IC: ConstFold to: " << *C << " from: " << *I);
7375
Chris Lattner99f48c62002-09-02 04:59:56 +00007376 // Add operands to the worklist...
Chris Lattner51ea1272004-02-28 05:22:00 +00007377 AddUsesToWorkList(*I);
Chris Lattnerc6509f42002-12-05 22:41:53 +00007378 ReplaceInstUsesWith(*I, C);
7379
Chris Lattner99f48c62002-09-02 04:59:56 +00007380 ++NumConstProp;
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00007381 I->getParent()->getInstList().erase(I);
Chris Lattner800aaaf2003-10-07 15:17:02 +00007382 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00007383 continue;
Chris Lattner99f48c62002-09-02 04:59:56 +00007384 }
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00007385
Chris Lattner39c98bb2004-12-08 23:43:58 +00007386 // See if we can trivially sink this instruction to a successor basic block.
7387 if (I->hasOneUse()) {
7388 BasicBlock *BB = I->getParent();
7389 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
7390 if (UserParent != BB) {
7391 bool UserIsSuccessor = false;
7392 // See if the user is one of our successors.
7393 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
7394 if (*SI == UserParent) {
7395 UserIsSuccessor = true;
7396 break;
7397 }
7398
7399 // If the user is one of our immediate successors, and if that successor
7400 // only has us as a predecessors (we'd have to split the critical edge
7401 // otherwise), we can keep going.
7402 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
7403 next(pred_begin(UserParent)) == pred_end(UserParent))
7404 // Okay, the CFG is simple enough, try to sink this instruction.
7405 Changed |= TryToSinkInstruction(I, UserParent);
7406 }
7407 }
7408
Chris Lattnerca081252001-12-14 16:52:21 +00007409 // Now that we have an instruction, try combining it to simplify it...
Chris Lattnerae7a0d32002-08-02 19:29:35 +00007410 if (Instruction *Result = visit(*I)) {
Chris Lattner0b18c1d2002-05-10 15:38:35 +00007411 ++NumCombined;
Chris Lattner260ab202002-04-18 17:39:14 +00007412 // Should we replace the old instruction with a new one?
Chris Lattner053c0932002-05-14 15:24:07 +00007413 if (Result != I) {
Chris Lattner7d2a5392004-03-13 23:54:27 +00007414 DEBUG(std::cerr << "IC: Old = " << *I
7415 << " New = " << *Result);
7416
Chris Lattner396dbfe2004-06-09 05:08:07 +00007417 // Everything uses the new instruction now.
7418 I->replaceAllUsesWith(Result);
7419
7420 // Push the new instruction and any users onto the worklist.
7421 WorkList.push_back(Result);
7422 AddUsersToWorkList(*Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00007423
7424 // Move the name to the new instruction first...
7425 std::string OldName = I->getName(); I->setName("");
Chris Lattner950fc782003-10-07 22:58:41 +00007426 Result->setName(OldName);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00007427
7428 // Insert the new instruction into the basic block...
7429 BasicBlock *InstParent = I->getParent();
Chris Lattner7515cab2004-11-14 19:13:23 +00007430 BasicBlock::iterator InsertPos = I;
7431
7432 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
7433 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
7434 ++InsertPos;
7435
7436 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00007437
Chris Lattner63d75af2004-05-01 23:27:23 +00007438 // Make sure that we reprocess all operands now that we reduced their
7439 // use counts.
Chris Lattnerb643a9e2004-05-01 23:19:52 +00007440 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
7441 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
7442 WorkList.push_back(OpI);
7443
Chris Lattner396dbfe2004-06-09 05:08:07 +00007444 // Instructions can end up on the worklist more than once. Make sure
7445 // we do not process an instruction that has been deleted.
7446 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00007447
7448 // Erase the old instruction.
7449 InstParent->getInstList().erase(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00007450 } else {
Chris Lattner7d2a5392004-03-13 23:54:27 +00007451 DEBUG(std::cerr << "IC: MOD = " << *I);
7452
Chris Lattnerae7a0d32002-08-02 19:29:35 +00007453 // If the instruction was modified, it's possible that it is now dead.
7454 // if so, remove it.
Chris Lattner63d75af2004-05-01 23:27:23 +00007455 if (isInstructionTriviallyDead(I)) {
7456 // Make sure we process all operands now that we are reducing their
7457 // use counts.
7458 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
7459 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
7460 WorkList.push_back(OpI);
Misha Brukmanb1c93172005-04-21 23:48:37 +00007461
Chris Lattner63d75af2004-05-01 23:27:23 +00007462 // Instructions may end up in the worklist more than once. Erase all
Robert Bocchinoa8352962006-01-13 22:48:06 +00007463 // occurrences of this instruction.
Chris Lattner99f48c62002-09-02 04:59:56 +00007464 removeFromWorkList(I);
Chris Lattner31f486c2005-01-31 05:36:43 +00007465 I->eraseFromParent();
Chris Lattner396dbfe2004-06-09 05:08:07 +00007466 } else {
7467 WorkList.push_back(Result);
7468 AddUsersToWorkList(*Result);
Chris Lattnerae7a0d32002-08-02 19:29:35 +00007469 }
Chris Lattner053c0932002-05-14 15:24:07 +00007470 }
Chris Lattner260ab202002-04-18 17:39:14 +00007471 Changed = true;
Chris Lattnerca081252001-12-14 16:52:21 +00007472 }
7473 }
7474
Chris Lattner260ab202002-04-18 17:39:14 +00007475 return Changed;
Chris Lattner04805fa2002-02-26 21:46:54 +00007476}
7477
Brian Gaeke38b79e82004-07-27 17:43:21 +00007478FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattner260ab202002-04-18 17:39:14 +00007479 return new InstCombiner();
Chris Lattner04805fa2002-02-26 21:46:54 +00007480}
Brian Gaeke960707c2003-11-11 22:41:34 +00007481