blob: 2a48fc06c94bc9fc4866fd7169596459fcd514fe [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"
Reid Spencer7c16caa2004-09-01 22:55:40 +000051#include "llvm/ADT/Statistic.h"
Chris Lattner39c98bb2004-12-08 23:43:58 +000052#include "llvm/ADT/STLExtras.h"
Chris Lattner053c0932002-05-14 15:24:07 +000053#include <algorithm>
Chris Lattnerc597b8a2006-01-22 23:32:06 +000054#include <iostream>
Chris Lattner8427bff2003-12-07 01:24:23 +000055using namespace llvm;
Chris Lattnerd4252a72004-07-30 07:50:03 +000056using namespace llvm::PatternMatch;
Brian Gaeke960707c2003-11-11 22:41:34 +000057
Chris Lattner260ab202002-04-18 17:39:14 +000058namespace {
Chris Lattnerbf3a0992002-10-01 22:38:41 +000059 Statistic<> NumCombined ("instcombine", "Number of insts combined");
60 Statistic<> NumConstProp("instcombine", "Number of constant folds");
61 Statistic<> NumDeadInst ("instcombine", "Number of dead inst eliminated");
Chris Lattner5997cf92006-02-08 03:25:32 +000062 Statistic<> NumDeadStore("instcombine", "Number of dead stores eliminated");
Chris Lattner39c98bb2004-12-08 23:43:58 +000063 Statistic<> NumSunkInst ("instcombine", "Number of instructions sunk");
Chris Lattnerbf3a0992002-10-01 22:38:41 +000064
Chris Lattnerc8e66542002-04-27 06:56:12 +000065 class InstCombiner : public FunctionPass,
Chris Lattner260ab202002-04-18 17:39:14 +000066 public InstVisitor<InstCombiner, Instruction*> {
67 // Worklist of all of the instructions that need to be simplified.
68 std::vector<Instruction*> WorkList;
Chris Lattnerf4ad1652003-11-02 05:57:39 +000069 TargetData *TD;
Chris Lattner260ab202002-04-18 17:39:14 +000070
Chris Lattner51ea1272004-02-28 05:22:00 +000071 /// AddUsersToWorkList - When an instruction is simplified, add all users of
72 /// the instruction to the work lists because they might get more simplified
73 /// now.
74 ///
Chris Lattner2590e512006-02-07 06:56:34 +000075 void AddUsersToWorkList(Value &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +000076 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
Chris Lattner260ab202002-04-18 17:39:14 +000077 UI != UE; ++UI)
78 WorkList.push_back(cast<Instruction>(*UI));
79 }
80
Chris Lattner51ea1272004-02-28 05:22:00 +000081 /// AddUsesToWorkList - When an instruction is simplified, add operands to
82 /// the work lists because they might get more simplified now.
83 ///
84 void AddUsesToWorkList(Instruction &I) {
85 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
86 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i)))
87 WorkList.push_back(Op);
88 }
89
Chris Lattner99f48c62002-09-02 04:59:56 +000090 // removeFromWorkList - remove all instances of I from the worklist.
91 void removeFromWorkList(Instruction *I);
Chris Lattner260ab202002-04-18 17:39:14 +000092 public:
Chris Lattner113f4f42002-06-25 16:13:24 +000093 virtual bool runOnFunction(Function &F);
Chris Lattner260ab202002-04-18 17:39:14 +000094
Chris Lattnerf12cc842002-04-28 21:27:06 +000095 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnerf4ad1652003-11-02 05:57:39 +000096 AU.addRequired<TargetData>();
Chris Lattner820d9712002-10-21 20:00:28 +000097 AU.setPreservesCFG();
Chris Lattnerf12cc842002-04-28 21:27:06 +000098 }
99
Chris Lattner69193f92004-04-05 01:30:19 +0000100 TargetData &getTargetData() const { return *TD; }
101
Chris Lattner260ab202002-04-18 17:39:14 +0000102 // Visitation implementation - Implement instruction combining for different
103 // instruction types. The semantics are as follows:
104 // Return Value:
105 // null - No change was made
Chris Lattnere6794492002-08-12 21:17:25 +0000106 // I - Change was made, I is still valid, I may be dead though
Chris Lattner260ab202002-04-18 17:39:14 +0000107 // otherwise - Change was made, replace I with returned instruction
Misha Brukmanb1c93172005-04-21 23:48:37 +0000108 //
Chris Lattner113f4f42002-06-25 16:13:24 +0000109 Instruction *visitAdd(BinaryOperator &I);
110 Instruction *visitSub(BinaryOperator &I);
111 Instruction *visitMul(BinaryOperator &I);
112 Instruction *visitDiv(BinaryOperator &I);
113 Instruction *visitRem(BinaryOperator &I);
114 Instruction *visitAnd(BinaryOperator &I);
115 Instruction *visitOr (BinaryOperator &I);
116 Instruction *visitXor(BinaryOperator &I);
Chris Lattnerd1f46d32005-04-24 06:59:08 +0000117 Instruction *visitSetCondInst(SetCondInst &I);
118 Instruction *visitSetCondInstWithCastAndCast(SetCondInst &SCI);
119
Chris Lattner0798af32005-01-13 20:14:25 +0000120 Instruction *FoldGEPSetCC(User *GEPLHS, Value *RHS,
121 Instruction::BinaryOps Cond, Instruction &I);
Chris Lattnere8d6c602003-03-10 19:16:08 +0000122 Instruction *visitShiftInst(ShiftInst &I);
Chris Lattner14553932006-01-06 07:12:35 +0000123 Instruction *FoldShiftByConstant(Value *Op0, ConstantUInt *Op1,
124 ShiftInst &I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000125 Instruction *visitCastInst(CastInst &CI);
Chris Lattner411336f2005-01-19 21:50:18 +0000126 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
127 Instruction *FI);
Chris Lattnerb909e8b2004-03-12 05:52:32 +0000128 Instruction *visitSelectInst(SelectInst &CI);
Chris Lattner970c33a2003-06-19 17:00:31 +0000129 Instruction *visitCallInst(CallInst &CI);
130 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner113f4f42002-06-25 16:13:24 +0000131 Instruction *visitPHINode(PHINode &PN);
132 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Chris Lattner1085bdf2002-11-04 16:18:53 +0000133 Instruction *visitAllocationInst(AllocationInst &AI);
Chris Lattner8427bff2003-12-07 01:24:23 +0000134 Instruction *visitFreeInst(FreeInst &FI);
Chris Lattner0f1d8a32003-06-26 05:06:25 +0000135 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattner31f486c2005-01-31 05:36:43 +0000136 Instruction *visitStoreInst(StoreInst &SI);
Chris Lattner9eef8a72003-06-04 04:46:00 +0000137 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner4c9c20a2004-07-03 00:26:11 +0000138 Instruction *visitSwitchInst(SwitchInst &SI);
Chris Lattner39fac442006-04-15 01:39:45 +0000139 Instruction *visitInsertElementInst(InsertElementInst &IE);
Robert Bocchinoa8352962006-01-13 22:48:06 +0000140 Instruction *visitExtractElementInst(ExtractElementInst &EI);
Chris Lattnerfbb77a42006-04-10 22:45:52 +0000141 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
Chris Lattner260ab202002-04-18 17:39:14 +0000142
143 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner113f4f42002-06-25 16:13:24 +0000144 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000145
Chris Lattner970c33a2003-06-19 17:00:31 +0000146 private:
Chris Lattneraec3d942003-10-07 22:32:43 +0000147 Instruction *visitCallSite(CallSite CS);
Chris Lattner970c33a2003-06-19 17:00:31 +0000148 bool transformConstExprCastCall(CallSite CS);
149
Chris Lattner69193f92004-04-05 01:30:19 +0000150 public:
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000151 // InsertNewInstBefore - insert an instruction New before instruction Old
152 // in the program. Add the new instruction to the worklist.
153 //
Chris Lattner623826c2004-09-28 21:48:02 +0000154 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattner65217ff2002-08-23 18:32:43 +0000155 assert(New && New->getParent() == 0 &&
156 "New instruction already inserted into a basic block!");
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000157 BasicBlock *BB = Old.getParent();
158 BB->getInstList().insert(&Old, New); // Insert inst
159 WorkList.push_back(New); // Add to worklist
Chris Lattnere79e8542004-02-23 06:38:22 +0000160 return New;
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000161 }
162
Chris Lattner7e794272004-09-24 15:21:34 +0000163 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
164 /// This also adds the cast to the worklist. Finally, this returns the
165 /// cast.
166 Value *InsertCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
167 if (V->getType() == Ty) return V;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000168
Chris Lattnere79d2492006-04-06 19:19:17 +0000169 if (Constant *CV = dyn_cast<Constant>(V))
170 return ConstantExpr::getCast(CV, Ty);
171
Chris Lattner7e794272004-09-24 15:21:34 +0000172 Instruction *C = new CastInst(V, Ty, V->getName(), &Pos);
173 WorkList.push_back(C);
174 return C;
175 }
176
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000177 // ReplaceInstUsesWith - This method is to be used when an instruction is
178 // found to be dead, replacable with another preexisting expression. Here
179 // we add all uses of I to the worklist, replace all uses of I with the new
180 // value, then return I, so that the inst combiner will know that I was
181 // modified.
182 //
183 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattner51ea1272004-02-28 05:22:00 +0000184 AddUsersToWorkList(I); // Add all modified instrs to worklist
Chris Lattner8953b902004-04-05 02:10:19 +0000185 if (&I != V) {
186 I.replaceAllUsesWith(V);
187 return &I;
188 } else {
189 // If we are replacing the instruction with itself, this must be in a
190 // segment of unreachable code, so just clobber the instruction.
Chris Lattner8ba9ec92004-10-18 02:59:09 +0000191 I.replaceAllUsesWith(UndefValue::get(I.getType()));
Chris Lattner8953b902004-04-05 02:10:19 +0000192 return &I;
193 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000194 }
Chris Lattner51ea1272004-02-28 05:22:00 +0000195
Chris Lattner2590e512006-02-07 06:56:34 +0000196 // UpdateValueUsesWith - This method is to be used when an value is
197 // found to be replacable with another preexisting expression or was
198 // updated. Here we add all uses of I to the worklist, replace all uses of
199 // I with the new value (unless the instruction was just updated), then
200 // return true, so that the inst combiner will know that I was modified.
201 //
202 bool UpdateValueUsesWith(Value *Old, Value *New) {
203 AddUsersToWorkList(*Old); // Add all modified instrs to worklist
204 if (Old != New)
205 Old->replaceAllUsesWith(New);
206 if (Instruction *I = dyn_cast<Instruction>(Old))
207 WorkList.push_back(I);
Chris Lattner5b2edb12006-02-12 08:02:11 +0000208 if (Instruction *I = dyn_cast<Instruction>(New))
209 WorkList.push_back(I);
Chris Lattner2590e512006-02-07 06:56:34 +0000210 return true;
211 }
212
Chris Lattner51ea1272004-02-28 05:22:00 +0000213 // EraseInstFromFunction - When dealing with an instruction that has side
214 // effects or produces a void value, we can't rely on DCE to delete the
215 // instruction. Instead, visit methods should return the value returned by
216 // this function.
217 Instruction *EraseInstFromFunction(Instruction &I) {
218 assert(I.use_empty() && "Cannot erase instruction that is used!");
219 AddUsesToWorkList(I);
220 removeFromWorkList(&I);
Chris Lattner95307542004-11-18 21:41:39 +0000221 I.eraseFromParent();
Chris Lattner51ea1272004-02-28 05:22:00 +0000222 return 0; // Don't do anything with FI
223 }
224
Chris Lattner3ac7c262003-08-13 20:16:26 +0000225 private:
Chris Lattnerdfae8be2003-07-24 17:35:25 +0000226 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
227 /// InsertBefore instruction. This is specialized a bit to avoid inserting
228 /// casts that are known to not do anything...
229 ///
230 Value *InsertOperandCastBefore(Value *V, const Type *DestTy,
231 Instruction *InsertBefore);
232
Chris Lattner7fb29e12003-03-11 00:12:48 +0000233 // SimplifyCommutative - This performs a few simplifications for commutative
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000234 // operators.
Chris Lattner7fb29e12003-03-11 00:12:48 +0000235 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerba1cb382003-09-19 17:17:26 +0000236
Chris Lattner0157e7f2006-02-11 09:31:47 +0000237 bool SimplifyDemandedBits(Value *V, uint64_t Mask,
238 uint64_t &KnownZero, uint64_t &KnownOne,
239 unsigned Depth = 0);
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000240
241 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
242 // PHI node as operand #0, see if we can fold the instruction into the PHI
243 // (which is only possible if all operands to the PHI are constants).
244 Instruction *FoldOpIntoPhi(Instruction &I);
245
Chris Lattner7515cab2004-11-14 19:13:23 +0000246 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
247 // operator and they all are only used by the PHI, PHI together their
248 // inputs, and do the operation once, to the result of the PHI.
249 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
250
Chris Lattnerba1cb382003-09-19 17:17:26 +0000251 Instruction *OptAndOp(Instruction *Op, ConstantIntegral *OpRHS,
252 ConstantIntegral *AndRHS, BinaryOperator &TheAnd);
Chris Lattneraf517572005-09-18 04:24:45 +0000253
254 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantIntegral *Mask,
255 bool isSub, Instruction &I);
Chris Lattner6862fbd2004-09-29 17:40:11 +0000256 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
257 bool Inside, Instruction &IB);
Chris Lattner216be912005-10-24 06:03:58 +0000258 Instruction *PromoteCastOfAllocation(CastInst &CI, AllocationInst &AI);
Chris Lattner1ebbe6a2006-05-13 02:06:03 +0000259
260 Value *EvaluateInDifferentType(Value *V, const Type *Ty);
Chris Lattner260ab202002-04-18 17:39:14 +0000261 };
Chris Lattnerb28b6802002-07-23 18:06:35 +0000262
Chris Lattnerc8b70922002-07-26 21:12:46 +0000263 RegisterOpt<InstCombiner> X("instcombine", "Combine redundant instructions");
Chris Lattner260ab202002-04-18 17:39:14 +0000264}
265
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000266// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattner81a7a232004-10-16 18:11:37 +0000267// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000268static unsigned getComplexity(Value *V) {
269 if (isa<Instruction>(V)) {
270 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
Chris Lattner81a7a232004-10-16 18:11:37 +0000271 return 3;
272 return 4;
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000273 }
Chris Lattner81a7a232004-10-16 18:11:37 +0000274 if (isa<Argument>(V)) return 3;
275 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000276}
Chris Lattner260ab202002-04-18 17:39:14 +0000277
Chris Lattner7fb29e12003-03-11 00:12:48 +0000278// isOnlyUse - Return true if this instruction will be deleted if we stop using
279// it.
280static bool isOnlyUse(Value *V) {
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000281 return V->hasOneUse() || isa<Constant>(V);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000282}
283
Chris Lattnere79e8542004-02-23 06:38:22 +0000284// getPromotedType - Return the specified type promoted as it would be to pass
285// though a va_arg area...
286static const Type *getPromotedType(const Type *Ty) {
Chris Lattner97bfcea2004-06-17 18:16:02 +0000287 switch (Ty->getTypeID()) {
Chris Lattnere79e8542004-02-23 06:38:22 +0000288 case Type::SByteTyID:
289 case Type::ShortTyID: return Type::IntTy;
290 case Type::UByteTyID:
291 case Type::UShortTyID: return Type::UIntTy;
292 case Type::FloatTyID: return Type::DoubleTy;
293 default: return Ty;
294 }
295}
296
Chris Lattner567b81f2005-09-13 00:40:14 +0000297/// isCast - If the specified operand is a CastInst or a constant expr cast,
298/// return the operand value, otherwise return null.
299static Value *isCast(Value *V) {
300 if (CastInst *I = dyn_cast<CastInst>(V))
301 return I->getOperand(0);
302 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
303 if (CE->getOpcode() == Instruction::Cast)
304 return CE->getOperand(0);
305 return 0;
306}
307
Chris Lattner1d441ad2006-05-06 09:00:16 +0000308enum CastType {
309 Noop = 0,
310 Truncate = 1,
311 Signext = 2,
312 Zeroext = 3
313};
314
315/// getCastType - In the future, we will split the cast instruction into these
316/// various types. Until then, we have to do the analysis here.
317static CastType getCastType(const Type *Src, const Type *Dest) {
318 assert(Src->isIntegral() && Dest->isIntegral() &&
319 "Only works on integral types!");
320 unsigned SrcSize = Src->getPrimitiveSizeInBits();
321 unsigned DestSize = Dest->getPrimitiveSizeInBits();
322
323 if (SrcSize == DestSize) return Noop;
324 if (SrcSize > DestSize) return Truncate;
325 if (Src->isSigned()) return Signext;
326 return Zeroext;
327}
328
329
330// isEliminableCastOfCast - Return true if it is valid to eliminate the CI
331// instruction.
332//
333static bool isEliminableCastOfCast(const Type *SrcTy, const Type *MidTy,
334 const Type *DstTy, TargetData *TD) {
335
336 // It is legal to eliminate the instruction if casting A->B->A if the sizes
337 // are identical and the bits don't get reinterpreted (for example
338 // int->float->int would not be allowed).
339 if (SrcTy == DstTy && SrcTy->isLosslesslyConvertibleTo(MidTy))
340 return true;
341
342 // If we are casting between pointer and integer types, treat pointers as
343 // integers of the appropriate size for the code below.
344 if (isa<PointerType>(SrcTy)) SrcTy = TD->getIntPtrType();
345 if (isa<PointerType>(MidTy)) MidTy = TD->getIntPtrType();
346 if (isa<PointerType>(DstTy)) DstTy = TD->getIntPtrType();
347
348 // Allow free casting and conversion of sizes as long as the sign doesn't
349 // change...
350 if (SrcTy->isIntegral() && MidTy->isIntegral() && DstTy->isIntegral()) {
351 CastType FirstCast = getCastType(SrcTy, MidTy);
352 CastType SecondCast = getCastType(MidTy, DstTy);
353
354 // Capture the effect of these two casts. If the result is a legal cast,
355 // the CastType is stored here, otherwise a special code is used.
356 static const unsigned CastResult[] = {
357 // First cast is noop
358 0, 1, 2, 3,
359 // First cast is a truncate
360 1, 1, 4, 4, // trunc->extend is not safe to eliminate
361 // First cast is a sign ext
362 2, 5, 2, 4, // signext->zeroext never ok
363 // First cast is a zero ext
364 3, 5, 3, 3,
365 };
366
367 unsigned Result = CastResult[FirstCast*4+SecondCast];
368 switch (Result) {
369 default: assert(0 && "Illegal table value!");
370 case 0:
371 case 1:
372 case 2:
373 case 3:
374 // FIXME: in the future, when LLVM has explicit sign/zeroextends and
375 // truncates, we could eliminate more casts.
376 return (unsigned)getCastType(SrcTy, DstTy) == Result;
377 case 4:
378 return false; // Not possible to eliminate this here.
379 case 5:
380 // Sign or zero extend followed by truncate is always ok if the result
381 // is a truncate or noop.
382 CastType ResultCast = getCastType(SrcTy, DstTy);
383 if (ResultCast == Noop || ResultCast == Truncate)
384 return true;
385 // Otherwise we are still growing the value, we are only safe if the
386 // result will match the sign/zeroextendness of the result.
387 return ResultCast == FirstCast;
388 }
389 }
390
391 // If this is a cast from 'float -> double -> integer', cast from
392 // 'float -> integer' directly, as the value isn't changed by the
393 // float->double conversion.
394 if (SrcTy->isFloatingPoint() && MidTy->isFloatingPoint() &&
395 DstTy->isIntegral() &&
396 SrcTy->getPrimitiveSize() < MidTy->getPrimitiveSize())
397 return true;
398
399 // Packed type conversions don't modify bits.
400 if (isa<PackedType>(SrcTy) && isa<PackedType>(MidTy) &&isa<PackedType>(DstTy))
401 return true;
402
403 return false;
404}
405
406/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
407/// in any code being generated. It does not require codegen if V is simple
408/// enough or if the cast can be folded into other casts.
409static bool ValueRequiresCast(const Value *V, const Type *Ty, TargetData *TD) {
410 if (V->getType() == Ty || isa<Constant>(V)) return false;
411
412 // If this is a noop cast, it isn't real codegen.
413 if (V->getType()->isLosslesslyConvertibleTo(Ty))
414 return false;
415
416 // If this is another cast that can be elimianted, it isn't codegen either.
417 if (const CastInst *CI = dyn_cast<CastInst>(V))
418 if (isEliminableCastOfCast(CI->getOperand(0)->getType(), CI->getType(), Ty,
419 TD))
420 return false;
421 return true;
422}
423
424/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
425/// InsertBefore instruction. This is specialized a bit to avoid inserting
426/// casts that are known to not do anything...
427///
428Value *InstCombiner::InsertOperandCastBefore(Value *V, const Type *DestTy,
429 Instruction *InsertBefore) {
430 if (V->getType() == DestTy) return V;
431 if (Constant *C = dyn_cast<Constant>(V))
432 return ConstantExpr::getCast(C, DestTy);
433
434 CastInst *CI = new CastInst(V, DestTy, V->getName());
435 InsertNewInstBefore(CI, *InsertBefore);
436 return CI;
437}
438
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000439// SimplifyCommutative - This performs a few simplifications for commutative
440// operators:
Chris Lattner260ab202002-04-18 17:39:14 +0000441//
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000442// 1. Order operands such that they are listed from right (least complex) to
443// left (most complex). This puts constants before unary operators before
444// binary operators.
445//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000446// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
447// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000448//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000449bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000450 bool Changed = false;
451 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
452 Changed = !I.swapOperands();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000453
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000454 if (!I.isAssociative()) return Changed;
455 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattner7fb29e12003-03-11 00:12:48 +0000456 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
457 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
458 if (isa<Constant>(I.getOperand(1))) {
Chris Lattner34428442003-05-27 16:40:51 +0000459 Constant *Folded = ConstantExpr::get(I.getOpcode(),
460 cast<Constant>(I.getOperand(1)),
461 cast<Constant>(Op->getOperand(1)));
Chris Lattner7fb29e12003-03-11 00:12:48 +0000462 I.setOperand(0, Op->getOperand(0));
463 I.setOperand(1, Folded);
464 return true;
465 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
466 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
467 isOnlyUse(Op) && isOnlyUse(Op1)) {
468 Constant *C1 = cast<Constant>(Op->getOperand(1));
469 Constant *C2 = cast<Constant>(Op1->getOperand(1));
470
471 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner34428442003-05-27 16:40:51 +0000472 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000473 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
474 Op1->getOperand(0),
475 Op1->getName(), &I);
476 WorkList.push_back(New);
477 I.setOperand(0, New);
478 I.setOperand(1, Folded);
479 return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000480 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000481 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000482 return Changed;
Chris Lattner260ab202002-04-18 17:39:14 +0000483}
Chris Lattnerca081252001-12-14 16:52:21 +0000484
Chris Lattnerbb74e222003-03-10 23:06:50 +0000485// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
486// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattner9fa53de2002-05-06 16:49:18 +0000487//
Chris Lattnerbb74e222003-03-10 23:06:50 +0000488static inline Value *dyn_castNegVal(Value *V) {
489 if (BinaryOperator::isNeg(V))
Chris Lattnerd6f636a2005-04-24 07:30:14 +0000490 return BinaryOperator::getNegArgument(V);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000491
Chris Lattner9ad0d552004-12-14 20:08:06 +0000492 // Constants can be considered to be negated values if they can be folded.
493 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
494 return ConstantExpr::getNeg(C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000495 return 0;
Chris Lattner9fa53de2002-05-06 16:49:18 +0000496}
497
Chris Lattnerbb74e222003-03-10 23:06:50 +0000498static inline Value *dyn_castNotVal(Value *V) {
499 if (BinaryOperator::isNot(V))
Chris Lattnerd6f636a2005-04-24 07:30:14 +0000500 return BinaryOperator::getNotArgument(V);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000501
502 // Constants can be considered to be not'ed values...
Chris Lattnerdd65d862003-04-30 22:34:06 +0000503 if (ConstantIntegral *C = dyn_cast<ConstantIntegral>(V))
Chris Lattnerc8e7e292004-06-10 02:12:35 +0000504 return ConstantExpr::getNot(C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000505 return 0;
506}
507
Chris Lattner7fb29e12003-03-11 00:12:48 +0000508// dyn_castFoldableMul - If this value is a multiply that can be folded into
509// other computations (because it has a constant operand), return the
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000510// non-constant operand of the multiply, and set CST to point to the multiplier.
511// Otherwise, return null.
Chris Lattner7fb29e12003-03-11 00:12:48 +0000512//
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000513static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000514 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000515 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattner7fb29e12003-03-11 00:12:48 +0000516 if (I->getOpcode() == Instruction::Mul)
Chris Lattner970136362004-11-15 05:54:07 +0000517 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattner7fb29e12003-03-11 00:12:48 +0000518 return I->getOperand(0);
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000519 if (I->getOpcode() == Instruction::Shl)
Chris Lattner970136362004-11-15 05:54:07 +0000520 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000521 // The multiplier is really 1 << CST.
522 Constant *One = ConstantInt::get(V->getType(), 1);
523 CST = cast<ConstantInt>(ConstantExpr::getShl(One, CST));
524 return I->getOperand(0);
525 }
526 }
Chris Lattner7fb29e12003-03-11 00:12:48 +0000527 return 0;
Chris Lattner3082c5a2003-02-18 19:28:33 +0000528}
Chris Lattner31ae8632002-08-14 17:51:49 +0000529
Chris Lattner0798af32005-01-13 20:14:25 +0000530/// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
531/// expression, return it.
532static User *dyn_castGetElementPtr(Value *V) {
533 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
534 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
535 if (CE->getOpcode() == Instruction::GetElementPtr)
536 return cast<User>(V);
537 return false;
538}
539
Chris Lattner623826c2004-09-28 21:48:02 +0000540// AddOne, SubOne - Add or subtract a constant one from an integer constant...
Chris Lattner6862fbd2004-09-29 17:40:11 +0000541static ConstantInt *AddOne(ConstantInt *C) {
542 return cast<ConstantInt>(ConstantExpr::getAdd(C,
543 ConstantInt::get(C->getType(), 1)));
Chris Lattner623826c2004-09-28 21:48:02 +0000544}
Chris Lattner6862fbd2004-09-29 17:40:11 +0000545static ConstantInt *SubOne(ConstantInt *C) {
546 return cast<ConstantInt>(ConstantExpr::getSub(C,
547 ConstantInt::get(C->getType(), 1)));
Chris Lattner623826c2004-09-28 21:48:02 +0000548}
549
Chris Lattner0157e7f2006-02-11 09:31:47 +0000550/// GetConstantInType - Return a ConstantInt with the specified type and value.
551///
Chris Lattneree0f2802006-02-12 02:07:56 +0000552static ConstantIntegral *GetConstantInType(const Type *Ty, uint64_t Val) {
Chris Lattner0157e7f2006-02-11 09:31:47 +0000553 if (Ty->isUnsigned())
554 return ConstantUInt::get(Ty, Val);
Chris Lattneree0f2802006-02-12 02:07:56 +0000555 else if (Ty->getTypeID() == Type::BoolTyID)
556 return ConstantBool::get(Val);
Chris Lattner0157e7f2006-02-11 09:31:47 +0000557 int64_t SVal = Val;
558 SVal <<= 64-Ty->getPrimitiveSizeInBits();
559 SVal >>= 64-Ty->getPrimitiveSizeInBits();
560 return ConstantSInt::get(Ty, SVal);
561}
562
563
Chris Lattner4534dd592006-02-09 07:38:58 +0000564/// ComputeMaskedBits - Determine which of the bits specified in Mask are
565/// known to be either zero or one and return them in the KnownZero/KnownOne
566/// bitsets. This code only analyzes bits in Mask, in order to short-circuit
567/// processing.
568static void ComputeMaskedBits(Value *V, uint64_t Mask, uint64_t &KnownZero,
569 uint64_t &KnownOne, unsigned Depth = 0) {
Chris Lattner0b3557f2005-09-24 23:43:33 +0000570 // Note, we cannot consider 'undef' to be "IsZero" here. The problem is that
571 // we cannot optimize based on the assumption that it is zero without changing
Chris Lattnerc3ebf402006-02-07 07:27:52 +0000572 // it to be an explicit zero. If we don't change it to zero, other code could
Chris Lattner0b3557f2005-09-24 23:43:33 +0000573 // optimized based on the contradictory assumption that it is non-zero.
574 // Because instcombine aggressively folds operations with undef args anyway,
575 // this won't lose us code quality.
Chris Lattner4534dd592006-02-09 07:38:58 +0000576 if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(V)) {
577 // We know all of the bits for a constant!
Chris Lattner0157e7f2006-02-11 09:31:47 +0000578 KnownOne = CI->getZExtValue() & Mask;
Chris Lattner4534dd592006-02-09 07:38:58 +0000579 KnownZero = ~KnownOne & Mask;
580 return;
581 }
582
583 KnownZero = KnownOne = 0; // Don't know anything.
Chris Lattner92a68652006-02-07 08:05:22 +0000584 if (Depth == 6 || Mask == 0)
Chris Lattner4534dd592006-02-09 07:38:58 +0000585 return; // Limit search depth.
586
587 uint64_t KnownZero2, KnownOne2;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000588 Instruction *I = dyn_cast<Instruction>(V);
589 if (!I) return;
590
Chris Lattnerfb296922006-05-04 17:33:35 +0000591 Mask &= V->getType()->getIntegralTypeMask();
592
Chris Lattner0157e7f2006-02-11 09:31:47 +0000593 switch (I->getOpcode()) {
594 case Instruction::And:
595 // If either the LHS or the RHS are Zero, the result is zero.
596 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
597 Mask &= ~KnownZero;
598 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
599 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
600 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
601
602 // Output known-1 bits are only known if set in both the LHS & RHS.
603 KnownOne &= KnownOne2;
604 // Output known-0 are known to be clear if zero in either the LHS | RHS.
605 KnownZero |= KnownZero2;
606 return;
607 case Instruction::Or:
608 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
609 Mask &= ~KnownOne;
610 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
611 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
612 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
613
614 // Output known-0 bits are only known if clear in both the LHS & RHS.
615 KnownZero &= KnownZero2;
616 // Output known-1 are known to be set if set in either the LHS | RHS.
617 KnownOne |= KnownOne2;
618 return;
619 case Instruction::Xor: {
620 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
621 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
622 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
623 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
624
625 // Output known-0 bits are known if clear or set in both the LHS & RHS.
626 uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
627 // Output known-1 are known to be set if set in only one of the LHS, RHS.
628 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
629 KnownZero = KnownZeroOut;
630 return;
631 }
632 case Instruction::Select:
633 ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
634 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
635 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
636 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
637
638 // Only known if known in both the LHS and RHS.
639 KnownOne &= KnownOne2;
640 KnownZero &= KnownZero2;
641 return;
642 case Instruction::Cast: {
643 const Type *SrcTy = I->getOperand(0)->getType();
644 if (!SrcTy->isIntegral()) return;
645
646 // If this is an integer truncate or noop, just look in the input.
647 if (SrcTy->getPrimitiveSizeInBits() >=
648 I->getType()->getPrimitiveSizeInBits()) {
649 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
Chris Lattner4534dd592006-02-09 07:38:58 +0000650 return;
651 }
Chris Lattner4534dd592006-02-09 07:38:58 +0000652
Chris Lattner0157e7f2006-02-11 09:31:47 +0000653 // Sign or Zero extension. Compute the bits in the result that are not
654 // present in the input.
655 uint64_t NotIn = ~SrcTy->getIntegralTypeMask();
656 uint64_t NewBits = I->getType()->getIntegralTypeMask() & NotIn;
Chris Lattner62010c42005-10-09 06:36:35 +0000657
Chris Lattner0157e7f2006-02-11 09:31:47 +0000658 // Handle zero extension.
659 if (!SrcTy->isSigned()) {
660 Mask &= SrcTy->getIntegralTypeMask();
661 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
662 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
663 // The top bits are known to be zero.
664 KnownZero |= NewBits;
665 } else {
666 // Sign extension.
667 Mask &= SrcTy->getIntegralTypeMask();
668 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
669 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattner92a68652006-02-07 08:05:22 +0000670
Chris Lattner0157e7f2006-02-11 09:31:47 +0000671 // If the sign bit of the input is known set or clear, then we know the
672 // top bits of the result.
673 uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
674 if (KnownZero & InSignBit) { // Input sign bit known zero
Chris Lattner4534dd592006-02-09 07:38:58 +0000675 KnownZero |= NewBits;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000676 KnownOne &= ~NewBits;
677 } else if (KnownOne & InSignBit) { // Input sign bit known set
678 KnownOne |= NewBits;
679 KnownZero &= ~NewBits;
680 } else { // Input sign bit unknown
681 KnownZero &= ~NewBits;
682 KnownOne &= ~NewBits;
683 }
684 }
685 return;
686 }
687 case Instruction::Shl:
688 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
689 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1))) {
690 Mask >>= SA->getValue();
691 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
692 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
693 KnownZero <<= SA->getValue();
694 KnownOne <<= SA->getValue();
695 KnownZero |= (1ULL << SA->getValue())-1; // low bits known zero.
696 return;
697 }
698 break;
699 case Instruction::Shr:
700 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
701 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1))) {
702 // Compute the new bits that are at the top now.
703 uint64_t HighBits = (1ULL << SA->getValue())-1;
704 HighBits <<= I->getType()->getPrimitiveSizeInBits()-SA->getValue();
705
706 if (I->getType()->isUnsigned()) { // Unsigned shift right.
707 Mask <<= SA->getValue();
708 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
709 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
710 KnownZero >>= SA->getValue();
711 KnownOne >>= SA->getValue();
712 KnownZero |= HighBits; // high bits known zero.
Chris Lattner4534dd592006-02-09 07:38:58 +0000713 } else {
Chris Lattner0157e7f2006-02-11 09:31:47 +0000714 Mask <<= SA->getValue();
715 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
716 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
717 KnownZero >>= SA->getValue();
718 KnownOne >>= SA->getValue();
719
720 // Handle the sign bits.
721 uint64_t SignBit = 1ULL << (I->getType()->getPrimitiveSizeInBits()-1);
722 SignBit >>= SA->getValue(); // Adjust to where it is now in the mask.
723
724 if (KnownZero & SignBit) { // New bits are known zero.
725 KnownZero |= HighBits;
726 } else if (KnownOne & SignBit) { // New bits are known one.
727 KnownOne |= HighBits;
Chris Lattner4534dd592006-02-09 07:38:58 +0000728 }
729 }
730 return;
Chris Lattner62010c42005-10-09 06:36:35 +0000731 }
Chris Lattner0157e7f2006-02-11 09:31:47 +0000732 break;
Chris Lattner0b3557f2005-09-24 23:43:33 +0000733 }
Chris Lattner92a68652006-02-07 08:05:22 +0000734}
735
736/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
737/// this predicate to simplify operations downstream. Mask is known to be zero
738/// for bits that V cannot have.
739static bool MaskedValueIsZero(Value *V, uint64_t Mask, unsigned Depth = 0) {
Chris Lattner4534dd592006-02-09 07:38:58 +0000740 uint64_t KnownZero, KnownOne;
741 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
742 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
743 return (KnownZero & Mask) == Mask;
Chris Lattner0b3557f2005-09-24 23:43:33 +0000744}
745
Chris Lattner0157e7f2006-02-11 09:31:47 +0000746/// ShrinkDemandedConstant - Check to see if the specified operand of the
747/// specified instruction is a constant integer. If so, check to see if there
748/// are any bits set in the constant that are not demanded. If so, shrink the
749/// constant and return true.
750static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
751 uint64_t Demanded) {
752 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
753 if (!OpC) return false;
754
755 // If there are no bits set that aren't demanded, nothing to do.
756 if ((~Demanded & OpC->getZExtValue()) == 0)
757 return false;
758
759 // This is producing any bits that are not needed, shrink the RHS.
760 uint64_t Val = Demanded & OpC->getZExtValue();
761 I->setOperand(OpNo, GetConstantInType(OpC->getType(), Val));
762 return true;
763}
764
Chris Lattneree0f2802006-02-12 02:07:56 +0000765// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
766// set of known zero and one bits, compute the maximum and minimum values that
767// could have the specified known zero and known one bits, returning them in
768// min/max.
769static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
770 uint64_t KnownZero,
771 uint64_t KnownOne,
772 int64_t &Min, int64_t &Max) {
773 uint64_t TypeBits = Ty->getIntegralTypeMask();
774 uint64_t UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
775
776 uint64_t SignBit = 1ULL << (Ty->getPrimitiveSizeInBits()-1);
777
778 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
779 // bit if it is unknown.
780 Min = KnownOne;
781 Max = KnownOne|UnknownBits;
782
783 if (SignBit & UnknownBits) { // Sign bit is unknown
784 Min |= SignBit;
785 Max &= ~SignBit;
786 }
787
788 // Sign extend the min/max values.
789 int ShAmt = 64-Ty->getPrimitiveSizeInBits();
790 Min = (Min << ShAmt) >> ShAmt;
791 Max = (Max << ShAmt) >> ShAmt;
792}
793
794// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
795// a set of known zero and one bits, compute the maximum and minimum values that
796// could have the specified known zero and known one bits, returning them in
797// min/max.
798static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
799 uint64_t KnownZero,
800 uint64_t KnownOne,
801 uint64_t &Min,
802 uint64_t &Max) {
803 uint64_t TypeBits = Ty->getIntegralTypeMask();
804 uint64_t UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
805
806 // The minimum value is when the unknown bits are all zeros.
807 Min = KnownOne;
808 // The maximum value is when the unknown bits are all ones.
809 Max = KnownOne|UnknownBits;
810}
Chris Lattner0157e7f2006-02-11 09:31:47 +0000811
812
813/// SimplifyDemandedBits - Look at V. At this point, we know that only the
814/// DemandedMask bits of the result of V are ever used downstream. If we can
815/// use this information to simplify V, do so and return true. Otherwise,
816/// analyze the expression and return a mask of KnownOne and KnownZero bits for
817/// the expression (used to simplify the caller). The KnownZero/One bits may
818/// only be accurate for those bits in the DemandedMask.
819bool InstCombiner::SimplifyDemandedBits(Value *V, uint64_t DemandedMask,
820 uint64_t &KnownZero, uint64_t &KnownOne,
Chris Lattner2590e512006-02-07 06:56:34 +0000821 unsigned Depth) {
Chris Lattner0157e7f2006-02-11 09:31:47 +0000822 if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(V)) {
823 // We know all of the bits for a constant!
824 KnownOne = CI->getZExtValue() & DemandedMask;
825 KnownZero = ~KnownOne & DemandedMask;
826 return false;
827 }
828
829 KnownZero = KnownOne = 0;
Chris Lattner2590e512006-02-07 06:56:34 +0000830 if (!V->hasOneUse()) { // Other users may use these bits.
Chris Lattner0157e7f2006-02-11 09:31:47 +0000831 if (Depth != 0) { // Not at the root.
832 // Just compute the KnownZero/KnownOne bits to simplify things downstream.
833 ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
Chris Lattner2590e512006-02-07 06:56:34 +0000834 return false;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000835 }
Chris Lattner2590e512006-02-07 06:56:34 +0000836 // If this is the root being simplified, allow it to have multiple uses,
Chris Lattner0157e7f2006-02-11 09:31:47 +0000837 // just set the DemandedMask to all bits.
838 DemandedMask = V->getType()->getIntegralTypeMask();
839 } else if (DemandedMask == 0) { // Not demanding any bits from V.
Chris Lattner92a68652006-02-07 08:05:22 +0000840 if (V != UndefValue::get(V->getType()))
841 return UpdateValueUsesWith(V, UndefValue::get(V->getType()));
842 return false;
Chris Lattner2590e512006-02-07 06:56:34 +0000843 } else if (Depth == 6) { // Limit search depth.
844 return false;
845 }
846
847 Instruction *I = dyn_cast<Instruction>(V);
848 if (!I) return false; // Only analyze instructions.
849
Chris Lattnerfb296922006-05-04 17:33:35 +0000850 DemandedMask &= V->getType()->getIntegralTypeMask();
851
Chris Lattner0157e7f2006-02-11 09:31:47 +0000852 uint64_t KnownZero2, KnownOne2;
Chris Lattner2590e512006-02-07 06:56:34 +0000853 switch (I->getOpcode()) {
854 default: break;
855 case Instruction::And:
Chris Lattner0157e7f2006-02-11 09:31:47 +0000856 // If either the LHS or the RHS are Zero, the result is zero.
857 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
858 KnownZero, KnownOne, Depth+1))
859 return true;
860 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
861
862 // If something is known zero on the RHS, the bits aren't demanded on the
863 // LHS.
864 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownZero,
865 KnownZero2, KnownOne2, Depth+1))
866 return true;
867 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
868
869 // If all of the demanded bits are known one on one side, return the other.
870 // These bits cannot contribute to the result of the 'and'.
871 if ((DemandedMask & ~KnownZero2 & KnownOne) == (DemandedMask & ~KnownZero2))
872 return UpdateValueUsesWith(I, I->getOperand(0));
873 if ((DemandedMask & ~KnownZero & KnownOne2) == (DemandedMask & ~KnownZero))
874 return UpdateValueUsesWith(I, I->getOperand(1));
Chris Lattner5b2edb12006-02-12 08:02:11 +0000875
876 // If all of the demanded bits in the inputs are known zeros, return zero.
877 if ((DemandedMask & (KnownZero|KnownZero2)) == DemandedMask)
878 return UpdateValueUsesWith(I, Constant::getNullValue(I->getType()));
879
Chris Lattner0157e7f2006-02-11 09:31:47 +0000880 // If the RHS is a constant, see if we can simplify it.
Chris Lattner5b2edb12006-02-12 08:02:11 +0000881 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~KnownZero2))
Chris Lattner0157e7f2006-02-11 09:31:47 +0000882 return UpdateValueUsesWith(I, I);
883
884 // Output known-1 bits are only known if set in both the LHS & RHS.
885 KnownOne &= KnownOne2;
886 // Output known-0 are known to be clear if zero in either the LHS | RHS.
887 KnownZero |= KnownZero2;
888 break;
889 case Instruction::Or:
890 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
891 KnownZero, KnownOne, Depth+1))
892 return true;
893 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
894 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownOne,
895 KnownZero2, KnownOne2, Depth+1))
896 return true;
897 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
898
899 // If all of the demanded bits are known zero on one side, return the other.
900 // These bits cannot contribute to the result of the 'or'.
Jeff Cohen0add83e2006-02-18 03:20:33 +0000901 if ((DemandedMask & ~KnownOne2 & KnownZero) == (DemandedMask & ~KnownOne2))
Chris Lattner0157e7f2006-02-11 09:31:47 +0000902 return UpdateValueUsesWith(I, I->getOperand(0));
Jeff Cohen0add83e2006-02-18 03:20:33 +0000903 if ((DemandedMask & ~KnownOne & KnownZero2) == (DemandedMask & ~KnownOne))
Chris Lattner0157e7f2006-02-11 09:31:47 +0000904 return UpdateValueUsesWith(I, I->getOperand(1));
Chris Lattner5b2edb12006-02-12 08:02:11 +0000905
906 // If all of the potentially set bits on one side are known to be set on
907 // the other side, just use the 'other' side.
908 if ((DemandedMask & (~KnownZero) & KnownOne2) ==
909 (DemandedMask & (~KnownZero)))
910 return UpdateValueUsesWith(I, I->getOperand(0));
Nate Begeman8a77efe2006-02-16 21:11:51 +0000911 if ((DemandedMask & (~KnownZero2) & KnownOne) ==
912 (DemandedMask & (~KnownZero2)))
913 return UpdateValueUsesWith(I, I->getOperand(1));
Chris Lattner0157e7f2006-02-11 09:31:47 +0000914
915 // If the RHS is a constant, see if we can simplify it.
916 if (ShrinkDemandedConstant(I, 1, DemandedMask))
917 return UpdateValueUsesWith(I, I);
918
919 // Output known-0 bits are only known if clear in both the LHS & RHS.
920 KnownZero &= KnownZero2;
921 // Output known-1 are known to be set if set in either the LHS | RHS.
922 KnownOne |= KnownOne2;
923 break;
924 case Instruction::Xor: {
925 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
926 KnownZero, KnownOne, Depth+1))
927 return true;
928 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
929 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
930 KnownZero2, KnownOne2, Depth+1))
931 return true;
932 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
933
934 // If all of the demanded bits are known zero on one side, return the other.
935 // These bits cannot contribute to the result of the 'xor'.
936 if ((DemandedMask & KnownZero) == DemandedMask)
937 return UpdateValueUsesWith(I, I->getOperand(0));
938 if ((DemandedMask & KnownZero2) == DemandedMask)
939 return UpdateValueUsesWith(I, I->getOperand(1));
940
941 // Output known-0 bits are known if clear or set in both the LHS & RHS.
942 uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
943 // Output known-1 are known to be set if set in only one of the LHS, RHS.
944 uint64_t KnownOneOut = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
945
946 // If all of the unknown bits are known to be zero on one side or the other
947 // (but not both) turn this into an *inclusive* or.
Chris Lattner5b2edb12006-02-12 08:02:11 +0000948 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattner0157e7f2006-02-11 09:31:47 +0000949 if (uint64_t UnknownBits = DemandedMask & ~(KnownZeroOut|KnownOneOut)) {
950 if ((UnknownBits & (KnownZero|KnownZero2)) == UnknownBits) {
951 Instruction *Or =
952 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
953 I->getName());
954 InsertNewInstBefore(Or, *I);
955 return UpdateValueUsesWith(I, Or);
Chris Lattner2590e512006-02-07 06:56:34 +0000956 }
957 }
Chris Lattner0157e7f2006-02-11 09:31:47 +0000958
Chris Lattner5b2edb12006-02-12 08:02:11 +0000959 // If all of the demanded bits on one side are known, and all of the set
960 // bits on that side are also known to be set on the other side, turn this
961 // into an AND, as we know the bits will be cleared.
962 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
963 if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask) { // all known
964 if ((KnownOne & KnownOne2) == KnownOne) {
965 Constant *AndC = GetConstantInType(I->getType(),
966 ~KnownOne & DemandedMask);
967 Instruction *And =
968 BinaryOperator::createAnd(I->getOperand(0), AndC, "tmp");
969 InsertNewInstBefore(And, *I);
970 return UpdateValueUsesWith(I, And);
971 }
972 }
973
Chris Lattner0157e7f2006-02-11 09:31:47 +0000974 // If the RHS is a constant, see if we can simplify it.
975 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
976 if (ShrinkDemandedConstant(I, 1, DemandedMask))
977 return UpdateValueUsesWith(I, I);
978
979 KnownZero = KnownZeroOut;
980 KnownOne = KnownOneOut;
981 break;
982 }
983 case Instruction::Select:
984 if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
985 KnownZero, KnownOne, Depth+1))
986 return true;
987 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
988 KnownZero2, KnownOne2, Depth+1))
989 return true;
990 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
991 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
992
993 // If the operands are constants, see if we can simplify them.
994 if (ShrinkDemandedConstant(I, 1, DemandedMask))
995 return UpdateValueUsesWith(I, I);
996 if (ShrinkDemandedConstant(I, 2, DemandedMask))
997 return UpdateValueUsesWith(I, I);
998
999 // Only known if known in both the LHS and RHS.
1000 KnownOne &= KnownOne2;
1001 KnownZero &= KnownZero2;
1002 break;
Chris Lattner2590e512006-02-07 06:56:34 +00001003 case Instruction::Cast: {
1004 const Type *SrcTy = I->getOperand(0)->getType();
Chris Lattner0157e7f2006-02-11 09:31:47 +00001005 if (!SrcTy->isIntegral()) return false;
Chris Lattner2590e512006-02-07 06:56:34 +00001006
Chris Lattner0157e7f2006-02-11 09:31:47 +00001007 // If this is an integer truncate or noop, just look in the input.
1008 if (SrcTy->getPrimitiveSizeInBits() >=
1009 I->getType()->getPrimitiveSizeInBits()) {
1010 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1011 KnownZero, KnownOne, Depth+1))
1012 return true;
1013 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1014 break;
1015 }
1016
1017 // Sign or Zero extension. Compute the bits in the result that are not
1018 // present in the input.
1019 uint64_t NotIn = ~SrcTy->getIntegralTypeMask();
1020 uint64_t NewBits = I->getType()->getIntegralTypeMask() & NotIn;
1021
1022 // Handle zero extension.
1023 if (!SrcTy->isSigned()) {
1024 DemandedMask &= SrcTy->getIntegralTypeMask();
1025 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1026 KnownZero, KnownOne, Depth+1))
1027 return true;
1028 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1029 // The top bits are known to be zero.
1030 KnownZero |= NewBits;
1031 } else {
1032 // Sign extension.
Chris Lattner7d852282006-02-13 22:41:07 +00001033 uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
1034 int64_t InputDemandedBits = DemandedMask & SrcTy->getIntegralTypeMask();
1035
1036 // If any of the sign extended bits are demanded, we know that the sign
1037 // bit is demanded.
1038 if (NewBits & DemandedMask)
1039 InputDemandedBits |= InSignBit;
1040
1041 if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
Chris Lattner0157e7f2006-02-11 09:31:47 +00001042 KnownZero, KnownOne, Depth+1))
1043 return true;
1044 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1045
1046 // If the sign bit of the input is known set or clear, then we know the
1047 // top bits of the result.
Chris Lattner2590e512006-02-07 06:56:34 +00001048
Chris Lattner0157e7f2006-02-11 09:31:47 +00001049 // If the input sign bit is known zero, or if the NewBits are not demanded
1050 // convert this into a zero extension.
1051 if ((KnownZero & InSignBit) || (NewBits & ~DemandedMask) == NewBits) {
Chris Lattner2590e512006-02-07 06:56:34 +00001052 // Convert to unsigned first.
Chris Lattner44314822006-02-07 19:07:40 +00001053 Instruction *NewVal;
Chris Lattner2590e512006-02-07 06:56:34 +00001054 NewVal = new CastInst(I->getOperand(0), SrcTy->getUnsignedVersion(),
Chris Lattner44314822006-02-07 19:07:40 +00001055 I->getOperand(0)->getName());
1056 InsertNewInstBefore(NewVal, *I);
Chris Lattner0157e7f2006-02-11 09:31:47 +00001057 // Then cast that to the destination type.
Chris Lattner44314822006-02-07 19:07:40 +00001058 NewVal = new CastInst(NewVal, I->getType(), I->getName());
1059 InsertNewInstBefore(NewVal, *I);
Chris Lattner2590e512006-02-07 06:56:34 +00001060 return UpdateValueUsesWith(I, NewVal);
Chris Lattner0157e7f2006-02-11 09:31:47 +00001061 } else if (KnownOne & InSignBit) { // Input sign bit known set
1062 KnownOne |= NewBits;
1063 KnownZero &= ~NewBits;
1064 } else { // Input sign bit unknown
1065 KnownZero &= ~NewBits;
1066 KnownOne &= ~NewBits;
Chris Lattner2590e512006-02-07 06:56:34 +00001067 }
Chris Lattner2590e512006-02-07 06:56:34 +00001068 }
Chris Lattner0157e7f2006-02-11 09:31:47 +00001069 break;
Chris Lattner2590e512006-02-07 06:56:34 +00001070 }
Chris Lattner2590e512006-02-07 06:56:34 +00001071 case Instruction::Shl:
Chris Lattner0157e7f2006-02-11 09:31:47 +00001072 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1))) {
1073 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask >> SA->getValue(),
1074 KnownZero, KnownOne, Depth+1))
1075 return true;
1076 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1077 KnownZero <<= SA->getValue();
1078 KnownOne <<= SA->getValue();
1079 KnownZero |= (1ULL << SA->getValue())-1; // low bits known zero.
1080 }
Chris Lattner2590e512006-02-07 06:56:34 +00001081 break;
1082 case Instruction::Shr:
Chris Lattner0157e7f2006-02-11 09:31:47 +00001083 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1))) {
1084 unsigned ShAmt = SA->getValue();
1085
1086 // Compute the new bits that are at the top now.
1087 uint64_t HighBits = (1ULL << ShAmt)-1;
1088 HighBits <<= I->getType()->getPrimitiveSizeInBits() - ShAmt;
Chris Lattner68e74752006-02-13 06:09:08 +00001089 uint64_t TypeMask = I->getType()->getIntegralTypeMask();
Chris Lattner0157e7f2006-02-11 09:31:47 +00001090 if (I->getType()->isUnsigned()) { // Unsigned shift right.
Chris Lattner68e74752006-02-13 06:09:08 +00001091 if (SimplifyDemandedBits(I->getOperand(0),
1092 (DemandedMask << ShAmt) & TypeMask,
Chris Lattner0157e7f2006-02-11 09:31:47 +00001093 KnownZero, KnownOne, Depth+1))
1094 return true;
1095 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattner68e74752006-02-13 06:09:08 +00001096 KnownZero &= TypeMask;
1097 KnownOne &= TypeMask;
Chris Lattner0157e7f2006-02-11 09:31:47 +00001098 KnownZero >>= ShAmt;
1099 KnownOne >>= ShAmt;
1100 KnownZero |= HighBits; // high bits known zero.
1101 } else { // Signed shift right.
Chris Lattner68e74752006-02-13 06:09:08 +00001102 if (SimplifyDemandedBits(I->getOperand(0),
1103 (DemandedMask << ShAmt) & TypeMask,
Chris Lattner0157e7f2006-02-11 09:31:47 +00001104 KnownZero, KnownOne, Depth+1))
1105 return true;
1106 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattner68e74752006-02-13 06:09:08 +00001107 KnownZero &= TypeMask;
1108 KnownOne &= TypeMask;
Chris Lattner0157e7f2006-02-11 09:31:47 +00001109 KnownZero >>= SA->getValue();
1110 KnownOne >>= SA->getValue();
1111
1112 // Handle the sign bits.
1113 uint64_t SignBit = 1ULL << (I->getType()->getPrimitiveSizeInBits()-1);
1114 SignBit >>= SA->getValue(); // Adjust to where it is now in the mask.
1115
1116 // If the input sign bit is known to be zero, or if none of the top bits
1117 // are demanded, turn this into an unsigned shift right.
1118 if ((KnownZero & SignBit) || (HighBits & ~DemandedMask) == HighBits) {
1119 // Convert the input to unsigned.
1120 Instruction *NewVal;
1121 NewVal = new CastInst(I->getOperand(0),
1122 I->getType()->getUnsignedVersion(),
1123 I->getOperand(0)->getName());
1124 InsertNewInstBefore(NewVal, *I);
1125 // Perform the unsigned shift right.
1126 NewVal = new ShiftInst(Instruction::Shr, NewVal, SA, I->getName());
1127 InsertNewInstBefore(NewVal, *I);
1128 // Then cast that to the destination type.
1129 NewVal = new CastInst(NewVal, I->getType(), I->getName());
1130 InsertNewInstBefore(NewVal, *I);
1131 return UpdateValueUsesWith(I, NewVal);
1132 } else if (KnownOne & SignBit) { // New bits are known one.
1133 KnownOne |= HighBits;
1134 }
Chris Lattner2590e512006-02-07 06:56:34 +00001135 }
Chris Lattner0157e7f2006-02-11 09:31:47 +00001136 }
Chris Lattner2590e512006-02-07 06:56:34 +00001137 break;
1138 }
Chris Lattner0157e7f2006-02-11 09:31:47 +00001139
1140 // If the client is only demanding bits that we know, return the known
1141 // constant.
1142 if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask)
1143 return UpdateValueUsesWith(I, GetConstantInType(I->getType(), KnownOne));
Chris Lattner2590e512006-02-07 06:56:34 +00001144 return false;
1145}
1146
Chris Lattner623826c2004-09-28 21:48:02 +00001147// isTrueWhenEqual - Return true if the specified setcondinst instruction is
1148// true when both operands are equal...
1149//
1150static bool isTrueWhenEqual(Instruction &I) {
1151 return I.getOpcode() == Instruction::SetEQ ||
1152 I.getOpcode() == Instruction::SetGE ||
1153 I.getOpcode() == Instruction::SetLE;
1154}
Chris Lattnerb8b97502003-08-13 19:01:45 +00001155
1156/// AssociativeOpt - Perform an optimization on an associative operator. This
1157/// function is designed to check a chain of associative operators for a
1158/// potential to apply a certain optimization. Since the optimization may be
1159/// applicable if the expression was reassociated, this checks the chain, then
1160/// reassociates the expression as necessary to expose the optimization
1161/// opportunity. This makes use of a special Functor, which must define
1162/// 'shouldApply' and 'apply' methods.
1163///
1164template<typename Functor>
1165Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1166 unsigned Opcode = Root.getOpcode();
1167 Value *LHS = Root.getOperand(0);
1168
1169 // Quick check, see if the immediate LHS matches...
1170 if (F.shouldApply(LHS))
1171 return F.apply(Root);
1172
1173 // Otherwise, if the LHS is not of the same opcode as the root, return.
1174 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001175 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattnerb8b97502003-08-13 19:01:45 +00001176 // Should we apply this transform to the RHS?
1177 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1178
1179 // If not to the RHS, check to see if we should apply to the LHS...
1180 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1181 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1182 ShouldApply = true;
1183 }
1184
1185 // If the functor wants to apply the optimization to the RHS of LHSI,
1186 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1187 if (ShouldApply) {
1188 BasicBlock *BB = Root.getParent();
Misha Brukmanb1c93172005-04-21 23:48:37 +00001189
Chris Lattnerb8b97502003-08-13 19:01:45 +00001190 // Now all of the instructions are in the current basic block, go ahead
1191 // and perform the reassociation.
1192 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1193
1194 // First move the selected RHS to the LHS of the root...
1195 Root.setOperand(0, LHSI->getOperand(1));
1196
1197 // Make what used to be the LHS of the root be the user of the root...
1198 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner284d3b02004-04-16 18:08:07 +00001199 if (&Root == TmpLHSI) {
Chris Lattner8953b902004-04-05 02:10:19 +00001200 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1201 return 0;
1202 }
Chris Lattner284d3b02004-04-16 18:08:07 +00001203 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattnerb8b97502003-08-13 19:01:45 +00001204 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner284d3b02004-04-16 18:08:07 +00001205 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
1206 BasicBlock::iterator ARI = &Root; ++ARI;
1207 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
1208 ARI = Root;
Chris Lattnerb8b97502003-08-13 19:01:45 +00001209
1210 // Now propagate the ExtraOperand down the chain of instructions until we
1211 // get to LHSI.
1212 while (TmpLHSI != LHSI) {
1213 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner284d3b02004-04-16 18:08:07 +00001214 // Move the instruction to immediately before the chain we are
1215 // constructing to avoid breaking dominance properties.
1216 NextLHSI->getParent()->getInstList().remove(NextLHSI);
1217 BB->getInstList().insert(ARI, NextLHSI);
1218 ARI = NextLHSI;
1219
Chris Lattnerb8b97502003-08-13 19:01:45 +00001220 Value *NextOp = NextLHSI->getOperand(1);
1221 NextLHSI->setOperand(1, ExtraOperand);
1222 TmpLHSI = NextLHSI;
1223 ExtraOperand = NextOp;
1224 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001225
Chris Lattnerb8b97502003-08-13 19:01:45 +00001226 // Now that the instructions are reassociated, have the functor perform
1227 // the transformation...
1228 return F.apply(Root);
1229 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001230
Chris Lattnerb8b97502003-08-13 19:01:45 +00001231 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1232 }
1233 return 0;
1234}
1235
1236
1237// AddRHS - Implements: X + X --> X << 1
1238struct AddRHS {
1239 Value *RHS;
1240 AddRHS(Value *rhs) : RHS(rhs) {}
1241 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1242 Instruction *apply(BinaryOperator &Add) const {
1243 return new ShiftInst(Instruction::Shl, Add.getOperand(0),
1244 ConstantInt::get(Type::UByteTy, 1));
1245 }
1246};
1247
1248// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1249// iff C1&C2 == 0
1250struct AddMaskingAnd {
1251 Constant *C2;
1252 AddMaskingAnd(Constant *c) : C2(c) {}
1253 bool shouldApply(Value *LHS) const {
Chris Lattnerd4252a72004-07-30 07:50:03 +00001254 ConstantInt *C1;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001255 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Chris Lattnerd4252a72004-07-30 07:50:03 +00001256 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattnerb8b97502003-08-13 19:01:45 +00001257 }
1258 Instruction *apply(BinaryOperator &Add) const {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001259 return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattnerb8b97502003-08-13 19:01:45 +00001260 }
1261};
1262
Chris Lattner86102b82005-01-01 16:22:27 +00001263static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner183b3362004-04-09 19:05:30 +00001264 InstCombiner *IC) {
Chris Lattner86102b82005-01-01 16:22:27 +00001265 if (isa<CastInst>(I)) {
1266 if (Constant *SOC = dyn_cast<Constant>(SO))
1267 return ConstantExpr::getCast(SOC, I.getType());
Misha Brukmanb1c93172005-04-21 23:48:37 +00001268
Chris Lattner86102b82005-01-01 16:22:27 +00001269 return IC->InsertNewInstBefore(new CastInst(SO, I.getType(),
1270 SO->getName() + ".cast"), I);
1271 }
1272
Chris Lattner183b3362004-04-09 19:05:30 +00001273 // Figure out if the constant is the left or the right argument.
Chris Lattner86102b82005-01-01 16:22:27 +00001274 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1275 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattnerb8b97502003-08-13 19:01:45 +00001276
Chris Lattner183b3362004-04-09 19:05:30 +00001277 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1278 if (ConstIsRHS)
Chris Lattner86102b82005-01-01 16:22:27 +00001279 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1280 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner183b3362004-04-09 19:05:30 +00001281 }
1282
1283 Value *Op0 = SO, *Op1 = ConstOperand;
1284 if (!ConstIsRHS)
1285 std::swap(Op0, Op1);
1286 Instruction *New;
Chris Lattner86102b82005-01-01 16:22:27 +00001287 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1288 New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
1289 else if (ShiftInst *SI = dyn_cast<ShiftInst>(&I))
1290 New = new ShiftInst(SI->getOpcode(), Op0, Op1, SO->getName()+".sh");
Chris Lattnerf9d96652004-04-10 19:15:56 +00001291 else {
Chris Lattner183b3362004-04-09 19:05:30 +00001292 assert(0 && "Unknown binary instruction type!");
Chris Lattnerf9d96652004-04-10 19:15:56 +00001293 abort();
1294 }
Chris Lattner86102b82005-01-01 16:22:27 +00001295 return IC->InsertNewInstBefore(New, I);
1296}
1297
1298// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1299// constant as the other operand, try to fold the binary operator into the
1300// select arguments. This also works for Cast instructions, which obviously do
1301// not have a second operand.
1302static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1303 InstCombiner *IC) {
1304 // Don't modify shared select instructions
1305 if (!SI->hasOneUse()) return 0;
1306 Value *TV = SI->getOperand(1);
1307 Value *FV = SI->getOperand(2);
1308
1309 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner374e6592005-04-21 05:43:13 +00001310 // Bool selects with constant operands can be folded to logical ops.
1311 if (SI->getType() == Type::BoolTy) return 0;
1312
Chris Lattner86102b82005-01-01 16:22:27 +00001313 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1314 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1315
1316 return new SelectInst(SI->getCondition(), SelectTrueVal,
1317 SelectFalseVal);
1318 }
1319 return 0;
Chris Lattner183b3362004-04-09 19:05:30 +00001320}
1321
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001322
1323/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1324/// node as operand #0, see if we can fold the instruction into the PHI (which
1325/// is only possible if all operands to the PHI are constants).
1326Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1327 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattner7515cab2004-11-14 19:13:23 +00001328 unsigned NumPHIValues = PN->getNumIncomingValues();
1329 if (!PN->hasOneUse() || NumPHIValues == 0 ||
1330 !isa<Constant>(PN->getIncomingValue(0))) return 0;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001331
1332 // Check to see if all of the operands of the PHI are constants. If not, we
1333 // cannot do the transformation.
Chris Lattner7515cab2004-11-14 19:13:23 +00001334 for (unsigned i = 1; i != NumPHIValues; ++i)
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001335 if (!isa<Constant>(PN->getIncomingValue(i)))
1336 return 0;
1337
1338 // Okay, we can do the transformation: create the new PHI node.
1339 PHINode *NewPN = new PHINode(I.getType(), I.getName());
1340 I.setName("");
Chris Lattnerd8e20182005-01-29 00:39:08 +00001341 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001342 InsertNewInstBefore(NewPN, *PN);
1343
1344 // Next, add all of the operands to the PHI.
1345 if (I.getNumOperands() == 2) {
1346 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattner7515cab2004-11-14 19:13:23 +00001347 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001348 Constant *InV = cast<Constant>(PN->getIncomingValue(i));
1349 NewPN->addIncoming(ConstantExpr::get(I.getOpcode(), InV, C),
1350 PN->getIncomingBlock(i));
1351 }
1352 } else {
1353 assert(isa<CastInst>(I) && "Unary op should be a cast!");
1354 const Type *RetTy = I.getType();
Chris Lattner7515cab2004-11-14 19:13:23 +00001355 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001356 Constant *InV = cast<Constant>(PN->getIncomingValue(i));
1357 NewPN->addIncoming(ConstantExpr::getCast(InV, RetTy),
1358 PN->getIncomingBlock(i));
1359 }
1360 }
1361 return ReplaceInstUsesWith(I, NewPN);
1362}
1363
Chris Lattner113f4f42002-06-25 16:13:24 +00001364Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001365 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00001366 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattner9fa53de2002-05-06 16:49:18 +00001367
Chris Lattnercf4a9962004-04-10 22:01:55 +00001368 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattner81a7a232004-10-16 18:11:37 +00001369 // X + undef -> undef
1370 if (isa<UndefValue>(RHS))
1371 return ReplaceInstUsesWith(I, RHS);
1372
Chris Lattnercf4a9962004-04-10 22:01:55 +00001373 // X + 0 --> X
Chris Lattner7fde91e2005-10-17 17:56:38 +00001374 if (!I.getType()->isFloatingPoint()) { // NOTE: -0 + +0 = +0.
1375 if (RHSC->isNullValue())
1376 return ReplaceInstUsesWith(I, LHS);
Chris Lattnerda1b1522005-10-17 20:18:38 +00001377 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
1378 if (CFP->isExactlyValue(-0.0))
1379 return ReplaceInstUsesWith(I, LHS);
Chris Lattner7fde91e2005-10-17 17:56:38 +00001380 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001381
Chris Lattnercf4a9962004-04-10 22:01:55 +00001382 // X + (signbit) --> X ^ signbit
1383 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattner92a68652006-02-07 08:05:22 +00001384 uint64_t Val = CI->getZExtValue();
Chris Lattner77defba2006-02-07 07:00:41 +00001385 if (Val == (1ULL << (CI->getType()->getPrimitiveSizeInBits()-1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001386 return BinaryOperator::createXor(LHS, RHS);
Chris Lattnercf4a9962004-04-10 22:01:55 +00001387 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001388
1389 if (isa<PHINode>(LHS))
1390 if (Instruction *NV = FoldOpIntoPhi(I))
1391 return NV;
Chris Lattner0b3557f2005-09-24 23:43:33 +00001392
Chris Lattner330628a2006-01-06 17:59:59 +00001393 ConstantInt *XorRHS = 0;
1394 Value *XorLHS = 0;
Chris Lattner0b3557f2005-09-24 23:43:33 +00001395 if (match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
1396 unsigned TySizeBits = I.getType()->getPrimitiveSizeInBits();
1397 int64_t RHSSExt = cast<ConstantInt>(RHSC)->getSExtValue();
1398 uint64_t RHSZExt = cast<ConstantInt>(RHSC)->getZExtValue();
1399
1400 uint64_t C0080Val = 1ULL << 31;
1401 int64_t CFF80Val = -C0080Val;
1402 unsigned Size = 32;
1403 do {
1404 if (TySizeBits > Size) {
1405 bool Found = false;
1406 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
1407 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
1408 if (RHSSExt == CFF80Val) {
1409 if (XorRHS->getZExtValue() == C0080Val)
1410 Found = true;
1411 } else if (RHSZExt == C0080Val) {
1412 if (XorRHS->getSExtValue() == CFF80Val)
1413 Found = true;
1414 }
1415 if (Found) {
1416 // This is a sign extend if the top bits are known zero.
Chris Lattner4534dd592006-02-09 07:38:58 +00001417 uint64_t Mask = ~0ULL;
Chris Lattnerc3ebf402006-02-07 07:27:52 +00001418 Mask <<= 64-(TySizeBits-Size);
Chris Lattner4534dd592006-02-09 07:38:58 +00001419 Mask &= XorLHS->getType()->getIntegralTypeMask();
Chris Lattnerc3ebf402006-02-07 07:27:52 +00001420 if (!MaskedValueIsZero(XorLHS, Mask))
Chris Lattner0b3557f2005-09-24 23:43:33 +00001421 Size = 0; // Not a sign ext, but can't be any others either.
1422 goto FoundSExt;
1423 }
1424 }
1425 Size >>= 1;
1426 C0080Val >>= Size;
1427 CFF80Val >>= Size;
1428 } while (Size >= 8);
1429
1430FoundSExt:
1431 const Type *MiddleType = 0;
1432 switch (Size) {
1433 default: break;
1434 case 32: MiddleType = Type::IntTy; break;
1435 case 16: MiddleType = Type::ShortTy; break;
1436 case 8: MiddleType = Type::SByteTy; break;
1437 }
1438 if (MiddleType) {
1439 Instruction *NewTrunc = new CastInst(XorLHS, MiddleType, "sext");
1440 InsertNewInstBefore(NewTrunc, I);
1441 return new CastInst(NewTrunc, I.getType());
1442 }
1443 }
Chris Lattnercf4a9962004-04-10 22:01:55 +00001444 }
Chris Lattner9fa53de2002-05-06 16:49:18 +00001445
Chris Lattnerb8b97502003-08-13 19:01:45 +00001446 // X + X --> X << 1
Robert Bocchino7b5b86c2004-07-27 21:02:21 +00001447 if (I.getType()->isInteger()) {
Chris Lattnerb8b97502003-08-13 19:01:45 +00001448 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Chris Lattner47060462005-04-07 17:14:51 +00001449
1450 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
1451 if (RHSI->getOpcode() == Instruction::Sub)
1452 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
1453 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
1454 }
1455 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
1456 if (LHSI->getOpcode() == Instruction::Sub)
1457 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
1458 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
1459 }
Robert Bocchino7b5b86c2004-07-27 21:02:21 +00001460 }
Chris Lattnerede3fe02003-08-13 04:18:28 +00001461
Chris Lattner147e9752002-05-08 22:46:53 +00001462 // -A + B --> B - A
Chris Lattnerbb74e222003-03-10 23:06:50 +00001463 if (Value *V = dyn_castNegVal(LHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001464 return BinaryOperator::createSub(RHS, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +00001465
1466 // A + -B --> A - B
Chris Lattnerbb74e222003-03-10 23:06:50 +00001467 if (!isa<Constant>(RHS))
1468 if (Value *V = dyn_castNegVal(RHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001469 return BinaryOperator::createSub(LHS, V);
Chris Lattner260ab202002-04-18 17:39:14 +00001470
Misha Brukmanb1c93172005-04-21 23:48:37 +00001471
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001472 ConstantInt *C2;
1473 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
1474 if (X == RHS) // X*C + X --> X * (C+1)
1475 return BinaryOperator::createMul(RHS, AddOne(C2));
1476
1477 // X*C1 + X*C2 --> X * (C1+C2)
1478 ConstantInt *C1;
1479 if (X == dyn_castFoldableMul(RHS, C1))
1480 return BinaryOperator::createMul(X, ConstantExpr::getAdd(C1, C2));
Chris Lattner57c8d992003-02-18 19:57:07 +00001481 }
1482
1483 // X + X*C --> X * (C+1)
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001484 if (dyn_castFoldableMul(RHS, C2) == LHS)
1485 return BinaryOperator::createMul(LHS, AddOne(C2));
1486
Chris Lattner57c8d992003-02-18 19:57:07 +00001487
Chris Lattnerb8b97502003-08-13 19:01:45 +00001488 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattnerd4252a72004-07-30 07:50:03 +00001489 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattnerb8b97502003-08-13 19:01:45 +00001490 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2))) return R;
Chris Lattner7fb29e12003-03-11 00:12:48 +00001491
Chris Lattnerb9cde762003-10-02 15:11:26 +00001492 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner330628a2006-01-06 17:59:59 +00001493 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00001494 if (match(LHS, m_Not(m_Value(X)))) { // ~X + C --> (C-1) - X
1495 Constant *C= ConstantExpr::getSub(CRHS, ConstantInt::get(I.getType(), 1));
1496 return BinaryOperator::createSub(C, X);
Chris Lattnerb9cde762003-10-02 15:11:26 +00001497 }
Chris Lattnerd4252a72004-07-30 07:50:03 +00001498
Chris Lattnerbff91d92004-10-08 05:07:56 +00001499 // (X & FF00) + xx00 -> (X+xx00) & FF00
1500 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
1501 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
1502 if (Anded == CRHS) {
1503 // See if all bits from the first bit set in the Add RHS up are included
1504 // in the mask. First, get the rightmost bit.
1505 uint64_t AddRHSV = CRHS->getRawValue();
1506
1507 // Form a mask of all bits from the lowest bit added through the top.
1508 uint64_t AddRHSHighBits = ~((AddRHSV & -AddRHSV)-1);
Chris Lattner77defba2006-02-07 07:00:41 +00001509 AddRHSHighBits &= C2->getType()->getIntegralTypeMask();
Chris Lattnerbff91d92004-10-08 05:07:56 +00001510
1511 // See if the and mask includes all of these bits.
1512 uint64_t AddRHSHighBitsAnd = AddRHSHighBits & C2->getRawValue();
Misha Brukmanb1c93172005-04-21 23:48:37 +00001513
Chris Lattnerbff91d92004-10-08 05:07:56 +00001514 if (AddRHSHighBits == AddRHSHighBitsAnd) {
1515 // Okay, the xform is safe. Insert the new add pronto.
1516 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
1517 LHS->getName()), I);
1518 return BinaryOperator::createAnd(NewAdd, C2);
1519 }
1520 }
1521 }
1522
Chris Lattnerd4252a72004-07-30 07:50:03 +00001523 // Try to fold constant add into select arguments.
1524 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner86102b82005-01-01 16:22:27 +00001525 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattnerd4252a72004-07-30 07:50:03 +00001526 return R;
Chris Lattnerb9cde762003-10-02 15:11:26 +00001527 }
1528
Chris Lattner113f4f42002-06-25 16:13:24 +00001529 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +00001530}
1531
Chris Lattnerbdb0ce02003-07-22 21:46:59 +00001532// isSignBit - Return true if the value represented by the constant only has the
1533// highest order bit set.
1534static bool isSignBit(ConstantInt *CI) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001535 unsigned NumBits = CI->getType()->getPrimitiveSizeInBits();
Chris Lattner2f1457f2005-04-24 17:46:05 +00001536 return (CI->getRawValue() & (~0ULL >> (64-NumBits))) == (1ULL << (NumBits-1));
Chris Lattnerbdb0ce02003-07-22 21:46:59 +00001537}
1538
Chris Lattner022167f2004-03-13 00:11:49 +00001539/// RemoveNoopCast - Strip off nonconverting casts from the value.
1540///
1541static Value *RemoveNoopCast(Value *V) {
1542 if (CastInst *CI = dyn_cast<CastInst>(V)) {
1543 const Type *CTy = CI->getType();
1544 const Type *OpTy = CI->getOperand(0)->getType();
1545 if (CTy->isInteger() && OpTy->isInteger()) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001546 if (CTy->getPrimitiveSizeInBits() == OpTy->getPrimitiveSizeInBits())
Chris Lattner022167f2004-03-13 00:11:49 +00001547 return RemoveNoopCast(CI->getOperand(0));
1548 } else if (isa<PointerType>(CTy) && isa<PointerType>(OpTy))
1549 return RemoveNoopCast(CI->getOperand(0));
1550 }
1551 return V;
1552}
1553
Chris Lattner113f4f42002-06-25 16:13:24 +00001554Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +00001555 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001556
Chris Lattnere6794492002-08-12 21:17:25 +00001557 if (Op0 == Op1) // sub X, X -> 0
1558 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner260ab202002-04-18 17:39:14 +00001559
Chris Lattnere6794492002-08-12 21:17:25 +00001560 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattnerbb74e222003-03-10 23:06:50 +00001561 if (Value *V = dyn_castNegVal(Op1))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001562 return BinaryOperator::createAdd(Op0, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +00001563
Chris Lattner81a7a232004-10-16 18:11:37 +00001564 if (isa<UndefValue>(Op0))
1565 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
1566 if (isa<UndefValue>(Op1))
1567 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
1568
Chris Lattner8f2f5982003-11-05 01:06:05 +00001569 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
1570 // Replace (-1 - A) with (~A)...
Chris Lattner3082c5a2003-02-18 19:28:33 +00001571 if (C->isAllOnesValue())
1572 return BinaryOperator::createNot(Op1);
Chris Lattnerad3c4952002-05-09 01:29:19 +00001573
Chris Lattner8f2f5982003-11-05 01:06:05 +00001574 // C - ~X == X + (1+C)
Reid Spencer4fdd96c2005-06-18 17:37:34 +00001575 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00001576 if (match(Op1, m_Not(m_Value(X))))
1577 return BinaryOperator::createAdd(X,
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001578 ConstantExpr::getAdd(C, ConstantInt::get(I.getType(), 1)));
Chris Lattner92295c52004-03-12 23:53:13 +00001579 // -((uint)X >> 31) -> ((int)X >> 31)
1580 // -((int)X >> 31) -> ((uint)X >> 31)
Chris Lattner022167f2004-03-13 00:11:49 +00001581 if (C->isNullValue()) {
1582 Value *NoopCastedRHS = RemoveNoopCast(Op1);
1583 if (ShiftInst *SI = dyn_cast<ShiftInst>(NoopCastedRHS))
Chris Lattner92295c52004-03-12 23:53:13 +00001584 if (SI->getOpcode() == Instruction::Shr)
1585 if (ConstantUInt *CU = dyn_cast<ConstantUInt>(SI->getOperand(1))) {
1586 const Type *NewTy;
Chris Lattner022167f2004-03-13 00:11:49 +00001587 if (SI->getType()->isSigned())
Chris Lattner97bfcea2004-06-17 18:16:02 +00001588 NewTy = SI->getType()->getUnsignedVersion();
Chris Lattner92295c52004-03-12 23:53:13 +00001589 else
Chris Lattner97bfcea2004-06-17 18:16:02 +00001590 NewTy = SI->getType()->getSignedVersion();
Chris Lattner92295c52004-03-12 23:53:13 +00001591 // Check to see if we are shifting out everything but the sign bit.
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001592 if (CU->getValue() == SI->getType()->getPrimitiveSizeInBits()-1) {
Chris Lattner92295c52004-03-12 23:53:13 +00001593 // Ok, the transformation is safe. Insert a cast of the incoming
1594 // value, then the new shift, then the new cast.
1595 Instruction *FirstCast = new CastInst(SI->getOperand(0), NewTy,
1596 SI->getOperand(0)->getName());
1597 Value *InV = InsertNewInstBefore(FirstCast, I);
1598 Instruction *NewShift = new ShiftInst(Instruction::Shr, FirstCast,
1599 CU, SI->getName());
Chris Lattner022167f2004-03-13 00:11:49 +00001600 if (NewShift->getType() == I.getType())
1601 return NewShift;
1602 else {
1603 InV = InsertNewInstBefore(NewShift, I);
1604 return new CastInst(NewShift, I.getType());
1605 }
Chris Lattner92295c52004-03-12 23:53:13 +00001606 }
1607 }
Chris Lattner022167f2004-03-13 00:11:49 +00001608 }
Chris Lattner183b3362004-04-09 19:05:30 +00001609
1610 // Try to fold constant sub into select arguments.
1611 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner86102b82005-01-01 16:22:27 +00001612 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00001613 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001614
1615 if (isa<PHINode>(Op0))
1616 if (Instruction *NV = FoldOpIntoPhi(I))
1617 return NV;
Chris Lattner8f2f5982003-11-05 01:06:05 +00001618 }
1619
Chris Lattnera9be4492005-04-07 16:15:25 +00001620 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
1621 if (Op1I->getOpcode() == Instruction::Add &&
1622 !Op0->getType()->isFloatingPoint()) {
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00001623 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Chris Lattnera9be4492005-04-07 16:15:25 +00001624 return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00001625 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Chris Lattnera9be4492005-04-07 16:15:25 +00001626 return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00001627 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
1628 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
1629 // C1-(X+C2) --> (C1-C2)-X
1630 return BinaryOperator::createSub(ConstantExpr::getSub(CI1, CI2),
1631 Op1I->getOperand(0));
1632 }
Chris Lattnera9be4492005-04-07 16:15:25 +00001633 }
1634
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001635 if (Op1I->hasOneUse()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00001636 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
1637 // is not used by anyone else...
1638 //
Chris Lattnerc2f0aa52004-02-02 20:09:56 +00001639 if (Op1I->getOpcode() == Instruction::Sub &&
1640 !Op1I->getType()->isFloatingPoint()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00001641 // Swap the two operands of the subexpr...
1642 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
1643 Op1I->setOperand(0, IIOp1);
1644 Op1I->setOperand(1, IIOp0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001645
Chris Lattner3082c5a2003-02-18 19:28:33 +00001646 // Create the new top level add instruction...
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001647 return BinaryOperator::createAdd(Op0, Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001648 }
1649
1650 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
1651 //
1652 if (Op1I->getOpcode() == Instruction::And &&
1653 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
1654 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
1655
Chris Lattner396dbfe2004-06-09 05:08:07 +00001656 Value *NewNot =
1657 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001658 return BinaryOperator::createAnd(Op0, NewNot);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001659 }
Chris Lattner57c8d992003-02-18 19:57:07 +00001660
Chris Lattner0aee4b72004-10-06 15:08:25 +00001661 // -(X sdiv C) -> (X sdiv -C)
1662 if (Op1I->getOpcode() == Instruction::Div)
1663 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
Chris Lattnera9be4492005-04-07 16:15:25 +00001664 if (CSI->isNullValue())
Chris Lattner0aee4b72004-10-06 15:08:25 +00001665 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Misha Brukmanb1c93172005-04-21 23:48:37 +00001666 return BinaryOperator::createDiv(Op1I->getOperand(0),
Chris Lattner0aee4b72004-10-06 15:08:25 +00001667 ConstantExpr::getNeg(DivRHS));
1668
Chris Lattner57c8d992003-02-18 19:57:07 +00001669 // X - X*C --> X * (1-C)
Reid Spencer4fdd96c2005-06-18 17:37:34 +00001670 ConstantInt *C2 = 0;
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001671 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00001672 Constant *CP1 =
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001673 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1), C2);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001674 return BinaryOperator::createMul(Op0, CP1);
Chris Lattner57c8d992003-02-18 19:57:07 +00001675 }
Chris Lattnerad3c4952002-05-09 01:29:19 +00001676 }
Chris Lattnera9be4492005-04-07 16:15:25 +00001677 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00001678
Chris Lattner47060462005-04-07 17:14:51 +00001679 if (!Op0->getType()->isFloatingPoint())
1680 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
1681 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner411336f2005-01-19 21:50:18 +00001682 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
1683 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
1684 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
1685 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner47060462005-04-07 17:14:51 +00001686 } else if (Op0I->getOpcode() == Instruction::Sub) {
1687 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
1688 return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
Chris Lattner411336f2005-01-19 21:50:18 +00001689 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001690
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001691 ConstantInt *C1;
1692 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
1693 if (X == Op1) { // X*C - X --> X * (C-1)
1694 Constant *CP1 = ConstantExpr::getSub(C1, ConstantInt::get(I.getType(),1));
1695 return BinaryOperator::createMul(Op1, CP1);
1696 }
Chris Lattner57c8d992003-02-18 19:57:07 +00001697
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001698 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
1699 if (X == dyn_castFoldableMul(Op1, C2))
1700 return BinaryOperator::createMul(Op1, ConstantExpr::getSub(C1, C2));
1701 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001702 return 0;
Chris Lattner260ab202002-04-18 17:39:14 +00001703}
1704
Chris Lattnere79e8542004-02-23 06:38:22 +00001705/// isSignBitCheck - Given an exploded setcc instruction, return true if it is
1706/// really just returns true if the most significant (sign) bit is set.
1707static bool isSignBitCheck(unsigned Opcode, Value *LHS, ConstantInt *RHS) {
1708 if (RHS->getType()->isSigned()) {
1709 // True if source is LHS < 0 or LHS <= -1
1710 return Opcode == Instruction::SetLT && RHS->isNullValue() ||
1711 Opcode == Instruction::SetLE && RHS->isAllOnesValue();
1712 } else {
1713 ConstantUInt *RHSC = cast<ConstantUInt>(RHS);
1714 // True if source is LHS > 127 or LHS >= 128, where the constants depend on
1715 // the size of the integer type.
1716 if (Opcode == Instruction::SetGE)
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001717 return RHSC->getValue() ==
1718 1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1);
Chris Lattnere79e8542004-02-23 06:38:22 +00001719 if (Opcode == Instruction::SetGT)
1720 return RHSC->getValue() ==
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001721 (1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1))-1;
Chris Lattnere79e8542004-02-23 06:38:22 +00001722 }
1723 return false;
1724}
1725
Chris Lattner113f4f42002-06-25 16:13:24 +00001726Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001727 bool Changed = SimplifyCommutative(I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001728 Value *Op0 = I.getOperand(0);
Chris Lattner260ab202002-04-18 17:39:14 +00001729
Chris Lattner81a7a232004-10-16 18:11:37 +00001730 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
1731 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1732
Chris Lattnere6794492002-08-12 21:17:25 +00001733 // Simplify mul instructions with a constant RHS...
Chris Lattner3082c5a2003-02-18 19:28:33 +00001734 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
1735 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerede3fe02003-08-13 04:18:28 +00001736
1737 // ((X << C1)*C2) == (X * (C2 << C1))
1738 if (ShiftInst *SI = dyn_cast<ShiftInst>(Op0))
1739 if (SI->getOpcode() == Instruction::Shl)
1740 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001741 return BinaryOperator::createMul(SI->getOperand(0),
1742 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanb1c93172005-04-21 23:48:37 +00001743
Chris Lattnercce81be2003-09-11 22:24:54 +00001744 if (CI->isNullValue())
1745 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
1746 if (CI->equalsInt(1)) // X * 1 == X
1747 return ReplaceInstUsesWith(I, Op0);
1748 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Chris Lattner35236d82003-06-25 17:09:20 +00001749 return BinaryOperator::createNeg(Op0, I.getName());
Chris Lattner31ba1292002-04-29 22:24:47 +00001750
Chris Lattnercce81be2003-09-11 22:24:54 +00001751 int64_t Val = (int64_t)cast<ConstantInt>(CI)->getRawValue();
Chris Lattner22d00a82005-08-02 19:16:58 +00001752 if (isPowerOf2_64(Val)) { // Replace X*(2^C) with X << C
1753 uint64_t C = Log2_64(Val);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001754 return new ShiftInst(Instruction::Shl, Op0,
1755 ConstantUInt::get(Type::UByteTy, C));
Chris Lattner22d00a82005-08-02 19:16:58 +00001756 }
Robert Bocchino7b5b86c2004-07-27 21:02:21 +00001757 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00001758 if (Op1F->isNullValue())
1759 return ReplaceInstUsesWith(I, Op1);
Chris Lattner31ba1292002-04-29 22:24:47 +00001760
Chris Lattner3082c5a2003-02-18 19:28:33 +00001761 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
1762 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
1763 if (Op1F->getValue() == 1.0)
1764 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
1765 }
Chris Lattner32c01df2006-03-04 06:04:02 +00001766
1767 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
1768 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
1769 isa<ConstantInt>(Op0I->getOperand(1))) {
1770 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
1771 Instruction *Add = BinaryOperator::createMul(Op0I->getOperand(0),
1772 Op1, "tmp");
1773 InsertNewInstBefore(Add, I);
1774 Value *C1C2 = ConstantExpr::getMul(Op1,
1775 cast<Constant>(Op0I->getOperand(1)));
1776 return BinaryOperator::createAdd(Add, C1C2);
1777
1778 }
Chris Lattner183b3362004-04-09 19:05:30 +00001779
1780 // Try to fold constant mul into select arguments.
1781 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00001782 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00001783 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001784
1785 if (isa<PHINode>(Op0))
1786 if (Instruction *NV = FoldOpIntoPhi(I))
1787 return NV;
Chris Lattner260ab202002-04-18 17:39:14 +00001788 }
1789
Chris Lattner934a64cf2003-03-10 23:23:04 +00001790 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
1791 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001792 return BinaryOperator::createMul(Op0v, Op1v);
Chris Lattner934a64cf2003-03-10 23:23:04 +00001793
Chris Lattner2635b522004-02-23 05:39:21 +00001794 // If one of the operands of the multiply is a cast from a boolean value, then
1795 // we know the bool is either zero or one, so this is a 'masking' multiply.
1796 // See if we can simplify things based on how the boolean was originally
1797 // formed.
1798 CastInst *BoolCast = 0;
1799 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(0)))
1800 if (CI->getOperand(0)->getType() == Type::BoolTy)
1801 BoolCast = CI;
1802 if (!BoolCast)
1803 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(1)))
1804 if (CI->getOperand(0)->getType() == Type::BoolTy)
1805 BoolCast = CI;
1806 if (BoolCast) {
1807 if (SetCondInst *SCI = dyn_cast<SetCondInst>(BoolCast->getOperand(0))) {
1808 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
1809 const Type *SCOpTy = SCIOp0->getType();
1810
Chris Lattnere79e8542004-02-23 06:38:22 +00001811 // If the setcc is true iff the sign bit of X is set, then convert this
1812 // multiply into a shift/and combination.
1813 if (isa<ConstantInt>(SCIOp1) &&
1814 isSignBitCheck(SCI->getOpcode(), SCIOp0, cast<ConstantInt>(SCIOp1))) {
Chris Lattner2635b522004-02-23 05:39:21 +00001815 // Shift the X value right to turn it into "all signbits".
1816 Constant *Amt = ConstantUInt::get(Type::UByteTy,
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001817 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattnere79e8542004-02-23 06:38:22 +00001818 if (SCIOp0->getType()->isUnsigned()) {
Chris Lattner97bfcea2004-06-17 18:16:02 +00001819 const Type *NewTy = SCIOp0->getType()->getSignedVersion();
Chris Lattnere79e8542004-02-23 06:38:22 +00001820 SCIOp0 = InsertNewInstBefore(new CastInst(SCIOp0, NewTy,
1821 SCIOp0->getName()), I);
1822 }
1823
1824 Value *V =
1825 InsertNewInstBefore(new ShiftInst(Instruction::Shr, SCIOp0, Amt,
1826 BoolCast->getOperand(0)->getName()+
1827 ".mask"), I);
Chris Lattner2635b522004-02-23 05:39:21 +00001828
1829 // If the multiply type is not the same as the source type, sign extend
1830 // or truncate to the multiply type.
1831 if (I.getType() != V->getType())
Chris Lattnere79e8542004-02-23 06:38:22 +00001832 V = InsertNewInstBefore(new CastInst(V, I.getType(), V->getName()),I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001833
Chris Lattner2635b522004-02-23 05:39:21 +00001834 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001835 return BinaryOperator::createAnd(V, OtherOp);
Chris Lattner2635b522004-02-23 05:39:21 +00001836 }
1837 }
1838 }
1839
Chris Lattner113f4f42002-06-25 16:13:24 +00001840 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +00001841}
1842
Chris Lattner113f4f42002-06-25 16:13:24 +00001843Instruction *InstCombiner::visitDiv(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001844 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner81a7a232004-10-16 18:11:37 +00001845
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001846 if (isa<UndefValue>(Op0)) // undef / X -> 0
1847 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1848 if (isa<UndefValue>(Op1))
1849 return ReplaceInstUsesWith(I, Op1); // X / undef -> undef
1850
1851 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnere20c3342004-04-26 14:01:59 +00001852 // div X, 1 == X
Chris Lattnere6794492002-08-12 21:17:25 +00001853 if (RHS->equalsInt(1))
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001854 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001855
Chris Lattnere20c3342004-04-26 14:01:59 +00001856 // div X, -1 == -X
1857 if (RHS->isAllOnesValue())
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001858 return BinaryOperator::createNeg(Op0);
Chris Lattnere20c3342004-04-26 14:01:59 +00001859
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001860 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
Chris Lattner272d5ca2004-09-28 18:22:15 +00001861 if (LHS->getOpcode() == Instruction::Div)
1862 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Chris Lattner272d5ca2004-09-28 18:22:15 +00001863 // (X / C1) / C2 -> X / (C1*C2)
1864 return BinaryOperator::createDiv(LHS->getOperand(0),
1865 ConstantExpr::getMul(RHS, LHSRHS));
1866 }
1867
Chris Lattner3082c5a2003-02-18 19:28:33 +00001868 // Check to see if this is an unsigned division with an exact power of 2,
1869 // if so, convert to a right shift.
1870 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
1871 if (uint64_t Val = C->getValue()) // Don't break X / 0
Chris Lattner22d00a82005-08-02 19:16:58 +00001872 if (isPowerOf2_64(Val)) {
1873 uint64_t C = Log2_64(Val);
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001874 return new ShiftInst(Instruction::Shr, Op0,
Chris Lattner3082c5a2003-02-18 19:28:33 +00001875 ConstantUInt::get(Type::UByteTy, C));
Chris Lattner22d00a82005-08-02 19:16:58 +00001876 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001877
Chris Lattner4ad08352004-10-09 02:50:40 +00001878 // -X/C -> X/-C
1879 if (RHS->getType()->isSigned())
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001880 if (Value *LHSNeg = dyn_castNegVal(Op0))
Chris Lattner4ad08352004-10-09 02:50:40 +00001881 return BinaryOperator::createDiv(LHSNeg, ConstantExpr::getNeg(RHS));
1882
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001883 if (!RHS->isNullValue()) {
1884 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00001885 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001886 return R;
1887 if (isa<PHINode>(Op0))
1888 if (Instruction *NV = FoldOpIntoPhi(I))
1889 return NV;
1890 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00001891 }
1892
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001893 // If this is 'udiv X, (Cond ? C1, C2)' where C1&C2 are powers of two,
1894 // transform this into: '(Cond ? (udiv X, C1) : (udiv X, C2))'.
1895 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1896 if (ConstantUInt *STO = dyn_cast<ConstantUInt>(SI->getOperand(1)))
1897 if (ConstantUInt *SFO = dyn_cast<ConstantUInt>(SI->getOperand(2))) {
1898 if (STO->getValue() == 0) { // Couldn't be this argument.
1899 I.setOperand(1, SFO);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001900 return &I;
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001901 } else if (SFO->getValue() == 0) {
Chris Lattner89dc4f12005-06-16 04:55:52 +00001902 I.setOperand(1, STO);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001903 return &I;
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001904 }
1905
Chris Lattner42362612005-04-08 04:03:26 +00001906 uint64_t TVA = STO->getValue(), FVA = SFO->getValue();
Chris Lattner22d00a82005-08-02 19:16:58 +00001907 if (isPowerOf2_64(TVA) && isPowerOf2_64(FVA)) {
1908 unsigned TSA = Log2_64(TVA), FSA = Log2_64(FVA);
Chris Lattner42362612005-04-08 04:03:26 +00001909 Constant *TC = ConstantUInt::get(Type::UByteTy, TSA);
1910 Instruction *TSI = new ShiftInst(Instruction::Shr, Op0,
1911 TC, SI->getName()+".t");
1912 TSI = InsertNewInstBefore(TSI, I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001913
Chris Lattner42362612005-04-08 04:03:26 +00001914 Constant *FC = ConstantUInt::get(Type::UByteTy, FSA);
1915 Instruction *FSI = new ShiftInst(Instruction::Shr, Op0,
1916 FC, SI->getName()+".f");
1917 FSI = InsertNewInstBefore(FSI, I);
1918 return new SelectInst(SI->getOperand(0), TSI, FSI);
1919 }
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001920 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001921
Chris Lattner3082c5a2003-02-18 19:28:33 +00001922 // 0 / X == 0, we don't need to preserve faults!
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001923 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattner3082c5a2003-02-18 19:28:33 +00001924 if (LHS->equalsInt(0))
1925 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1926
Chris Lattnerdd0c1742005-11-05 07:40:31 +00001927 if (I.getType()->isSigned()) {
Chris Lattnerc3ebf402006-02-07 07:27:52 +00001928 // If the sign bits of both operands are zero (i.e. we can prove they are
Chris Lattnerdd0c1742005-11-05 07:40:31 +00001929 // unsigned inputs), turn this into a udiv.
Chris Lattnerc3ebf402006-02-07 07:27:52 +00001930 uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
1931 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
Chris Lattnerdd0c1742005-11-05 07:40:31 +00001932 const Type *NTy = Op0->getType()->getUnsignedVersion();
1933 Instruction *LHS = new CastInst(Op0, NTy, Op0->getName());
1934 InsertNewInstBefore(LHS, I);
1935 Value *RHS;
1936 if (Constant *R = dyn_cast<Constant>(Op1))
1937 RHS = ConstantExpr::getCast(R, NTy);
1938 else
1939 RHS = InsertNewInstBefore(new CastInst(Op1, NTy, Op1->getName()), I);
1940 Instruction *Div = BinaryOperator::createDiv(LHS, RHS, I.getName());
1941 InsertNewInstBefore(Div, I);
1942 return new CastInst(Div, I.getType());
1943 }
Chris Lattner2e90b732006-02-05 07:54:04 +00001944 } else {
1945 // Known to be an unsigned division.
1946 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
1947 // Turn A / (C1 << N), where C1 is "1<<C2" into A >> (N+C2) [udiv only].
1948 if (RHSI->getOpcode() == Instruction::Shl &&
1949 isa<ConstantUInt>(RHSI->getOperand(0))) {
1950 unsigned C1 = cast<ConstantUInt>(RHSI->getOperand(0))->getRawValue();
1951 if (isPowerOf2_64(C1)) {
1952 unsigned C2 = Log2_64(C1);
1953 Value *Add = RHSI->getOperand(1);
1954 if (C2) {
1955 Constant *C2V = ConstantUInt::get(Add->getType(), C2);
1956 Add = InsertNewInstBefore(BinaryOperator::createAdd(Add, C2V,
1957 "tmp"), I);
1958 }
1959 return new ShiftInst(Instruction::Shr, Op0, Add);
1960 }
1961 }
1962 }
Chris Lattnerdd0c1742005-11-05 07:40:31 +00001963 }
1964
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001965 return 0;
1966}
1967
1968
Chris Lattner85dda9a2006-03-02 06:50:58 +00001969/// GetFactor - If we can prove that the specified value is at least a multiple
1970/// of some factor, return that factor.
1971static Constant *GetFactor(Value *V) {
1972 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
1973 return CI;
1974
1975 // Unless we can be tricky, we know this is a multiple of 1.
1976 Constant *Result = ConstantInt::get(V->getType(), 1);
1977
1978 Instruction *I = dyn_cast<Instruction>(V);
1979 if (!I) return Result;
1980
1981 if (I->getOpcode() == Instruction::Mul) {
1982 // Handle multiplies by a constant, etc.
1983 return ConstantExpr::getMul(GetFactor(I->getOperand(0)),
1984 GetFactor(I->getOperand(1)));
1985 } else if (I->getOpcode() == Instruction::Shl) {
1986 // (X<<C) -> X * (1 << C)
1987 if (Constant *ShRHS = dyn_cast<Constant>(I->getOperand(1))) {
1988 ShRHS = ConstantExpr::getShl(Result, ShRHS);
1989 return ConstantExpr::getMul(GetFactor(I->getOperand(0)), ShRHS);
1990 }
1991 } else if (I->getOpcode() == Instruction::And) {
1992 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1993 // X & 0xFFF0 is known to be a multiple of 16.
1994 unsigned Zeros = CountTrailingZeros_64(RHS->getZExtValue());
1995 if (Zeros != V->getType()->getPrimitiveSizeInBits())
1996 return ConstantExpr::getShl(Result,
1997 ConstantUInt::get(Type::UByteTy, Zeros));
1998 }
1999 } else if (I->getOpcode() == Instruction::Cast) {
2000 Value *Op = I->getOperand(0);
2001 // Only handle int->int casts.
2002 if (!Op->getType()->isInteger()) return Result;
2003 return ConstantExpr::getCast(GetFactor(Op), V->getType());
2004 }
2005 return Result;
2006}
2007
Chris Lattner113f4f42002-06-25 16:13:24 +00002008Instruction *InstCombiner::visitRem(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002009 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner0de4a8d2006-02-28 05:30:45 +00002010
2011 // 0 % X == 0, we don't need to preserve faults!
2012 if (Constant *LHS = dyn_cast<Constant>(Op0))
2013 if (LHS->isNullValue())
2014 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2015
2016 if (isa<UndefValue>(Op0)) // undef % X -> 0
2017 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2018 if (isa<UndefValue>(Op1))
2019 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
2020
Chris Lattnere9ff0ea2005-11-05 07:28:37 +00002021 if (I.getType()->isSigned()) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002022 if (Value *RHSNeg = dyn_castNegVal(Op1))
Chris Lattner98c6bdf2004-07-06 07:11:42 +00002023 if (!isa<ConstantSInt>(RHSNeg) ||
Chris Lattner8e726062004-08-09 21:05:48 +00002024 cast<ConstantSInt>(RHSNeg)->getValue() > 0) {
Chris Lattner7fd5f072004-07-06 07:01:22 +00002025 // X % -Y -> X % Y
2026 AddUsesToWorkList(I);
2027 I.setOperand(1, RHSNeg);
2028 return &I;
2029 }
Chris Lattnere9ff0ea2005-11-05 07:28:37 +00002030
2031 // If the top bits of both operands are zero (i.e. we can prove they are
2032 // unsigned inputs), turn this into a urem.
Chris Lattnerc3ebf402006-02-07 07:27:52 +00002033 uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
2034 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
Chris Lattnere9ff0ea2005-11-05 07:28:37 +00002035 const Type *NTy = Op0->getType()->getUnsignedVersion();
2036 Instruction *LHS = new CastInst(Op0, NTy, Op0->getName());
2037 InsertNewInstBefore(LHS, I);
2038 Value *RHS;
2039 if (Constant *R = dyn_cast<Constant>(Op1))
2040 RHS = ConstantExpr::getCast(R, NTy);
2041 else
2042 RHS = InsertNewInstBefore(new CastInst(Op1, NTy, Op1->getName()), I);
2043 Instruction *Rem = BinaryOperator::createRem(LHS, RHS, I.getName());
2044 InsertNewInstBefore(Rem, I);
2045 return new CastInst(Rem, I.getType());
2046 }
2047 }
Chris Lattner7fd5f072004-07-06 07:01:22 +00002048
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002049 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner0de4a8d2006-02-28 05:30:45 +00002050 // X % 0 == undef, we don't need to preserve faults!
2051 if (RHS->equalsInt(0))
2052 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2053
Chris Lattner3082c5a2003-02-18 19:28:33 +00002054 if (RHS->equalsInt(1)) // X % 1 == 0
2055 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2056
2057 // Check to see if this is an unsigned remainder with an exact power of 2,
2058 // if so, convert to a bitwise and.
2059 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
Chris Lattner0de4a8d2006-02-28 05:30:45 +00002060 if (isPowerOf2_64(C->getValue()))
2061 return BinaryOperator::createAnd(Op0, SubOne(C));
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002062
Chris Lattnerb70f1412006-02-28 05:49:21 +00002063 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2064 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2065 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2066 return R;
2067 } else if (isa<PHINode>(Op0I)) {
2068 if (Instruction *NV = FoldOpIntoPhi(I))
2069 return NV;
Chris Lattnerb70f1412006-02-28 05:49:21 +00002070 }
Chris Lattner85dda9a2006-03-02 06:50:58 +00002071
2072 // X*C1%C2 --> 0 iff C1%C2 == 0
2073 if (ConstantExpr::getRem(GetFactor(Op0I), RHS)->isNullValue())
2074 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerb70f1412006-02-28 05:49:21 +00002075 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00002076 }
2077
Chris Lattner2e90b732006-02-05 07:54:04 +00002078 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
2079 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1) [urem only].
2080 if (I.getType()->isUnsigned() &&
2081 RHSI->getOpcode() == Instruction::Shl &&
2082 isa<ConstantUInt>(RHSI->getOperand(0))) {
2083 unsigned C1 = cast<ConstantUInt>(RHSI->getOperand(0))->getRawValue();
2084 if (isPowerOf2_64(C1)) {
2085 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
2086 Value *Add = InsertNewInstBefore(BinaryOperator::createAdd(RHSI, N1,
2087 "tmp"), I);
2088 return BinaryOperator::createAnd(Op0, Add);
2089 }
2090 }
Chris Lattner0de4a8d2006-02-28 05:30:45 +00002091
2092 // If this is 'urem X, (Cond ? C1, C2)' where C1&C2 are powers of two,
2093 // transform this into: '(Cond ? (urem X, C1) : (urem X, C2))'.
2094 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2095 if (ConstantUInt *STO = dyn_cast<ConstantUInt>(SI->getOperand(1)))
2096 if (ConstantUInt *SFO = dyn_cast<ConstantUInt>(SI->getOperand(2))) {
2097 if (STO->getValue() == 0) { // Couldn't be this argument.
2098 I.setOperand(1, SFO);
2099 return &I;
2100 } else if (SFO->getValue() == 0) {
2101 I.setOperand(1, STO);
2102 return &I;
2103 }
2104
2105 if (isPowerOf2_64(STO->getValue()) && isPowerOf2_64(SFO->getValue())){
2106 Value *TrueAnd = InsertNewInstBefore(BinaryOperator::createAnd(Op0,
2107 SubOne(STO), SI->getName()+".t"), I);
2108 Value *FalseAnd = InsertNewInstBefore(BinaryOperator::createAnd(Op0,
2109 SubOne(SFO), SI->getName()+".f"), I);
2110 return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
2111 }
2112 }
Chris Lattner2e90b732006-02-05 07:54:04 +00002113 }
2114
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002115 return 0;
2116}
2117
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002118// isMaxValueMinusOne - return true if this is Max-1
Chris Lattnere6794492002-08-12 21:17:25 +00002119static bool isMaxValueMinusOne(const ConstantInt *C) {
Chris Lattner77defba2006-02-07 07:00:41 +00002120 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
2121 return CU->getValue() == C->getType()->getIntegralTypeMask()-1;
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002122
2123 const ConstantSInt *CS = cast<ConstantSInt>(C);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002124
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002125 // Calculate 0111111111..11111
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002126 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002127 int64_t Val = INT64_MAX; // All ones
2128 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
2129 return CS->getValue() == Val-1;
2130}
2131
2132// isMinValuePlusOne - return true if this is Min+1
Chris Lattnere6794492002-08-12 21:17:25 +00002133static bool isMinValuePlusOne(const ConstantInt *C) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002134 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
2135 return CU->getValue() == 1;
2136
2137 const ConstantSInt *CS = cast<ConstantSInt>(C);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002138
2139 // Calculate 1111111111000000000000
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002140 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002141 int64_t Val = -1; // All ones
2142 Val <<= TypeBits-1; // Shift over to the right spot
2143 return CS->getValue() == Val+1;
2144}
2145
Chris Lattner35167c32004-06-09 07:59:58 +00002146// isOneBitSet - Return true if there is exactly one bit set in the specified
2147// constant.
2148static bool isOneBitSet(const ConstantInt *CI) {
2149 uint64_t V = CI->getRawValue();
2150 return V && (V & (V-1)) == 0;
2151}
2152
Chris Lattner8fc5af42004-09-23 21:46:38 +00002153#if 0 // Currently unused
2154// isLowOnes - Return true if the constant is of the form 0+1+.
2155static bool isLowOnes(const ConstantInt *CI) {
2156 uint64_t V = CI->getRawValue();
2157
2158 // There won't be bits set in parts that the type doesn't contain.
2159 V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
2160
2161 uint64_t U = V+1; // If it is low ones, this should be a power of two.
2162 return U && V && (U & V) == 0;
2163}
2164#endif
2165
2166// isHighOnes - Return true if the constant is of the form 1+0+.
2167// This is the same as lowones(~X).
2168static bool isHighOnes(const ConstantInt *CI) {
2169 uint64_t V = ~CI->getRawValue();
Chris Lattner2c14cf72005-08-07 07:03:10 +00002170 if (~V == 0) return false; // 0's does not match "1+"
Chris Lattner8fc5af42004-09-23 21:46:38 +00002171
2172 // There won't be bits set in parts that the type doesn't contain.
2173 V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
2174
2175 uint64_t U = V+1; // If it is low ones, this should be a power of two.
2176 return U && V && (U & V) == 0;
2177}
2178
2179
Chris Lattner3ac7c262003-08-13 20:16:26 +00002180/// getSetCondCode - Encode a setcc opcode into a three bit mask. These bits
2181/// are carefully arranged to allow folding of expressions such as:
2182///
2183/// (A < B) | (A > B) --> (A != B)
2184///
2185/// Bit value '4' represents that the comparison is true if A > B, bit value '2'
2186/// represents that the comparison is true if A == B, and bit value '1' is true
2187/// if A < B.
2188///
2189static unsigned getSetCondCode(const SetCondInst *SCI) {
2190 switch (SCI->getOpcode()) {
2191 // False -> 0
2192 case Instruction::SetGT: return 1;
2193 case Instruction::SetEQ: return 2;
2194 case Instruction::SetGE: return 3;
2195 case Instruction::SetLT: return 4;
2196 case Instruction::SetNE: return 5;
2197 case Instruction::SetLE: return 6;
2198 // True -> 7
2199 default:
2200 assert(0 && "Invalid SetCC opcode!");
2201 return 0;
2202 }
2203}
2204
2205/// getSetCCValue - This is the complement of getSetCondCode, which turns an
2206/// opcode and two operands into either a constant true or false, or a brand new
2207/// SetCC instruction.
2208static Value *getSetCCValue(unsigned Opcode, Value *LHS, Value *RHS) {
2209 switch (Opcode) {
2210 case 0: return ConstantBool::False;
2211 case 1: return new SetCondInst(Instruction::SetGT, LHS, RHS);
2212 case 2: return new SetCondInst(Instruction::SetEQ, LHS, RHS);
2213 case 3: return new SetCondInst(Instruction::SetGE, LHS, RHS);
2214 case 4: return new SetCondInst(Instruction::SetLT, LHS, RHS);
2215 case 5: return new SetCondInst(Instruction::SetNE, LHS, RHS);
2216 case 6: return new SetCondInst(Instruction::SetLE, LHS, RHS);
2217 case 7: return ConstantBool::True;
2218 default: assert(0 && "Illegal SetCCCode!"); return 0;
2219 }
2220}
2221
2222// FoldSetCCLogical - Implements (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
2223struct FoldSetCCLogical {
2224 InstCombiner &IC;
2225 Value *LHS, *RHS;
2226 FoldSetCCLogical(InstCombiner &ic, SetCondInst *SCI)
2227 : IC(ic), LHS(SCI->getOperand(0)), RHS(SCI->getOperand(1)) {}
2228 bool shouldApply(Value *V) const {
2229 if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
2230 return (SCI->getOperand(0) == LHS && SCI->getOperand(1) == RHS ||
2231 SCI->getOperand(0) == RHS && SCI->getOperand(1) == LHS);
2232 return false;
2233 }
2234 Instruction *apply(BinaryOperator &Log) const {
2235 SetCondInst *SCI = cast<SetCondInst>(Log.getOperand(0));
2236 if (SCI->getOperand(0) != LHS) {
2237 assert(SCI->getOperand(1) == LHS);
2238 SCI->swapOperands(); // Swap the LHS and RHS of the SetCC
2239 }
2240
2241 unsigned LHSCode = getSetCondCode(SCI);
2242 unsigned RHSCode = getSetCondCode(cast<SetCondInst>(Log.getOperand(1)));
2243 unsigned Code;
2244 switch (Log.getOpcode()) {
2245 case Instruction::And: Code = LHSCode & RHSCode; break;
2246 case Instruction::Or: Code = LHSCode | RHSCode; break;
2247 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner2caaaba2003-09-22 20:33:34 +00002248 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattner3ac7c262003-08-13 20:16:26 +00002249 }
2250
2251 Value *RV = getSetCCValue(Code, LHS, RHS);
2252 if (Instruction *I = dyn_cast<Instruction>(RV))
2253 return I;
2254 // Otherwise, it's a constant boolean value...
2255 return IC.ReplaceInstUsesWith(Log, RV);
2256 }
2257};
2258
Chris Lattnerba1cb382003-09-19 17:17:26 +00002259// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
2260// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
2261// guaranteed to be either a shift instruction or a binary operator.
2262Instruction *InstCombiner::OptAndOp(Instruction *Op,
2263 ConstantIntegral *OpRHS,
2264 ConstantIntegral *AndRHS,
2265 BinaryOperator &TheAnd) {
2266 Value *X = Op->getOperand(0);
Chris Lattnerfcf21a72004-01-12 19:47:05 +00002267 Constant *Together = 0;
2268 if (!isa<ShiftInst>(Op))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002269 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002270
Chris Lattnerba1cb382003-09-19 17:17:26 +00002271 switch (Op->getOpcode()) {
2272 case Instruction::Xor:
Chris Lattner86102b82005-01-01 16:22:27 +00002273 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00002274 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
2275 std::string OpName = Op->getName(); Op->setName("");
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002276 Instruction *And = BinaryOperator::createAnd(X, AndRHS, OpName);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002277 InsertNewInstBefore(And, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002278 return BinaryOperator::createXor(And, Together);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002279 }
2280 break;
2281 case Instruction::Or:
Chris Lattner86102b82005-01-01 16:22:27 +00002282 if (Together == AndRHS) // (X | C) & C --> C
2283 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002284
Chris Lattner86102b82005-01-01 16:22:27 +00002285 if (Op->hasOneUse() && Together != OpRHS) {
2286 // (X | C1) & C2 --> (X | (C1&C2)) & C2
2287 std::string Op0Name = Op->getName(); Op->setName("");
2288 Instruction *Or = BinaryOperator::createOr(X, Together, Op0Name);
2289 InsertNewInstBefore(Or, TheAnd);
2290 return BinaryOperator::createAnd(Or, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002291 }
2292 break;
2293 case Instruction::Add:
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002294 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00002295 // Adding a one to a single bit bit-field should be turned into an XOR
2296 // of the bit. First thing to check is to see if this AND is with a
2297 // single bit constant.
Chris Lattner35167c32004-06-09 07:59:58 +00002298 uint64_t AndRHSV = cast<ConstantInt>(AndRHS)->getRawValue();
Chris Lattnerba1cb382003-09-19 17:17:26 +00002299
2300 // Clear bits that are not part of the constant.
Chris Lattner77defba2006-02-07 07:00:41 +00002301 AndRHSV &= AndRHS->getType()->getIntegralTypeMask();
Chris Lattnerba1cb382003-09-19 17:17:26 +00002302
2303 // If there is only one bit set...
Chris Lattner35167c32004-06-09 07:59:58 +00002304 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00002305 // Ok, at this point, we know that we are masking the result of the
2306 // ADD down to exactly one bit. If the constant we are adding has
2307 // no bits set below this bit, then we can eliminate the ADD.
Chris Lattner35167c32004-06-09 07:59:58 +00002308 uint64_t AddRHS = cast<ConstantInt>(OpRHS)->getRawValue();
Misha Brukmanb1c93172005-04-21 23:48:37 +00002309
Chris Lattnerba1cb382003-09-19 17:17:26 +00002310 // Check to see if any bits below the one bit set in AndRHSV are set.
2311 if ((AddRHS & (AndRHSV-1)) == 0) {
2312 // If not, the only thing that can effect the output of the AND is
2313 // the bit specified by AndRHSV. If that bit is set, the effect of
2314 // the XOR is to toggle the bit. If it is clear, then the ADD has
2315 // no effect.
2316 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
2317 TheAnd.setOperand(0, X);
2318 return &TheAnd;
2319 } else {
2320 std::string Name = Op->getName(); Op->setName("");
2321 // Pull the XOR out of the AND.
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002322 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS, Name);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002323 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002324 return BinaryOperator::createXor(NewAnd, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002325 }
2326 }
2327 }
2328 }
2329 break;
Chris Lattner2da29172003-09-19 19:05:02 +00002330
2331 case Instruction::Shl: {
2332 // We know that the AND will not produce any of the bits shifted in, so if
2333 // the anded constant includes them, clear them now!
2334 //
2335 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner7e794272004-09-24 15:21:34 +00002336 Constant *ShlMask = ConstantExpr::getShl(AllOne, OpRHS);
2337 Constant *CI = ConstantExpr::getAnd(AndRHS, ShlMask);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002338
Chris Lattner7e794272004-09-24 15:21:34 +00002339 if (CI == ShlMask) { // Masking out bits that the shift already masks
2340 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
2341 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner2da29172003-09-19 19:05:02 +00002342 TheAnd.setOperand(1, CI);
2343 return &TheAnd;
2344 }
2345 break;
Misha Brukmanb1c93172005-04-21 23:48:37 +00002346 }
Chris Lattner2da29172003-09-19 19:05:02 +00002347 case Instruction::Shr:
2348 // We know that the AND will not produce any of the bits shifted in, so if
2349 // the anded constant includes them, clear them now! This only applies to
2350 // unsigned shifts, because a signed shr may bring in set bits!
2351 //
2352 if (AndRHS->getType()->isUnsigned()) {
2353 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner7e794272004-09-24 15:21:34 +00002354 Constant *ShrMask = ConstantExpr::getShr(AllOne, OpRHS);
2355 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
2356
2357 if (CI == ShrMask) { // Masking out bits that the shift already masks.
2358 return ReplaceInstUsesWith(TheAnd, Op);
2359 } else if (CI != AndRHS) {
2360 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
Chris Lattner2da29172003-09-19 19:05:02 +00002361 return &TheAnd;
2362 }
Chris Lattner7e794272004-09-24 15:21:34 +00002363 } else { // Signed shr.
2364 // See if this is shifting in some sign extension, then masking it out
2365 // with an and.
2366 if (Op->hasOneUse()) {
2367 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
2368 Constant *ShrMask = ConstantExpr::getUShr(AllOne, OpRHS);
2369 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
Chris Lattner5c3c21e2004-10-22 04:53:16 +00002370 if (CI == AndRHS) { // Masking out bits shifted in.
Chris Lattner7e794272004-09-24 15:21:34 +00002371 // Make the argument unsigned.
2372 Value *ShVal = Op->getOperand(0);
2373 ShVal = InsertCastBefore(ShVal,
2374 ShVal->getType()->getUnsignedVersion(),
2375 TheAnd);
2376 ShVal = InsertNewInstBefore(new ShiftInst(Instruction::Shr, ShVal,
2377 OpRHS, Op->getName()),
2378 TheAnd);
Chris Lattner70c20392004-10-27 05:57:15 +00002379 Value *AndRHS2 = ConstantExpr::getCast(AndRHS, ShVal->getType());
2380 ShVal = InsertNewInstBefore(BinaryOperator::createAnd(ShVal, AndRHS2,
2381 TheAnd.getName()),
2382 TheAnd);
Chris Lattner7e794272004-09-24 15:21:34 +00002383 return new CastInst(ShVal, Op->getType());
2384 }
2385 }
Chris Lattner2da29172003-09-19 19:05:02 +00002386 }
2387 break;
Chris Lattnerba1cb382003-09-19 17:17:26 +00002388 }
2389 return 0;
2390}
2391
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002392
Chris Lattner6862fbd2004-09-29 17:40:11 +00002393/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
2394/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
2395/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. IB is the location to
2396/// insert new instructions.
2397Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
2398 bool Inside, Instruction &IB) {
2399 assert(cast<ConstantBool>(ConstantExpr::getSetLE(Lo, Hi))->getValue() &&
2400 "Lo is not <= Hi in range emission code!");
2401 if (Inside) {
2402 if (Lo == Hi) // Trivially false.
2403 return new SetCondInst(Instruction::SetNE, V, V);
2404 if (cast<ConstantIntegral>(Lo)->isMinValue())
2405 return new SetCondInst(Instruction::SetLT, V, Hi);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002406
Chris Lattner6862fbd2004-09-29 17:40:11 +00002407 Constant *AddCST = ConstantExpr::getNeg(Lo);
2408 Instruction *Add = BinaryOperator::createAdd(V, AddCST,V->getName()+".off");
2409 InsertNewInstBefore(Add, IB);
2410 // Convert to unsigned for the comparison.
2411 const Type *UnsType = Add->getType()->getUnsignedVersion();
2412 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
2413 AddCST = ConstantExpr::getAdd(AddCST, Hi);
2414 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2415 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
2416 }
2417
2418 if (Lo == Hi) // Trivially true.
2419 return new SetCondInst(Instruction::SetEQ, V, V);
2420
2421 Hi = SubOne(cast<ConstantInt>(Hi));
2422 if (cast<ConstantIntegral>(Lo)->isMinValue()) // V < 0 || V >= Hi ->'V > Hi-1'
2423 return new SetCondInst(Instruction::SetGT, V, Hi);
2424
2425 // Emit X-Lo > Hi-Lo-1
2426 Constant *AddCST = ConstantExpr::getNeg(Lo);
2427 Instruction *Add = BinaryOperator::createAdd(V, AddCST, V->getName()+".off");
2428 InsertNewInstBefore(Add, IB);
2429 // Convert to unsigned for the comparison.
2430 const Type *UnsType = Add->getType()->getUnsignedVersion();
2431 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
2432 AddCST = ConstantExpr::getAdd(AddCST, Hi);
2433 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2434 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
2435}
2436
Chris Lattnerb4b25302005-09-18 07:22:02 +00002437// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
2438// any number of 0s on either side. The 1s are allowed to wrap from LSB to
2439// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
2440// not, since all 1s are not contiguous.
2441static bool isRunOfOnes(ConstantIntegral *Val, unsigned &MB, unsigned &ME) {
2442 uint64_t V = Val->getRawValue();
2443 if (!isShiftedMask_64(V)) return false;
2444
2445 // look for the first zero bit after the run of ones
2446 MB = 64-CountLeadingZeros_64((V - 1) ^ V);
2447 // look for the first non-zero bit
2448 ME = 64-CountLeadingZeros_64(V);
2449 return true;
2450}
2451
2452
2453
2454/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
2455/// where isSub determines whether the operator is a sub. If we can fold one of
2456/// the following xforms:
Chris Lattneraf517572005-09-18 04:24:45 +00002457///
2458/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
2459/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
2460/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
2461///
2462/// return (A +/- B).
2463///
2464Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
2465 ConstantIntegral *Mask, bool isSub,
2466 Instruction &I) {
2467 Instruction *LHSI = dyn_cast<Instruction>(LHS);
2468 if (!LHSI || LHSI->getNumOperands() != 2 ||
2469 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
2470
2471 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
2472
2473 switch (LHSI->getOpcode()) {
2474 default: return 0;
2475 case Instruction::And:
Chris Lattnerb4b25302005-09-18 07:22:02 +00002476 if (ConstantExpr::getAnd(N, Mask) == Mask) {
2477 // If the AndRHS is a power of two minus one (0+1+), this is simple.
2478 if ((Mask->getRawValue() & Mask->getRawValue()+1) == 0)
2479 break;
2480
2481 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
2482 // part, we don't need any explicit masks to take them out of A. If that
2483 // is all N is, ignore it.
2484 unsigned MB, ME;
2485 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Chris Lattnerc3ebf402006-02-07 07:27:52 +00002486 uint64_t Mask = RHS->getType()->getIntegralTypeMask();
2487 Mask >>= 64-MB+1;
2488 if (MaskedValueIsZero(RHS, Mask))
Chris Lattnerb4b25302005-09-18 07:22:02 +00002489 break;
2490 }
2491 }
Chris Lattneraf517572005-09-18 04:24:45 +00002492 return 0;
2493 case Instruction::Or:
2494 case Instruction::Xor:
Chris Lattnerb4b25302005-09-18 07:22:02 +00002495 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
2496 if ((Mask->getRawValue() & Mask->getRawValue()+1) == 0 &&
2497 ConstantExpr::getAnd(N, Mask)->isNullValue())
Chris Lattneraf517572005-09-18 04:24:45 +00002498 break;
2499 return 0;
2500 }
2501
2502 Instruction *New;
2503 if (isSub)
2504 New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
2505 else
2506 New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
2507 return InsertNewInstBefore(New, I);
2508}
2509
Chris Lattner113f4f42002-06-25 16:13:24 +00002510Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00002511 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00002512 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002513
Chris Lattner81a7a232004-10-16 18:11:37 +00002514 if (isa<UndefValue>(Op1)) // X & undef -> 0
2515 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2516
Chris Lattner86102b82005-01-01 16:22:27 +00002517 // and X, X = X
2518 if (Op0 == Op1)
Chris Lattnere6794492002-08-12 21:17:25 +00002519 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002520
Chris Lattner5b2edb12006-02-12 08:02:11 +00002521 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner5997cf92006-02-08 03:25:32 +00002522 // purpose is to compute bits we don't care about.
Chris Lattner0157e7f2006-02-11 09:31:47 +00002523 uint64_t KnownZero, KnownOne;
Chris Lattnerd70d9f52006-03-25 21:58:26 +00002524 if (!isa<PackedType>(I.getType()) &&
2525 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
Chris Lattner0157e7f2006-02-11 09:31:47 +00002526 KnownZero, KnownOne))
Chris Lattner5997cf92006-02-08 03:25:32 +00002527 return &I;
2528
Chris Lattner86102b82005-01-01 16:22:27 +00002529 if (ConstantIntegral *AndRHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00002530 uint64_t AndRHSMask = AndRHS->getZExtValue();
2531 uint64_t TypeMask = Op0->getType()->getIntegralTypeMask();
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00002532 uint64_t NotAndRHS = AndRHSMask^TypeMask;
Chris Lattner86102b82005-01-01 16:22:27 +00002533
Chris Lattnerba1cb382003-09-19 17:17:26 +00002534 // Optimize a variety of ((val OP C1) & C2) combinations...
2535 if (isa<BinaryOperator>(Op0) || isa<ShiftInst>(Op0)) {
2536 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner86102b82005-01-01 16:22:27 +00002537 Value *Op0LHS = Op0I->getOperand(0);
2538 Value *Op0RHS = Op0I->getOperand(1);
2539 switch (Op0I->getOpcode()) {
2540 case Instruction::Xor:
2541 case Instruction::Or:
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00002542 // If the mask is only needed on one incoming arm, push it up.
2543 if (Op0I->hasOneUse()) {
2544 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
2545 // Not masking anything out for the LHS, move to RHS.
2546 Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
2547 Op0RHS->getName()+".masked");
2548 InsertNewInstBefore(NewRHS, I);
2549 return BinaryOperator::create(
2550 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002551 }
Chris Lattnerc3ebf402006-02-07 07:27:52 +00002552 if (!isa<Constant>(Op0RHS) &&
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00002553 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
2554 // Not masking anything out for the RHS, move to LHS.
2555 Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
2556 Op0LHS->getName()+".masked");
2557 InsertNewInstBefore(NewLHS, I);
2558 return BinaryOperator::create(
2559 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
2560 }
2561 }
2562
Chris Lattner86102b82005-01-01 16:22:27 +00002563 break;
Chris Lattneraf517572005-09-18 04:24:45 +00002564 case Instruction::Add:
Chris Lattnerb4b25302005-09-18 07:22:02 +00002565 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
2566 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
2567 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
2568 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
2569 return BinaryOperator::createAnd(V, AndRHS);
2570 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
2571 return BinaryOperator::createAnd(V, AndRHS); // Add commutes
Chris Lattneraf517572005-09-18 04:24:45 +00002572 break;
2573
2574 case Instruction::Sub:
Chris Lattnerb4b25302005-09-18 07:22:02 +00002575 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
2576 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
2577 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
2578 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
2579 return BinaryOperator::createAnd(V, AndRHS);
Chris Lattneraf517572005-09-18 04:24:45 +00002580 break;
Chris Lattner86102b82005-01-01 16:22:27 +00002581 }
2582
Chris Lattner16464b32003-07-23 19:25:52 +00002583 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner86102b82005-01-01 16:22:27 +00002584 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerba1cb382003-09-19 17:17:26 +00002585 return Res;
Chris Lattner86102b82005-01-01 16:22:27 +00002586 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
2587 const Type *SrcTy = CI->getOperand(0)->getType();
2588
Chris Lattner2c14cf72005-08-07 07:03:10 +00002589 // If this is an integer truncation or change from signed-to-unsigned, and
2590 // if the source is an and/or with immediate, transform it. This
2591 // frequently occurs for bitfield accesses.
2592 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
2593 if (SrcTy->getPrimitiveSizeInBits() >=
2594 I.getType()->getPrimitiveSizeInBits() &&
2595 CastOp->getNumOperands() == 2)
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00002596 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1)))
Chris Lattner2c14cf72005-08-07 07:03:10 +00002597 if (CastOp->getOpcode() == Instruction::And) {
2598 // Change: and (cast (and X, C1) to T), C2
2599 // into : and (cast X to T), trunc(C1)&C2
2600 // This will folds the two ands together, which may allow other
2601 // simplifications.
2602 Instruction *NewCast =
2603 new CastInst(CastOp->getOperand(0), I.getType(),
2604 CastOp->getName()+".shrunk");
2605 NewCast = InsertNewInstBefore(NewCast, I);
2606
2607 Constant *C3=ConstantExpr::getCast(AndCI, I.getType());//trunc(C1)
2608 C3 = ConstantExpr::getAnd(C3, AndRHS); // trunc(C1)&C2
2609 return BinaryOperator::createAnd(NewCast, C3);
2610 } else if (CastOp->getOpcode() == Instruction::Or) {
2611 // Change: and (cast (or X, C1) to T), C2
2612 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
2613 Constant *C3=ConstantExpr::getCast(AndCI, I.getType());//trunc(C1)
2614 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
2615 return ReplaceInstUsesWith(I, AndRHS);
2616 }
2617 }
Chris Lattner33217db2003-07-23 19:36:21 +00002618 }
Chris Lattner183b3362004-04-09 19:05:30 +00002619
2620 // Try to fold constant and into select arguments.
2621 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00002622 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00002623 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002624 if (isa<PHINode>(Op0))
2625 if (Instruction *NV = FoldOpIntoPhi(I))
2626 return NV;
Chris Lattner49b47ae2003-07-23 17:57:01 +00002627 }
2628
Chris Lattnerbb74e222003-03-10 23:06:50 +00002629 Value *Op0NotVal = dyn_castNotVal(Op0);
2630 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002631
Chris Lattner023a4832004-06-18 06:07:51 +00002632 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
2633 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2634
Misha Brukman9c003d82004-07-30 12:50:08 +00002635 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattnerbb74e222003-03-10 23:06:50 +00002636 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002637 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
2638 I.getName()+".demorgan");
Chris Lattner49b47ae2003-07-23 17:57:01 +00002639 InsertNewInstBefore(Or, I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002640 return BinaryOperator::createNot(Or);
2641 }
Chris Lattner8b10ab32006-02-13 23:07:23 +00002642
2643 {
2644 Value *A = 0, *B = 0;
2645 ConstantInt *C1 = 0, *C2 = 0;
2646 if (match(Op0, m_Or(m_Value(A), m_Value(B))))
2647 if (A == Op1 || B == Op1) // (A | ?) & A --> A
2648 return ReplaceInstUsesWith(I, Op1);
2649 if (match(Op1, m_Or(m_Value(A), m_Value(B))))
2650 if (A == Op0 || B == Op0) // A & (A | ?) --> A
2651 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerdcd07922006-04-01 08:03:55 +00002652
2653 if (Op0->hasOneUse() &&
2654 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
2655 if (A == Op1) { // (A^B)&A -> A&(A^B)
2656 I.swapOperands(); // Simplify below
2657 std::swap(Op0, Op1);
2658 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
2659 cast<BinaryOperator>(Op0)->swapOperands();
2660 I.swapOperands(); // Simplify below
2661 std::swap(Op0, Op1);
2662 }
2663 }
2664 if (Op1->hasOneUse() &&
2665 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
2666 if (B == Op0) { // B&(A^B) -> B&(B^A)
2667 cast<BinaryOperator>(Op1)->swapOperands();
2668 std::swap(A, B);
2669 }
2670 if (A == Op0) { // A&(A^B) -> A & ~B
2671 Instruction *NotB = BinaryOperator::createNot(B, "tmp");
2672 InsertNewInstBefore(NotB, I);
2673 return BinaryOperator::createAnd(A, NotB);
2674 }
2675 }
Chris Lattner8b10ab32006-02-13 23:07:23 +00002676 }
2677
Chris Lattner3082c5a2003-02-18 19:28:33 +00002678
Chris Lattner623826c2004-09-28 21:48:02 +00002679 if (SetCondInst *RHS = dyn_cast<SetCondInst>(Op1)) {
2680 // (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
Chris Lattner3ac7c262003-08-13 20:16:26 +00002681 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
2682 return R;
2683
Chris Lattner623826c2004-09-28 21:48:02 +00002684 Value *LHSVal, *RHSVal;
2685 ConstantInt *LHSCst, *RHSCst;
2686 Instruction::BinaryOps LHSCC, RHSCC;
2687 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
2688 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
2689 if (LHSVal == RHSVal && // Found (X setcc C1) & (X setcc C2)
2690 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
Misha Brukmanb1c93172005-04-21 23:48:37 +00002691 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
Chris Lattner623826c2004-09-28 21:48:02 +00002692 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
2693 // Ensure that the larger constant is on the RHS.
2694 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
2695 SetCondInst *LHS = cast<SetCondInst>(Op0);
2696 if (cast<ConstantBool>(Cmp)->getValue()) {
2697 std::swap(LHS, RHS);
2698 std::swap(LHSCst, RHSCst);
2699 std::swap(LHSCC, RHSCC);
2700 }
2701
2702 // At this point, we know we have have two setcc instructions
2703 // comparing a value against two constants and and'ing the result
2704 // together. Because of the above check, we know that we only have
2705 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
2706 // FoldSetCCLogical check above), that the two constants are not
2707 // equal.
2708 assert(LHSCst != RHSCst && "Compares not folded above?");
2709
2710 switch (LHSCC) {
2711 default: assert(0 && "Unknown integer condition code!");
2712 case Instruction::SetEQ:
2713 switch (RHSCC) {
2714 default: assert(0 && "Unknown integer condition code!");
2715 case Instruction::SetEQ: // (X == 13 & X == 15) -> false
2716 case Instruction::SetGT: // (X == 13 & X > 15) -> false
2717 return ReplaceInstUsesWith(I, ConstantBool::False);
2718 case Instruction::SetNE: // (X == 13 & X != 15) -> X == 13
2719 case Instruction::SetLT: // (X == 13 & X < 15) -> X == 13
2720 return ReplaceInstUsesWith(I, LHS);
2721 }
2722 case Instruction::SetNE:
2723 switch (RHSCC) {
2724 default: assert(0 && "Unknown integer condition code!");
2725 case Instruction::SetLT:
2726 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X < 14) -> X < 13
2727 return new SetCondInst(Instruction::SetLT, LHSVal, LHSCst);
2728 break; // (X != 13 & X < 15) -> no change
2729 case Instruction::SetEQ: // (X != 13 & X == 15) -> X == 15
2730 case Instruction::SetGT: // (X != 13 & X > 15) -> X > 15
2731 return ReplaceInstUsesWith(I, RHS);
2732 case Instruction::SetNE:
2733 if (LHSCst == SubOne(RHSCst)) {// (X != 13 & X != 14) -> X-13 >u 1
2734 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
2735 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
2736 LHSVal->getName()+".off");
2737 InsertNewInstBefore(Add, I);
2738 const Type *UnsType = Add->getType()->getUnsignedVersion();
2739 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
2740 AddCST = ConstantExpr::getSub(RHSCst, LHSCst);
2741 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2742 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
2743 }
2744 break; // (X != 13 & X != 15) -> no change
2745 }
2746 break;
2747 case Instruction::SetLT:
2748 switch (RHSCC) {
2749 default: assert(0 && "Unknown integer condition code!");
2750 case Instruction::SetEQ: // (X < 13 & X == 15) -> false
2751 case Instruction::SetGT: // (X < 13 & X > 15) -> false
2752 return ReplaceInstUsesWith(I, ConstantBool::False);
2753 case Instruction::SetNE: // (X < 13 & X != 15) -> X < 13
2754 case Instruction::SetLT: // (X < 13 & X < 15) -> X < 13
2755 return ReplaceInstUsesWith(I, LHS);
2756 }
2757 case Instruction::SetGT:
2758 switch (RHSCC) {
2759 default: assert(0 && "Unknown integer condition code!");
2760 case Instruction::SetEQ: // (X > 13 & X == 15) -> X > 13
2761 return ReplaceInstUsesWith(I, LHS);
2762 case Instruction::SetGT: // (X > 13 & X > 15) -> X > 15
2763 return ReplaceInstUsesWith(I, RHS);
2764 case Instruction::SetNE:
2765 if (RHSCst == AddOne(LHSCst)) // (X > 13 & X != 14) -> X > 14
2766 return new SetCondInst(Instruction::SetGT, LHSVal, RHSCst);
2767 break; // (X > 13 & X != 15) -> no change
Chris Lattner6862fbd2004-09-29 17:40:11 +00002768 case Instruction::SetLT: // (X > 13 & X < 15) -> (X-14) <u 1
2769 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true, I);
Chris Lattner623826c2004-09-28 21:48:02 +00002770 }
2771 }
2772 }
2773 }
2774
Chris Lattner3af10532006-05-05 06:39:07 +00002775 // fold (and (cast A), (cast B)) -> (cast (and A, B))
2776 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattnere745c7d2006-05-05 20:51:30 +00002777 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner3af10532006-05-05 06:39:07 +00002778 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Chris Lattnere745c7d2006-05-05 20:51:30 +00002779 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegral() &&
Chris Lattner1d441ad2006-05-06 09:00:16 +00002780 // Only do this if the casts both really cause code to be generated.
2781 ValueRequiresCast(Op0C->getOperand(0), I.getType(), TD) &&
2782 ValueRequiresCast(Op1C->getOperand(0), I.getType(), TD)) {
Chris Lattner3af10532006-05-05 06:39:07 +00002783 Instruction *NewOp = BinaryOperator::createAnd(Op0C->getOperand(0),
2784 Op1C->getOperand(0),
2785 I.getName());
2786 InsertNewInstBefore(NewOp, I);
2787 return new CastInst(NewOp, I.getType());
2788 }
2789 }
2790
Chris Lattner113f4f42002-06-25 16:13:24 +00002791 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002792}
2793
Chris Lattner113f4f42002-06-25 16:13:24 +00002794Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00002795 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00002796 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002797
Chris Lattner81a7a232004-10-16 18:11:37 +00002798 if (isa<UndefValue>(Op1))
2799 return ReplaceInstUsesWith(I, // X | undef -> -1
2800 ConstantIntegral::getAllOnesValue(I.getType()));
2801
Chris Lattner5b2edb12006-02-12 08:02:11 +00002802 // or X, X = X
2803 if (Op0 == Op1)
Chris Lattnere6794492002-08-12 21:17:25 +00002804 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002805
Chris Lattner5b2edb12006-02-12 08:02:11 +00002806 // See if we can simplify any instructions used by the instruction whose sole
2807 // purpose is to compute bits we don't care about.
2808 uint64_t KnownZero, KnownOne;
Chris Lattnerd70d9f52006-03-25 21:58:26 +00002809 if (!isa<PackedType>(I.getType()) &&
2810 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
Chris Lattner5b2edb12006-02-12 08:02:11 +00002811 KnownZero, KnownOne))
2812 return &I;
2813
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002814 // or X, -1 == -1
Chris Lattner8f0d1562003-07-23 18:29:44 +00002815 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner330628a2006-01-06 17:59:59 +00002816 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00002817 // (X & C1) | C2 --> (X | C2) & (C1|C2)
2818 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Chris Lattnerb62f5082005-05-09 04:58:36 +00002819 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0->getName());
2820 Op0->setName("");
Chris Lattnerd4252a72004-07-30 07:50:03 +00002821 InsertNewInstBefore(Or, I);
2822 return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, C1));
2823 }
Chris Lattner8f0d1562003-07-23 18:29:44 +00002824
Chris Lattnerd4252a72004-07-30 07:50:03 +00002825 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
2826 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
2827 std::string Op0Name = Op0->getName(); Op0->setName("");
2828 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
2829 InsertNewInstBefore(Or, I);
2830 return BinaryOperator::createXor(Or,
2831 ConstantExpr::getAnd(C1, ConstantExpr::getNot(RHS)));
Chris Lattner8f0d1562003-07-23 18:29:44 +00002832 }
Chris Lattner183b3362004-04-09 19:05:30 +00002833
2834 // Try to fold constant and into select arguments.
2835 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00002836 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00002837 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002838 if (isa<PHINode>(Op0))
2839 if (Instruction *NV = FoldOpIntoPhi(I))
2840 return NV;
Chris Lattner8f0d1562003-07-23 18:29:44 +00002841 }
2842
Chris Lattner330628a2006-01-06 17:59:59 +00002843 Value *A = 0, *B = 0;
2844 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattner4294cec2005-05-07 23:49:08 +00002845
2846 if (match(Op0, m_And(m_Value(A), m_Value(B))))
2847 if (A == Op1 || B == Op1) // (A & ?) | A --> A
2848 return ReplaceInstUsesWith(I, Op1);
2849 if (match(Op1, m_And(m_Value(A), m_Value(B))))
2850 if (A == Op0 || B == Op0) // A | (A & ?) --> A
2851 return ReplaceInstUsesWith(I, Op0);
2852
Chris Lattnerb62f5082005-05-09 04:58:36 +00002853 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
2854 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattnerc3ebf402006-02-07 07:27:52 +00002855 MaskedValueIsZero(Op1, C1->getZExtValue())) {
Chris Lattnerb62f5082005-05-09 04:58:36 +00002856 Instruction *NOr = BinaryOperator::createOr(A, Op1, Op0->getName());
2857 Op0->setName("");
2858 return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
2859 }
2860
2861 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
2862 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattnerc3ebf402006-02-07 07:27:52 +00002863 MaskedValueIsZero(Op0, C1->getZExtValue())) {
Chris Lattnerb62f5082005-05-09 04:58:36 +00002864 Instruction *NOr = BinaryOperator::createOr(A, Op0, Op1->getName());
2865 Op0->setName("");
2866 return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
2867 }
2868
Chris Lattner15212982005-09-18 03:42:07 +00002869 // (A & C1)|(B & C2)
Chris Lattnerd4252a72004-07-30 07:50:03 +00002870 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattner15212982005-09-18 03:42:07 +00002871 match(Op1, m_And(m_Value(B), m_ConstantInt(C2)))) {
2872
2873 if (A == B) // (A & C1)|(A & C2) == A & (C1|C2)
2874 return BinaryOperator::createAnd(A, ConstantExpr::getOr(C1, C2));
2875
2876
Chris Lattner01f56c62005-09-18 06:02:59 +00002877 // If we have: ((V + N) & C1) | (V & C2)
2878 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
2879 // replace with V+N.
2880 if (C1 == ConstantExpr::getNot(C2)) {
Chris Lattner330628a2006-01-06 17:59:59 +00002881 Value *V1 = 0, *V2 = 0;
Chris Lattner01f56c62005-09-18 06:02:59 +00002882 if ((C2->getRawValue() & (C2->getRawValue()+1)) == 0 && // C2 == 0+1+
2883 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
2884 // Add commutes, try both ways.
Chris Lattnerc3ebf402006-02-07 07:27:52 +00002885 if (V1 == B && MaskedValueIsZero(V2, C2->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00002886 return ReplaceInstUsesWith(I, A);
Chris Lattnerc3ebf402006-02-07 07:27:52 +00002887 if (V2 == B && MaskedValueIsZero(V1, C2->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00002888 return ReplaceInstUsesWith(I, A);
2889 }
2890 // Or commutes, try both ways.
2891 if ((C1->getRawValue() & (C1->getRawValue()+1)) == 0 &&
2892 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
2893 // Add commutes, try both ways.
Chris Lattnerc3ebf402006-02-07 07:27:52 +00002894 if (V1 == A && MaskedValueIsZero(V2, C1->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00002895 return ReplaceInstUsesWith(I, B);
Chris Lattnerc3ebf402006-02-07 07:27:52 +00002896 if (V2 == A && MaskedValueIsZero(V1, C1->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00002897 return ReplaceInstUsesWith(I, B);
Chris Lattner15212982005-09-18 03:42:07 +00002898 }
2899 }
2900 }
Chris Lattner812aab72003-08-12 19:11:07 +00002901
Chris Lattnerd4252a72004-07-30 07:50:03 +00002902 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
2903 if (A == Op1) // ~A | A == -1
Misha Brukmanb1c93172005-04-21 23:48:37 +00002904 return ReplaceInstUsesWith(I,
Chris Lattnerd4252a72004-07-30 07:50:03 +00002905 ConstantIntegral::getAllOnesValue(I.getType()));
2906 } else {
2907 A = 0;
2908 }
Chris Lattner4294cec2005-05-07 23:49:08 +00002909 // Note, A is still live here!
Chris Lattnerd4252a72004-07-30 07:50:03 +00002910 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
2911 if (Op0 == B)
Misha Brukmanb1c93172005-04-21 23:48:37 +00002912 return ReplaceInstUsesWith(I,
Chris Lattnerd4252a72004-07-30 07:50:03 +00002913 ConstantIntegral::getAllOnesValue(I.getType()));
Chris Lattner3e327a42003-03-10 23:13:59 +00002914
Misha Brukman9c003d82004-07-30 12:50:08 +00002915 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattnerd4252a72004-07-30 07:50:03 +00002916 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
2917 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
2918 I.getName()+".demorgan"), I);
2919 return BinaryOperator::createNot(And);
2920 }
Chris Lattner3e327a42003-03-10 23:13:59 +00002921 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00002922
Chris Lattner3ac7c262003-08-13 20:16:26 +00002923 // (setcc1 A, B) | (setcc2 A, B) --> (setcc3 A, B)
Chris Lattnerdcf756e2004-09-28 22:33:08 +00002924 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1))) {
Chris Lattner3ac7c262003-08-13 20:16:26 +00002925 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
2926 return R;
2927
Chris Lattnerdcf756e2004-09-28 22:33:08 +00002928 Value *LHSVal, *RHSVal;
2929 ConstantInt *LHSCst, *RHSCst;
2930 Instruction::BinaryOps LHSCC, RHSCC;
2931 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
2932 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
2933 if (LHSVal == RHSVal && // Found (X setcc C1) | (X setcc C2)
2934 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
Misha Brukmanb1c93172005-04-21 23:48:37 +00002935 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
Chris Lattnerdcf756e2004-09-28 22:33:08 +00002936 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
2937 // Ensure that the larger constant is on the RHS.
2938 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
2939 SetCondInst *LHS = cast<SetCondInst>(Op0);
2940 if (cast<ConstantBool>(Cmp)->getValue()) {
2941 std::swap(LHS, RHS);
2942 std::swap(LHSCst, RHSCst);
2943 std::swap(LHSCC, RHSCC);
2944 }
2945
2946 // At this point, we know we have have two setcc instructions
2947 // comparing a value against two constants and or'ing the result
2948 // together. Because of the above check, we know that we only have
2949 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
2950 // FoldSetCCLogical check above), that the two constants are not
2951 // equal.
2952 assert(LHSCst != RHSCst && "Compares not folded above?");
2953
2954 switch (LHSCC) {
2955 default: assert(0 && "Unknown integer condition code!");
2956 case Instruction::SetEQ:
2957 switch (RHSCC) {
2958 default: assert(0 && "Unknown integer condition code!");
2959 case Instruction::SetEQ:
2960 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
2961 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
2962 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
2963 LHSVal->getName()+".off");
2964 InsertNewInstBefore(Add, I);
2965 const Type *UnsType = Add->getType()->getUnsignedVersion();
2966 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
2967 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
2968 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2969 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
2970 }
2971 break; // (X == 13 | X == 15) -> no change
2972
Chris Lattner5c219462005-04-19 06:04:18 +00002973 case Instruction::SetGT: // (X == 13 | X > 14) -> no change
2974 break;
Chris Lattnerdcf756e2004-09-28 22:33:08 +00002975 case Instruction::SetNE: // (X == 13 | X != 15) -> X != 15
2976 case Instruction::SetLT: // (X == 13 | X < 15) -> X < 15
2977 return ReplaceInstUsesWith(I, RHS);
2978 }
2979 break;
2980 case Instruction::SetNE:
2981 switch (RHSCC) {
2982 default: assert(0 && "Unknown integer condition code!");
Chris Lattnerdcf756e2004-09-28 22:33:08 +00002983 case Instruction::SetEQ: // (X != 13 | X == 15) -> X != 13
2984 case Instruction::SetGT: // (X != 13 | X > 15) -> X != 13
2985 return ReplaceInstUsesWith(I, LHS);
2986 case Instruction::SetNE: // (X != 13 | X != 15) -> true
Chris Lattner2ceb6ee2005-06-17 03:59:17 +00002987 case Instruction::SetLT: // (X != 13 | X < 15) -> true
Chris Lattnerdcf756e2004-09-28 22:33:08 +00002988 return ReplaceInstUsesWith(I, ConstantBool::True);
2989 }
2990 break;
2991 case Instruction::SetLT:
2992 switch (RHSCC) {
2993 default: assert(0 && "Unknown integer condition code!");
2994 case Instruction::SetEQ: // (X < 13 | X == 14) -> no change
2995 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00002996 case Instruction::SetGT: // (X < 13 | X > 15) -> (X-13) > 2
2997 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false, I);
Chris Lattnerdcf756e2004-09-28 22:33:08 +00002998 case Instruction::SetNE: // (X < 13 | X != 15) -> X != 15
2999 case Instruction::SetLT: // (X < 13 | X < 15) -> X < 15
3000 return ReplaceInstUsesWith(I, RHS);
3001 }
3002 break;
3003 case Instruction::SetGT:
3004 switch (RHSCC) {
3005 default: assert(0 && "Unknown integer condition code!");
3006 case Instruction::SetEQ: // (X > 13 | X == 15) -> X > 13
3007 case Instruction::SetGT: // (X > 13 | X > 15) -> X > 13
3008 return ReplaceInstUsesWith(I, LHS);
3009 case Instruction::SetNE: // (X > 13 | X != 15) -> true
3010 case Instruction::SetLT: // (X > 13 | X < 15) -> true
3011 return ReplaceInstUsesWith(I, ConstantBool::True);
3012 }
3013 }
3014 }
3015 }
Chris Lattner3af10532006-05-05 06:39:07 +00003016
3017 // fold (or (cast A), (cast B)) -> (cast (or A, B))
3018 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattnere745c7d2006-05-05 20:51:30 +00003019 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner3af10532006-05-05 06:39:07 +00003020 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Chris Lattnere745c7d2006-05-05 20:51:30 +00003021 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegral() &&
Chris Lattner1d441ad2006-05-06 09:00:16 +00003022 // Only do this if the casts both really cause code to be generated.
3023 ValueRequiresCast(Op0C->getOperand(0), I.getType(), TD) &&
3024 ValueRequiresCast(Op1C->getOperand(0), I.getType(), TD)) {
Chris Lattner3af10532006-05-05 06:39:07 +00003025 Instruction *NewOp = BinaryOperator::createOr(Op0C->getOperand(0),
3026 Op1C->getOperand(0),
3027 I.getName());
3028 InsertNewInstBefore(NewOp, I);
3029 return new CastInst(NewOp, I.getType());
3030 }
3031 }
3032
Chris Lattner15212982005-09-18 03:42:07 +00003033
Chris Lattner113f4f42002-06-25 16:13:24 +00003034 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003035}
3036
Chris Lattnerc2076352004-02-16 01:20:27 +00003037// XorSelf - Implements: X ^ X --> 0
3038struct XorSelf {
3039 Value *RHS;
3040 XorSelf(Value *rhs) : RHS(rhs) {}
3041 bool shouldApply(Value *LHS) const { return LHS == RHS; }
3042 Instruction *apply(BinaryOperator &Xor) const {
3043 return &Xor;
3044 }
3045};
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003046
3047
Chris Lattner113f4f42002-06-25 16:13:24 +00003048Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003049 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00003050 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003051
Chris Lattner81a7a232004-10-16 18:11:37 +00003052 if (isa<UndefValue>(Op1))
3053 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
3054
Chris Lattnerc2076352004-02-16 01:20:27 +00003055 // xor X, X = 0, even if X is nested in a sequence of Xor's.
3056 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
3057 assert(Result == &I && "AssociativeOpt didn't work?");
Chris Lattnere6794492002-08-12 21:17:25 +00003058 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc2076352004-02-16 01:20:27 +00003059 }
Chris Lattner5b2edb12006-02-12 08:02:11 +00003060
3061 // See if we can simplify any instructions used by the instruction whose sole
3062 // purpose is to compute bits we don't care about.
3063 uint64_t KnownZero, KnownOne;
Chris Lattnerd70d9f52006-03-25 21:58:26 +00003064 if (!isa<PackedType>(I.getType()) &&
3065 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
Chris Lattner5b2edb12006-02-12 08:02:11 +00003066 KnownZero, KnownOne))
3067 return &I;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003068
Chris Lattner97638592003-07-23 21:37:07 +00003069 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner97638592003-07-23 21:37:07 +00003070 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerb8d6e402002-08-20 18:24:26 +00003071 // xor (setcc A, B), true = not (setcc A, B) = setncc A, B
Chris Lattner97638592003-07-23 21:37:07 +00003072 if (SetCondInst *SCI = dyn_cast<SetCondInst>(Op0I))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00003073 if (RHS == ConstantBool::True && SCI->hasOneUse())
Chris Lattnerb8d6e402002-08-20 18:24:26 +00003074 return new SetCondInst(SCI->getInverseCondition(),
3075 SCI->getOperand(0), SCI->getOperand(1));
Chris Lattnere5806662003-11-04 23:50:51 +00003076
Chris Lattner8f2f5982003-11-05 01:06:05 +00003077 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003078 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
3079 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003080 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
3081 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003082 ConstantInt::get(I.getType(), 1));
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003083 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003084 }
Chris Lattner023a4832004-06-18 06:07:51 +00003085
3086 // ~(~X & Y) --> (X | ~Y)
3087 if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
3088 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
3089 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
3090 Instruction *NotY =
Misha Brukmanb1c93172005-04-21 23:48:37 +00003091 BinaryOperator::createNot(Op0I->getOperand(1),
Chris Lattner023a4832004-06-18 06:07:51 +00003092 Op0I->getOperand(1)->getName()+".not");
3093 InsertNewInstBefore(NotY, I);
3094 return BinaryOperator::createOr(Op0NotVal, NotY);
3095 }
3096 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003097
Chris Lattner97638592003-07-23 21:37:07 +00003098 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner5b2edb12006-02-12 08:02:11 +00003099 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner0f68fa62003-11-04 23:37:10 +00003100 // ~(X-c) --> (-c-1)-X
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003101 if (RHS->isAllOnesValue()) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003102 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
3103 return BinaryOperator::createSub(
3104 ConstantExpr::getSub(NegOp0CI,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003105 ConstantInt::get(I.getType(), 1)),
Chris Lattner0f68fa62003-11-04 23:37:10 +00003106 Op0I->getOperand(0));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003107 }
Chris Lattnerf78df7c2006-02-26 19:57:54 +00003108 } else if (Op0I->getOpcode() == Instruction::Or) {
3109 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
3110 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getZExtValue())) {
3111 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
3112 // Anything in both C1 and C2 is known to be zero, remove it from
3113 // NewRHS.
3114 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
3115 NewRHS = ConstantExpr::getAnd(NewRHS,
3116 ConstantExpr::getNot(CommonBits));
3117 WorkList.push_back(Op0I);
3118 I.setOperand(0, Op0I->getOperand(0));
3119 I.setOperand(1, NewRHS);
3120 return &I;
3121 }
Chris Lattner97638592003-07-23 21:37:07 +00003122 }
Chris Lattnerb8d6e402002-08-20 18:24:26 +00003123 }
Chris Lattner183b3362004-04-09 19:05:30 +00003124
3125 // Try to fold constant and into select arguments.
3126 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00003127 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00003128 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00003129 if (isa<PHINode>(Op0))
3130 if (Instruction *NV = FoldOpIntoPhi(I))
3131 return NV;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003132 }
3133
Chris Lattnerbb74e222003-03-10 23:06:50 +00003134 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00003135 if (X == Op1)
3136 return ReplaceInstUsesWith(I,
3137 ConstantIntegral::getAllOnesValue(I.getType()));
3138
Chris Lattnerbb74e222003-03-10 23:06:50 +00003139 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00003140 if (X == Op0)
3141 return ReplaceInstUsesWith(I,
3142 ConstantIntegral::getAllOnesValue(I.getType()));
3143
Chris Lattnerdcd07922006-04-01 08:03:55 +00003144 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1))
Chris Lattnerb36d9082004-02-16 03:54:20 +00003145 if (Op1I->getOpcode() == Instruction::Or) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003146 if (Op1I->getOperand(0) == Op0) { // B^(B|A) == (A|B)^B
Chris Lattnerdcd07922006-04-01 08:03:55 +00003147 Op1I->swapOperands();
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003148 I.swapOperands();
3149 std::swap(Op0, Op1);
3150 } else if (Op1I->getOperand(1) == Op0) { // B^(A|B) == (A|B)^B
Chris Lattnerdcd07922006-04-01 08:03:55 +00003151 I.swapOperands(); // Simplified below.
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003152 std::swap(Op0, Op1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003153 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00003154 } else if (Op1I->getOpcode() == Instruction::Xor) {
3155 if (Op0 == Op1I->getOperand(0)) // A^(A^B) == B
3156 return ReplaceInstUsesWith(I, Op1I->getOperand(1));
3157 else if (Op0 == Op1I->getOperand(1)) // A^(B^A) == B
3158 return ReplaceInstUsesWith(I, Op1I->getOperand(0));
Chris Lattnerdcd07922006-04-01 08:03:55 +00003159 } else if (Op1I->getOpcode() == Instruction::And && Op1I->hasOneUse()) {
3160 if (Op1I->getOperand(0) == Op0) // A^(A&B) -> A^(B&A)
3161 Op1I->swapOperands();
3162 if (Op0 == Op1I->getOperand(1)) { // A^(B&A) -> (B&A)^A
3163 I.swapOperands(); // Simplified below.
3164 std::swap(Op0, Op1);
3165 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00003166 }
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003167
Chris Lattnerdcd07922006-04-01 08:03:55 +00003168 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00003169 if (Op0I->getOpcode() == Instruction::Or && Op0I->hasOneUse()) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003170 if (Op0I->getOperand(0) == Op1) // (B|A)^B == (A|B)^B
Chris Lattnerdcd07922006-04-01 08:03:55 +00003171 Op0I->swapOperands();
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003172 if (Op0I->getOperand(1) == Op1) { // (A|B)^B == A & ~B
Chris Lattnerdcd07922006-04-01 08:03:55 +00003173 Instruction *NotB = BinaryOperator::createNot(Op1, "tmp");
3174 InsertNewInstBefore(NotB, I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003175 return BinaryOperator::createAnd(Op0I->getOperand(0), NotB);
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003176 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00003177 } else if (Op0I->getOpcode() == Instruction::Xor) {
3178 if (Op1 == Op0I->getOperand(0)) // (A^B)^A == B
3179 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
3180 else if (Op1 == Op0I->getOperand(1)) // (B^A)^A == B
3181 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattnerdcd07922006-04-01 08:03:55 +00003182 } else if (Op0I->getOpcode() == Instruction::And && Op0I->hasOneUse()) {
3183 if (Op0I->getOperand(0) == Op1) // (A&B)^A -> (B&A)^A
3184 Op0I->swapOperands();
Chris Lattner6cf49142006-04-01 22:05:01 +00003185 if (Op0I->getOperand(1) == Op1 && // (B&A)^A == ~B & A
3186 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattnerdcd07922006-04-01 08:03:55 +00003187 Instruction *N = BinaryOperator::createNot(Op0I->getOperand(0), "tmp");
3188 InsertNewInstBefore(N, I);
3189 return BinaryOperator::createAnd(N, Op1);
3190 }
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003191 }
3192
Chris Lattner3ac7c262003-08-13 20:16:26 +00003193 // (setcc1 A, B) ^ (setcc2 A, B) --> (setcc3 A, B)
3194 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
3195 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
3196 return R;
3197
Chris Lattner3af10532006-05-05 06:39:07 +00003198 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
3199 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattnere745c7d2006-05-05 20:51:30 +00003200 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner3af10532006-05-05 06:39:07 +00003201 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Chris Lattnere745c7d2006-05-05 20:51:30 +00003202 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegral() &&
Chris Lattner1d441ad2006-05-06 09:00:16 +00003203 // Only do this if the casts both really cause code to be generated.
3204 ValueRequiresCast(Op0C->getOperand(0), I.getType(), TD) &&
3205 ValueRequiresCast(Op1C->getOperand(0), I.getType(), TD)) {
Chris Lattner3af10532006-05-05 06:39:07 +00003206 Instruction *NewOp = BinaryOperator::createXor(Op0C->getOperand(0),
3207 Op1C->getOperand(0),
3208 I.getName());
3209 InsertNewInstBefore(NewOp, I);
3210 return new CastInst(NewOp, I.getType());
3211 }
3212 }
3213
Chris Lattner113f4f42002-06-25 16:13:24 +00003214 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003215}
3216
Chris Lattner6862fbd2004-09-29 17:40:11 +00003217/// MulWithOverflow - Compute Result = In1*In2, returning true if the result
3218/// overflowed for this type.
3219static bool MulWithOverflow(ConstantInt *&Result, ConstantInt *In1,
3220 ConstantInt *In2) {
3221 Result = cast<ConstantInt>(ConstantExpr::getMul(In1, In2));
3222 return !In2->isNullValue() && ConstantExpr::getDiv(Result, In2) != In1;
3223}
3224
3225static bool isPositive(ConstantInt *C) {
3226 return cast<ConstantSInt>(C)->getValue() >= 0;
3227}
3228
3229/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
3230/// overflowed for this type.
3231static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
3232 ConstantInt *In2) {
3233 Result = cast<ConstantInt>(ConstantExpr::getAdd(In1, In2));
3234
3235 if (In1->getType()->isUnsigned())
3236 return cast<ConstantUInt>(Result)->getValue() <
3237 cast<ConstantUInt>(In1)->getValue();
3238 if (isPositive(In1) != isPositive(In2))
3239 return false;
3240 if (isPositive(In1))
3241 return cast<ConstantSInt>(Result)->getValue() <
3242 cast<ConstantSInt>(In1)->getValue();
3243 return cast<ConstantSInt>(Result)->getValue() >
3244 cast<ConstantSInt>(In1)->getValue();
3245}
3246
Chris Lattner0798af32005-01-13 20:14:25 +00003247/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
3248/// code necessary to compute the offset from the base pointer (without adding
3249/// in the base pointer). Return the result as a signed integer of intptr size.
3250static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
3251 TargetData &TD = IC.getTargetData();
3252 gep_type_iterator GTI = gep_type_begin(GEP);
3253 const Type *UIntPtrTy = TD.getIntPtrType();
3254 const Type *SIntPtrTy = UIntPtrTy->getSignedVersion();
3255 Value *Result = Constant::getNullValue(SIntPtrTy);
3256
3257 // Build a mask for high order bits.
Chris Lattner77defba2006-02-07 07:00:41 +00003258 uint64_t PtrSizeMask = ~0ULL >> (64-TD.getPointerSize()*8);
Chris Lattner0798af32005-01-13 20:14:25 +00003259
Chris Lattner0798af32005-01-13 20:14:25 +00003260 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
3261 Value *Op = GEP->getOperand(i);
Chris Lattnerd35d2102005-01-13 23:26:48 +00003262 uint64_t Size = TD.getTypeSize(GTI.getIndexedType()) & PtrSizeMask;
Chris Lattner0798af32005-01-13 20:14:25 +00003263 Constant *Scale = ConstantExpr::getCast(ConstantUInt::get(UIntPtrTy, Size),
3264 SIntPtrTy);
3265 if (Constant *OpC = dyn_cast<Constant>(Op)) {
3266 if (!OpC->isNullValue()) {
Chris Lattner4cb9fa32005-01-13 20:40:58 +00003267 OpC = ConstantExpr::getCast(OpC, SIntPtrTy);
Chris Lattner0798af32005-01-13 20:14:25 +00003268 Scale = ConstantExpr::getMul(OpC, Scale);
3269 if (Constant *RC = dyn_cast<Constant>(Result))
3270 Result = ConstantExpr::getAdd(RC, Scale);
3271 else {
3272 // Emit an add instruction.
3273 Result = IC.InsertNewInstBefore(
3274 BinaryOperator::createAdd(Result, Scale,
3275 GEP->getName()+".offs"), I);
3276 }
3277 }
3278 } else {
Chris Lattner7aa41cf2005-01-14 17:17:59 +00003279 // Convert to correct type.
3280 Op = IC.InsertNewInstBefore(new CastInst(Op, SIntPtrTy,
3281 Op->getName()+".c"), I);
3282 if (Size != 1)
Chris Lattner4cb9fa32005-01-13 20:40:58 +00003283 // We'll let instcombine(mul) convert this to a shl if possible.
3284 Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
3285 GEP->getName()+".idx"), I);
Chris Lattner0798af32005-01-13 20:14:25 +00003286
3287 // Emit an add instruction.
Chris Lattner4cb9fa32005-01-13 20:40:58 +00003288 Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
Chris Lattner0798af32005-01-13 20:14:25 +00003289 GEP->getName()+".offs"), I);
3290 }
3291 }
3292 return Result;
3293}
3294
3295/// FoldGEPSetCC - Fold comparisons between a GEP instruction and something
3296/// else. At this point we know that the GEP is on the LHS of the comparison.
3297Instruction *InstCombiner::FoldGEPSetCC(User *GEPLHS, Value *RHS,
3298 Instruction::BinaryOps Cond,
3299 Instruction &I) {
3300 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattner81e84172005-01-13 22:25:21 +00003301
3302 if (CastInst *CI = dyn_cast<CastInst>(RHS))
3303 if (isa<PointerType>(CI->getOperand(0)->getType()))
3304 RHS = CI->getOperand(0);
3305
Chris Lattner0798af32005-01-13 20:14:25 +00003306 Value *PtrBase = GEPLHS->getOperand(0);
3307 if (PtrBase == RHS) {
3308 // As an optimization, we don't actually have to compute the actual value of
3309 // OFFSET if this is a seteq or setne comparison, just return whether each
3310 // index is zero or not.
Chris Lattner81e84172005-01-13 22:25:21 +00003311 if (Cond == Instruction::SetEQ || Cond == Instruction::SetNE) {
3312 Instruction *InVal = 0;
Chris Lattnercd517ff2005-01-28 19:32:01 +00003313 gep_type_iterator GTI = gep_type_begin(GEPLHS);
3314 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i, ++GTI) {
Chris Lattner81e84172005-01-13 22:25:21 +00003315 bool EmitIt = true;
3316 if (Constant *C = dyn_cast<Constant>(GEPLHS->getOperand(i))) {
3317 if (isa<UndefValue>(C)) // undef index -> undef.
3318 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
3319 if (C->isNullValue())
3320 EmitIt = false;
Chris Lattnercd517ff2005-01-28 19:32:01 +00003321 else if (TD->getTypeSize(GTI.getIndexedType()) == 0) {
3322 EmitIt = false; // This is indexing into a zero sized array?
Misha Brukmanb1c93172005-04-21 23:48:37 +00003323 } else if (isa<ConstantInt>(C))
Chris Lattner81e84172005-01-13 22:25:21 +00003324 return ReplaceInstUsesWith(I, // No comparison is needed here.
3325 ConstantBool::get(Cond == Instruction::SetNE));
3326 }
3327
3328 if (EmitIt) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00003329 Instruction *Comp =
Chris Lattner81e84172005-01-13 22:25:21 +00003330 new SetCondInst(Cond, GEPLHS->getOperand(i),
3331 Constant::getNullValue(GEPLHS->getOperand(i)->getType()));
3332 if (InVal == 0)
3333 InVal = Comp;
3334 else {
3335 InVal = InsertNewInstBefore(InVal, I);
3336 InsertNewInstBefore(Comp, I);
3337 if (Cond == Instruction::SetNE) // True if any are unequal
3338 InVal = BinaryOperator::createOr(InVal, Comp);
3339 else // True if all are equal
3340 InVal = BinaryOperator::createAnd(InVal, Comp);
3341 }
3342 }
3343 }
3344
3345 if (InVal)
3346 return InVal;
3347 else
3348 ReplaceInstUsesWith(I, // No comparison is needed here, all indexes = 0
3349 ConstantBool::get(Cond == Instruction::SetEQ));
3350 }
Chris Lattner0798af32005-01-13 20:14:25 +00003351
3352 // Only lower this if the setcc is the only user of the GEP or if we expect
3353 // the result to fold to a constant!
3354 if (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) {
3355 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
3356 Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
3357 return new SetCondInst(Cond, Offset,
3358 Constant::getNullValue(Offset->getType()));
3359 }
3360 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
Chris Lattnera21bf8d2005-04-25 20:17:30 +00003361 // If the base pointers are different, but the indices are the same, just
3362 // compare the base pointer.
3363 if (PtrBase != GEPRHS->getOperand(0)) {
3364 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00003365 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattnerbd43b9d2005-04-26 14:40:41 +00003366 GEPRHS->getOperand(0)->getType();
Chris Lattnera21bf8d2005-04-25 20:17:30 +00003367 if (IndicesTheSame)
3368 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
3369 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
3370 IndicesTheSame = false;
3371 break;
3372 }
3373
3374 // If all indices are the same, just compare the base pointers.
3375 if (IndicesTheSame)
3376 return new SetCondInst(Cond, GEPLHS->getOperand(0),
3377 GEPRHS->getOperand(0));
3378
3379 // Otherwise, the base pointers are different and the indices are
3380 // different, bail out.
Chris Lattner0798af32005-01-13 20:14:25 +00003381 return 0;
Chris Lattnera21bf8d2005-04-25 20:17:30 +00003382 }
Chris Lattner0798af32005-01-13 20:14:25 +00003383
Chris Lattner81e84172005-01-13 22:25:21 +00003384 // If one of the GEPs has all zero indices, recurse.
3385 bool AllZeros = true;
3386 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
3387 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
3388 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
3389 AllZeros = false;
3390 break;
3391 }
3392 if (AllZeros)
3393 return FoldGEPSetCC(GEPRHS, GEPLHS->getOperand(0),
3394 SetCondInst::getSwappedCondition(Cond), I);
Chris Lattner4fa89822005-01-14 00:20:05 +00003395
3396 // If the other GEP has all zero indices, recurse.
Chris Lattner81e84172005-01-13 22:25:21 +00003397 AllZeros = true;
3398 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
3399 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
3400 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
3401 AllZeros = false;
3402 break;
3403 }
3404 if (AllZeros)
3405 return FoldGEPSetCC(GEPLHS, GEPRHS->getOperand(0), Cond, I);
3406
Chris Lattner4fa89822005-01-14 00:20:05 +00003407 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
3408 // If the GEPs only differ by one index, compare it.
3409 unsigned NumDifferences = 0; // Keep track of # differences.
3410 unsigned DiffOperand = 0; // The operand that differs.
3411 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
3412 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003413 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
3414 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattnerfc4429e2005-01-21 23:06:49 +00003415 // Irreconcilable differences.
Chris Lattner4fa89822005-01-14 00:20:05 +00003416 NumDifferences = 2;
3417 break;
3418 } else {
3419 if (NumDifferences++) break;
3420 DiffOperand = i;
3421 }
3422 }
3423
3424 if (NumDifferences == 0) // SAME GEP?
3425 return ReplaceInstUsesWith(I, // No comparison is needed here.
3426 ConstantBool::get(Cond == Instruction::SetEQ));
3427 else if (NumDifferences == 1) {
Chris Lattnerfc4429e2005-01-21 23:06:49 +00003428 Value *LHSV = GEPLHS->getOperand(DiffOperand);
3429 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Chris Lattner247aef82005-07-18 23:07:33 +00003430
3431 // Convert the operands to signed values to make sure to perform a
3432 // signed comparison.
3433 const Type *NewTy = LHSV->getType()->getSignedVersion();
3434 if (LHSV->getType() != NewTy)
3435 LHSV = InsertNewInstBefore(new CastInst(LHSV, NewTy,
3436 LHSV->getName()), I);
3437 if (RHSV->getType() != NewTy)
3438 RHSV = InsertNewInstBefore(new CastInst(RHSV, NewTy,
3439 RHSV->getName()), I);
3440 return new SetCondInst(Cond, LHSV, RHSV);
Chris Lattner4fa89822005-01-14 00:20:05 +00003441 }
3442 }
3443
Chris Lattner0798af32005-01-13 20:14:25 +00003444 // Only lower this if the setcc is the only user of the GEP or if we expect
3445 // the result to fold to a constant!
3446 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
3447 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
3448 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
3449 Value *L = EmitGEPOffset(GEPLHS, I, *this);
3450 Value *R = EmitGEPOffset(GEPRHS, I, *this);
3451 return new SetCondInst(Cond, L, R);
3452 }
3453 }
3454 return 0;
3455}
3456
3457
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003458Instruction *InstCombiner::visitSetCondInst(SetCondInst &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003459 bool Changed = SimplifyCommutative(I);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003460 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3461 const Type *Ty = Op0->getType();
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003462
3463 // setcc X, X
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003464 if (Op0 == Op1)
3465 return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
Chris Lattner1fc23f32002-05-09 20:11:54 +00003466
Chris Lattner81a7a232004-10-16 18:11:37 +00003467 if (isa<UndefValue>(Op1)) // X setcc undef -> undef
3468 return ReplaceInstUsesWith(I, UndefValue::get(Type::BoolTy));
3469
Chris Lattner15ff1e12004-11-14 07:33:16 +00003470 // setcc <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
3471 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanb1c93172005-04-21 23:48:37 +00003472 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
3473 isa<ConstantPointerNull>(Op0)) &&
3474 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner15ff1e12004-11-14 07:33:16 +00003475 isa<ConstantPointerNull>(Op1)))
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003476 return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
3477
3478 // setcc's with boolean values can always be turned into bitwise operations
3479 if (Ty == Type::BoolTy) {
Chris Lattner4456da62004-08-11 00:50:51 +00003480 switch (I.getOpcode()) {
3481 default: assert(0 && "Invalid setcc instruction!");
3482 case Instruction::SetEQ: { // seteq bool %A, %B -> ~(A^B)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003483 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003484 InsertNewInstBefore(Xor, I);
Chris Lattner16930792003-11-03 04:25:02 +00003485 return BinaryOperator::createNot(Xor);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003486 }
Chris Lattner4456da62004-08-11 00:50:51 +00003487 case Instruction::SetNE:
3488 return BinaryOperator::createXor(Op0, Op1);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003489
Chris Lattner4456da62004-08-11 00:50:51 +00003490 case Instruction::SetGT:
3491 std::swap(Op0, Op1); // Change setgt -> setlt
3492 // FALL THROUGH
3493 case Instruction::SetLT: { // setlt bool A, B -> ~X & Y
3494 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
3495 InsertNewInstBefore(Not, I);
3496 return BinaryOperator::createAnd(Not, Op1);
3497 }
3498 case Instruction::SetGE:
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003499 std::swap(Op0, Op1); // Change setge -> setle
Chris Lattner4456da62004-08-11 00:50:51 +00003500 // FALL THROUGH
3501 case Instruction::SetLE: { // setle bool %A, %B -> ~A | B
3502 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
3503 InsertNewInstBefore(Not, I);
3504 return BinaryOperator::createOr(Not, Op1);
3505 }
3506 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003507 }
3508
Chris Lattner2dd01742004-06-09 04:24:29 +00003509 // See if we are doing a comparison between a constant and an instruction that
3510 // can be folded into the comparison.
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003511 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner6862fbd2004-09-29 17:40:11 +00003512 // Check to see if we are comparing against the minimum or maximum value...
3513 if (CI->isMinValue()) {
3514 if (I.getOpcode() == Instruction::SetLT) // A < MIN -> FALSE
3515 return ReplaceInstUsesWith(I, ConstantBool::False);
3516 if (I.getOpcode() == Instruction::SetGE) // A >= MIN -> TRUE
3517 return ReplaceInstUsesWith(I, ConstantBool::True);
3518 if (I.getOpcode() == Instruction::SetLE) // A <= MIN -> A == MIN
3519 return BinaryOperator::createSetEQ(Op0, Op1);
3520 if (I.getOpcode() == Instruction::SetGT) // A > MIN -> A != MIN
3521 return BinaryOperator::createSetNE(Op0, Op1);
3522
3523 } else if (CI->isMaxValue()) {
3524 if (I.getOpcode() == Instruction::SetGT) // A > MAX -> FALSE
3525 return ReplaceInstUsesWith(I, ConstantBool::False);
3526 if (I.getOpcode() == Instruction::SetLE) // A <= MAX -> TRUE
3527 return ReplaceInstUsesWith(I, ConstantBool::True);
3528 if (I.getOpcode() == Instruction::SetGE) // A >= MAX -> A == MAX
3529 return BinaryOperator::createSetEQ(Op0, Op1);
3530 if (I.getOpcode() == Instruction::SetLT) // A < MAX -> A != MAX
3531 return BinaryOperator::createSetNE(Op0, Op1);
3532
3533 // Comparing against a value really close to min or max?
3534 } else if (isMinValuePlusOne(CI)) {
3535 if (I.getOpcode() == Instruction::SetLT) // A < MIN+1 -> A == MIN
3536 return BinaryOperator::createSetEQ(Op0, SubOne(CI));
3537 if (I.getOpcode() == Instruction::SetGE) // A >= MIN-1 -> A != MIN
3538 return BinaryOperator::createSetNE(Op0, SubOne(CI));
3539
3540 } else if (isMaxValueMinusOne(CI)) {
3541 if (I.getOpcode() == Instruction::SetGT) // A > MAX-1 -> A == MAX
3542 return BinaryOperator::createSetEQ(Op0, AddOne(CI));
3543 if (I.getOpcode() == Instruction::SetLE) // A <= MAX-1 -> A != MAX
3544 return BinaryOperator::createSetNE(Op0, AddOne(CI));
3545 }
3546
3547 // If we still have a setle or setge instruction, turn it into the
3548 // appropriate setlt or setgt instruction. Since the border cases have
3549 // already been handled above, this requires little checking.
3550 //
3551 if (I.getOpcode() == Instruction::SetLE)
3552 return BinaryOperator::createSetLT(Op0, AddOne(CI));
3553 if (I.getOpcode() == Instruction::SetGE)
3554 return BinaryOperator::createSetGT(Op0, SubOne(CI));
3555
Chris Lattneree0f2802006-02-12 02:07:56 +00003556
3557 // See if we can fold the comparison based on bits known to be zero or one
3558 // in the input.
3559 uint64_t KnownZero, KnownOne;
3560 if (SimplifyDemandedBits(Op0, Ty->getIntegralTypeMask(),
3561 KnownZero, KnownOne, 0))
3562 return &I;
3563
3564 // Given the known and unknown bits, compute a range that the LHS could be
3565 // in.
3566 if (KnownOne | KnownZero) {
3567 if (Ty->isUnsigned()) { // Unsigned comparison.
3568 uint64_t Min, Max;
3569 uint64_t RHSVal = CI->getZExtValue();
3570 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne,
3571 Min, Max);
3572 switch (I.getOpcode()) { // LE/GE have been folded already.
3573 default: assert(0 && "Unknown setcc opcode!");
3574 case Instruction::SetEQ:
3575 if (Max < RHSVal || Min > RHSVal)
3576 return ReplaceInstUsesWith(I, ConstantBool::False);
3577 break;
3578 case Instruction::SetNE:
3579 if (Max < RHSVal || Min > RHSVal)
3580 return ReplaceInstUsesWith(I, ConstantBool::True);
3581 break;
3582 case Instruction::SetLT:
3583 if (Max < RHSVal) return ReplaceInstUsesWith(I, ConstantBool::True);
3584 if (Min > RHSVal) return ReplaceInstUsesWith(I, ConstantBool::False);
3585 break;
3586 case Instruction::SetGT:
3587 if (Min > RHSVal) return ReplaceInstUsesWith(I, ConstantBool::True);
3588 if (Max < RHSVal) return ReplaceInstUsesWith(I, ConstantBool::False);
3589 break;
3590 }
3591 } else { // Signed comparison.
3592 int64_t Min, Max;
3593 int64_t RHSVal = CI->getSExtValue();
3594 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne,
3595 Min, Max);
3596 switch (I.getOpcode()) { // LE/GE have been folded already.
3597 default: assert(0 && "Unknown setcc opcode!");
3598 case Instruction::SetEQ:
3599 if (Max < RHSVal || Min > RHSVal)
3600 return ReplaceInstUsesWith(I, ConstantBool::False);
3601 break;
3602 case Instruction::SetNE:
3603 if (Max < RHSVal || Min > RHSVal)
3604 return ReplaceInstUsesWith(I, ConstantBool::True);
3605 break;
3606 case Instruction::SetLT:
3607 if (Max < RHSVal) return ReplaceInstUsesWith(I, ConstantBool::True);
3608 if (Min > RHSVal) return ReplaceInstUsesWith(I, ConstantBool::False);
3609 break;
3610 case Instruction::SetGT:
3611 if (Min > RHSVal) return ReplaceInstUsesWith(I, ConstantBool::True);
3612 if (Max < RHSVal) return ReplaceInstUsesWith(I, ConstantBool::False);
3613 break;
3614 }
3615 }
3616 }
3617
3618
Chris Lattnere1e10e12004-05-25 06:32:08 +00003619 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00003620 switch (LHSI->getOpcode()) {
3621 case Instruction::And:
3622 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
3623 LHSI->getOperand(0)->hasOneUse()) {
3624 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
3625 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
3626 // happens a LOT in code produced by the C front-end, for bitfield
3627 // access.
3628 ShiftInst *Shift = dyn_cast<ShiftInst>(LHSI->getOperand(0));
Chris Lattneree0f2802006-02-12 02:07:56 +00003629 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
3630
3631 // Check to see if there is a noop-cast between the shift and the and.
3632 if (!Shift) {
3633 if (CastInst *CI = dyn_cast<CastInst>(LHSI->getOperand(0)))
3634 if (CI->getOperand(0)->getType()->isIntegral() &&
3635 CI->getOperand(0)->getType()->getPrimitiveSizeInBits() ==
3636 CI->getType()->getPrimitiveSizeInBits())
3637 Shift = dyn_cast<ShiftInst>(CI->getOperand(0));
3638 }
3639
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00003640 ConstantUInt *ShAmt;
3641 ShAmt = Shift ? dyn_cast<ConstantUInt>(Shift->getOperand(1)) : 0;
Chris Lattneree0f2802006-02-12 02:07:56 +00003642 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
3643 const Type *AndTy = AndCST->getType(); // Type of the and.
Misha Brukmanb1c93172005-04-21 23:48:37 +00003644
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00003645 // We can fold this as long as we can't shift unknown bits
3646 // into the mask. This can only happen with signed shift
3647 // rights, as they sign-extend.
3648 if (ShAmt) {
3649 bool CanFold = Shift->getOpcode() != Instruction::Shr ||
Chris Lattneree0f2802006-02-12 02:07:56 +00003650 Ty->isUnsigned();
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00003651 if (!CanFold) {
3652 // To test for the bad case of the signed shr, see if any
3653 // of the bits shifted in could be tested after the mask.
Chris Lattnerc53cb9d2005-06-17 01:29:28 +00003654 int ShAmtVal = Ty->getPrimitiveSizeInBits()-ShAmt->getValue();
3655 if (ShAmtVal < 0) ShAmtVal = 0; // Out of range shift.
3656
3657 Constant *OShAmt = ConstantUInt::get(Type::UByteTy, ShAmtVal);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003658 Constant *ShVal =
Chris Lattneree0f2802006-02-12 02:07:56 +00003659 ConstantExpr::getShl(ConstantInt::getAllOnesValue(AndTy),
3660 OShAmt);
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00003661 if (ConstantExpr::getAnd(ShVal, AndCST)->isNullValue())
3662 CanFold = true;
3663 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003664
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00003665 if (CanFold) {
Chris Lattner6afc02f2004-09-28 17:54:07 +00003666 Constant *NewCst;
3667 if (Shift->getOpcode() == Instruction::Shl)
3668 NewCst = ConstantExpr::getUShr(CI, ShAmt);
3669 else
3670 NewCst = ConstantExpr::getShl(CI, ShAmt);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00003671
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00003672 // Check to see if we are shifting out any of the bits being
3673 // compared.
3674 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != CI){
3675 // If we shifted bits out, the fold is not going to work out.
3676 // As a special case, check to see if this means that the
3677 // result is always true or false now.
3678 if (I.getOpcode() == Instruction::SetEQ)
3679 return ReplaceInstUsesWith(I, ConstantBool::False);
3680 if (I.getOpcode() == Instruction::SetNE)
3681 return ReplaceInstUsesWith(I, ConstantBool::True);
3682 } else {
3683 I.setOperand(1, NewCst);
Chris Lattner6afc02f2004-09-28 17:54:07 +00003684 Constant *NewAndCST;
3685 if (Shift->getOpcode() == Instruction::Shl)
3686 NewAndCST = ConstantExpr::getUShr(AndCST, ShAmt);
3687 else
3688 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
3689 LHSI->setOperand(1, NewAndCST);
Chris Lattneree0f2802006-02-12 02:07:56 +00003690 if (AndTy == Ty)
3691 LHSI->setOperand(0, Shift->getOperand(0));
3692 else {
3693 Value *NewCast = InsertCastBefore(Shift->getOperand(0), AndTy,
3694 *Shift);
3695 LHSI->setOperand(0, NewCast);
3696 }
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00003697 WorkList.push_back(Shift); // Shift is dead.
3698 AddUsesToWorkList(I);
3699 return &I;
Chris Lattner1638de42004-07-21 19:50:44 +00003700 }
3701 }
Chris Lattner35167c32004-06-09 07:59:58 +00003702 }
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00003703 }
3704 break;
Chris Lattnerbfff18a2004-09-27 19:29:18 +00003705
Chris Lattner272d5ca2004-09-28 18:22:15 +00003706 case Instruction::Shl: // (setcc (shl X, ShAmt), CI)
3707 if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
3708 switch (I.getOpcode()) {
3709 default: break;
3710 case Instruction::SetEQ:
3711 case Instruction::SetNE: {
Chris Lattner19b57f52005-06-15 20:53:31 +00003712 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
3713
3714 // Check that the shift amount is in range. If not, don't perform
3715 // undefined shifts. When the shift is visited it will be
3716 // simplified.
3717 if (ShAmt->getValue() >= TypeBits)
3718 break;
3719
Chris Lattner272d5ca2004-09-28 18:22:15 +00003720 // If we are comparing against bits always shifted out, the
3721 // comparison cannot succeed.
Misha Brukmanb1c93172005-04-21 23:48:37 +00003722 Constant *Comp =
Chris Lattner272d5ca2004-09-28 18:22:15 +00003723 ConstantExpr::getShl(ConstantExpr::getShr(CI, ShAmt), ShAmt);
3724 if (Comp != CI) {// Comparing against a bit that we know is zero.
3725 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
3726 Constant *Cst = ConstantBool::get(IsSetNE);
3727 return ReplaceInstUsesWith(I, Cst);
3728 }
3729
3730 if (LHSI->hasOneUse()) {
3731 // Otherwise strength reduce the shift into an and.
Chris Lattnerfdfe3e492005-01-08 19:42:22 +00003732 unsigned ShAmtVal = (unsigned)ShAmt->getValue();
Chris Lattner272d5ca2004-09-28 18:22:15 +00003733 uint64_t Val = (1ULL << (TypeBits-ShAmtVal))-1;
3734
3735 Constant *Mask;
3736 if (CI->getType()->isUnsigned()) {
3737 Mask = ConstantUInt::get(CI->getType(), Val);
3738 } else if (ShAmtVal != 0) {
3739 Mask = ConstantSInt::get(CI->getType(), Val);
3740 } else {
3741 Mask = ConstantInt::getAllOnesValue(CI->getType());
3742 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003743
Chris Lattner272d5ca2004-09-28 18:22:15 +00003744 Instruction *AndI =
3745 BinaryOperator::createAnd(LHSI->getOperand(0),
3746 Mask, LHSI->getName()+".mask");
3747 Value *And = InsertNewInstBefore(AndI, I);
3748 return new SetCondInst(I.getOpcode(), And,
3749 ConstantExpr::getUShr(CI, ShAmt));
3750 }
3751 }
3752 }
3753 }
3754 break;
3755
Chris Lattnerbfff18a2004-09-27 19:29:18 +00003756 case Instruction::Shr: // (setcc (shr X, ShAmt), CI)
Chris Lattner1023b872004-09-27 16:18:50 +00003757 if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
Chris Lattner1023b872004-09-27 16:18:50 +00003758 switch (I.getOpcode()) {
3759 default: break;
3760 case Instruction::SetEQ:
3761 case Instruction::SetNE: {
Chris Lattner19b57f52005-06-15 20:53:31 +00003762
3763 // Check that the shift amount is in range. If not, don't perform
3764 // undefined shifts. When the shift is visited it will be
3765 // simplified.
Chris Lattner104002b2005-06-16 01:52:07 +00003766 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
Chris Lattner19b57f52005-06-15 20:53:31 +00003767 if (ShAmt->getValue() >= TypeBits)
3768 break;
3769
Chris Lattner1023b872004-09-27 16:18:50 +00003770 // If we are comparing against bits always shifted out, the
3771 // comparison cannot succeed.
Misha Brukmanb1c93172005-04-21 23:48:37 +00003772 Constant *Comp =
Chris Lattner1023b872004-09-27 16:18:50 +00003773 ConstantExpr::getShr(ConstantExpr::getShl(CI, ShAmt), ShAmt);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003774
Chris Lattner1023b872004-09-27 16:18:50 +00003775 if (Comp != CI) {// Comparing against a bit that we know is zero.
3776 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
3777 Constant *Cst = ConstantBool::get(IsSetNE);
3778 return ReplaceInstUsesWith(I, Cst);
3779 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003780
Chris Lattner1023b872004-09-27 16:18:50 +00003781 if (LHSI->hasOneUse() || CI->isNullValue()) {
Chris Lattnerfdfe3e492005-01-08 19:42:22 +00003782 unsigned ShAmtVal = (unsigned)ShAmt->getValue();
Chris Lattner272d5ca2004-09-28 18:22:15 +00003783
Chris Lattner1023b872004-09-27 16:18:50 +00003784 // Otherwise strength reduce the shift into an and.
3785 uint64_t Val = ~0ULL; // All ones.
3786 Val <<= ShAmtVal; // Shift over to the right spot.
3787
3788 Constant *Mask;
3789 if (CI->getType()->isUnsigned()) {
Chris Lattner2f1457f2005-04-24 17:46:05 +00003790 Val &= ~0ULL >> (64-TypeBits);
Chris Lattner1023b872004-09-27 16:18:50 +00003791 Mask = ConstantUInt::get(CI->getType(), Val);
3792 } else {
3793 Mask = ConstantSInt::get(CI->getType(), Val);
3794 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003795
Chris Lattner1023b872004-09-27 16:18:50 +00003796 Instruction *AndI =
3797 BinaryOperator::createAnd(LHSI->getOperand(0),
3798 Mask, LHSI->getName()+".mask");
3799 Value *And = InsertNewInstBefore(AndI, I);
3800 return new SetCondInst(I.getOpcode(), And,
3801 ConstantExpr::getShl(CI, ShAmt));
3802 }
3803 break;
3804 }
3805 }
3806 }
3807 break;
Chris Lattner7e794272004-09-24 15:21:34 +00003808
Chris Lattner6862fbd2004-09-29 17:40:11 +00003809 case Instruction::Div:
3810 // Fold: (div X, C1) op C2 -> range check
3811 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
3812 // Fold this div into the comparison, producing a range check.
3813 // Determine, based on the divide type, what the range is being
3814 // checked. If there is an overflow on the low or high side, remember
3815 // it, otherwise compute the range [low, hi) bounding the new value.
3816 bool LoOverflow = false, HiOverflow = 0;
3817 ConstantInt *LoBound = 0, *HiBound = 0;
3818
3819 ConstantInt *Prod;
3820 bool ProdOV = MulWithOverflow(Prod, CI, DivRHS);
3821
Chris Lattnera92af962004-10-11 19:40:04 +00003822 Instruction::BinaryOps Opcode = I.getOpcode();
3823
Chris Lattner6862fbd2004-09-29 17:40:11 +00003824 if (DivRHS->isNullValue()) { // Don't hack on divide by zeros.
3825 } else if (LHSI->getType()->isUnsigned()) { // udiv
3826 LoBound = Prod;
3827 LoOverflow = ProdOV;
3828 HiOverflow = ProdOV || AddWithOverflow(HiBound, LoBound, DivRHS);
3829 } else if (isPositive(DivRHS)) { // Divisor is > 0.
3830 if (CI->isNullValue()) { // (X / pos) op 0
3831 // Can't overflow.
3832 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
3833 HiBound = DivRHS;
3834 } else if (isPositive(CI)) { // (X / pos) op pos
3835 LoBound = Prod;
3836 LoOverflow = ProdOV;
3837 HiOverflow = ProdOV || AddWithOverflow(HiBound, Prod, DivRHS);
3838 } else { // (X / pos) op neg
3839 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
3840 LoOverflow = AddWithOverflow(LoBound, Prod,
3841 cast<ConstantInt>(DivRHSH));
3842 HiBound = Prod;
3843 HiOverflow = ProdOV;
3844 }
3845 } else { // Divisor is < 0.
3846 if (CI->isNullValue()) { // (X / neg) op 0
3847 LoBound = AddOne(DivRHS);
3848 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner73bcba52005-06-17 02:05:55 +00003849 if (HiBound == DivRHS)
3850 LoBound = 0; // - INTMIN = INTMIN
Chris Lattner6862fbd2004-09-29 17:40:11 +00003851 } else if (isPositive(CI)) { // (X / neg) op pos
3852 HiOverflow = LoOverflow = ProdOV;
3853 if (!LoOverflow)
3854 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS));
3855 HiBound = AddOne(Prod);
3856 } else { // (X / neg) op neg
3857 LoBound = Prod;
3858 LoOverflow = HiOverflow = ProdOV;
3859 HiBound = cast<ConstantInt>(ConstantExpr::getSub(Prod, DivRHS));
3860 }
Chris Lattner0b41e862004-10-08 19:15:44 +00003861
Chris Lattnera92af962004-10-11 19:40:04 +00003862 // Dividing by a negate swaps the condition.
3863 Opcode = SetCondInst::getSwappedCondition(Opcode);
Chris Lattner6862fbd2004-09-29 17:40:11 +00003864 }
3865
3866 if (LoBound) {
3867 Value *X = LHSI->getOperand(0);
Chris Lattnera92af962004-10-11 19:40:04 +00003868 switch (Opcode) {
Chris Lattner6862fbd2004-09-29 17:40:11 +00003869 default: assert(0 && "Unhandled setcc opcode!");
3870 case Instruction::SetEQ:
3871 if (LoOverflow && HiOverflow)
3872 return ReplaceInstUsesWith(I, ConstantBool::False);
3873 else if (HiOverflow)
3874 return new SetCondInst(Instruction::SetGE, X, LoBound);
3875 else if (LoOverflow)
3876 return new SetCondInst(Instruction::SetLT, X, HiBound);
3877 else
3878 return InsertRangeTest(X, LoBound, HiBound, true, I);
3879 case Instruction::SetNE:
3880 if (LoOverflow && HiOverflow)
3881 return ReplaceInstUsesWith(I, ConstantBool::True);
3882 else if (HiOverflow)
3883 return new SetCondInst(Instruction::SetLT, X, LoBound);
3884 else if (LoOverflow)
3885 return new SetCondInst(Instruction::SetGE, X, HiBound);
3886 else
3887 return InsertRangeTest(X, LoBound, HiBound, false, I);
3888 case Instruction::SetLT:
3889 if (LoOverflow)
3890 return ReplaceInstUsesWith(I, ConstantBool::False);
3891 return new SetCondInst(Instruction::SetLT, X, LoBound);
3892 case Instruction::SetGT:
3893 if (HiOverflow)
3894 return ReplaceInstUsesWith(I, ConstantBool::False);
3895 return new SetCondInst(Instruction::SetGE, X, HiBound);
3896 }
3897 }
3898 }
3899 break;
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00003900 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003901
Chris Lattnerd492a0b2003-07-23 17:02:11 +00003902 // Simplify seteq and setne instructions...
3903 if (I.getOpcode() == Instruction::SetEQ ||
3904 I.getOpcode() == Instruction::SetNE) {
3905 bool isSetNE = I.getOpcode() == Instruction::SetNE;
3906
Chris Lattnercfbce7c2003-07-23 17:26:36 +00003907 // If the first operand is (and|or|xor) with a constant, and the second
Chris Lattnerd492a0b2003-07-23 17:02:11 +00003908 // operand is a constant, simplify a bit.
Chris Lattnerc992add2003-08-13 05:33:12 +00003909 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
3910 switch (BO->getOpcode()) {
Chris Lattner23b47b62004-07-06 07:38:18 +00003911 case Instruction::Rem:
3912 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
3913 if (CI->isNullValue() && isa<ConstantSInt>(BO->getOperand(1)) &&
3914 BO->hasOneUse() &&
Chris Lattner22d00a82005-08-02 19:16:58 +00003915 cast<ConstantSInt>(BO->getOperand(1))->getValue() > 1) {
3916 int64_t V = cast<ConstantSInt>(BO->getOperand(1))->getValue();
3917 if (isPowerOf2_64(V)) {
3918 unsigned L2 = Log2_64(V);
Chris Lattner23b47b62004-07-06 07:38:18 +00003919 const Type *UTy = BO->getType()->getUnsignedVersion();
3920 Value *NewX = InsertNewInstBefore(new CastInst(BO->getOperand(0),
3921 UTy, "tmp"), I);
3922 Constant *RHSCst = ConstantUInt::get(UTy, 1ULL << L2);
3923 Value *NewRem =InsertNewInstBefore(BinaryOperator::createRem(NewX,
3924 RHSCst, BO->getName()), I);
3925 return BinaryOperator::create(I.getOpcode(), NewRem,
3926 Constant::getNullValue(UTy));
3927 }
Chris Lattner22d00a82005-08-02 19:16:58 +00003928 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003929 break;
Chris Lattner23b47b62004-07-06 07:38:18 +00003930
Chris Lattnerc992add2003-08-13 05:33:12 +00003931 case Instruction::Add:
Chris Lattner6e079362004-06-27 22:51:36 +00003932 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
3933 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerb121ae12004-09-21 21:35:23 +00003934 if (BO->hasOneUse())
3935 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
3936 ConstantExpr::getSub(CI, BOp1C));
Chris Lattner6e079362004-06-27 22:51:36 +00003937 } else if (CI->isNullValue()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00003938 // Replace ((add A, B) != 0) with (A != -B) if A or B is
3939 // efficiently invertible, or if the add has just this one use.
3940 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003941
Chris Lattnerc992add2003-08-13 05:33:12 +00003942 if (Value *NegVal = dyn_castNegVal(BOp1))
3943 return new SetCondInst(I.getOpcode(), BOp0, NegVal);
3944 else if (Value *NegVal = dyn_castNegVal(BOp0))
3945 return new SetCondInst(I.getOpcode(), NegVal, BOp1);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00003946 else if (BO->hasOneUse()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00003947 Instruction *Neg = BinaryOperator::createNeg(BOp1, BO->getName());
3948 BO->setName("");
3949 InsertNewInstBefore(Neg, I);
3950 return new SetCondInst(I.getOpcode(), BOp0, Neg);
3951 }
3952 }
3953 break;
3954 case Instruction::Xor:
3955 // For the xor case, we can xor two constants together, eliminating
3956 // the explicit xor.
3957 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
3958 return BinaryOperator::create(I.getOpcode(), BO->getOperand(0),
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003959 ConstantExpr::getXor(CI, BOC));
Chris Lattnerc992add2003-08-13 05:33:12 +00003960
3961 // FALLTHROUGH
3962 case Instruction::Sub:
3963 // Replace (([sub|xor] A, B) != 0) with (A != B)
3964 if (CI->isNullValue())
3965 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
3966 BO->getOperand(1));
3967 break;
3968
3969 case Instruction::Or:
3970 // If bits are being or'd in that are not present in the constant we
3971 // are comparing against, then the comparison could never succeed!
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003972 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Chris Lattnerc8e7e292004-06-10 02:12:35 +00003973 Constant *NotCI = ConstantExpr::getNot(CI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003974 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Chris Lattnerd492a0b2003-07-23 17:02:11 +00003975 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003976 }
Chris Lattnerc992add2003-08-13 05:33:12 +00003977 break;
3978
3979 case Instruction::And:
3980 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerd492a0b2003-07-23 17:02:11 +00003981 // If bits are being compared against that are and'd out, then the
3982 // comparison can never succeed!
Chris Lattnerc8e7e292004-06-10 02:12:35 +00003983 if (!ConstantExpr::getAnd(CI,
3984 ConstantExpr::getNot(BOC))->isNullValue())
Chris Lattnerd492a0b2003-07-23 17:02:11 +00003985 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattnerc992add2003-08-13 05:33:12 +00003986
Chris Lattner35167c32004-06-09 07:59:58 +00003987 // If we have ((X & C) == C), turn it into ((X & C) != 0).
Chris Lattneree59d4b2004-06-10 02:33:20 +00003988 if (CI == BOC && isOneBitSet(CI))
Chris Lattner35167c32004-06-09 07:59:58 +00003989 return new SetCondInst(isSetNE ? Instruction::SetEQ :
3990 Instruction::SetNE, Op0,
3991 Constant::getNullValue(CI->getType()));
Chris Lattner35167c32004-06-09 07:59:58 +00003992
Chris Lattnerc992add2003-08-13 05:33:12 +00003993 // Replace (and X, (1 << size(X)-1) != 0) with x < 0, converting X
3994 // to be a signed value as appropriate.
3995 if (isSignBit(BOC)) {
3996 Value *X = BO->getOperand(0);
3997 // If 'X' is not signed, insert a cast now...
3998 if (!BOC->getType()->isSigned()) {
Chris Lattner97bfcea2004-06-17 18:16:02 +00003999 const Type *DestTy = BOC->getType()->getSignedVersion();
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004000 X = InsertCastBefore(X, DestTy, I);
Chris Lattnerc992add2003-08-13 05:33:12 +00004001 }
4002 return new SetCondInst(isSetNE ? Instruction::SetLT :
4003 Instruction::SetGE, X,
4004 Constant::getNullValue(X->getType()));
4005 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004006
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004007 // ((X & ~7) == 0) --> X < 8
Chris Lattner8fc5af42004-09-23 21:46:38 +00004008 if (CI->isNullValue() && isHighOnes(BOC)) {
4009 Value *X = BO->getOperand(0);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004010 Constant *NegX = ConstantExpr::getNeg(BOC);
Chris Lattner8fc5af42004-09-23 21:46:38 +00004011
4012 // If 'X' is signed, insert a cast now.
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004013 if (NegX->getType()->isSigned()) {
4014 const Type *DestTy = NegX->getType()->getUnsignedVersion();
4015 X = InsertCastBefore(X, DestTy, I);
4016 NegX = ConstantExpr::getCast(NegX, DestTy);
Chris Lattner8fc5af42004-09-23 21:46:38 +00004017 }
4018
4019 return new SetCondInst(isSetNE ? Instruction::SetGE :
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004020 Instruction::SetLT, X, NegX);
Chris Lattner8fc5af42004-09-23 21:46:38 +00004021 }
4022
Chris Lattnerd492a0b2003-07-23 17:02:11 +00004023 }
Chris Lattnerc992add2003-08-13 05:33:12 +00004024 default: break;
4025 }
4026 }
Chris Lattner2b55ea32004-02-23 07:16:20 +00004027 } else { // Not a SetEQ/SetNE
Misha Brukmanb1c93172005-04-21 23:48:37 +00004028 // If the LHS is a cast from an integral value of the same size,
Chris Lattner2b55ea32004-02-23 07:16:20 +00004029 if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
4030 Value *CastOp = Cast->getOperand(0);
4031 const Type *SrcTy = CastOp->getType();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004032 unsigned SrcTySize = SrcTy->getPrimitiveSizeInBits();
Chris Lattner2b55ea32004-02-23 07:16:20 +00004033 if (SrcTy != Cast->getType() && SrcTy->isInteger() &&
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004034 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00004035 assert((SrcTy->isSigned() ^ Cast->getType()->isSigned()) &&
Chris Lattner2b55ea32004-02-23 07:16:20 +00004036 "Source and destination signednesses should differ!");
4037 if (Cast->getType()->isSigned()) {
4038 // If this is a signed comparison, check for comparisons in the
4039 // vicinity of zero.
4040 if (I.getOpcode() == Instruction::SetLT && CI->isNullValue())
4041 // X < 0 => x > 127
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004042 return BinaryOperator::createSetGT(CastOp,
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004043 ConstantUInt::get(SrcTy, (1ULL << (SrcTySize-1))-1));
Chris Lattner2b55ea32004-02-23 07:16:20 +00004044 else if (I.getOpcode() == Instruction::SetGT &&
4045 cast<ConstantSInt>(CI)->getValue() == -1)
4046 // X > -1 => x < 128
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004047 return BinaryOperator::createSetLT(CastOp,
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004048 ConstantUInt::get(SrcTy, 1ULL << (SrcTySize-1)));
Chris Lattner2b55ea32004-02-23 07:16:20 +00004049 } else {
4050 ConstantUInt *CUI = cast<ConstantUInt>(CI);
4051 if (I.getOpcode() == Instruction::SetLT &&
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004052 CUI->getValue() == 1ULL << (SrcTySize-1))
Chris Lattner2b55ea32004-02-23 07:16:20 +00004053 // X < 128 => X > -1
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004054 return BinaryOperator::createSetGT(CastOp,
4055 ConstantSInt::get(SrcTy, -1));
Chris Lattner2b55ea32004-02-23 07:16:20 +00004056 else if (I.getOpcode() == Instruction::SetGT &&
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004057 CUI->getValue() == (1ULL << (SrcTySize-1))-1)
Chris Lattner2b55ea32004-02-23 07:16:20 +00004058 // X > 127 => X < 0
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004059 return BinaryOperator::createSetLT(CastOp,
4060 Constant::getNullValue(SrcTy));
Chris Lattner2b55ea32004-02-23 07:16:20 +00004061 }
4062 }
4063 }
Chris Lattnere967b342003-06-04 05:10:11 +00004064 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004065 }
4066
Chris Lattner77c32c32005-04-23 15:31:55 +00004067 // Handle setcc with constant RHS's that can be integer, FP or pointer.
4068 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
4069 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4070 switch (LHSI->getOpcode()) {
Chris Lattnera816eee2005-05-01 04:42:15 +00004071 case Instruction::GetElementPtr:
4072 if (RHSC->isNullValue()) {
4073 // Transform setcc GEP P, int 0, int 0, int 0, null -> setcc P, null
4074 bool isAllZeros = true;
4075 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
4076 if (!isa<Constant>(LHSI->getOperand(i)) ||
4077 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
4078 isAllZeros = false;
4079 break;
4080 }
4081 if (isAllZeros)
4082 return new SetCondInst(I.getOpcode(), LHSI->getOperand(0),
4083 Constant::getNullValue(LHSI->getOperand(0)->getType()));
4084 }
4085 break;
4086
Chris Lattner77c32c32005-04-23 15:31:55 +00004087 case Instruction::PHI:
4088 if (Instruction *NV = FoldOpIntoPhi(I))
4089 return NV;
4090 break;
4091 case Instruction::Select:
4092 // If either operand of the select is a constant, we can fold the
4093 // comparison into the select arms, which will cause one to be
4094 // constant folded and the select turned into a bitwise or.
4095 Value *Op1 = 0, *Op2 = 0;
4096 if (LHSI->hasOneUse()) {
4097 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
4098 // Fold the known value into the constant operand.
4099 Op1 = ConstantExpr::get(I.getOpcode(), C, RHSC);
4100 // Insert a new SetCC of the other select operand.
4101 Op2 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
4102 LHSI->getOperand(2), RHSC,
4103 I.getName()), I);
4104 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
4105 // Fold the known value into the constant operand.
4106 Op2 = ConstantExpr::get(I.getOpcode(), C, RHSC);
4107 // Insert a new SetCC of the other select operand.
4108 Op1 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
4109 LHSI->getOperand(1), RHSC,
4110 I.getName()), I);
4111 }
4112 }
Jeff Cohen82639852005-04-23 21:38:35 +00004113
Chris Lattner77c32c32005-04-23 15:31:55 +00004114 if (Op1)
4115 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
4116 break;
4117 }
4118 }
4119
Chris Lattner0798af32005-01-13 20:14:25 +00004120 // If we can optimize a 'setcc GEP, P' or 'setcc P, GEP', do so now.
4121 if (User *GEP = dyn_castGetElementPtr(Op0))
4122 if (Instruction *NI = FoldGEPSetCC(GEP, Op1, I.getOpcode(), I))
4123 return NI;
4124 if (User *GEP = dyn_castGetElementPtr(Op1))
4125 if (Instruction *NI = FoldGEPSetCC(GEP, Op0,
4126 SetCondInst::getSwappedCondition(I.getOpcode()), I))
4127 return NI;
4128
Chris Lattner16930792003-11-03 04:25:02 +00004129 // Test to see if the operands of the setcc are casted versions of other
4130 // values. If the cast can be stripped off both arguments, we do so now.
Chris Lattner6444c372003-11-03 05:17:03 +00004131 if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
4132 Value *CastOp0 = CI->getOperand(0);
4133 if (CastOp0->getType()->isLosslesslyConvertibleTo(CI->getType()) &&
Chris Lattner7d2a5392004-03-13 23:54:27 +00004134 (isa<Constant>(Op1) || isa<CastInst>(Op1)) &&
Chris Lattner16930792003-11-03 04:25:02 +00004135 (I.getOpcode() == Instruction::SetEQ ||
4136 I.getOpcode() == Instruction::SetNE)) {
4137 // We keep moving the cast from the left operand over to the right
4138 // operand, where it can often be eliminated completely.
Chris Lattner6444c372003-11-03 05:17:03 +00004139 Op0 = CastOp0;
Misha Brukmanb1c93172005-04-21 23:48:37 +00004140
Chris Lattner16930792003-11-03 04:25:02 +00004141 // If operand #1 is a cast instruction, see if we can eliminate it as
4142 // well.
Chris Lattner6444c372003-11-03 05:17:03 +00004143 if (CastInst *CI2 = dyn_cast<CastInst>(Op1))
4144 if (CI2->getOperand(0)->getType()->isLosslesslyConvertibleTo(
Chris Lattner16930792003-11-03 04:25:02 +00004145 Op0->getType()))
Chris Lattner6444c372003-11-03 05:17:03 +00004146 Op1 = CI2->getOperand(0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004147
Chris Lattner16930792003-11-03 04:25:02 +00004148 // If Op1 is a constant, we can fold the cast into the constant.
4149 if (Op1->getType() != Op0->getType())
4150 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
4151 Op1 = ConstantExpr::getCast(Op1C, Op0->getType());
4152 } else {
4153 // Otherwise, cast the RHS right before the setcc
4154 Op1 = new CastInst(Op1, Op0->getType(), Op1->getName());
4155 InsertNewInstBefore(cast<Instruction>(Op1), I);
4156 }
4157 return BinaryOperator::create(I.getOpcode(), Op0, Op1);
4158 }
4159
Chris Lattner6444c372003-11-03 05:17:03 +00004160 // Handle the special case of: setcc (cast bool to X), <cst>
4161 // This comes up when you have code like
4162 // int X = A < B;
4163 // if (X) ...
4164 // For generality, we handle any zero-extension of any operand comparison
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004165 // with a constant or another cast from the same type.
4166 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
4167 if (Instruction *R = visitSetCondInstWithCastAndCast(I))
4168 return R;
Chris Lattner6444c372003-11-03 05:17:03 +00004169 }
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00004170
4171 if (I.getOpcode() == Instruction::SetNE ||
4172 I.getOpcode() == Instruction::SetEQ) {
4173 Value *A, *B;
4174 if (match(Op0, m_Xor(m_Value(A), m_Value(B))) &&
4175 (A == Op1 || B == Op1)) {
4176 // (A^B) == A -> B == 0
4177 Value *OtherVal = A == Op1 ? B : A;
4178 return BinaryOperator::create(I.getOpcode(), OtherVal,
4179 Constant::getNullValue(A->getType()));
4180 } else if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
4181 (A == Op0 || B == Op0)) {
4182 // A == (A^B) -> B == 0
4183 Value *OtherVal = A == Op0 ? B : A;
4184 return BinaryOperator::create(I.getOpcode(), OtherVal,
4185 Constant::getNullValue(A->getType()));
4186 } else if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
4187 // (A-B) == A -> B == 0
4188 return BinaryOperator::create(I.getOpcode(), B,
4189 Constant::getNullValue(B->getType()));
4190 } else if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
4191 // A == (A-B) -> B == 0
4192 return BinaryOperator::create(I.getOpcode(), B,
4193 Constant::getNullValue(B->getType()));
4194 }
4195 }
Chris Lattner113f4f42002-06-25 16:13:24 +00004196 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004197}
4198
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004199// visitSetCondInstWithCastAndCast - Handle setcond (cast x to y), (cast/cst).
4200// We only handle extending casts so far.
4201//
4202Instruction *InstCombiner::visitSetCondInstWithCastAndCast(SetCondInst &SCI) {
4203 Value *LHSCIOp = cast<CastInst>(SCI.getOperand(0))->getOperand(0);
4204 const Type *SrcTy = LHSCIOp->getType();
4205 const Type *DestTy = SCI.getOperand(0)->getType();
4206 Value *RHSCIOp;
4207
4208 if (!DestTy->isIntegral() || !SrcTy->isIntegral())
Chris Lattner03f06f12005-01-17 03:20:02 +00004209 return 0;
4210
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004211 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
4212 unsigned DestBits = DestTy->getPrimitiveSizeInBits();
4213 if (SrcBits >= DestBits) return 0; // Only handle extending cast.
4214
4215 // Is this a sign or zero extension?
4216 bool isSignSrc = SrcTy->isSigned();
4217 bool isSignDest = DestTy->isSigned();
4218
4219 if (CastInst *CI = dyn_cast<CastInst>(SCI.getOperand(1))) {
4220 // Not an extension from the same type?
4221 RHSCIOp = CI->getOperand(0);
4222 if (RHSCIOp->getType() != LHSCIOp->getType()) return 0;
4223 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(SCI.getOperand(1))) {
4224 // Compute the constant that would happen if we truncated to SrcTy then
4225 // reextended to DestTy.
4226 Constant *Res = ConstantExpr::getCast(CI, SrcTy);
4227
4228 if (ConstantExpr::getCast(Res, DestTy) == CI) {
4229 RHSCIOp = Res;
4230 } else {
4231 // If the value cannot be represented in the shorter type, we cannot emit
4232 // a simple comparison.
4233 if (SCI.getOpcode() == Instruction::SetEQ)
4234 return ReplaceInstUsesWith(SCI, ConstantBool::False);
4235 if (SCI.getOpcode() == Instruction::SetNE)
4236 return ReplaceInstUsesWith(SCI, ConstantBool::True);
4237
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004238 // Evaluate the comparison for LT.
4239 Value *Result;
4240 if (DestTy->isSigned()) {
4241 // We're performing a signed comparison.
4242 if (isSignSrc) {
4243 // Signed extend and signed comparison.
4244 if (cast<ConstantSInt>(CI)->getValue() < 0) // X < (small) --> false
4245 Result = ConstantBool::False;
4246 else
4247 Result = ConstantBool::True; // X < (large) --> true
4248 } else {
4249 // Unsigned extend and signed comparison.
4250 if (cast<ConstantSInt>(CI)->getValue() < 0)
4251 Result = ConstantBool::False;
4252 else
4253 Result = ConstantBool::True;
4254 }
4255 } else {
4256 // We're performing an unsigned comparison.
4257 if (!isSignSrc) {
4258 // Unsigned extend & compare -> always true.
4259 Result = ConstantBool::True;
4260 } else {
4261 // We're performing an unsigned comp with a sign extended value.
4262 // This is true if the input is >= 0. [aka >s -1]
4263 Constant *NegOne = ConstantIntegral::getAllOnesValue(SrcTy);
4264 Result = InsertNewInstBefore(BinaryOperator::createSetGT(LHSCIOp,
4265 NegOne, SCI.getName()), SCI);
4266 }
Reid Spencer279fa252004-11-28 21:31:15 +00004267 }
Chris Lattner03f06f12005-01-17 03:20:02 +00004268
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00004269 // Finally, return the value computed.
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004270 if (SCI.getOpcode() == Instruction::SetLT) {
4271 return ReplaceInstUsesWith(SCI, Result);
4272 } else {
4273 assert(SCI.getOpcode()==Instruction::SetGT &&"SetCC should be folded!");
4274 if (Constant *CI = dyn_cast<Constant>(Result))
4275 return ReplaceInstUsesWith(SCI, ConstantExpr::getNot(CI));
4276 else
4277 return BinaryOperator::createNot(Result);
4278 }
Chris Lattner03f06f12005-01-17 03:20:02 +00004279 }
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004280 } else {
4281 return 0;
Reid Spencer279fa252004-11-28 21:31:15 +00004282 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004283
Chris Lattner252a8452005-06-16 03:00:08 +00004284 // Okay, just insert a compare of the reduced operands now!
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004285 return BinaryOperator::create(SCI.getOpcode(), LHSCIOp, RHSCIOp);
4286}
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004287
Chris Lattnere8d6c602003-03-10 19:16:08 +00004288Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +00004289 assert(I.getOperand(1)->getType() == Type::UByteTy);
4290 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00004291 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004292
4293 // shl X, 0 == X and shr X, 0 == X
4294 // shl 0, X == 0 and shr 0, X == 0
4295 if (Op1 == Constant::getNullValue(Type::UByteTy) ||
Chris Lattnere6794492002-08-12 21:17:25 +00004296 Op0 == Constant::getNullValue(Op0->getType()))
4297 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf5b4ef72006-02-12 08:07:37 +00004298
Chris Lattner81a7a232004-10-16 18:11:37 +00004299 if (isa<UndefValue>(Op0)) { // undef >>s X -> undef
4300 if (!isLeftShift && I.getType()->isSigned())
Chris Lattner67f05452004-10-16 23:28:04 +00004301 return ReplaceInstUsesWith(I, Op0);
Chris Lattner81a7a232004-10-16 18:11:37 +00004302 else // undef << X -> 0 AND undef >>u X -> 0
4303 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4304 }
4305 if (isa<UndefValue>(Op1)) {
Chris Lattner18aa4d82005-07-20 18:49:28 +00004306 if (isLeftShift || I.getType()->isUnsigned())// X << undef, X >>u undef -> 0
Chris Lattner81a7a232004-10-16 18:11:37 +00004307 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4308 else
4309 return ReplaceInstUsesWith(I, Op0); // X >>s undef -> X
4310 }
4311
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00004312 // shr int -1, X = -1 (for any arithmetic shift rights of ~0)
4313 if (!isLeftShift)
4314 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
4315 if (CSI->isAllOnesValue())
4316 return ReplaceInstUsesWith(I, CSI);
4317
Chris Lattner183b3362004-04-09 19:05:30 +00004318 // Try to fold constant and into select arguments.
4319 if (isa<Constant>(Op0))
4320 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner86102b82005-01-01 16:22:27 +00004321 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00004322 return R;
4323
Chris Lattnerb18dbbf2005-05-08 17:34:56 +00004324 // See if we can turn a signed shr into an unsigned shr.
4325 if (!isLeftShift && I.getType()->isSigned()) {
Chris Lattnerc3ebf402006-02-07 07:27:52 +00004326 if (MaskedValueIsZero(Op0,
4327 1ULL << (I.getType()->getPrimitiveSizeInBits()-1))) {
Chris Lattnerb18dbbf2005-05-08 17:34:56 +00004328 Value *V = InsertCastBefore(Op0, I.getType()->getUnsignedVersion(), I);
4329 V = InsertNewInstBefore(new ShiftInst(Instruction::Shr, V, Op1,
4330 I.getName()), I);
4331 return new CastInst(V, I.getType());
4332 }
4333 }
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00004334
Chris Lattner14553932006-01-06 07:12:35 +00004335 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op1))
4336 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
4337 return Res;
4338 return 0;
4339}
4340
4341Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantUInt *Op1,
4342 ShiftInst &I) {
4343 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattnerb3309392006-01-06 07:22:22 +00004344 bool isSignedShift = Op0->getType()->isSigned();
4345 bool isUnsignedShift = !isSignedShift;
Chris Lattner14553932006-01-06 07:12:35 +00004346
Chris Lattnerf5b4ef72006-02-12 08:07:37 +00004347 // See if we can simplify any instructions used by the instruction whose sole
4348 // purpose is to compute bits we don't care about.
4349 uint64_t KnownZero, KnownOne;
4350 if (SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
4351 KnownZero, KnownOne))
4352 return &I;
4353
Chris Lattner14553932006-01-06 07:12:35 +00004354 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
4355 // of a signed value.
4356 //
4357 unsigned TypeBits = Op0->getType()->getPrimitiveSizeInBits();
4358 if (Op1->getValue() >= TypeBits) {
Chris Lattnerb3309392006-01-06 07:22:22 +00004359 if (isUnsignedShift || isLeftShift)
Chris Lattner14553932006-01-06 07:12:35 +00004360 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
4361 else {
4362 I.setOperand(1, ConstantUInt::get(Type::UByteTy, TypeBits-1));
4363 return &I;
Chris Lattnerf5ce2542004-02-23 20:30:06 +00004364 }
Chris Lattner14553932006-01-06 07:12:35 +00004365 }
4366
4367 // ((X*C1) << C2) == (X * (C1 << C2))
4368 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
4369 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
4370 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
4371 return BinaryOperator::createMul(BO->getOperand(0),
4372 ConstantExpr::getShl(BOOp, Op1));
4373
4374 // Try to fold constant and into select arguments.
4375 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4376 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4377 return R;
4378 if (isa<PHINode>(Op0))
4379 if (Instruction *NV = FoldOpIntoPhi(I))
4380 return NV;
4381
4382 if (Op0->hasOneUse()) {
Chris Lattner14553932006-01-06 07:12:35 +00004383 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
4384 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
4385 Value *V1, *V2;
4386 ConstantInt *CC;
4387 switch (Op0BO->getOpcode()) {
Chris Lattner27cb9db2005-09-18 05:12:10 +00004388 default: break;
4389 case Instruction::Add:
4390 case Instruction::And:
4391 case Instruction::Or:
4392 case Instruction::Xor:
4393 // These operators commute.
4394 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner797dee72005-09-18 06:30:59 +00004395 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
4396 match(Op0BO->getOperand(1),
Chris Lattner14553932006-01-06 07:12:35 +00004397 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Chris Lattner797dee72005-09-18 06:30:59 +00004398 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00004399 Op0BO->getOperand(0), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00004400 Op0BO->getName());
4401 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner24cd2fa2006-02-09 07:41:14 +00004402 Instruction *X =
4403 BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
4404 Op0BO->getOperand(1)->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00004405 InsertNewInstBefore(X, I); // (X + (Y << C))
4406 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
Chris Lattner14553932006-01-06 07:12:35 +00004407 C2 = ConstantExpr::getShl(C2, Op1);
Chris Lattner797dee72005-09-18 06:30:59 +00004408 return BinaryOperator::createAnd(X, C2);
4409 }
Chris Lattner14553932006-01-06 07:12:35 +00004410
Chris Lattner797dee72005-09-18 06:30:59 +00004411 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
4412 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
4413 match(Op0BO->getOperand(1),
4414 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner14553932006-01-06 07:12:35 +00004415 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner24cd2fa2006-02-09 07:41:14 +00004416 cast<BinaryOperator>(Op0BO->getOperand(1))->getOperand(0)->hasOneUse()) {
Chris Lattner797dee72005-09-18 06:30:59 +00004417 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00004418 Op0BO->getOperand(0), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00004419 Op0BO->getName());
4420 InsertNewInstBefore(YS, I); // (Y << C)
4421 Instruction *XM =
Chris Lattner14553932006-01-06 07:12:35 +00004422 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner797dee72005-09-18 06:30:59 +00004423 V1->getName()+".mask");
4424 InsertNewInstBefore(XM, I); // X & (CC << C)
4425
4426 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
4427 }
Chris Lattner14553932006-01-06 07:12:35 +00004428
Chris Lattner797dee72005-09-18 06:30:59 +00004429 // FALL THROUGH.
Chris Lattner27cb9db2005-09-18 05:12:10 +00004430 case Instruction::Sub:
4431 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner797dee72005-09-18 06:30:59 +00004432 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
4433 match(Op0BO->getOperand(0),
Chris Lattner14553932006-01-06 07:12:35 +00004434 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Chris Lattner797dee72005-09-18 06:30:59 +00004435 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00004436 Op0BO->getOperand(1), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00004437 Op0BO->getName());
4438 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner24cd2fa2006-02-09 07:41:14 +00004439 Instruction *X =
4440 BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
4441 Op0BO->getOperand(0)->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00004442 InsertNewInstBefore(X, I); // (X + (Y << C))
4443 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
Chris Lattner14553932006-01-06 07:12:35 +00004444 C2 = ConstantExpr::getShl(C2, Op1);
Chris Lattner797dee72005-09-18 06:30:59 +00004445 return BinaryOperator::createAnd(X, C2);
4446 }
Chris Lattner14553932006-01-06 07:12:35 +00004447
Chris Lattner797dee72005-09-18 06:30:59 +00004448 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
4449 match(Op0BO->getOperand(0),
4450 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner14553932006-01-06 07:12:35 +00004451 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner24cd2fa2006-02-09 07:41:14 +00004452 cast<BinaryOperator>(Op0BO->getOperand(0))
4453 ->getOperand(0)->hasOneUse()) {
Chris Lattner797dee72005-09-18 06:30:59 +00004454 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00004455 Op0BO->getOperand(1), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00004456 Op0BO->getName());
4457 InsertNewInstBefore(YS, I); // (Y << C)
4458 Instruction *XM =
Chris Lattner14553932006-01-06 07:12:35 +00004459 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner797dee72005-09-18 06:30:59 +00004460 V1->getName()+".mask");
4461 InsertNewInstBefore(XM, I); // X & (CC << C)
4462
4463 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
4464 }
Chris Lattner14553932006-01-06 07:12:35 +00004465
Chris Lattner27cb9db2005-09-18 05:12:10 +00004466 break;
Chris Lattner14553932006-01-06 07:12:35 +00004467 }
4468
4469
4470 // If the operand is an bitwise operator with a constant RHS, and the
4471 // shift is the only use, we can pull it out of the shift.
4472 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
4473 bool isValid = true; // Valid only for And, Or, Xor
4474 bool highBitSet = false; // Transform if high bit of constant set?
4475
4476 switch (Op0BO->getOpcode()) {
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00004477 default: isValid = false; break; // Do not perform transform!
Chris Lattner44bd3922004-10-08 03:46:20 +00004478 case Instruction::Add:
4479 isValid = isLeftShift;
4480 break;
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00004481 case Instruction::Or:
4482 case Instruction::Xor:
4483 highBitSet = false;
4484 break;
4485 case Instruction::And:
4486 highBitSet = true;
4487 break;
Chris Lattner14553932006-01-06 07:12:35 +00004488 }
4489
4490 // If this is a signed shift right, and the high bit is modified
4491 // by the logical operation, do not perform the transformation.
4492 // The highBitSet boolean indicates the value of the high bit of
4493 // the constant which would cause it to be modified for this
4494 // operation.
4495 //
Chris Lattnerb3309392006-01-06 07:22:22 +00004496 if (isValid && !isLeftShift && isSignedShift) {
Chris Lattner14553932006-01-06 07:12:35 +00004497 uint64_t Val = Op0C->getRawValue();
4498 isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
4499 }
4500
4501 if (isValid) {
4502 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
4503
4504 Instruction *NewShift =
4505 new ShiftInst(I.getOpcode(), Op0BO->getOperand(0), Op1,
4506 Op0BO->getName());
4507 Op0BO->setName("");
4508 InsertNewInstBefore(NewShift, I);
4509
4510 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
4511 NewRHS);
4512 }
4513 }
4514 }
4515 }
4516
Chris Lattnereb372a02006-01-06 07:52:12 +00004517 // Find out if this is a shift of a shift by a constant.
4518 ShiftInst *ShiftOp = 0;
Chris Lattner14553932006-01-06 07:12:35 +00004519 if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0))
Chris Lattnereb372a02006-01-06 07:52:12 +00004520 ShiftOp = Op0SI;
4521 else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
4522 // If this is a noop-integer case of a shift instruction, use the shift.
4523 if (CI->getOperand(0)->getType()->isInteger() &&
4524 CI->getOperand(0)->getType()->getPrimitiveSizeInBits() ==
4525 CI->getType()->getPrimitiveSizeInBits() &&
4526 isa<ShiftInst>(CI->getOperand(0))) {
4527 ShiftOp = cast<ShiftInst>(CI->getOperand(0));
4528 }
4529 }
4530
4531 if (ShiftOp && isa<ConstantUInt>(ShiftOp->getOperand(1))) {
4532 // Find the operands and properties of the input shift. Note that the
4533 // signedness of the input shift may differ from the current shift if there
4534 // is a noop cast between the two.
4535 bool isShiftOfLeftShift = ShiftOp->getOpcode() == Instruction::Shl;
4536 bool isShiftOfSignedShift = ShiftOp->getType()->isSigned();
Chris Lattner9cbfbc22006-01-07 01:32:28 +00004537 bool isShiftOfUnsignedShift = !isShiftOfSignedShift;
Chris Lattnereb372a02006-01-06 07:52:12 +00004538
4539 ConstantUInt *ShiftAmt1C = cast<ConstantUInt>(ShiftOp->getOperand(1));
4540
4541 unsigned ShiftAmt1 = (unsigned)ShiftAmt1C->getValue();
4542 unsigned ShiftAmt2 = (unsigned)Op1->getValue();
4543
4544 // Check for (A << c1) << c2 and (A >> c1) >> c2.
4545 if (isLeftShift == isShiftOfLeftShift) {
4546 // Do not fold these shifts if the first one is signed and the second one
4547 // is unsigned and this is a right shift. Further, don't do any folding
4548 // on them.
4549 if (isShiftOfSignedShift && isUnsignedShift && !isLeftShift)
4550 return 0;
Chris Lattner14553932006-01-06 07:12:35 +00004551
Chris Lattnereb372a02006-01-06 07:52:12 +00004552 unsigned Amt = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
4553 if (Amt > Op0->getType()->getPrimitiveSizeInBits())
4554 Amt = Op0->getType()->getPrimitiveSizeInBits();
Chris Lattner14553932006-01-06 07:12:35 +00004555
Chris Lattnereb372a02006-01-06 07:52:12 +00004556 Value *Op = ShiftOp->getOperand(0);
4557 if (isShiftOfSignedShift != isSignedShift)
4558 Op = InsertNewInstBefore(new CastInst(Op, I.getType(), "tmp"), I);
4559 return new ShiftInst(I.getOpcode(), Op,
4560 ConstantUInt::get(Type::UByteTy, Amt));
4561 }
4562
4563 // Check for (A << c1) >> c2 or (A >> c1) << c2. If we are dealing with
4564 // signed types, we can only support the (A >> c1) << c2 configuration,
4565 // because it can not turn an arbitrary bit of A into a sign bit.
4566 if (isUnsignedShift || isLeftShift) {
4567 // Calculate bitmask for what gets shifted off the edge.
4568 Constant *C = ConstantIntegral::getAllOnesValue(I.getType());
4569 if (isLeftShift)
4570 C = ConstantExpr::getShl(C, ShiftAmt1C);
4571 else
Chris Lattner9cbfbc22006-01-07 01:32:28 +00004572 C = ConstantExpr::getUShr(C, ShiftAmt1C);
Chris Lattnereb372a02006-01-06 07:52:12 +00004573
4574 Value *Op = ShiftOp->getOperand(0);
4575 if (isShiftOfSignedShift != isSignedShift)
4576 Op = InsertNewInstBefore(new CastInst(Op, I.getType(),Op->getName()),I);
4577
4578 Instruction *Mask =
4579 BinaryOperator::createAnd(Op, C, Op->getName()+".mask");
4580 InsertNewInstBefore(Mask, I);
4581
4582 // Figure out what flavor of shift we should use...
Chris Lattner9cbfbc22006-01-07 01:32:28 +00004583 if (ShiftAmt1 == ShiftAmt2) {
Chris Lattnereb372a02006-01-06 07:52:12 +00004584 return ReplaceInstUsesWith(I, Mask); // (A << c) >> c === A & c2
Chris Lattner9cbfbc22006-01-07 01:32:28 +00004585 } else if (ShiftAmt1 < ShiftAmt2) {
Chris Lattnereb372a02006-01-06 07:52:12 +00004586 return new ShiftInst(I.getOpcode(), Mask,
4587 ConstantUInt::get(Type::UByteTy, ShiftAmt2-ShiftAmt1));
Chris Lattner9cbfbc22006-01-07 01:32:28 +00004588 } else if (isShiftOfUnsignedShift || isShiftOfLeftShift) {
4589 if (isShiftOfUnsignedShift && !isShiftOfLeftShift && isSignedShift) {
4590 // Make sure to emit an unsigned shift right, not a signed one.
4591 Mask = InsertNewInstBefore(new CastInst(Mask,
4592 Mask->getType()->getUnsignedVersion(),
4593 Op->getName()), I);
4594 Mask = new ShiftInst(Instruction::Shr, Mask,
Chris Lattnereb372a02006-01-06 07:52:12 +00004595 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
Chris Lattner9cbfbc22006-01-07 01:32:28 +00004596 InsertNewInstBefore(Mask, I);
4597 return new CastInst(Mask, I.getType());
4598 } else {
4599 return new ShiftInst(ShiftOp->getOpcode(), Mask,
4600 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
4601 }
4602 } else {
4603 // (X >>s C1) << C2 where C1 > C2 === (X >>s (C1-C2)) & mask
4604 Op = InsertNewInstBefore(new CastInst(Mask,
4605 I.getType()->getSignedVersion(),
4606 Mask->getName()), I);
4607 Instruction *Shift =
4608 new ShiftInst(ShiftOp->getOpcode(), Op,
4609 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
4610 InsertNewInstBefore(Shift, I);
4611
4612 C = ConstantIntegral::getAllOnesValue(Shift->getType());
4613 C = ConstantExpr::getShl(C, Op1);
4614 Mask = BinaryOperator::createAnd(Shift, C, Op->getName()+".mask");
4615 InsertNewInstBefore(Mask, I);
4616 return new CastInst(Mask, I.getType());
Chris Lattnereb372a02006-01-06 07:52:12 +00004617 }
4618 } else {
Chris Lattner9cbfbc22006-01-07 01:32:28 +00004619 // We can handle signed (X << C1) >>s C2 if it's a sign extend. In
Chris Lattnereb372a02006-01-06 07:52:12 +00004620 // this case, C1 == C2 and C1 is 8, 16, or 32.
4621 if (ShiftAmt1 == ShiftAmt2) {
4622 const Type *SExtType = 0;
Chris Lattner655d08f2006-04-28 22:21:41 +00004623 switch (Op0->getType()->getPrimitiveSizeInBits() - ShiftAmt1) {
Chris Lattnereb372a02006-01-06 07:52:12 +00004624 case 8 : SExtType = Type::SByteTy; break;
4625 case 16: SExtType = Type::ShortTy; break;
4626 case 32: SExtType = Type::IntTy; break;
4627 }
4628
4629 if (SExtType) {
4630 Instruction *NewTrunc = new CastInst(ShiftOp->getOperand(0),
4631 SExtType, "sext");
4632 InsertNewInstBefore(NewTrunc, I);
4633 return new CastInst(NewTrunc, I.getType());
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00004634 }
Chris Lattner27cb9db2005-09-18 05:12:10 +00004635 }
Chris Lattner86102b82005-01-01 16:22:27 +00004636 }
Chris Lattnereb372a02006-01-06 07:52:12 +00004637 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004638 return 0;
4639}
4640
Chris Lattner48a44f72002-05-02 17:06:02 +00004641
Chris Lattner8f663e82005-10-29 04:36:15 +00004642/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
4643/// expression. If so, decompose it, returning some value X, such that Val is
4644/// X*Scale+Offset.
4645///
4646static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
4647 unsigned &Offset) {
4648 assert(Val->getType() == Type::UIntTy && "Unexpected allocation size type!");
4649 if (ConstantUInt *CI = dyn_cast<ConstantUInt>(Val)) {
4650 Offset = CI->getValue();
4651 Scale = 1;
4652 return ConstantUInt::get(Type::UIntTy, 0);
4653 } else if (Instruction *I = dyn_cast<Instruction>(Val)) {
4654 if (I->getNumOperands() == 2) {
4655 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(I->getOperand(1))) {
4656 if (I->getOpcode() == Instruction::Shl) {
4657 // This is a value scaled by '1 << the shift amt'.
4658 Scale = 1U << CUI->getValue();
4659 Offset = 0;
4660 return I->getOperand(0);
4661 } else if (I->getOpcode() == Instruction::Mul) {
4662 // This value is scaled by 'CUI'.
4663 Scale = CUI->getValue();
4664 Offset = 0;
4665 return I->getOperand(0);
4666 } else if (I->getOpcode() == Instruction::Add) {
4667 // We have X+C. Check to see if we really have (X*C2)+C1, where C1 is
4668 // divisible by C2.
4669 unsigned SubScale;
4670 Value *SubVal = DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
4671 Offset);
4672 Offset += CUI->getValue();
4673 if (SubScale > 1 && (Offset % SubScale == 0)) {
4674 Scale = SubScale;
4675 return SubVal;
4676 }
4677 }
4678 }
4679 }
4680 }
4681
4682 // Otherwise, we can't look past this.
4683 Scale = 1;
4684 Offset = 0;
4685 return Val;
4686}
4687
4688
Chris Lattner216be912005-10-24 06:03:58 +00004689/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
4690/// try to eliminate the cast by moving the type information into the alloc.
4691Instruction *InstCombiner::PromoteCastOfAllocation(CastInst &CI,
4692 AllocationInst &AI) {
4693 const PointerType *PTy = dyn_cast<PointerType>(CI.getType());
Chris Lattnerbb171802005-10-27 05:53:56 +00004694 if (!PTy) return 0; // Not casting the allocation to a pointer type.
Chris Lattner216be912005-10-24 06:03:58 +00004695
Chris Lattnerac87beb2005-10-24 06:22:12 +00004696 // Remove any uses of AI that are dead.
4697 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
4698 std::vector<Instruction*> DeadUsers;
4699 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
4700 Instruction *User = cast<Instruction>(*UI++);
4701 if (isInstructionTriviallyDead(User)) {
4702 while (UI != E && *UI == User)
4703 ++UI; // If this instruction uses AI more than once, don't break UI.
4704
4705 // Add operands to the worklist.
4706 AddUsesToWorkList(*User);
4707 ++NumDeadInst;
4708 DEBUG(std::cerr << "IC: DCE: " << *User);
4709
4710 User->eraseFromParent();
4711 removeFromWorkList(User);
4712 }
4713 }
4714
Chris Lattner216be912005-10-24 06:03:58 +00004715 // Get the type really allocated and the type casted to.
4716 const Type *AllocElTy = AI.getAllocatedType();
4717 const Type *CastElTy = PTy->getElementType();
4718 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner355ecc02005-10-24 06:26:18 +00004719
4720 unsigned AllocElTyAlign = TD->getTypeSize(AllocElTy);
4721 unsigned CastElTyAlign = TD->getTypeSize(CastElTy);
4722 if (CastElTyAlign < AllocElTyAlign) return 0;
4723
Chris Lattner46705b22005-10-24 06:35:18 +00004724 // If the allocation has multiple uses, only promote it if we are strictly
4725 // increasing the alignment of the resultant allocation. If we keep it the
4726 // same, we open the door to infinite loops of various kinds.
4727 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
4728
Chris Lattner216be912005-10-24 06:03:58 +00004729 uint64_t AllocElTySize = TD->getTypeSize(AllocElTy);
4730 uint64_t CastElTySize = TD->getTypeSize(CastElTy);
Chris Lattnerbb171802005-10-27 05:53:56 +00004731 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner355ecc02005-10-24 06:26:18 +00004732
Chris Lattner8270c332005-10-29 03:19:53 +00004733 // See if we can satisfy the modulus by pulling a scale out of the array
4734 // size argument.
Chris Lattner8f663e82005-10-29 04:36:15 +00004735 unsigned ArraySizeScale, ArrayOffset;
4736 Value *NumElements = // See if the array size is a decomposable linear expr.
4737 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
4738
Chris Lattner8270c332005-10-29 03:19:53 +00004739 // If we can now satisfy the modulus, by using a non-1 scale, we really can
4740 // do the xform.
Chris Lattner8f663e82005-10-29 04:36:15 +00004741 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
4742 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattnerb3ecf962005-10-27 06:12:00 +00004743
Chris Lattner8270c332005-10-29 03:19:53 +00004744 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
4745 Value *Amt = 0;
4746 if (Scale == 1) {
4747 Amt = NumElements;
4748 } else {
4749 Amt = ConstantUInt::get(Type::UIntTy, Scale);
4750 if (ConstantUInt *CI = dyn_cast<ConstantUInt>(NumElements))
4751 Amt = ConstantExpr::getMul(CI, cast<ConstantUInt>(Amt));
4752 else if (Scale != 1) {
4753 Instruction *Tmp = BinaryOperator::createMul(Amt, NumElements, "tmp");
4754 Amt = InsertNewInstBefore(Tmp, AI);
Chris Lattnerb3ecf962005-10-27 06:12:00 +00004755 }
Chris Lattnerbb171802005-10-27 05:53:56 +00004756 }
4757
Chris Lattner8f663e82005-10-29 04:36:15 +00004758 if (unsigned Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
4759 Value *Off = ConstantUInt::get(Type::UIntTy, Offset);
4760 Instruction *Tmp = BinaryOperator::createAdd(Amt, Off, "tmp");
4761 Amt = InsertNewInstBefore(Tmp, AI);
4762 }
4763
Chris Lattner216be912005-10-24 06:03:58 +00004764 std::string Name = AI.getName(); AI.setName("");
4765 AllocationInst *New;
4766 if (isa<MallocInst>(AI))
Nate Begeman848622f2005-11-05 09:21:28 +00004767 New = new MallocInst(CastElTy, Amt, AI.getAlignment(), Name);
Chris Lattner216be912005-10-24 06:03:58 +00004768 else
Nate Begeman848622f2005-11-05 09:21:28 +00004769 New = new AllocaInst(CastElTy, Amt, AI.getAlignment(), Name);
Chris Lattner216be912005-10-24 06:03:58 +00004770 InsertNewInstBefore(New, AI);
Chris Lattner46705b22005-10-24 06:35:18 +00004771
4772 // If the allocation has multiple uses, insert a cast and change all things
4773 // that used it to use the new cast. This will also hack on CI, but it will
4774 // die soon.
4775 if (!AI.hasOneUse()) {
4776 AddUsesToWorkList(AI);
4777 CastInst *NewCast = new CastInst(New, AI.getType(), "tmpcast");
4778 InsertNewInstBefore(NewCast, AI);
4779 AI.replaceAllUsesWith(NewCast);
4780 }
Chris Lattner216be912005-10-24 06:03:58 +00004781 return ReplaceInstUsesWith(CI, New);
4782}
4783
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00004784/// CanEvaluateInDifferentType - Return true if we can take the specified value
4785/// and return it without inserting any new casts. This is used by code that
4786/// tries to decide whether promoting or shrinking integer operations to wider
4787/// or smaller types will allow us to eliminate a truncate or extend.
4788static bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
4789 int &NumCastsRemoved) {
4790 if (isa<Constant>(V)) return true;
4791
4792 Instruction *I = dyn_cast<Instruction>(V);
4793 if (!I || !I->hasOneUse()) return false;
4794
4795 switch (I->getOpcode()) {
4796 case Instruction::And:
4797 case Instruction::Or:
4798 case Instruction::Xor:
4799 // These operators can all arbitrarily be extended or truncated.
4800 return CanEvaluateInDifferentType(I->getOperand(0), Ty, NumCastsRemoved) &&
4801 CanEvaluateInDifferentType(I->getOperand(1), Ty, NumCastsRemoved);
4802 case Instruction::Cast:
4803 // If this is a cast from the destination type, we can trivially eliminate
4804 // it, and this will remove a cast overall.
4805 if (I->getOperand(0)->getType() == Ty) {
4806 ++NumCastsRemoved;
4807 return true;
4808 }
4809 // TODO: Can handle more cases here.
4810 break;
4811 }
4812
4813 return false;
4814}
4815
4816/// EvaluateInDifferentType - Given an expression that
4817/// CanEvaluateInDifferentType returns true for, actually insert the code to
4818/// evaluate the expression.
4819Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty) {
4820 if (Constant *C = dyn_cast<Constant>(V))
4821 return ConstantExpr::getCast(C, Ty);
4822
4823 // Otherwise, it must be an instruction.
4824 Instruction *I = cast<Instruction>(V);
Chris Lattnerd0622b62006-05-20 23:14:03 +00004825 Instruction *Res = 0;
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00004826 switch (I->getOpcode()) {
4827 case Instruction::And:
4828 case Instruction::Or:
4829 case Instruction::Xor: {
4830 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty);
4831 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty);
4832 Res = BinaryOperator::create((Instruction::BinaryOps)I->getOpcode(),
4833 LHS, RHS, I->getName());
4834 break;
4835 }
4836 case Instruction::Cast:
4837 // If this is a cast from the destination type, return the input.
4838 if (I->getOperand(0)->getType() == Ty)
4839 return I->getOperand(0);
4840
4841 // TODO: Can handle more cases here.
4842 assert(0 && "Unreachable!");
4843 break;
4844 }
4845
4846 return InsertNewInstBefore(Res, *I);
4847}
4848
Chris Lattner216be912005-10-24 06:03:58 +00004849
Chris Lattner48a44f72002-05-02 17:06:02 +00004850// CastInst simplification
Chris Lattner260ab202002-04-18 17:39:14 +00004851//
Chris Lattner113f4f42002-06-25 16:13:24 +00004852Instruction *InstCombiner::visitCastInst(CastInst &CI) {
Chris Lattner55d4bda2003-06-23 21:59:52 +00004853 Value *Src = CI.getOperand(0);
4854
Chris Lattner48a44f72002-05-02 17:06:02 +00004855 // If the user is casting a value to the same type, eliminate this cast
4856 // instruction...
Chris Lattner55d4bda2003-06-23 21:59:52 +00004857 if (CI.getType() == Src->getType())
4858 return ReplaceInstUsesWith(CI, Src);
Chris Lattner48a44f72002-05-02 17:06:02 +00004859
Chris Lattner81a7a232004-10-16 18:11:37 +00004860 if (isa<UndefValue>(Src)) // cast undef -> undef
4861 return ReplaceInstUsesWith(CI, UndefValue::get(CI.getType()));
4862
Chris Lattner48a44f72002-05-02 17:06:02 +00004863 // If casting the result of another cast instruction, try to eliminate this
4864 // one!
4865 //
Chris Lattner86102b82005-01-01 16:22:27 +00004866 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
4867 Value *A = CSrc->getOperand(0);
4868 if (isEliminableCastOfCast(A->getType(), CSrc->getType(),
4869 CI.getType(), TD)) {
Chris Lattner48a44f72002-05-02 17:06:02 +00004870 // This instruction now refers directly to the cast's src operand. This
4871 // has a good chance of making CSrc dead.
Chris Lattner113f4f42002-06-25 16:13:24 +00004872 CI.setOperand(0, CSrc->getOperand(0));
4873 return &CI;
Chris Lattner48a44f72002-05-02 17:06:02 +00004874 }
4875
Chris Lattner650b6da2002-08-02 20:00:25 +00004876 // If this is an A->B->A cast, and we are dealing with integral types, try
4877 // to convert this into a logical 'and' instruction.
4878 //
Misha Brukmanb1c93172005-04-21 23:48:37 +00004879 if (A->getType()->isInteger() &&
Chris Lattnerb0b412e2002-09-03 01:08:28 +00004880 CI.getType()->isInteger() && CSrc->getType()->isInteger() &&
Chris Lattner86102b82005-01-01 16:22:27 +00004881 CSrc->getType()->isUnsigned() && // B->A cast must zero extend
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004882 CSrc->getType()->getPrimitiveSizeInBits() <
4883 CI.getType()->getPrimitiveSizeInBits()&&
4884 A->getType()->getPrimitiveSizeInBits() ==
4885 CI.getType()->getPrimitiveSizeInBits()) {
Chris Lattner650b6da2002-08-02 20:00:25 +00004886 assert(CSrc->getType() != Type::ULongTy &&
4887 "Cannot have type bigger than ulong!");
Chris Lattner77defba2006-02-07 07:00:41 +00004888 uint64_t AndValue = CSrc->getType()->getIntegralTypeMask();
Chris Lattner86102b82005-01-01 16:22:27 +00004889 Constant *AndOp = ConstantUInt::get(A->getType()->getUnsignedVersion(),
4890 AndValue);
4891 AndOp = ConstantExpr::getCast(AndOp, A->getType());
4892 Instruction *And = BinaryOperator::createAnd(CSrc->getOperand(0), AndOp);
4893 if (And->getType() != CI.getType()) {
4894 And->setName(CSrc->getName()+".mask");
4895 InsertNewInstBefore(And, CI);
4896 And = new CastInst(And, CI.getType());
4897 }
4898 return And;
Chris Lattner650b6da2002-08-02 20:00:25 +00004899 }
4900 }
Chris Lattner2590e512006-02-07 06:56:34 +00004901
Chris Lattner03841652004-05-25 04:29:21 +00004902 // If this is a cast to bool, turn it into the appropriate setne instruction.
4903 if (CI.getType() == Type::BoolTy)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004904 return BinaryOperator::createSetNE(CI.getOperand(0),
Chris Lattner03841652004-05-25 04:29:21 +00004905 Constant::getNullValue(CI.getOperand(0)->getType()));
4906
Chris Lattner2590e512006-02-07 06:56:34 +00004907 // See if we can simplify any instructions used by the LHS whose sole
4908 // purpose is to compute bits we don't care about.
Chris Lattner0157e7f2006-02-11 09:31:47 +00004909 if (CI.getType()->isInteger() && CI.getOperand(0)->getType()->isIntegral()) {
4910 uint64_t KnownZero, KnownOne;
4911 if (SimplifyDemandedBits(&CI, CI.getType()->getIntegralTypeMask(),
4912 KnownZero, KnownOne))
4913 return &CI;
4914 }
Chris Lattner2590e512006-02-07 06:56:34 +00004915
Chris Lattnerd0d51602003-06-21 23:12:02 +00004916 // If casting the result of a getelementptr instruction with no offset, turn
4917 // this into a cast of the original pointer!
4918 //
Chris Lattner55d4bda2003-06-23 21:59:52 +00004919 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattnerd0d51602003-06-21 23:12:02 +00004920 bool AllZeroOperands = true;
4921 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
4922 if (!isa<Constant>(GEP->getOperand(i)) ||
4923 !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
4924 AllZeroOperands = false;
4925 break;
4926 }
4927 if (AllZeroOperands) {
4928 CI.setOperand(0, GEP->getOperand(0));
4929 return &CI;
4930 }
4931 }
4932
Chris Lattnerf4ad1652003-11-02 05:57:39 +00004933 // If we are casting a malloc or alloca to a pointer to a type of the same
4934 // size, rewrite the allocation instruction to allocate the "right" type.
4935 //
4936 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
Chris Lattner216be912005-10-24 06:03:58 +00004937 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
4938 return V;
Chris Lattnerf4ad1652003-11-02 05:57:39 +00004939
Chris Lattner86102b82005-01-01 16:22:27 +00004940 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
4941 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
4942 return NV;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00004943 if (isa<PHINode>(Src))
4944 if (Instruction *NV = FoldOpIntoPhi(CI))
4945 return NV;
Chris Lattnerb19a5c62006-04-12 18:09:35 +00004946
4947 // If the source and destination are pointers, and this cast is equivalent to
4948 // a getelementptr X, 0, 0, 0... turn it into the appropriate getelementptr.
4949 // This can enhance SROA and other transforms that want type-safe pointers.
4950 if (const PointerType *DstPTy = dyn_cast<PointerType>(CI.getType()))
4951 if (const PointerType *SrcPTy = dyn_cast<PointerType>(Src->getType())) {
4952 const Type *DstTy = DstPTy->getElementType();
4953 const Type *SrcTy = SrcPTy->getElementType();
4954
4955 Constant *ZeroUInt = Constant::getNullValue(Type::UIntTy);
4956 unsigned NumZeros = 0;
4957 while (SrcTy != DstTy &&
4958 isa<CompositeType>(SrcTy) && !isa<PointerType>(SrcTy)) {
4959 SrcTy = cast<CompositeType>(SrcTy)->getTypeAtIndex(ZeroUInt);
4960 ++NumZeros;
4961 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00004962
Chris Lattnerb19a5c62006-04-12 18:09:35 +00004963 // If we found a path from the src to dest, create the getelementptr now.
4964 if (SrcTy == DstTy) {
4965 std::vector<Value*> Idxs(NumZeros+1, ZeroUInt);
4966 return new GetElementPtrInst(Src, Idxs);
4967 }
4968 }
4969
Chris Lattnerdfae8be2003-07-24 17:35:25 +00004970 // If the source value is an instruction with only this use, we can attempt to
4971 // propagate the cast into the instruction. Also, only handle integral types
4972 // for now.
4973 if (Instruction *SrcI = dyn_cast<Instruction>(Src))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00004974 if (SrcI->hasOneUse() && Src->getType()->isIntegral() &&
Chris Lattnerdfae8be2003-07-24 17:35:25 +00004975 CI.getType()->isInteger()) { // Don't mess with casts to bool here
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00004976
4977 int NumCastsRemoved = 0;
4978 if (CanEvaluateInDifferentType(SrcI, CI.getType(), NumCastsRemoved)) {
4979 // If this cast is a truncate, evaluting in a different type always
4980 // eliminates the cast, so it is always a win. If this is a noop-cast
4981 // this just removes a noop cast which isn't pointful, but simplifies
4982 // the code. If this is a zero-extension, we need to do an AND to
4983 // maintain the clear top-part of the computation, so we require that
4984 // the input have eliminated at least one cast. If this is a sign
4985 // extension, we insert two new casts (to do the extension) so we
4986 // require that two casts have been eliminated.
4987 bool DoXForm;
4988 switch (getCastType(Src->getType(), CI.getType())) {
4989 default: assert(0 && "Unknown cast type!");
4990 case Noop:
4991 case Truncate:
4992 DoXForm = true;
4993 break;
4994 case Zeroext:
4995 DoXForm = NumCastsRemoved >= 1;
4996 break;
4997 case Signext:
4998 DoXForm = NumCastsRemoved >= 2;
4999 break;
5000 }
5001
5002 if (DoXForm) {
5003 Value *Res = EvaluateInDifferentType(SrcI, CI.getType());
5004 assert(Res->getType() == CI.getType());
5005 switch (getCastType(Src->getType(), CI.getType())) {
5006 default: assert(0 && "Unknown cast type!");
5007 case Noop:
5008 case Truncate:
5009 // Just replace this cast with the result.
5010 return ReplaceInstUsesWith(CI, Res);
5011 case Zeroext: {
5012 // We need to emit an AND to clear the high bits.
5013 unsigned SrcBitSize = Src->getType()->getPrimitiveSizeInBits();
5014 unsigned DestBitSize = CI.getType()->getPrimitiveSizeInBits();
5015 assert(SrcBitSize < DestBitSize && "Not a zext?");
5016 Constant *C = ConstantUInt::get(Type::ULongTy, (1 << SrcBitSize)-1);
5017 C = ConstantExpr::getCast(C, CI.getType());
5018 return BinaryOperator::createAnd(Res, C);
5019 }
5020 case Signext:
5021 // We need to emit a cast to truncate, then a cast to sext.
5022 return new CastInst(InsertCastBefore(Res, Src->getType(), CI),
5023 CI.getType());
5024 }
5025 }
5026 }
5027
Chris Lattnerdfae8be2003-07-24 17:35:25 +00005028 const Type *DestTy = CI.getType();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005029 unsigned SrcBitSize = Src->getType()->getPrimitiveSizeInBits();
5030 unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
Chris Lattnerdfae8be2003-07-24 17:35:25 +00005031
5032 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
5033 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
5034
5035 switch (SrcI->getOpcode()) {
5036 case Instruction::Add:
5037 case Instruction::Mul:
5038 case Instruction::And:
5039 case Instruction::Or:
5040 case Instruction::Xor:
5041 // If we are discarding information, or just changing the sign, rewrite.
5042 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
5043 // Don't insert two casts if they cannot be eliminated. We allow two
5044 // casts to be inserted if the sizes are the same. This could only be
5045 // converting signedness, which is a noop.
Chris Lattner11ffd592004-07-20 05:21:00 +00005046 if (DestBitSize == SrcBitSize || !ValueRequiresCast(Op1, DestTy,TD) ||
5047 !ValueRequiresCast(Op0, DestTy, TD)) {
Chris Lattnerdfae8be2003-07-24 17:35:25 +00005048 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
5049 Value *Op1c = InsertOperandCastBefore(Op1, DestTy, SrcI);
5050 return BinaryOperator::create(cast<BinaryOperator>(SrcI)
5051 ->getOpcode(), Op0c, Op1c);
5052 }
5053 }
Chris Lattner72086162005-05-06 02:07:39 +00005054
5055 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
5056 if (SrcBitSize == 1 && SrcI->getOpcode() == Instruction::Xor &&
5057 Op1 == ConstantBool::True &&
5058 (!Op0->hasOneUse() || !isa<SetCondInst>(Op0))) {
5059 Value *New = InsertOperandCastBefore(Op0, DestTy, &CI);
5060 return BinaryOperator::createXor(New,
5061 ConstantInt::get(CI.getType(), 1));
5062 }
Chris Lattnerdfae8be2003-07-24 17:35:25 +00005063 break;
5064 case Instruction::Shl:
5065 // Allow changing the sign of the source operand. Do not allow changing
5066 // the size of the shift, UNLESS the shift amount is a constant. We
5067 // mush not change variable sized shifts to a smaller size, because it
5068 // is undefined to shift more bits out than exist in the value.
5069 if (DestBitSize == SrcBitSize ||
5070 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
5071 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
5072 return new ShiftInst(Instruction::Shl, Op0c, Op1);
5073 }
5074 break;
Chris Lattner87380412005-05-06 04:18:52 +00005075 case Instruction::Shr:
5076 // If this is a signed shr, and if all bits shifted in are about to be
5077 // truncated off, turn it into an unsigned shr to allow greater
5078 // simplifications.
5079 if (DestBitSize < SrcBitSize && Src->getType()->isSigned() &&
5080 isa<ConstantInt>(Op1)) {
5081 unsigned ShiftAmt = cast<ConstantUInt>(Op1)->getValue();
5082 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
5083 // Convert to unsigned.
5084 Value *N1 = InsertOperandCastBefore(Op0,
5085 Op0->getType()->getUnsignedVersion(), &CI);
5086 // Insert the new shift, which is now unsigned.
5087 N1 = InsertNewInstBefore(new ShiftInst(Instruction::Shr, N1,
5088 Op1, Src->getName()), CI);
5089 return new CastInst(N1, CI.getType());
5090 }
5091 }
5092 break;
5093
Chris Lattnerc7bfed02006-02-27 02:38:23 +00005094 case Instruction::SetEQ:
Chris Lattner809dfac2005-05-04 19:10:26 +00005095 case Instruction::SetNE:
Chris Lattnerc7bfed02006-02-27 02:38:23 +00005096 // We if we are just checking for a seteq of a single bit and casting it
5097 // to an integer. If so, shift the bit to the appropriate place then
5098 // cast to integer to avoid the comparison.
Chris Lattner809dfac2005-05-04 19:10:26 +00005099 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerc7bfed02006-02-27 02:38:23 +00005100 uint64_t Op1CV = Op1C->getZExtValue();
5101 // cast (X == 0) to int --> X^1 iff X has only the low bit set.
5102 // cast (X == 0) to int --> (X>>1)^1 iff X has only the 2nd bit set.
5103 // cast (X == 1) to int --> X iff X has only the low bit set.
5104 // cast (X == 2) to int --> X>>1 iff X has only the 2nd bit set.
5105 // cast (X != 0) to int --> X iff X has only the low bit set.
5106 // cast (X != 0) to int --> X>>1 iff X has only the 2nd bit set.
5107 // cast (X != 1) to int --> X^1 iff X has only the low bit set.
5108 // cast (X != 2) to int --> (X>>1)^1 iff X has only the 2nd bit set.
5109 if (Op1CV == 0 || isPowerOf2_64(Op1CV)) {
5110 // If Op1C some other power of two, convert:
5111 uint64_t KnownZero, KnownOne;
5112 uint64_t TypeMask = Op1->getType()->getIntegralTypeMask();
5113 ComputeMaskedBits(Op0, TypeMask, KnownZero, KnownOne);
5114
5115 if (isPowerOf2_64(KnownZero^TypeMask)) { // Exactly one possible 1?
5116 bool isSetNE = SrcI->getOpcode() == Instruction::SetNE;
5117 if (Op1CV && (Op1CV != (KnownZero^TypeMask))) {
5118 // (X&4) == 2 --> false
5119 // (X&4) != 2 --> true
Chris Lattnerc5b6c9a2006-02-28 19:47:20 +00005120 Constant *Res = ConstantBool::get(isSetNE);
5121 Res = ConstantExpr::getCast(Res, CI.getType());
5122 return ReplaceInstUsesWith(CI, Res);
Chris Lattnerc7bfed02006-02-27 02:38:23 +00005123 }
5124
5125 unsigned ShiftAmt = Log2_64(KnownZero^TypeMask);
5126 Value *In = Op0;
5127 if (ShiftAmt) {
Chris Lattner4c2d3782005-05-06 01:53:19 +00005128 // Perform an unsigned shr by shiftamt. Convert input to
5129 // unsigned if it is signed.
Chris Lattner4c2d3782005-05-06 01:53:19 +00005130 if (In->getType()->isSigned())
5131 In = InsertNewInstBefore(new CastInst(In,
5132 In->getType()->getUnsignedVersion(), In->getName()),CI);
5133 // Insert the shift to put the result in the low bit.
5134 In = InsertNewInstBefore(new ShiftInst(Instruction::Shr, In,
Chris Lattnerc7bfed02006-02-27 02:38:23 +00005135 ConstantInt::get(Type::UByteTy, ShiftAmt),
5136 In->getName()+".lobit"), CI);
Chris Lattner4c2d3782005-05-06 01:53:19 +00005137 }
Chris Lattnerc7bfed02006-02-27 02:38:23 +00005138
5139 if ((Op1CV != 0) == isSetNE) { // Toggle the low bit.
5140 Constant *One = ConstantInt::get(In->getType(), 1);
5141 In = BinaryOperator::createXor(In, One, "tmp");
5142 InsertNewInstBefore(cast<Instruction>(In), CI);
Chris Lattner4c2d3782005-05-06 01:53:19 +00005143 }
Chris Lattnerc7bfed02006-02-27 02:38:23 +00005144
5145 if (CI.getType() == In->getType())
5146 return ReplaceInstUsesWith(CI, In);
5147 else
5148 return new CastInst(In, CI.getType());
Chris Lattner4c2d3782005-05-06 01:53:19 +00005149 }
Chris Lattner809dfac2005-05-04 19:10:26 +00005150 }
5151 }
5152 break;
Chris Lattnerdfae8be2003-07-24 17:35:25 +00005153 }
5154 }
Chris Lattnerbb171802005-10-27 05:53:56 +00005155
Chris Lattner260ab202002-04-18 17:39:14 +00005156 return 0;
Chris Lattnerca081252001-12-14 16:52:21 +00005157}
5158
Chris Lattner56e4d3d2004-04-09 23:46:01 +00005159/// GetSelectFoldableOperands - We want to turn code that looks like this:
5160/// %C = or %A, %B
5161/// %D = select %cond, %C, %A
5162/// into:
5163/// %C = select %cond, %B, 0
5164/// %D = or %A, %C
5165///
5166/// Assuming that the specified instruction is an operand to the select, return
5167/// a bitmask indicating which operands of this instruction are foldable if they
5168/// equal the other incoming value of the select.
5169///
5170static unsigned GetSelectFoldableOperands(Instruction *I) {
5171 switch (I->getOpcode()) {
5172 case Instruction::Add:
5173 case Instruction::Mul:
5174 case Instruction::And:
5175 case Instruction::Or:
5176 case Instruction::Xor:
5177 return 3; // Can fold through either operand.
5178 case Instruction::Sub: // Can only fold on the amount subtracted.
5179 case Instruction::Shl: // Can only fold on the shift amount.
5180 case Instruction::Shr:
Misha Brukmanb1c93172005-04-21 23:48:37 +00005181 return 1;
Chris Lattner56e4d3d2004-04-09 23:46:01 +00005182 default:
5183 return 0; // Cannot fold
5184 }
5185}
5186
5187/// GetSelectFoldableConstant - For the same transformation as the previous
5188/// function, return the identity constant that goes into the select.
5189static Constant *GetSelectFoldableConstant(Instruction *I) {
5190 switch (I->getOpcode()) {
5191 default: assert(0 && "This cannot happen!"); abort();
5192 case Instruction::Add:
5193 case Instruction::Sub:
5194 case Instruction::Or:
5195 case Instruction::Xor:
5196 return Constant::getNullValue(I->getType());
5197 case Instruction::Shl:
5198 case Instruction::Shr:
5199 return Constant::getNullValue(Type::UByteTy);
5200 case Instruction::And:
5201 return ConstantInt::getAllOnesValue(I->getType());
5202 case Instruction::Mul:
5203 return ConstantInt::get(I->getType(), 1);
5204 }
5205}
5206
Chris Lattner411336f2005-01-19 21:50:18 +00005207/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
5208/// have the same opcode and only one use each. Try to simplify this.
5209Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
5210 Instruction *FI) {
5211 if (TI->getNumOperands() == 1) {
5212 // If this is a non-volatile load or a cast from the same type,
5213 // merge.
5214 if (TI->getOpcode() == Instruction::Cast) {
5215 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
5216 return 0;
5217 } else {
5218 return 0; // unknown unary op.
5219 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00005220
Chris Lattner411336f2005-01-19 21:50:18 +00005221 // Fold this by inserting a select from the input values.
5222 SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
5223 FI->getOperand(0), SI.getName()+".v");
5224 InsertNewInstBefore(NewSI, SI);
5225 return new CastInst(NewSI, TI->getType());
5226 }
5227
5228 // Only handle binary operators here.
5229 if (!isa<ShiftInst>(TI) && !isa<BinaryOperator>(TI))
5230 return 0;
5231
5232 // Figure out if the operations have any operands in common.
5233 Value *MatchOp, *OtherOpT, *OtherOpF;
5234 bool MatchIsOpZero;
5235 if (TI->getOperand(0) == FI->getOperand(0)) {
5236 MatchOp = TI->getOperand(0);
5237 OtherOpT = TI->getOperand(1);
5238 OtherOpF = FI->getOperand(1);
5239 MatchIsOpZero = true;
5240 } else if (TI->getOperand(1) == FI->getOperand(1)) {
5241 MatchOp = TI->getOperand(1);
5242 OtherOpT = TI->getOperand(0);
5243 OtherOpF = FI->getOperand(0);
5244 MatchIsOpZero = false;
5245 } else if (!TI->isCommutative()) {
5246 return 0;
5247 } else if (TI->getOperand(0) == FI->getOperand(1)) {
5248 MatchOp = TI->getOperand(0);
5249 OtherOpT = TI->getOperand(1);
5250 OtherOpF = FI->getOperand(0);
5251 MatchIsOpZero = true;
5252 } else if (TI->getOperand(1) == FI->getOperand(0)) {
5253 MatchOp = TI->getOperand(1);
5254 OtherOpT = TI->getOperand(0);
5255 OtherOpF = FI->getOperand(1);
5256 MatchIsOpZero = true;
5257 } else {
5258 return 0;
5259 }
5260
5261 // If we reach here, they do have operations in common.
5262 SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
5263 OtherOpF, SI.getName()+".v");
5264 InsertNewInstBefore(NewSI, SI);
5265
5266 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
5267 if (MatchIsOpZero)
5268 return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
5269 else
5270 return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
5271 } else {
5272 if (MatchIsOpZero)
5273 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), MatchOp, NewSI);
5274 else
5275 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), NewSI, MatchOp);
5276 }
5277}
5278
Chris Lattnerb909e8b2004-03-12 05:52:32 +00005279Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattner533bc492004-03-30 19:37:13 +00005280 Value *CondVal = SI.getCondition();
5281 Value *TrueVal = SI.getTrueValue();
5282 Value *FalseVal = SI.getFalseValue();
5283
5284 // select true, X, Y -> X
5285 // select false, X, Y -> Y
5286 if (ConstantBool *C = dyn_cast<ConstantBool>(CondVal))
Chris Lattnerb909e8b2004-03-12 05:52:32 +00005287 if (C == ConstantBool::True)
Chris Lattner533bc492004-03-30 19:37:13 +00005288 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattnerb909e8b2004-03-12 05:52:32 +00005289 else {
5290 assert(C == ConstantBool::False);
Chris Lattner533bc492004-03-30 19:37:13 +00005291 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattnerb909e8b2004-03-12 05:52:32 +00005292 }
Chris Lattner533bc492004-03-30 19:37:13 +00005293
5294 // select C, X, X -> X
5295 if (TrueVal == FalseVal)
5296 return ReplaceInstUsesWith(SI, TrueVal);
5297
Chris Lattner81a7a232004-10-16 18:11:37 +00005298 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
5299 return ReplaceInstUsesWith(SI, FalseVal);
5300 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
5301 return ReplaceInstUsesWith(SI, TrueVal);
5302 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
5303 if (isa<Constant>(TrueVal))
5304 return ReplaceInstUsesWith(SI, TrueVal);
5305 else
5306 return ReplaceInstUsesWith(SI, FalseVal);
5307 }
5308
Chris Lattner1c631e82004-04-08 04:43:23 +00005309 if (SI.getType() == Type::BoolTy)
5310 if (ConstantBool *C = dyn_cast<ConstantBool>(TrueVal)) {
5311 if (C == ConstantBool::True) {
5312 // Change: A = select B, true, C --> A = or B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00005313 return BinaryOperator::createOr(CondVal, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00005314 } else {
5315 // Change: A = select B, false, C --> A = and !B, C
5316 Value *NotCond =
5317 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
5318 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00005319 return BinaryOperator::createAnd(NotCond, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00005320 }
5321 } else if (ConstantBool *C = dyn_cast<ConstantBool>(FalseVal)) {
5322 if (C == ConstantBool::False) {
5323 // Change: A = select B, C, false --> A = and B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00005324 return BinaryOperator::createAnd(CondVal, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00005325 } else {
5326 // Change: A = select B, C, true --> A = or !B, C
5327 Value *NotCond =
5328 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
5329 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00005330 return BinaryOperator::createOr(NotCond, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00005331 }
5332 }
5333
Chris Lattner183b3362004-04-09 19:05:30 +00005334 // Selecting between two integer constants?
5335 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
5336 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
5337 // select C, 1, 0 -> cast C to int
5338 if (FalseValC->isNullValue() && TrueValC->getRawValue() == 1) {
5339 return new CastInst(CondVal, SI.getType());
5340 } else if (TrueValC->isNullValue() && FalseValC->getRawValue() == 1) {
5341 // select C, 0, 1 -> cast !C to int
5342 Value *NotCond =
5343 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
Chris Lattnercf7baf32004-04-09 18:19:44 +00005344 "not."+CondVal->getName()), SI);
Chris Lattner183b3362004-04-09 19:05:30 +00005345 return new CastInst(NotCond, SI.getType());
Chris Lattnercf7baf32004-04-09 18:19:44 +00005346 }
Chris Lattner35167c32004-06-09 07:59:58 +00005347
5348 // If one of the constants is zero (we know they can't both be) and we
5349 // have a setcc instruction with zero, and we have an 'and' with the
5350 // non-constant value, eliminate this whole mess. This corresponds to
5351 // cases like this: ((X & 27) ? 27 : 0)
5352 if (TrueValC->isNullValue() || FalseValC->isNullValue())
5353 if (Instruction *IC = dyn_cast<Instruction>(SI.getCondition()))
5354 if ((IC->getOpcode() == Instruction::SetEQ ||
5355 IC->getOpcode() == Instruction::SetNE) &&
5356 isa<ConstantInt>(IC->getOperand(1)) &&
5357 cast<Constant>(IC->getOperand(1))->isNullValue())
5358 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
5359 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00005360 isa<ConstantInt>(ICA->getOperand(1)) &&
5361 (ICA->getOperand(1) == TrueValC ||
5362 ICA->getOperand(1) == FalseValC) &&
Chris Lattner35167c32004-06-09 07:59:58 +00005363 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
5364 // Okay, now we know that everything is set up, we just don't
5365 // know whether we have a setne or seteq and whether the true or
5366 // false val is the zero.
5367 bool ShouldNotVal = !TrueValC->isNullValue();
5368 ShouldNotVal ^= IC->getOpcode() == Instruction::SetNE;
5369 Value *V = ICA;
5370 if (ShouldNotVal)
5371 V = InsertNewInstBefore(BinaryOperator::create(
5372 Instruction::Xor, V, ICA->getOperand(1)), SI);
5373 return ReplaceInstUsesWith(SI, V);
5374 }
Chris Lattner533bc492004-03-30 19:37:13 +00005375 }
Chris Lattner623fba12004-04-10 22:21:27 +00005376
5377 // See if we are selecting two values based on a comparison of the two values.
5378 if (SetCondInst *SCI = dyn_cast<SetCondInst>(CondVal)) {
5379 if (SCI->getOperand(0) == TrueVal && SCI->getOperand(1) == FalseVal) {
5380 // Transform (X == Y) ? X : Y -> Y
5381 if (SCI->getOpcode() == Instruction::SetEQ)
5382 return ReplaceInstUsesWith(SI, FalseVal);
5383 // Transform (X != Y) ? X : Y -> X
5384 if (SCI->getOpcode() == Instruction::SetNE)
5385 return ReplaceInstUsesWith(SI, TrueVal);
5386 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
5387
5388 } else if (SCI->getOperand(0) == FalseVal && SCI->getOperand(1) == TrueVal){
5389 // Transform (X == Y) ? Y : X -> X
5390 if (SCI->getOpcode() == Instruction::SetEQ)
Chris Lattner24cf0202004-04-11 01:39:19 +00005391 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattner623fba12004-04-10 22:21:27 +00005392 // Transform (X != Y) ? Y : X -> Y
5393 if (SCI->getOpcode() == Instruction::SetNE)
Chris Lattner24cf0202004-04-11 01:39:19 +00005394 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattner623fba12004-04-10 22:21:27 +00005395 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
5396 }
5397 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00005398
Chris Lattnera04c9042005-01-13 22:52:24 +00005399 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
5400 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
5401 if (TI->hasOneUse() && FI->hasOneUse()) {
5402 bool isInverse = false;
5403 Instruction *AddOp = 0, *SubOp = 0;
5404
Chris Lattner411336f2005-01-19 21:50:18 +00005405 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
5406 if (TI->getOpcode() == FI->getOpcode())
5407 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
5408 return IV;
5409
5410 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
5411 // even legal for FP.
Chris Lattnera04c9042005-01-13 22:52:24 +00005412 if (TI->getOpcode() == Instruction::Sub &&
5413 FI->getOpcode() == Instruction::Add) {
5414 AddOp = FI; SubOp = TI;
5415 } else if (FI->getOpcode() == Instruction::Sub &&
5416 TI->getOpcode() == Instruction::Add) {
5417 AddOp = TI; SubOp = FI;
5418 }
5419
5420 if (AddOp) {
5421 Value *OtherAddOp = 0;
5422 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
5423 OtherAddOp = AddOp->getOperand(1);
5424 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
5425 OtherAddOp = AddOp->getOperand(0);
5426 }
5427
5428 if (OtherAddOp) {
Chris Lattnerb580d262006-02-24 18:05:58 +00005429 // So at this point we know we have (Y -> OtherAddOp):
5430 // select C, (add X, Y), (sub X, Z)
5431 Value *NegVal; // Compute -Z
5432 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
5433 NegVal = ConstantExpr::getNeg(C);
5434 } else {
5435 NegVal = InsertNewInstBefore(
5436 BinaryOperator::createNeg(SubOp->getOperand(1), "tmp"), SI);
Chris Lattnera04c9042005-01-13 22:52:24 +00005437 }
Chris Lattnerb580d262006-02-24 18:05:58 +00005438
5439 Value *NewTrueOp = OtherAddOp;
5440 Value *NewFalseOp = NegVal;
5441 if (AddOp != TI)
5442 std::swap(NewTrueOp, NewFalseOp);
5443 Instruction *NewSel =
5444 new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
5445
5446 NewSel = InsertNewInstBefore(NewSel, SI);
5447 return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
Chris Lattnera04c9042005-01-13 22:52:24 +00005448 }
5449 }
5450 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00005451
Chris Lattner56e4d3d2004-04-09 23:46:01 +00005452 // See if we can fold the select into one of our operands.
5453 if (SI.getType()->isInteger()) {
5454 // See the comment above GetSelectFoldableOperands for a description of the
5455 // transformation we are doing here.
5456 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
5457 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
5458 !isa<Constant>(FalseVal))
5459 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
5460 unsigned OpToFold = 0;
5461 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
5462 OpToFold = 1;
5463 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
5464 OpToFold = 2;
5465 }
5466
5467 if (OpToFold) {
5468 Constant *C = GetSelectFoldableConstant(TVI);
5469 std::string Name = TVI->getName(); TVI->setName("");
5470 Instruction *NewSel =
5471 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C,
5472 Name);
5473 InsertNewInstBefore(NewSel, SI);
5474 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
5475 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
5476 else if (ShiftInst *SI = dyn_cast<ShiftInst>(TVI))
5477 return new ShiftInst(SI->getOpcode(), FalseVal, NewSel);
5478 else {
5479 assert(0 && "Unknown instruction!!");
5480 }
5481 }
5482 }
Chris Lattner6862fbd2004-09-29 17:40:11 +00005483
Chris Lattner56e4d3d2004-04-09 23:46:01 +00005484 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
5485 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
5486 !isa<Constant>(TrueVal))
5487 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
5488 unsigned OpToFold = 0;
5489 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
5490 OpToFold = 1;
5491 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
5492 OpToFold = 2;
5493 }
5494
5495 if (OpToFold) {
5496 Constant *C = GetSelectFoldableConstant(FVI);
5497 std::string Name = FVI->getName(); FVI->setName("");
5498 Instruction *NewSel =
5499 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold),
5500 Name);
5501 InsertNewInstBefore(NewSel, SI);
5502 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
5503 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
5504 else if (ShiftInst *SI = dyn_cast<ShiftInst>(FVI))
5505 return new ShiftInst(SI->getOpcode(), TrueVal, NewSel);
5506 else {
5507 assert(0 && "Unknown instruction!!");
5508 }
5509 }
5510 }
5511 }
Chris Lattnerd6f636a2005-04-24 07:30:14 +00005512
5513 if (BinaryOperator::isNot(CondVal)) {
5514 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
5515 SI.setOperand(1, FalseVal);
5516 SI.setOperand(2, TrueVal);
5517 return &SI;
5518 }
5519
Chris Lattnerb909e8b2004-03-12 05:52:32 +00005520 return 0;
5521}
5522
Chris Lattner82f2ef22006-03-06 20:18:44 +00005523/// GetKnownAlignment - If the specified pointer has an alignment that we can
5524/// determine, return it, otherwise return 0.
5525static unsigned GetKnownAlignment(Value *V, TargetData *TD) {
5526 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
5527 unsigned Align = GV->getAlignment();
5528 if (Align == 0 && TD)
5529 Align = TD->getTypeAlignment(GV->getType()->getElementType());
5530 return Align;
5531 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
5532 unsigned Align = AI->getAlignment();
5533 if (Align == 0 && TD) {
5534 if (isa<AllocaInst>(AI))
5535 Align = TD->getTypeAlignment(AI->getType()->getElementType());
5536 else if (isa<MallocInst>(AI)) {
5537 // Malloc returns maximally aligned memory.
5538 Align = TD->getTypeAlignment(AI->getType()->getElementType());
5539 Align = std::max(Align, (unsigned)TD->getTypeAlignment(Type::DoubleTy));
5540 Align = std::max(Align, (unsigned)TD->getTypeAlignment(Type::LongTy));
5541 }
5542 }
5543 return Align;
Chris Lattner53ef5a02006-03-07 01:28:57 +00005544 } else if (isa<CastInst>(V) ||
5545 (isa<ConstantExpr>(V) &&
5546 cast<ConstantExpr>(V)->getOpcode() == Instruction::Cast)) {
5547 User *CI = cast<User>(V);
Chris Lattner82f2ef22006-03-06 20:18:44 +00005548 if (isa<PointerType>(CI->getOperand(0)->getType()))
5549 return GetKnownAlignment(CI->getOperand(0), TD);
5550 return 0;
Chris Lattner53ef5a02006-03-07 01:28:57 +00005551 } else if (isa<GetElementPtrInst>(V) ||
5552 (isa<ConstantExpr>(V) &&
5553 cast<ConstantExpr>(V)->getOpcode()==Instruction::GetElementPtr)) {
5554 User *GEPI = cast<User>(V);
Chris Lattner82f2ef22006-03-06 20:18:44 +00005555 unsigned BaseAlignment = GetKnownAlignment(GEPI->getOperand(0), TD);
5556 if (BaseAlignment == 0) return 0;
5557
5558 // If all indexes are zero, it is just the alignment of the base pointer.
5559 bool AllZeroOperands = true;
5560 for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
5561 if (!isa<Constant>(GEPI->getOperand(i)) ||
5562 !cast<Constant>(GEPI->getOperand(i))->isNullValue()) {
5563 AllZeroOperands = false;
5564 break;
5565 }
5566 if (AllZeroOperands)
5567 return BaseAlignment;
5568
5569 // Otherwise, if the base alignment is >= the alignment we expect for the
5570 // base pointer type, then we know that the resultant pointer is aligned at
5571 // least as much as its type requires.
5572 if (!TD) return 0;
5573
5574 const Type *BasePtrTy = GEPI->getOperand(0)->getType();
5575 if (TD->getTypeAlignment(cast<PointerType>(BasePtrTy)->getElementType())
Chris Lattner53ef5a02006-03-07 01:28:57 +00005576 <= BaseAlignment) {
5577 const Type *GEPTy = GEPI->getType();
5578 return TD->getTypeAlignment(cast<PointerType>(GEPTy)->getElementType());
5579 }
Chris Lattner82f2ef22006-03-06 20:18:44 +00005580 return 0;
5581 }
5582 return 0;
5583}
5584
Chris Lattnerb909e8b2004-03-12 05:52:32 +00005585
Chris Lattnerc66b2232006-01-13 20:11:04 +00005586/// visitCallInst - CallInst simplification. This mostly only handles folding
5587/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
5588/// the heavy lifting.
5589///
Chris Lattner970c33a2003-06-19 17:00:31 +00005590Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattnerc66b2232006-01-13 20:11:04 +00005591 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
5592 if (!II) return visitCallSite(&CI);
5593
Chris Lattner51ea1272004-02-28 05:22:00 +00005594 // Intrinsics cannot occur in an invoke, so handle them here instead of in
5595 // visitCallSite.
Chris Lattnerc66b2232006-01-13 20:11:04 +00005596 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner00648e12004-10-12 04:52:52 +00005597 bool Changed = false;
5598
5599 // memmove/cpy/set of zero bytes is a noop.
5600 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
5601 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
5602
Chris Lattner00648e12004-10-12 04:52:52 +00005603 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
5604 if (CI->getRawValue() == 1) {
5605 // Replace the instruction with just byte operations. We would
5606 // transform other cases to loads/stores, but we don't know if
5607 // alignment is sufficient.
5608 }
Chris Lattner51ea1272004-02-28 05:22:00 +00005609 }
5610
Chris Lattner00648e12004-10-12 04:52:52 +00005611 // If we have a memmove and the source operation is a constant global,
5612 // then the source and dest pointers can't alias, so we can change this
5613 // into a call to memcpy.
Chris Lattner82f2ef22006-03-06 20:18:44 +00005614 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(II)) {
Chris Lattner00648e12004-10-12 04:52:52 +00005615 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
5616 if (GVSrc->isConstant()) {
5617 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner681ef2f2006-03-03 01:34:17 +00005618 const char *Name;
5619 if (CI.getCalledFunction()->getFunctionType()->getParamType(3) ==
5620 Type::UIntTy)
5621 Name = "llvm.memcpy.i32";
5622 else
5623 Name = "llvm.memcpy.i64";
5624 Function *MemCpy = M->getOrInsertFunction(Name,
Chris Lattner00648e12004-10-12 04:52:52 +00005625 CI.getCalledFunction()->getFunctionType());
5626 CI.setOperand(0, MemCpy);
5627 Changed = true;
5628 }
Chris Lattner82f2ef22006-03-06 20:18:44 +00005629 }
Chris Lattner00648e12004-10-12 04:52:52 +00005630
Chris Lattner82f2ef22006-03-06 20:18:44 +00005631 // If we can determine a pointer alignment that is bigger than currently
5632 // set, update the alignment.
5633 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
5634 unsigned Alignment1 = GetKnownAlignment(MI->getOperand(1), TD);
5635 unsigned Alignment2 = GetKnownAlignment(MI->getOperand(2), TD);
5636 unsigned Align = std::min(Alignment1, Alignment2);
5637 if (MI->getAlignment()->getRawValue() < Align) {
5638 MI->setAlignment(ConstantUInt::get(Type::UIntTy, Align));
5639 Changed = true;
5640 }
5641 } else if (isa<MemSetInst>(MI)) {
5642 unsigned Alignment = GetKnownAlignment(MI->getDest(), TD);
5643 if (MI->getAlignment()->getRawValue() < Alignment) {
5644 MI->setAlignment(ConstantUInt::get(Type::UIntTy, Alignment));
5645 Changed = true;
5646 }
5647 }
5648
Chris Lattnerc66b2232006-01-13 20:11:04 +00005649 if (Changed) return II;
Chris Lattner503221f2006-01-13 21:28:09 +00005650 } else {
5651 switch (II->getIntrinsicID()) {
5652 default: break;
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00005653 case Intrinsic::ppc_altivec_lvx:
5654 case Intrinsic::ppc_altivec_lvxl:
Chris Lattner36dd7c92006-04-17 22:26:56 +00005655 case Intrinsic::x86_sse_loadu_ps:
5656 case Intrinsic::x86_sse2_loadu_pd:
5657 case Intrinsic::x86_sse2_loadu_dq:
5658 // Turn PPC lvx -> load if the pointer is known aligned.
5659 // Turn X86 loadups -> load if the pointer is known aligned.
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00005660 if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
Chris Lattnere79d2492006-04-06 19:19:17 +00005661 Value *Ptr = InsertCastBefore(II->getOperand(1),
5662 PointerType::get(II->getType()), CI);
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00005663 return new LoadInst(Ptr);
5664 }
5665 break;
5666 case Intrinsic::ppc_altivec_stvx:
5667 case Intrinsic::ppc_altivec_stvxl:
5668 // Turn stvx -> store if the pointer is known aligned.
5669 if (GetKnownAlignment(II->getOperand(2), TD) >= 16) {
Chris Lattnere79d2492006-04-06 19:19:17 +00005670 const Type *OpPtrTy = PointerType::get(II->getOperand(1)->getType());
5671 Value *Ptr = InsertCastBefore(II->getOperand(2), OpPtrTy, CI);
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00005672 return new StoreInst(II->getOperand(1), Ptr);
5673 }
5674 break;
Chris Lattner36dd7c92006-04-17 22:26:56 +00005675 case Intrinsic::x86_sse_storeu_ps:
5676 case Intrinsic::x86_sse2_storeu_pd:
5677 case Intrinsic::x86_sse2_storeu_dq:
5678 case Intrinsic::x86_sse2_storel_dq:
5679 // Turn X86 storeu -> store if the pointer is known aligned.
5680 if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
5681 const Type *OpPtrTy = PointerType::get(II->getOperand(2)->getType());
5682 Value *Ptr = InsertCastBefore(II->getOperand(1), OpPtrTy, CI);
5683 return new StoreInst(II->getOperand(2), Ptr);
5684 }
5685 break;
Chris Lattnere79d2492006-04-06 19:19:17 +00005686 case Intrinsic::ppc_altivec_vperm:
5687 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
5688 if (ConstantPacked *Mask = dyn_cast<ConstantPacked>(II->getOperand(3))) {
5689 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
5690
5691 // Check that all of the elements are integer constants or undefs.
5692 bool AllEltsOk = true;
5693 for (unsigned i = 0; i != 16; ++i) {
5694 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
5695 !isa<UndefValue>(Mask->getOperand(i))) {
5696 AllEltsOk = false;
5697 break;
5698 }
5699 }
5700
5701 if (AllEltsOk) {
5702 // Cast the input vectors to byte vectors.
5703 Value *Op0 = InsertCastBefore(II->getOperand(1), Mask->getType(), CI);
5704 Value *Op1 = InsertCastBefore(II->getOperand(2), Mask->getType(), CI);
5705 Value *Result = UndefValue::get(Op0->getType());
5706
5707 // Only extract each element once.
5708 Value *ExtractedElts[32];
5709 memset(ExtractedElts, 0, sizeof(ExtractedElts));
5710
5711 for (unsigned i = 0; i != 16; ++i) {
5712 if (isa<UndefValue>(Mask->getOperand(i)))
5713 continue;
5714 unsigned Idx =cast<ConstantInt>(Mask->getOperand(i))->getRawValue();
5715 Idx &= 31; // Match the hardware behavior.
5716
5717 if (ExtractedElts[Idx] == 0) {
5718 Instruction *Elt =
5719 new ExtractElementInst(Idx < 16 ? Op0 : Op1,
5720 ConstantUInt::get(Type::UIntTy, Idx&15),
5721 "tmp");
5722 InsertNewInstBefore(Elt, CI);
5723 ExtractedElts[Idx] = Elt;
5724 }
5725
5726 // Insert this value into the result vector.
5727 Result = new InsertElementInst(Result, ExtractedElts[Idx],
5728 ConstantUInt::get(Type::UIntTy, i),
5729 "tmp");
5730 InsertNewInstBefore(cast<Instruction>(Result), CI);
5731 }
5732 return new CastInst(Result, CI.getType());
5733 }
5734 }
5735 break;
5736
Chris Lattner503221f2006-01-13 21:28:09 +00005737 case Intrinsic::stackrestore: {
5738 // If the save is right next to the restore, remove the restore. This can
5739 // happen when variable allocas are DCE'd.
5740 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
5741 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
5742 BasicBlock::iterator BI = SS;
5743 if (&*++BI == II)
5744 return EraseInstFromFunction(CI);
5745 }
5746 }
5747
5748 // If the stack restore is in a return/unwind block and if there are no
5749 // allocas or calls between the restore and the return, nuke the restore.
5750 TerminatorInst *TI = II->getParent()->getTerminator();
5751 if (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)) {
5752 BasicBlock::iterator BI = II;
5753 bool CannotRemove = false;
5754 for (++BI; &*BI != TI; ++BI) {
5755 if (isa<AllocaInst>(BI) ||
5756 (isa<CallInst>(BI) && !isa<IntrinsicInst>(BI))) {
5757 CannotRemove = true;
5758 break;
5759 }
5760 }
5761 if (!CannotRemove)
5762 return EraseInstFromFunction(CI);
5763 }
5764 break;
5765 }
5766 }
Chris Lattner00648e12004-10-12 04:52:52 +00005767 }
5768
Chris Lattnerc66b2232006-01-13 20:11:04 +00005769 return visitCallSite(II);
Chris Lattner970c33a2003-06-19 17:00:31 +00005770}
5771
5772// InvokeInst simplification
5773//
5774Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattneraec3d942003-10-07 22:32:43 +00005775 return visitCallSite(&II);
Chris Lattner970c33a2003-06-19 17:00:31 +00005776}
5777
Chris Lattneraec3d942003-10-07 22:32:43 +00005778// visitCallSite - Improvements for call and invoke instructions.
5779//
5780Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner75b4d1d2003-10-07 22:54:13 +00005781 bool Changed = false;
5782
5783 // If the callee is a constexpr cast of a function, attempt to move the cast
5784 // to the arguments of the call/invoke.
Chris Lattneraec3d942003-10-07 22:32:43 +00005785 if (transformConstExprCastCall(CS)) return 0;
5786
Chris Lattner75b4d1d2003-10-07 22:54:13 +00005787 Value *Callee = CS.getCalledValue();
Chris Lattner81a7a232004-10-16 18:11:37 +00005788
Chris Lattner61d9d812005-05-13 07:09:09 +00005789 if (Function *CalleeF = dyn_cast<Function>(Callee))
5790 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
5791 Instruction *OldCall = CS.getInstruction();
5792 // If the call and callee calling conventions don't match, this call must
5793 // be unreachable, as the call is undefined.
5794 new StoreInst(ConstantBool::True,
5795 UndefValue::get(PointerType::get(Type::BoolTy)), OldCall);
5796 if (!OldCall->use_empty())
5797 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
5798 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
5799 return EraseInstFromFunction(*OldCall);
5800 return 0;
5801 }
5802
Chris Lattner8ba9ec92004-10-18 02:59:09 +00005803 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
5804 // This instruction is not reachable, just remove it. We insert a store to
5805 // undef so that we know that this code is not reachable, despite the fact
5806 // that we can't modify the CFG here.
5807 new StoreInst(ConstantBool::True,
5808 UndefValue::get(PointerType::get(Type::BoolTy)),
5809 CS.getInstruction());
5810
5811 if (!CS.getInstruction()->use_empty())
5812 CS.getInstruction()->
5813 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
5814
5815 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
5816 // Don't break the CFG, insert a dummy cond branch.
5817 new BranchInst(II->getNormalDest(), II->getUnwindDest(),
5818 ConstantBool::True, II);
Chris Lattner81a7a232004-10-16 18:11:37 +00005819 }
Chris Lattner8ba9ec92004-10-18 02:59:09 +00005820 return EraseInstFromFunction(*CS.getInstruction());
5821 }
Chris Lattner81a7a232004-10-16 18:11:37 +00005822
Chris Lattner75b4d1d2003-10-07 22:54:13 +00005823 const PointerType *PTy = cast<PointerType>(Callee->getType());
5824 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
5825 if (FTy->isVarArg()) {
5826 // See if we can optimize any arguments passed through the varargs area of
5827 // the call.
5828 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
5829 E = CS.arg_end(); I != E; ++I)
5830 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
5831 // If this cast does not effect the value passed through the varargs
5832 // area, we can eliminate the use of the cast.
5833 Value *Op = CI->getOperand(0);
5834 if (CI->getType()->isLosslesslyConvertibleTo(Op->getType())) {
5835 *I = Op;
5836 Changed = true;
5837 }
5838 }
5839 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00005840
Chris Lattner75b4d1d2003-10-07 22:54:13 +00005841 return Changed ? CS.getInstruction() : 0;
Chris Lattneraec3d942003-10-07 22:32:43 +00005842}
5843
Chris Lattner970c33a2003-06-19 17:00:31 +00005844// transformConstExprCastCall - If the callee is a constexpr cast of a function,
5845// attempt to move the cast to the arguments of the call/invoke.
5846//
5847bool InstCombiner::transformConstExprCastCall(CallSite CS) {
5848 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
5849 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Chris Lattnerf3edc492004-07-18 18:59:44 +00005850 if (CE->getOpcode() != Instruction::Cast || !isa<Function>(CE->getOperand(0)))
Chris Lattner970c33a2003-06-19 17:00:31 +00005851 return false;
Reid Spencer87436872004-07-18 00:38:32 +00005852 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner970c33a2003-06-19 17:00:31 +00005853 Instruction *Caller = CS.getInstruction();
5854
5855 // Okay, this is a cast from a function to a different type. Unless doing so
5856 // would cause a type conversion of one of our arguments, change this call to
5857 // be a direct call with arguments casted to the appropriate types.
5858 //
5859 const FunctionType *FT = Callee->getFunctionType();
5860 const Type *OldRetTy = Caller->getType();
5861
Chris Lattner1f7942f2004-01-14 06:06:08 +00005862 // Check to see if we are changing the return type...
5863 if (OldRetTy != FT->getReturnType()) {
5864 if (Callee->isExternal() &&
Andrew Lenharth61eae292006-04-20 14:56:47 +00005865 !(OldRetTy->isLosslesslyConvertibleTo(FT->getReturnType()) ||
5866 (isa<PointerType>(FT->getReturnType()) &&
Andrew Lenharthf89e6302006-04-20 15:41:37 +00005867 TD->getIntPtrType()->isLosslesslyConvertibleTo(OldRetTy)))
Andrew Lenharth61eae292006-04-20 14:56:47 +00005868 && !Caller->use_empty())
Chris Lattner1f7942f2004-01-14 06:06:08 +00005869 return false; // Cannot transform this return value...
5870
5871 // If the callsite is an invoke instruction, and the return value is used by
5872 // a PHI node in a successor, we cannot change the return type of the call
5873 // because there is no place to put the cast instruction (without breaking
5874 // the critical edge). Bail out in this case.
5875 if (!Caller->use_empty())
5876 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
5877 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
5878 UI != E; ++UI)
5879 if (PHINode *PN = dyn_cast<PHINode>(*UI))
5880 if (PN->getParent() == II->getNormalDest() ||
Chris Lattnerfae8ab32004-02-08 21:44:31 +00005881 PN->getParent() == II->getUnwindDest())
Chris Lattner1f7942f2004-01-14 06:06:08 +00005882 return false;
5883 }
Chris Lattner970c33a2003-06-19 17:00:31 +00005884
5885 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
5886 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanb1c93172005-04-21 23:48:37 +00005887
Chris Lattner970c33a2003-06-19 17:00:31 +00005888 CallSite::arg_iterator AI = CS.arg_begin();
5889 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
5890 const Type *ParamTy = FT->getParamType(i);
5891 bool isConvertible = (*AI)->getType()->isLosslesslyConvertibleTo(ParamTy);
Misha Brukmanb1c93172005-04-21 23:48:37 +00005892 if (Callee->isExternal() && !isConvertible) return false;
Chris Lattner970c33a2003-06-19 17:00:31 +00005893 }
5894
5895 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
5896 Callee->isExternal())
5897 return false; // Do not delete arguments unless we have a function body...
5898
5899 // Okay, we decided that this is a safe thing to do: go ahead and start
5900 // inserting cast instructions as necessary...
5901 std::vector<Value*> Args;
5902 Args.reserve(NumActualArgs);
5903
5904 AI = CS.arg_begin();
5905 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
5906 const Type *ParamTy = FT->getParamType(i);
5907 if ((*AI)->getType() == ParamTy) {
5908 Args.push_back(*AI);
5909 } else {
Chris Lattner1c631e82004-04-08 04:43:23 +00005910 Args.push_back(InsertNewInstBefore(new CastInst(*AI, ParamTy, "tmp"),
5911 *Caller));
Chris Lattner970c33a2003-06-19 17:00:31 +00005912 }
5913 }
5914
5915 // If the function takes more arguments than the call was taking, add them
5916 // now...
5917 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
5918 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
5919
5920 // If we are removing arguments to the function, emit an obnoxious warning...
5921 if (FT->getNumParams() < NumActualArgs)
5922 if (!FT->isVarArg()) {
5923 std::cerr << "WARNING: While resolving call to function '"
5924 << Callee->getName() << "' arguments were dropped!\n";
5925 } else {
5926 // Add all of the arguments in their promoted form to the arg list...
5927 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
5928 const Type *PTy = getPromotedType((*AI)->getType());
5929 if (PTy != (*AI)->getType()) {
5930 // Must promote to pass through va_arg area!
5931 Instruction *Cast = new CastInst(*AI, PTy, "tmp");
5932 InsertNewInstBefore(Cast, *Caller);
5933 Args.push_back(Cast);
5934 } else {
5935 Args.push_back(*AI);
5936 }
5937 }
5938 }
5939
5940 if (FT->getReturnType() == Type::VoidTy)
5941 Caller->setName(""); // Void type should not have a name...
5942
5943 Instruction *NC;
5944 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Chris Lattnerfae8ab32004-02-08 21:44:31 +00005945 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
Chris Lattner970c33a2003-06-19 17:00:31 +00005946 Args, Caller->getName(), Caller);
Chris Lattner05c703e2005-05-14 12:25:32 +00005947 cast<InvokeInst>(II)->setCallingConv(II->getCallingConv());
Chris Lattner970c33a2003-06-19 17:00:31 +00005948 } else {
5949 NC = new CallInst(Callee, Args, Caller->getName(), Caller);
Chris Lattner6aacb0f2005-05-06 06:48:21 +00005950 if (cast<CallInst>(Caller)->isTailCall())
5951 cast<CallInst>(NC)->setTailCall();
Chris Lattner05c703e2005-05-14 12:25:32 +00005952 cast<CallInst>(NC)->setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Chris Lattner970c33a2003-06-19 17:00:31 +00005953 }
5954
5955 // Insert a cast of the return type as necessary...
5956 Value *NV = NC;
5957 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
5958 if (NV->getType() != Type::VoidTy) {
5959 NV = NC = new CastInst(NC, Caller->getType(), "tmp");
Chris Lattner686767f2003-10-30 00:46:41 +00005960
5961 // If this is an invoke instruction, we should insert it after the first
5962 // non-phi, instruction in the normal successor block.
5963 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
5964 BasicBlock::iterator I = II->getNormalDest()->begin();
5965 while (isa<PHINode>(I)) ++I;
5966 InsertNewInstBefore(NC, *I);
5967 } else {
5968 // Otherwise, it's a call, just insert cast right after the call instr
5969 InsertNewInstBefore(NC, *Caller);
5970 }
Chris Lattner51ea1272004-02-28 05:22:00 +00005971 AddUsersToWorkList(*Caller);
Chris Lattner970c33a2003-06-19 17:00:31 +00005972 } else {
Chris Lattnere29d6342004-10-17 21:22:38 +00005973 NV = UndefValue::get(Caller->getType());
Chris Lattner970c33a2003-06-19 17:00:31 +00005974 }
5975 }
5976
5977 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
5978 Caller->replaceAllUsesWith(NV);
5979 Caller->getParent()->getInstList().erase(Caller);
5980 removeFromWorkList(Caller);
5981 return true;
5982}
5983
5984
Chris Lattner7515cab2004-11-14 19:13:23 +00005985// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
5986// operator and they all are only used by the PHI, PHI together their
5987// inputs, and do the operation once, to the result of the PHI.
5988Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
5989 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
5990
5991 // Scan the instruction, looking for input operations that can be folded away.
5992 // If all input operands to the phi are the same instruction (e.g. a cast from
5993 // the same type or "+42") we can pull the operation through the PHI, reducing
5994 // code size and simplifying code.
5995 Constant *ConstantOp = 0;
5996 const Type *CastSrcTy = 0;
5997 if (isa<CastInst>(FirstInst)) {
5998 CastSrcTy = FirstInst->getOperand(0)->getType();
5999 } else if (isa<BinaryOperator>(FirstInst) || isa<ShiftInst>(FirstInst)) {
6000 // Can fold binop or shift if the RHS is a constant.
6001 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
6002 if (ConstantOp == 0) return 0;
6003 } else {
6004 return 0; // Cannot fold this operation.
6005 }
6006
6007 // Check to see if all arguments are the same operation.
6008 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
6009 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
6010 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
6011 if (!I->hasOneUse() || I->getOpcode() != FirstInst->getOpcode())
6012 return 0;
6013 if (CastSrcTy) {
6014 if (I->getOperand(0)->getType() != CastSrcTy)
6015 return 0; // Cast operation must match.
6016 } else if (I->getOperand(1) != ConstantOp) {
6017 return 0;
6018 }
6019 }
6020
6021 // Okay, they are all the same operation. Create a new PHI node of the
6022 // correct type, and PHI together all of the LHS's of the instructions.
6023 PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
6024 PN.getName()+".in");
Chris Lattnerd8e20182005-01-29 00:39:08 +00006025 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattner46dd5a62004-11-14 19:29:34 +00006026
6027 Value *InVal = FirstInst->getOperand(0);
6028 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattner7515cab2004-11-14 19:13:23 +00006029
6030 // Add all operands to the new PHI.
Chris Lattner46dd5a62004-11-14 19:29:34 +00006031 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
6032 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
6033 if (NewInVal != InVal)
6034 InVal = 0;
6035 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
6036 }
6037
6038 Value *PhiVal;
6039 if (InVal) {
6040 // The new PHI unions all of the same values together. This is really
6041 // common, so we handle it intelligently here for compile-time speed.
6042 PhiVal = InVal;
6043 delete NewPN;
6044 } else {
6045 InsertNewInstBefore(NewPN, PN);
6046 PhiVal = NewPN;
6047 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00006048
Chris Lattner7515cab2004-11-14 19:13:23 +00006049 // Insert and return the new operation.
6050 if (isa<CastInst>(FirstInst))
Chris Lattner46dd5a62004-11-14 19:29:34 +00006051 return new CastInst(PhiVal, PN.getType());
Chris Lattner7515cab2004-11-14 19:13:23 +00006052 else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattner46dd5a62004-11-14 19:29:34 +00006053 return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattner7515cab2004-11-14 19:13:23 +00006054 else
6055 return new ShiftInst(cast<ShiftInst>(FirstInst)->getOpcode(),
Chris Lattner46dd5a62004-11-14 19:29:34 +00006056 PhiVal, ConstantOp);
Chris Lattner7515cab2004-11-14 19:13:23 +00006057}
Chris Lattner48a44f72002-05-02 17:06:02 +00006058
Chris Lattner71536432005-01-17 05:10:15 +00006059/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
6060/// that is dead.
6061static bool DeadPHICycle(PHINode *PN, std::set<PHINode*> &PotentiallyDeadPHIs) {
6062 if (PN->use_empty()) return true;
6063 if (!PN->hasOneUse()) return false;
6064
6065 // Remember this node, and if we find the cycle, return.
6066 if (!PotentiallyDeadPHIs.insert(PN).second)
6067 return true;
6068
6069 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
6070 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanb1c93172005-04-21 23:48:37 +00006071
Chris Lattner71536432005-01-17 05:10:15 +00006072 return false;
6073}
6074
Chris Lattnerbbbdd852002-05-06 18:06:38 +00006075// PHINode simplification
6076//
Chris Lattner113f4f42002-06-25 16:13:24 +00006077Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Chris Lattner9f9c2602005-08-05 01:04:30 +00006078 if (Value *V = PN.hasConstantValue())
6079 return ReplaceInstUsesWith(PN, V);
Chris Lattner4db2d222004-02-16 05:07:08 +00006080
6081 // If the only user of this instruction is a cast instruction, and all of the
6082 // incoming values are constants, change this PHI to merge together the casted
6083 // constants.
6084 if (PN.hasOneUse())
6085 if (CastInst *CI = dyn_cast<CastInst>(PN.use_back()))
6086 if (CI->getType() != PN.getType()) { // noop casts will be folded
6087 bool AllConstant = true;
6088 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
6089 if (!isa<Constant>(PN.getIncomingValue(i))) {
6090 AllConstant = false;
6091 break;
6092 }
6093 if (AllConstant) {
6094 // Make a new PHI with all casted values.
6095 PHINode *New = new PHINode(CI->getType(), PN.getName(), &PN);
6096 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
6097 Constant *OldArg = cast<Constant>(PN.getIncomingValue(i));
6098 New->addIncoming(ConstantExpr::getCast(OldArg, New->getType()),
6099 PN.getIncomingBlock(i));
6100 }
6101
6102 // Update the cast instruction.
6103 CI->setOperand(0, New);
6104 WorkList.push_back(CI); // revisit the cast instruction to fold.
6105 WorkList.push_back(New); // Make sure to revisit the new Phi
6106 return &PN; // PN is now dead!
6107 }
6108 }
Chris Lattner7515cab2004-11-14 19:13:23 +00006109
6110 // If all PHI operands are the same operation, pull them through the PHI,
6111 // reducing code size.
6112 if (isa<Instruction>(PN.getIncomingValue(0)) &&
6113 PN.getIncomingValue(0)->hasOneUse())
6114 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
6115 return Result;
6116
Chris Lattner71536432005-01-17 05:10:15 +00006117 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
6118 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
6119 // PHI)... break the cycle.
6120 if (PN.hasOneUse())
6121 if (PHINode *PU = dyn_cast<PHINode>(PN.use_back())) {
6122 std::set<PHINode*> PotentiallyDeadPHIs;
6123 PotentiallyDeadPHIs.insert(&PN);
6124 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
6125 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
6126 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00006127
Chris Lattner91daeb52003-12-19 05:58:40 +00006128 return 0;
Chris Lattnerbbbdd852002-05-06 18:06:38 +00006129}
6130
Chris Lattner69193f92004-04-05 01:30:19 +00006131static Value *InsertSignExtendToPtrTy(Value *V, const Type *DTy,
6132 Instruction *InsertPoint,
6133 InstCombiner *IC) {
6134 unsigned PS = IC->getTargetData().getPointerSize();
6135 const Type *VTy = V->getType();
Chris Lattner69193f92004-04-05 01:30:19 +00006136 if (!VTy->isSigned() && VTy->getPrimitiveSize() < PS)
6137 // We must insert a cast to ensure we sign-extend.
6138 V = IC->InsertNewInstBefore(new CastInst(V, VTy->getSignedVersion(),
6139 V->getName()), *InsertPoint);
6140 return IC->InsertNewInstBefore(new CastInst(V, DTy, V->getName()),
6141 *InsertPoint);
6142}
6143
Chris Lattner48a44f72002-05-02 17:06:02 +00006144
Chris Lattner113f4f42002-06-25 16:13:24 +00006145Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner5f667a62004-05-07 22:09:22 +00006146 Value *PtrOp = GEP.getOperand(0);
Chris Lattner471bd762003-05-22 19:07:21 +00006147 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
Chris Lattner113f4f42002-06-25 16:13:24 +00006148 // If so, eliminate the noop.
Chris Lattner8d0bacb2004-02-22 05:25:17 +00006149 if (GEP.getNumOperands() == 1)
Chris Lattner5f667a62004-05-07 22:09:22 +00006150 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner8d0bacb2004-02-22 05:25:17 +00006151
Chris Lattner81a7a232004-10-16 18:11:37 +00006152 if (isa<UndefValue>(GEP.getOperand(0)))
6153 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
6154
Chris Lattner8d0bacb2004-02-22 05:25:17 +00006155 bool HasZeroPointerIndex = false;
6156 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
6157 HasZeroPointerIndex = C->isNullValue();
6158
6159 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner5f667a62004-05-07 22:09:22 +00006160 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner48a44f72002-05-02 17:06:02 +00006161
Chris Lattner69193f92004-04-05 01:30:19 +00006162 // Eliminate unneeded casts for indices.
6163 bool MadeChange = false;
Chris Lattner2b2412d2004-04-07 18:38:20 +00006164 gep_type_iterator GTI = gep_type_begin(GEP);
6165 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI)
6166 if (isa<SequentialType>(*GTI)) {
6167 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
6168 Value *Src = CI->getOperand(0);
6169 const Type *SrcTy = Src->getType();
6170 const Type *DestTy = CI->getType();
6171 if (Src->getType()->isInteger()) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00006172 if (SrcTy->getPrimitiveSizeInBits() ==
6173 DestTy->getPrimitiveSizeInBits()) {
Chris Lattner2b2412d2004-04-07 18:38:20 +00006174 // We can always eliminate a cast from ulong or long to the other.
6175 // We can always eliminate a cast from uint to int or the other on
6176 // 32-bit pointer platforms.
Chris Lattnerd1f46d32005-04-24 06:59:08 +00006177 if (DestTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()){
Chris Lattner2b2412d2004-04-07 18:38:20 +00006178 MadeChange = true;
6179 GEP.setOperand(i, Src);
6180 }
6181 } else if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
6182 SrcTy->getPrimitiveSize() == 4) {
6183 // We can always eliminate a cast from int to [u]long. We can
6184 // eliminate a cast from uint to [u]long iff the target is a 32-bit
6185 // pointer target.
Misha Brukmanb1c93172005-04-21 23:48:37 +00006186 if (SrcTy->isSigned() ||
Chris Lattnerd1f46d32005-04-24 06:59:08 +00006187 SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
Chris Lattner2b2412d2004-04-07 18:38:20 +00006188 MadeChange = true;
6189 GEP.setOperand(i, Src);
6190 }
Chris Lattner69193f92004-04-05 01:30:19 +00006191 }
6192 }
6193 }
Chris Lattner2b2412d2004-04-07 18:38:20 +00006194 // If we are using a wider index than needed for this platform, shrink it
6195 // to what we need. If the incoming value needs a cast instruction,
6196 // insert it. This explicit cast can make subsequent optimizations more
6197 // obvious.
6198 Value *Op = GEP.getOperand(i);
6199 if (Op->getType()->getPrimitiveSize() > TD->getPointerSize())
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00006200 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner44d0b952004-07-20 01:48:15 +00006201 GEP.setOperand(i, ConstantExpr::getCast(C,
6202 TD->getIntPtrType()->getSignedVersion()));
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00006203 MadeChange = true;
6204 } else {
Chris Lattner2b2412d2004-04-07 18:38:20 +00006205 Op = InsertNewInstBefore(new CastInst(Op, TD->getIntPtrType(),
6206 Op->getName()), GEP);
6207 GEP.setOperand(i, Op);
6208 MadeChange = true;
6209 }
Chris Lattner44d0b952004-07-20 01:48:15 +00006210
6211 // If this is a constant idx, make sure to canonicalize it to be a signed
6212 // operand, otherwise CSE and other optimizations are pessimized.
6213 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op)) {
6214 GEP.setOperand(i, ConstantExpr::getCast(CUI,
6215 CUI->getType()->getSignedVersion()));
6216 MadeChange = true;
6217 }
Chris Lattner69193f92004-04-05 01:30:19 +00006218 }
6219 if (MadeChange) return &GEP;
6220
Chris Lattnerae7a0d32002-08-02 19:29:35 +00006221 // Combine Indices - If the source pointer to this getelementptr instruction
6222 // is a getelementptr instruction, combine the indices of the two
6223 // getelementptr instructions into a single instruction.
6224 //
Chris Lattner57c67b02004-03-25 22:59:29 +00006225 std::vector<Value*> SrcGEPOperands;
Chris Lattner0798af32005-01-13 20:14:25 +00006226 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattner57c67b02004-03-25 22:59:29 +00006227 SrcGEPOperands.assign(Src->op_begin(), Src->op_end());
Chris Lattner57c67b02004-03-25 22:59:29 +00006228
6229 if (!SrcGEPOperands.empty()) {
Chris Lattner5f667a62004-05-07 22:09:22 +00006230 // Note that if our source is a gep chain itself that we wait for that
6231 // chain to be resolved before we perform this transformation. This
6232 // avoids us creating a TON of code in some cases.
6233 //
6234 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
6235 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
6236 return 0; // Wait until our source is folded to completion.
6237
Chris Lattnerae7a0d32002-08-02 19:29:35 +00006238 std::vector<Value *> Indices;
Chris Lattner5f667a62004-05-07 22:09:22 +00006239
6240 // Find out whether the last index in the source GEP is a sequential idx.
6241 bool EndsWithSequential = false;
6242 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
6243 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattner8ec5f882004-05-08 22:41:42 +00006244 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00006245
Chris Lattnerae7a0d32002-08-02 19:29:35 +00006246 // Can we combine the two pointer arithmetics offsets?
Chris Lattner5f667a62004-05-07 22:09:22 +00006247 if (EndsWithSequential) {
Chris Lattner235af562003-03-05 22:33:14 +00006248 // Replace: gep (gep %P, long B), long A, ...
6249 // With: T = long A+B; gep %P, T, ...
6250 //
Chris Lattner5f667a62004-05-07 22:09:22 +00006251 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner69193f92004-04-05 01:30:19 +00006252 if (SO1 == Constant::getNullValue(SO1->getType())) {
6253 Sum = GO1;
6254 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
6255 Sum = SO1;
6256 } else {
6257 // If they aren't the same type, convert both to an integer of the
6258 // target's pointer size.
6259 if (SO1->getType() != GO1->getType()) {
6260 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
6261 SO1 = ConstantExpr::getCast(SO1C, GO1->getType());
6262 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
6263 GO1 = ConstantExpr::getCast(GO1C, SO1->getType());
6264 } else {
6265 unsigned PS = TD->getPointerSize();
Chris Lattner69193f92004-04-05 01:30:19 +00006266 if (SO1->getType()->getPrimitiveSize() == PS) {
6267 // Convert GO1 to SO1's type.
6268 GO1 = InsertSignExtendToPtrTy(GO1, SO1->getType(), &GEP, this);
6269
6270 } else if (GO1->getType()->getPrimitiveSize() == PS) {
6271 // Convert SO1 to GO1's type.
6272 SO1 = InsertSignExtendToPtrTy(SO1, GO1->getType(), &GEP, this);
6273 } else {
6274 const Type *PT = TD->getIntPtrType();
6275 SO1 = InsertSignExtendToPtrTy(SO1, PT, &GEP, this);
6276 GO1 = InsertSignExtendToPtrTy(GO1, PT, &GEP, this);
6277 }
6278 }
6279 }
Chris Lattner5f667a62004-05-07 22:09:22 +00006280 if (isa<Constant>(SO1) && isa<Constant>(GO1))
6281 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
6282 else {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00006283 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
6284 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner5f667a62004-05-07 22:09:22 +00006285 }
Chris Lattner69193f92004-04-05 01:30:19 +00006286 }
Chris Lattner5f667a62004-05-07 22:09:22 +00006287
6288 // Recycle the GEP we already have if possible.
6289 if (SrcGEPOperands.size() == 2) {
6290 GEP.setOperand(0, SrcGEPOperands[0]);
6291 GEP.setOperand(1, Sum);
6292 return &GEP;
6293 } else {
6294 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
6295 SrcGEPOperands.end()-1);
6296 Indices.push_back(Sum);
6297 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
6298 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00006299 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner69193f92004-04-05 01:30:19 +00006300 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00006301 SrcGEPOperands.size() != 1) {
Chris Lattnerae7a0d32002-08-02 19:29:35 +00006302 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattner57c67b02004-03-25 22:59:29 +00006303 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
6304 SrcGEPOperands.end());
Chris Lattnerae7a0d32002-08-02 19:29:35 +00006305 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
6306 }
6307
6308 if (!Indices.empty())
Chris Lattner57c67b02004-03-25 22:59:29 +00006309 return new GetElementPtrInst(SrcGEPOperands[0], Indices, GEP.getName());
Chris Lattnerc59af1d2002-08-17 22:21:59 +00006310
Chris Lattner5f667a62004-05-07 22:09:22 +00006311 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattnerc59af1d2002-08-17 22:21:59 +00006312 // GEP of global variable. If all of the indices for this GEP are
6313 // constants, we can promote this to a constexpr instead of an instruction.
6314
6315 // Scan for nonconstants...
6316 std::vector<Constant*> Indices;
6317 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
6318 for (; I != E && isa<Constant>(*I); ++I)
6319 Indices.push_back(cast<Constant>(*I));
6320
6321 if (I == E) { // If they are all constants...
Chris Lattnerf3edc492004-07-18 18:59:44 +00006322 Constant *CE = ConstantExpr::getGetElementPtr(GV, Indices);
Chris Lattnerc59af1d2002-08-17 22:21:59 +00006323
6324 // Replace all uses of the GEP with the new constexpr...
6325 return ReplaceInstUsesWith(GEP, CE);
6326 }
Chris Lattner567b81f2005-09-13 00:40:14 +00006327 } else if (Value *X = isCast(PtrOp)) { // Is the operand a cast?
6328 if (!isa<PointerType>(X->getType())) {
6329 // Not interesting. Source pointer must be a cast from pointer.
6330 } else if (HasZeroPointerIndex) {
6331 // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
6332 // into : GEP [10 x ubyte]* X, long 0, ...
6333 //
6334 // This occurs when the program declares an array extern like "int X[];"
6335 //
6336 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
6337 const PointerType *XTy = cast<PointerType>(X->getType());
6338 if (const ArrayType *XATy =
6339 dyn_cast<ArrayType>(XTy->getElementType()))
6340 if (const ArrayType *CATy =
6341 dyn_cast<ArrayType>(CPTy->getElementType()))
6342 if (CATy->getElementType() == XATy->getElementType()) {
6343 // At this point, we know that the cast source type is a pointer
6344 // to an array of the same type as the destination pointer
6345 // array. Because the array type is never stepped over (there
6346 // is a leading zero) we can fold the cast into this GEP.
6347 GEP.setOperand(0, X);
6348 return &GEP;
6349 }
6350 } else if (GEP.getNumOperands() == 2) {
6351 // Transform things like:
Chris Lattner2a893292005-09-13 18:36:04 +00006352 // %t = getelementptr ubyte* cast ([2 x int]* %str to uint*), uint %V
6353 // into: %t1 = getelementptr [2 x int*]* %str, int 0, uint %V; cast
Chris Lattner567b81f2005-09-13 00:40:14 +00006354 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
6355 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
6356 if (isa<ArrayType>(SrcElTy) &&
6357 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
6358 TD->getTypeSize(ResElTy)) {
6359 Value *V = InsertNewInstBefore(
6360 new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
6361 GEP.getOperand(1), GEP.getName()), GEP);
6362 return new CastInst(V, GEP.getType());
Chris Lattner8d0bacb2004-02-22 05:25:17 +00006363 }
Chris Lattner2a893292005-09-13 18:36:04 +00006364
6365 // Transform things like:
6366 // getelementptr sbyte* cast ([100 x double]* X to sbyte*), int %tmp
6367 // (where tmp = 8*tmp2) into:
6368 // getelementptr [100 x double]* %arr, int 0, int %tmp.2
6369
6370 if (isa<ArrayType>(SrcElTy) &&
6371 (ResElTy == Type::SByteTy || ResElTy == Type::UByteTy)) {
6372 uint64_t ArrayEltSize =
6373 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType());
6374
6375 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
6376 // allow either a mul, shift, or constant here.
6377 Value *NewIdx = 0;
6378 ConstantInt *Scale = 0;
6379 if (ArrayEltSize == 1) {
6380 NewIdx = GEP.getOperand(1);
6381 Scale = ConstantInt::get(NewIdx->getType(), 1);
6382 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Chris Lattnera393e4d2005-09-14 17:32:56 +00006383 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner2a893292005-09-13 18:36:04 +00006384 Scale = CI;
6385 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
6386 if (Inst->getOpcode() == Instruction::Shl &&
6387 isa<ConstantInt>(Inst->getOperand(1))) {
6388 unsigned ShAmt =cast<ConstantUInt>(Inst->getOperand(1))->getValue();
6389 if (Inst->getType()->isSigned())
6390 Scale = ConstantSInt::get(Inst->getType(), 1ULL << ShAmt);
6391 else
6392 Scale = ConstantUInt::get(Inst->getType(), 1ULL << ShAmt);
6393 NewIdx = Inst->getOperand(0);
6394 } else if (Inst->getOpcode() == Instruction::Mul &&
6395 isa<ConstantInt>(Inst->getOperand(1))) {
6396 Scale = cast<ConstantInt>(Inst->getOperand(1));
6397 NewIdx = Inst->getOperand(0);
6398 }
6399 }
6400
6401 // If the index will be to exactly the right offset with the scale taken
6402 // out, perform the transformation.
6403 if (Scale && Scale->getRawValue() % ArrayEltSize == 0) {
6404 if (ConstantSInt *C = dyn_cast<ConstantSInt>(Scale))
6405 Scale = ConstantSInt::get(C->getType(),
Chris Lattnera393e4d2005-09-14 17:32:56 +00006406 (int64_t)C->getRawValue() /
6407 (int64_t)ArrayEltSize);
Chris Lattner2a893292005-09-13 18:36:04 +00006408 else
6409 Scale = ConstantUInt::get(Scale->getType(),
6410 Scale->getRawValue() / ArrayEltSize);
6411 if (Scale->getRawValue() != 1) {
6412 Constant *C = ConstantExpr::getCast(Scale, NewIdx->getType());
6413 Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
6414 NewIdx = InsertNewInstBefore(Sc, GEP);
6415 }
6416
6417 // Insert the new GEP instruction.
6418 Instruction *Idx =
6419 new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
6420 NewIdx, GEP.getName());
6421 Idx = InsertNewInstBefore(Idx, GEP);
6422 return new CastInst(Idx, GEP.getType());
6423 }
6424 }
Chris Lattner8d0bacb2004-02-22 05:25:17 +00006425 }
Chris Lattnerca081252001-12-14 16:52:21 +00006426 }
6427
Chris Lattnerca081252001-12-14 16:52:21 +00006428 return 0;
6429}
6430
Chris Lattner1085bdf2002-11-04 16:18:53 +00006431Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
6432 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
6433 if (AI.isArrayAllocation()) // Check C != 1
6434 if (const ConstantUInt *C = dyn_cast<ConstantUInt>(AI.getArraySize())) {
6435 const Type *NewTy = ArrayType::get(AI.getAllocatedType(), C->getValue());
Chris Lattnera2620ac2002-11-09 00:49:43 +00006436 AllocationInst *New = 0;
Chris Lattner1085bdf2002-11-04 16:18:53 +00006437
6438 // Create and insert the replacement instruction...
6439 if (isa<MallocInst>(AI))
Nate Begeman848622f2005-11-05 09:21:28 +00006440 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00006441 else {
6442 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Nate Begeman848622f2005-11-05 09:21:28 +00006443 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00006444 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00006445
6446 InsertNewInstBefore(New, AI);
Misha Brukmanb1c93172005-04-21 23:48:37 +00006447
Chris Lattner1085bdf2002-11-04 16:18:53 +00006448 // Scan to the end of the allocation instructions, to skip over a block of
6449 // allocas if possible...
6450 //
6451 BasicBlock::iterator It = New;
6452 while (isa<AllocationInst>(*It)) ++It;
6453
6454 // Now that I is pointing to the first non-allocation-inst in the block,
6455 // insert our getelementptr instruction...
6456 //
Chris Lattner809dfac2005-05-04 19:10:26 +00006457 Value *NullIdx = Constant::getNullValue(Type::IntTy);
6458 Value *V = new GetElementPtrInst(New, NullIdx, NullIdx,
6459 New->getName()+".sub", It);
Chris Lattner1085bdf2002-11-04 16:18:53 +00006460
6461 // Now make everything use the getelementptr instead of the original
6462 // allocation.
Chris Lattnerabb77c92004-03-19 06:08:10 +00006463 return ReplaceInstUsesWith(AI, V);
Chris Lattner81a7a232004-10-16 18:11:37 +00006464 } else if (isa<UndefValue>(AI.getArraySize())) {
6465 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner1085bdf2002-11-04 16:18:53 +00006466 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00006467
6468 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
6469 // Note that we only do this for alloca's, because malloc should allocate and
6470 // return a unique pointer, even for a zero byte allocation.
Misha Brukmanb1c93172005-04-21 23:48:37 +00006471 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
Chris Lattner49df6ce2004-07-02 22:55:47 +00006472 TD->getTypeSize(AI.getAllocatedType()) == 0)
Chris Lattnerabb77c92004-03-19 06:08:10 +00006473 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
6474
Chris Lattner1085bdf2002-11-04 16:18:53 +00006475 return 0;
6476}
6477
Chris Lattner8427bff2003-12-07 01:24:23 +00006478Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
6479 Value *Op = FI.getOperand(0);
6480
6481 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
6482 if (CastInst *CI = dyn_cast<CastInst>(Op))
6483 if (isa<PointerType>(CI->getOperand(0)->getType())) {
6484 FI.setOperand(0, CI->getOperand(0));
6485 return &FI;
6486 }
6487
Chris Lattner8ba9ec92004-10-18 02:59:09 +00006488 // free undef -> unreachable.
6489 if (isa<UndefValue>(Op)) {
6490 // Insert a new store to null because we cannot modify the CFG here.
6491 new StoreInst(ConstantBool::True,
6492 UndefValue::get(PointerType::get(Type::BoolTy)), &FI);
6493 return EraseInstFromFunction(FI);
6494 }
6495
Chris Lattnerf3a36602004-02-28 04:57:37 +00006496 // If we have 'free null' delete the instruction. This can happen in stl code
6497 // when lots of inlining happens.
Chris Lattner8ba9ec92004-10-18 02:59:09 +00006498 if (isa<ConstantPointerNull>(Op))
Chris Lattner51ea1272004-02-28 05:22:00 +00006499 return EraseInstFromFunction(FI);
Chris Lattnerf3a36602004-02-28 04:57:37 +00006500
Chris Lattner8427bff2003-12-07 01:24:23 +00006501 return 0;
6502}
6503
6504
Chris Lattner72684fe2005-01-31 05:51:45 +00006505/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Chris Lattner35e24772004-07-13 01:49:43 +00006506static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
6507 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00006508 Value *CastOp = CI->getOperand(0);
Chris Lattner35e24772004-07-13 01:49:43 +00006509
6510 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00006511 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Chris Lattner35e24772004-07-13 01:49:43 +00006512 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00006513
Chris Lattnerebca4762006-04-02 05:37:12 +00006514 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
6515 isa<PackedType>(DestPTy)) {
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00006516 // If the source is an array, the code below will not succeed. Check to
6517 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
6518 // constants.
6519 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
6520 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
6521 if (ASrcTy->getNumElements() != 0) {
6522 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
6523 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
6524 SrcTy = cast<PointerType>(CastOp->getType());
6525 SrcPTy = SrcTy->getElementType();
6526 }
6527
Chris Lattnerebca4762006-04-02 05:37:12 +00006528 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
6529 isa<PackedType>(SrcPTy)) &&
Chris Lattnerecfa9b52005-03-29 06:37:47 +00006530 // Do not allow turning this into a load of an integer, which is then
6531 // casted to a pointer, this pessimizes pointer analysis a lot.
6532 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00006533 IC.getTargetData().getTypeSize(SrcPTy) ==
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00006534 IC.getTargetData().getTypeSize(DestPTy)) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00006535
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00006536 // Okay, we are casting from one integer or pointer type to another of
6537 // the same size. Instead of casting the pointer before the load, cast
6538 // the result of the loaded value.
6539 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
6540 CI->getName(),
6541 LI.isVolatile()),LI);
6542 // Now cast the result of the load.
6543 return new CastInst(NewLoad, LI.getType());
6544 }
Chris Lattner35e24772004-07-13 01:49:43 +00006545 }
6546 }
6547 return 0;
6548}
6549
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00006550/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattnere6f13092004-09-19 19:18:10 +00006551/// from this value cannot trap. If it is not obviously safe to load from the
6552/// specified pointer, we do a quick local scan of the basic block containing
6553/// ScanFrom, to determine if the address is already accessed.
6554static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
6555 // If it is an alloca or global variable, it is always safe to load from.
6556 if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
6557
6558 // Otherwise, be a little bit agressive by scanning the local block where we
6559 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00006560 // from/to. If so, the previous load or store would have already trapped,
6561 // so there is no harm doing an extra load (also, CSE will later eliminate
6562 // the load entirely).
Chris Lattnere6f13092004-09-19 19:18:10 +00006563 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
6564
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00006565 while (BBI != E) {
Chris Lattnere6f13092004-09-19 19:18:10 +00006566 --BBI;
6567
6568 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
6569 if (LI->getOperand(0) == V) return true;
6570 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
6571 if (SI->getOperand(1) == V) return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +00006572
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00006573 }
Chris Lattnere6f13092004-09-19 19:18:10 +00006574 return false;
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00006575}
6576
Chris Lattner0f1d8a32003-06-26 05:06:25 +00006577Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
6578 Value *Op = LI.getOperand(0);
Chris Lattner7e8af382004-01-12 04:13:56 +00006579
Chris Lattnera9d84e32005-05-01 04:24:53 +00006580 // load (cast X) --> cast (load X) iff safe
6581 if (CastInst *CI = dyn_cast<CastInst>(Op))
6582 if (Instruction *Res = InstCombineLoadCast(*this, LI))
6583 return Res;
6584
6585 // None of the following transforms are legal for volatile loads.
6586 if (LI.isVolatile()) return 0;
Chris Lattnerb990f7d2005-09-12 22:00:15 +00006587
Chris Lattnerb990f7d2005-09-12 22:00:15 +00006588 if (&LI.getParent()->front() != &LI) {
6589 BasicBlock::iterator BBI = &LI; --BBI;
Chris Lattnere0bfdf12005-09-12 22:21:03 +00006590 // If the instruction immediately before this is a store to the same
6591 // address, do a simple form of store->load forwarding.
Chris Lattnerb990f7d2005-09-12 22:00:15 +00006592 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
6593 if (SI->getOperand(1) == LI.getOperand(0))
6594 return ReplaceInstUsesWith(LI, SI->getOperand(0));
Chris Lattnere0bfdf12005-09-12 22:21:03 +00006595 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
6596 if (LIB->getOperand(0) == LI.getOperand(0))
6597 return ReplaceInstUsesWith(LI, LIB);
Chris Lattnerb990f7d2005-09-12 22:00:15 +00006598 }
Chris Lattnera9d84e32005-05-01 04:24:53 +00006599
6600 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op))
6601 if (isa<ConstantPointerNull>(GEPI->getOperand(0)) ||
6602 isa<UndefValue>(GEPI->getOperand(0))) {
6603 // Insert a new store to null instruction before the load to indicate
6604 // that this code is not reachable. We do this instead of inserting
6605 // an unreachable instruction directly because we cannot modify the
6606 // CFG.
6607 new StoreInst(UndefValue::get(LI.getType()),
6608 Constant::getNullValue(Op->getType()), &LI);
6609 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
6610 }
6611
Chris Lattner81a7a232004-10-16 18:11:37 +00006612 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattnera9d84e32005-05-01 04:24:53 +00006613 // load null/undef -> undef
6614 if ((C->isNullValue() || isa<UndefValue>(C))) {
Chris Lattner8ba9ec92004-10-18 02:59:09 +00006615 // Insert a new store to null instruction before the load to indicate that
6616 // this code is not reachable. We do this instead of inserting an
6617 // unreachable instruction directly because we cannot modify the CFG.
Chris Lattnera9d84e32005-05-01 04:24:53 +00006618 new StoreInst(UndefValue::get(LI.getType()),
6619 Constant::getNullValue(Op->getType()), &LI);
Chris Lattner81a7a232004-10-16 18:11:37 +00006620 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner8ba9ec92004-10-18 02:59:09 +00006621 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00006622
Chris Lattner81a7a232004-10-16 18:11:37 +00006623 // Instcombine load (constant global) into the value loaded.
6624 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
6625 if (GV->isConstant() && !GV->isExternal())
6626 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanb1c93172005-04-21 23:48:37 +00006627
Chris Lattner81a7a232004-10-16 18:11:37 +00006628 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
6629 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
6630 if (CE->getOpcode() == Instruction::GetElementPtr) {
6631 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
6632 if (GV->isConstant() && !GV->isExternal())
Chris Lattner0b011ec2005-09-26 05:28:06 +00006633 if (Constant *V =
6634 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
Chris Lattner81a7a232004-10-16 18:11:37 +00006635 return ReplaceInstUsesWith(LI, V);
Chris Lattnera9d84e32005-05-01 04:24:53 +00006636 if (CE->getOperand(0)->isNullValue()) {
6637 // Insert a new store to null instruction before the load to indicate
6638 // that this code is not reachable. We do this instead of inserting
6639 // an unreachable instruction directly because we cannot modify the
6640 // CFG.
6641 new StoreInst(UndefValue::get(LI.getType()),
6642 Constant::getNullValue(Op->getType()), &LI);
6643 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
6644 }
6645
Chris Lattner81a7a232004-10-16 18:11:37 +00006646 } else if (CE->getOpcode() == Instruction::Cast) {
6647 if (Instruction *Res = InstCombineLoadCast(*this, LI))
6648 return Res;
6649 }
6650 }
Chris Lattnere228ee52004-04-08 20:39:49 +00006651
Chris Lattnera9d84e32005-05-01 04:24:53 +00006652 if (Op->hasOneUse()) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00006653 // Change select and PHI nodes to select values instead of addresses: this
6654 // helps alias analysis out a lot, allows many others simplifications, and
6655 // exposes redundancy in the code.
6656 //
6657 // Note that we cannot do the transformation unless we know that the
6658 // introduced loads cannot trap! Something like this is valid as long as
6659 // the condition is always false: load (select bool %C, int* null, int* %G),
6660 // but it would not be valid if we transformed it to load from null
6661 // unconditionally.
6662 //
6663 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
6664 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattnere6f13092004-09-19 19:18:10 +00006665 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
6666 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00006667 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner42618552004-09-20 10:15:10 +00006668 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00006669 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner42618552004-09-20 10:15:10 +00006670 SI->getOperand(2)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00006671 return new SelectInst(SI->getCondition(), V1, V2);
6672 }
6673
Chris Lattnerbdcf41a2004-09-23 15:46:00 +00006674 // load (select (cond, null, P)) -> load P
6675 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
6676 if (C->isNullValue()) {
6677 LI.setOperand(0, SI->getOperand(2));
6678 return &LI;
6679 }
6680
6681 // load (select (cond, P, null)) -> load P
6682 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
6683 if (C->isNullValue()) {
6684 LI.setOperand(0, SI->getOperand(1));
6685 return &LI;
6686 }
6687
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00006688 } else if (PHINode *PN = dyn_cast<PHINode>(Op)) {
6689 // load (phi (&V1, &V2, &V3)) --> phi(load &V1, load &V2, load &V3)
Chris Lattner42618552004-09-20 10:15:10 +00006690 bool Safe = PN->getParent() == LI.getParent();
6691
6692 // Scan all of the instructions between the PHI and the load to make
6693 // sure there are no instructions that might possibly alter the value
6694 // loaded from the PHI.
6695 if (Safe) {
6696 BasicBlock::iterator I = &LI;
6697 for (--I; !isa<PHINode>(I); --I)
6698 if (isa<StoreInst>(I) || isa<CallInst>(I)) {
6699 Safe = false;
6700 break;
6701 }
6702 }
6703
6704 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e && Safe; ++i)
Chris Lattnere6f13092004-09-19 19:18:10 +00006705 if (!isSafeToLoadUnconditionally(PN->getIncomingValue(i),
Chris Lattner42618552004-09-20 10:15:10 +00006706 PN->getIncomingBlock(i)->getTerminator()))
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00006707 Safe = false;
Chris Lattner42618552004-09-20 10:15:10 +00006708
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00006709 if (Safe) {
6710 // Create the PHI.
6711 PHINode *NewPN = new PHINode(LI.getType(), PN->getName());
6712 InsertNewInstBefore(NewPN, *PN);
6713 std::map<BasicBlock*,Value*> LoadMap; // Don't insert duplicate loads
6714
6715 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
6716 BasicBlock *BB = PN->getIncomingBlock(i);
6717 Value *&TheLoad = LoadMap[BB];
6718 if (TheLoad == 0) {
6719 Value *InVal = PN->getIncomingValue(i);
6720 TheLoad = InsertNewInstBefore(new LoadInst(InVal,
6721 InVal->getName()+".val"),
6722 *BB->getTerminator());
6723 }
6724 NewPN->addIncoming(TheLoad, BB);
6725 }
6726 return ReplaceInstUsesWith(LI, NewPN);
6727 }
6728 }
6729 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00006730 return 0;
6731}
6732
Chris Lattner72684fe2005-01-31 05:51:45 +00006733/// InstCombineStoreToCast - Fold 'store V, (cast P)' -> store (cast V), P'
6734/// when possible.
6735static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
6736 User *CI = cast<User>(SI.getOperand(1));
6737 Value *CastOp = CI->getOperand(0);
6738
6739 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
6740 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
6741 const Type *SrcPTy = SrcTy->getElementType();
6742
6743 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
6744 // If the source is an array, the code below will not succeed. Check to
6745 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
6746 // constants.
6747 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
6748 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
6749 if (ASrcTy->getNumElements() != 0) {
6750 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
6751 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
6752 SrcTy = cast<PointerType>(CastOp->getType());
6753 SrcPTy = SrcTy->getElementType();
6754 }
6755
6756 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00006757 IC.getTargetData().getTypeSize(SrcPTy) ==
Chris Lattner72684fe2005-01-31 05:51:45 +00006758 IC.getTargetData().getTypeSize(DestPTy)) {
6759
6760 // Okay, we are casting from one integer or pointer type to another of
6761 // the same size. Instead of casting the pointer before the store, cast
6762 // the value to be stored.
6763 Value *NewCast;
6764 if (Constant *C = dyn_cast<Constant>(SI.getOperand(0)))
6765 NewCast = ConstantExpr::getCast(C, SrcPTy);
6766 else
6767 NewCast = IC.InsertNewInstBefore(new CastInst(SI.getOperand(0),
6768 SrcPTy,
6769 SI.getOperand(0)->getName()+".c"), SI);
6770
6771 return new StoreInst(NewCast, CastOp);
6772 }
6773 }
6774 }
6775 return 0;
6776}
6777
Chris Lattner31f486c2005-01-31 05:36:43 +00006778Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
6779 Value *Val = SI.getOperand(0);
6780 Value *Ptr = SI.getOperand(1);
6781
6782 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner5997cf92006-02-08 03:25:32 +00006783 EraseInstFromFunction(SI);
Chris Lattner31f486c2005-01-31 05:36:43 +00006784 ++NumCombined;
6785 return 0;
6786 }
6787
Chris Lattner5997cf92006-02-08 03:25:32 +00006788 // Do really simple DSE, to catch cases where there are several consequtive
6789 // stores to the same location, separated by a few arithmetic operations. This
6790 // situation often occurs with bitfield accesses.
6791 BasicBlock::iterator BBI = &SI;
6792 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
6793 --ScanInsts) {
6794 --BBI;
6795
6796 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
6797 // Prev store isn't volatile, and stores to the same location?
6798 if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
6799 ++NumDeadStore;
6800 ++BBI;
6801 EraseInstFromFunction(*PrevSI);
6802 continue;
6803 }
6804 break;
6805 }
6806
6807 // Don't skip over loads or things that can modify memory.
6808 if (BBI->mayWriteToMemory() || isa<LoadInst>(BBI))
6809 break;
6810 }
6811
6812
6813 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner31f486c2005-01-31 05:36:43 +00006814
6815 // store X, null -> turns into 'unreachable' in SimplifyCFG
6816 if (isa<ConstantPointerNull>(Ptr)) {
6817 if (!isa<UndefValue>(Val)) {
6818 SI.setOperand(0, UndefValue::get(Val->getType()));
6819 if (Instruction *U = dyn_cast<Instruction>(Val))
6820 WorkList.push_back(U); // Dropped a use.
6821 ++NumCombined;
6822 }
6823 return 0; // Do not modify these!
6824 }
6825
6826 // store undef, Ptr -> noop
6827 if (isa<UndefValue>(Val)) {
Chris Lattner5997cf92006-02-08 03:25:32 +00006828 EraseInstFromFunction(SI);
Chris Lattner31f486c2005-01-31 05:36:43 +00006829 ++NumCombined;
6830 return 0;
6831 }
6832
Chris Lattner72684fe2005-01-31 05:51:45 +00006833 // If the pointer destination is a cast, see if we can fold the cast into the
6834 // source instead.
6835 if (CastInst *CI = dyn_cast<CastInst>(Ptr))
6836 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
6837 return Res;
6838 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
6839 if (CE->getOpcode() == Instruction::Cast)
6840 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
6841 return Res;
6842
Chris Lattner219175c2005-09-12 23:23:25 +00006843
6844 // If this store is the last instruction in the basic block, and if the block
6845 // ends with an unconditional branch, try to move it to the successor block.
Chris Lattner5997cf92006-02-08 03:25:32 +00006846 BBI = &SI; ++BBI;
Chris Lattner219175c2005-09-12 23:23:25 +00006847 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
6848 if (BI->isUnconditional()) {
6849 // Check to see if the successor block has exactly two incoming edges. If
6850 // so, see if the other predecessor contains a store to the same location.
6851 // if so, insert a PHI node (if needed) and move the stores down.
6852 BasicBlock *Dest = BI->getSuccessor(0);
6853
6854 pred_iterator PI = pred_begin(Dest);
6855 BasicBlock *Other = 0;
6856 if (*PI != BI->getParent())
6857 Other = *PI;
6858 ++PI;
6859 if (PI != pred_end(Dest)) {
6860 if (*PI != BI->getParent())
6861 if (Other)
6862 Other = 0;
6863 else
6864 Other = *PI;
6865 if (++PI != pred_end(Dest))
6866 Other = 0;
6867 }
6868 if (Other) { // If only one other pred...
6869 BBI = Other->getTerminator();
6870 // Make sure this other block ends in an unconditional branch and that
6871 // there is an instruction before the branch.
6872 if (isa<BranchInst>(BBI) && cast<BranchInst>(BBI)->isUnconditional() &&
6873 BBI != Other->begin()) {
6874 --BBI;
6875 StoreInst *OtherStore = dyn_cast<StoreInst>(BBI);
6876
6877 // If this instruction is a store to the same location.
6878 if (OtherStore && OtherStore->getOperand(1) == SI.getOperand(1)) {
6879 // Okay, we know we can perform this transformation. Insert a PHI
6880 // node now if we need it.
6881 Value *MergedVal = OtherStore->getOperand(0);
6882 if (MergedVal != SI.getOperand(0)) {
6883 PHINode *PN = new PHINode(MergedVal->getType(), "storemerge");
6884 PN->reserveOperandSpace(2);
6885 PN->addIncoming(SI.getOperand(0), SI.getParent());
6886 PN->addIncoming(OtherStore->getOperand(0), Other);
6887 MergedVal = InsertNewInstBefore(PN, Dest->front());
6888 }
6889
6890 // Advance to a place where it is safe to insert the new store and
6891 // insert it.
6892 BBI = Dest->begin();
6893 while (isa<PHINode>(BBI)) ++BBI;
6894 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
6895 OtherStore->isVolatile()), *BBI);
6896
6897 // Nuke the old stores.
Chris Lattner5997cf92006-02-08 03:25:32 +00006898 EraseInstFromFunction(SI);
6899 EraseInstFromFunction(*OtherStore);
Chris Lattner219175c2005-09-12 23:23:25 +00006900 ++NumCombined;
6901 return 0;
6902 }
6903 }
6904 }
6905 }
6906
Chris Lattner31f486c2005-01-31 05:36:43 +00006907 return 0;
6908}
6909
6910
Chris Lattner9eef8a72003-06-04 04:46:00 +00006911Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
6912 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4fdd96c2005-06-18 17:37:34 +00006913 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00006914 BasicBlock *TrueDest;
6915 BasicBlock *FalseDest;
6916 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
6917 !isa<Constant>(X)) {
6918 // Swap Destinations and condition...
6919 BI.setCondition(X);
6920 BI.setSuccessor(0, FalseDest);
6921 BI.setSuccessor(1, TrueDest);
6922 return &BI;
6923 }
6924
6925 // Cannonicalize setne -> seteq
6926 Instruction::BinaryOps Op; Value *Y;
6927 if (match(&BI, m_Br(m_SetCond(Op, m_Value(X), m_Value(Y)),
6928 TrueDest, FalseDest)))
6929 if ((Op == Instruction::SetNE || Op == Instruction::SetLE ||
6930 Op == Instruction::SetGE) && BI.getCondition()->hasOneUse()) {
6931 SetCondInst *I = cast<SetCondInst>(BI.getCondition());
6932 std::string Name = I->getName(); I->setName("");
6933 Instruction::BinaryOps NewOpcode = SetCondInst::getInverseCondition(Op);
6934 Value *NewSCC = BinaryOperator::create(NewOpcode, X, Y, Name, I);
Chris Lattnere967b342003-06-04 05:10:11 +00006935 // Swap Destinations and condition...
Chris Lattnerd4252a72004-07-30 07:50:03 +00006936 BI.setCondition(NewSCC);
Chris Lattnere967b342003-06-04 05:10:11 +00006937 BI.setSuccessor(0, FalseDest);
6938 BI.setSuccessor(1, TrueDest);
Chris Lattnerd4252a72004-07-30 07:50:03 +00006939 removeFromWorkList(I);
6940 I->getParent()->getInstList().erase(I);
6941 WorkList.push_back(cast<Instruction>(NewSCC));
Chris Lattnere967b342003-06-04 05:10:11 +00006942 return &BI;
6943 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00006944
Chris Lattner9eef8a72003-06-04 04:46:00 +00006945 return 0;
6946}
Chris Lattner1085bdf2002-11-04 16:18:53 +00006947
Chris Lattner4c9c20a2004-07-03 00:26:11 +00006948Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
6949 Value *Cond = SI.getCondition();
6950 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
6951 if (I->getOpcode() == Instruction::Add)
6952 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
6953 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
6954 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattner81a7a232004-10-16 18:11:37 +00006955 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner4c9c20a2004-07-03 00:26:11 +00006956 AddRHS));
6957 SI.setOperand(0, I->getOperand(0));
6958 WorkList.push_back(I);
6959 return &SI;
6960 }
6961 }
6962 return 0;
6963}
6964
Chris Lattner6bc98652006-03-05 00:22:33 +00006965/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
6966/// is to leave as a vector operation.
6967static bool CheapToScalarize(Value *V, bool isConstant) {
6968 if (isa<ConstantAggregateZero>(V))
6969 return true;
6970 if (ConstantPacked *C = dyn_cast<ConstantPacked>(V)) {
6971 if (isConstant) return true;
6972 // If all elts are the same, we can extract.
6973 Constant *Op0 = C->getOperand(0);
6974 for (unsigned i = 1; i < C->getNumOperands(); ++i)
6975 if (C->getOperand(i) != Op0)
6976 return false;
6977 return true;
6978 }
6979 Instruction *I = dyn_cast<Instruction>(V);
6980 if (!I) return false;
6981
6982 // Insert element gets simplified to the inserted element or is deleted if
6983 // this is constant idx extract element and its a constant idx insertelt.
6984 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
6985 isa<ConstantInt>(I->getOperand(2)))
6986 return true;
6987 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
6988 return true;
6989 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
6990 if (BO->hasOneUse() &&
6991 (CheapToScalarize(BO->getOperand(0), isConstant) ||
6992 CheapToScalarize(BO->getOperand(1), isConstant)))
6993 return true;
6994
6995 return false;
6996}
6997
Chris Lattner8d1d8d32006-03-31 23:01:56 +00006998/// FindScalarElement - Given a vector and an element number, see if the scalar
6999/// value is already around as a register, for example if it were inserted then
7000/// extracted from the vector.
7001static Value *FindScalarElement(Value *V, unsigned EltNo) {
7002 assert(isa<PackedType>(V->getType()) && "Not looking at a vector?");
7003 const PackedType *PTy = cast<PackedType>(V->getType());
Chris Lattner2d37f922006-04-10 23:06:36 +00007004 unsigned Width = PTy->getNumElements();
7005 if (EltNo >= Width) // Out of range access.
Chris Lattner8d1d8d32006-03-31 23:01:56 +00007006 return UndefValue::get(PTy->getElementType());
7007
7008 if (isa<UndefValue>(V))
7009 return UndefValue::get(PTy->getElementType());
7010 else if (isa<ConstantAggregateZero>(V))
7011 return Constant::getNullValue(PTy->getElementType());
7012 else if (ConstantPacked *CP = dyn_cast<ConstantPacked>(V))
7013 return CP->getOperand(EltNo);
7014 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
7015 // If this is an insert to a variable element, we don't know what it is.
7016 if (!isa<ConstantUInt>(III->getOperand(2))) return 0;
7017 unsigned IIElt = cast<ConstantUInt>(III->getOperand(2))->getValue();
7018
7019 // If this is an insert to the element we are looking for, return the
7020 // inserted value.
7021 if (EltNo == IIElt) return III->getOperand(1);
7022
7023 // Otherwise, the insertelement doesn't modify the value, recurse on its
7024 // vector input.
7025 return FindScalarElement(III->getOperand(0), EltNo);
Chris Lattner2d37f922006-04-10 23:06:36 +00007026 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
7027 if (isa<ConstantAggregateZero>(SVI->getOperand(2))) {
7028 return FindScalarElement(SVI->getOperand(0), 0);
7029 } else if (ConstantPacked *CP =
7030 dyn_cast<ConstantPacked>(SVI->getOperand(2))) {
7031 if (isa<UndefValue>(CP->getOperand(EltNo)))
7032 return UndefValue::get(PTy->getElementType());
7033 unsigned InEl = cast<ConstantUInt>(CP->getOperand(EltNo))->getValue();
7034 if (InEl < Width)
7035 return FindScalarElement(SVI->getOperand(0), InEl);
7036 else
7037 return FindScalarElement(SVI->getOperand(1), InEl - Width);
7038 }
Chris Lattner8d1d8d32006-03-31 23:01:56 +00007039 }
7040
7041 // Otherwise, we don't know.
7042 return 0;
7043}
7044
Robert Bocchinoa8352962006-01-13 22:48:06 +00007045Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Chris Lattner8d1d8d32006-03-31 23:01:56 +00007046
Chris Lattner92346c32006-03-31 18:25:14 +00007047 // If packed val is undef, replace extract with scalar undef.
7048 if (isa<UndefValue>(EI.getOperand(0)))
7049 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
7050
7051 // If packed val is constant 0, replace extract with scalar 0.
7052 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
7053 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
7054
Robert Bocchinoa8352962006-01-13 22:48:06 +00007055 if (ConstantPacked *C = dyn_cast<ConstantPacked>(EI.getOperand(0))) {
7056 // If packed val is constant with uniform operands, replace EI
7057 // with that operand
Chris Lattner6bc98652006-03-05 00:22:33 +00007058 Constant *op0 = C->getOperand(0);
Robert Bocchinoa8352962006-01-13 22:48:06 +00007059 for (unsigned i = 1; i < C->getNumOperands(); ++i)
Chris Lattner6bc98652006-03-05 00:22:33 +00007060 if (C->getOperand(i) != op0) {
7061 op0 = 0;
7062 break;
7063 }
7064 if (op0)
7065 return ReplaceInstUsesWith(EI, op0);
Robert Bocchinoa8352962006-01-13 22:48:06 +00007066 }
Chris Lattner6bc98652006-03-05 00:22:33 +00007067
Chris Lattner8d1d8d32006-03-31 23:01:56 +00007068 // If extracting a specified index from the vector, see if we can recursively
7069 // find a previously computed scalar that was inserted into the vector.
Chris Lattner2d37f922006-04-10 23:06:36 +00007070 if (ConstantUInt *IdxC = dyn_cast<ConstantUInt>(EI.getOperand(1))) {
Chris Lattner8d1d8d32006-03-31 23:01:56 +00007071 if (Value *Elt = FindScalarElement(EI.getOperand(0), IdxC->getValue()))
7072 return ReplaceInstUsesWith(EI, Elt);
Chris Lattner2d37f922006-04-10 23:06:36 +00007073 }
Chris Lattner8d1d8d32006-03-31 23:01:56 +00007074
Robert Bocchinoa8352962006-01-13 22:48:06 +00007075 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0)))
7076 if (I->hasOneUse()) {
7077 // Push extractelement into predecessor operation if legal and
7078 // profitable to do so
7079 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Chris Lattner6bc98652006-03-05 00:22:33 +00007080 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
7081 if (CheapToScalarize(BO, isConstantElt)) {
7082 ExtractElementInst *newEI0 =
7083 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
7084 EI.getName()+".lhs");
7085 ExtractElementInst *newEI1 =
7086 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
7087 EI.getName()+".rhs");
7088 InsertNewInstBefore(newEI0, EI);
7089 InsertNewInstBefore(newEI1, EI);
7090 return BinaryOperator::create(BO->getOpcode(), newEI0, newEI1);
7091 }
7092 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Robert Bocchinoa8352962006-01-13 22:48:06 +00007093 Value *Ptr = InsertCastBefore(I->getOperand(0),
7094 PointerType::get(EI.getType()), EI);
7095 GetElementPtrInst *GEP =
7096 new GetElementPtrInst(Ptr, EI.getOperand(1),
7097 I->getName() + ".gep");
7098 InsertNewInstBefore(GEP, EI);
7099 return new LoadInst(GEP);
Chris Lattner6bc98652006-03-05 00:22:33 +00007100 } else if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
7101 // Extracting the inserted element?
7102 if (IE->getOperand(2) == EI.getOperand(1))
7103 return ReplaceInstUsesWith(EI, IE->getOperand(1));
7104 // If the inserted and extracted elements are constants, they must not
Chris Lattner612fa8e2006-03-30 22:02:40 +00007105 // be the same value, extract from the pre-inserted value instead.
7106 if (isa<Constant>(IE->getOperand(2)) &&
7107 isa<Constant>(EI.getOperand(1))) {
7108 AddUsesToWorkList(EI);
7109 EI.setOperand(0, IE->getOperand(0));
7110 return &EI;
7111 }
Robert Bocchinoa8352962006-01-13 22:48:06 +00007112 }
7113 }
7114 return 0;
7115}
7116
Chris Lattner90951862006-04-16 00:51:47 +00007117/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
7118/// elements from either LHS or RHS, return the shuffle mask and true.
7119/// Otherwise, return false.
7120static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
7121 std::vector<Constant*> &Mask) {
7122 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
7123 "Invalid CollectSingleShuffleElements");
7124 unsigned NumElts = cast<PackedType>(V->getType())->getNumElements();
7125
7126 if (isa<UndefValue>(V)) {
7127 Mask.assign(NumElts, UndefValue::get(Type::UIntTy));
7128 return true;
7129 } else if (V == LHS) {
7130 for (unsigned i = 0; i != NumElts; ++i)
7131 Mask.push_back(ConstantUInt::get(Type::UIntTy, i));
7132 return true;
7133 } else if (V == RHS) {
7134 for (unsigned i = 0; i != NumElts; ++i)
7135 Mask.push_back(ConstantUInt::get(Type::UIntTy, i+NumElts));
7136 return true;
7137 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
7138 // If this is an insert of an extract from some other vector, include it.
7139 Value *VecOp = IEI->getOperand(0);
7140 Value *ScalarOp = IEI->getOperand(1);
7141 Value *IdxOp = IEI->getOperand(2);
7142
Chris Lattnerb6cb64b2006-04-27 21:14:21 +00007143 if (!isa<ConstantInt>(IdxOp))
7144 return false;
7145 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getRawValue();
7146
7147 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
7148 // Okay, we can handle this if the vector we are insertinting into is
7149 // transitively ok.
7150 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
7151 // If so, update the mask to reflect the inserted undef.
7152 Mask[InsertedIdx] = UndefValue::get(Type::UIntTy);
7153 return true;
7154 }
7155 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
7156 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner90951862006-04-16 00:51:47 +00007157 EI->getOperand(0)->getType() == V->getType()) {
7158 unsigned ExtractedIdx =
7159 cast<ConstantInt>(EI->getOperand(1))->getRawValue();
Chris Lattner90951862006-04-16 00:51:47 +00007160
7161 // This must be extracting from either LHS or RHS.
7162 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
7163 // Okay, we can handle this if the vector we are insertinting into is
7164 // transitively ok.
7165 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
7166 // If so, update the mask to reflect the inserted value.
7167 if (EI->getOperand(0) == LHS) {
7168 Mask[InsertedIdx & (NumElts-1)] =
7169 ConstantUInt::get(Type::UIntTy, ExtractedIdx);
7170 } else {
7171 assert(EI->getOperand(0) == RHS);
7172 Mask[InsertedIdx & (NumElts-1)] =
7173 ConstantUInt::get(Type::UIntTy, ExtractedIdx+NumElts);
7174
7175 }
7176 return true;
7177 }
7178 }
7179 }
7180 }
7181 }
7182 // TODO: Handle shufflevector here!
7183
7184 return false;
7185}
7186
7187/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
7188/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
7189/// that computes V and the LHS value of the shuffle.
Chris Lattner39fac442006-04-15 01:39:45 +00007190static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Chris Lattner90951862006-04-16 00:51:47 +00007191 Value *&RHS) {
7192 assert(isa<PackedType>(V->getType()) &&
7193 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattner39fac442006-04-15 01:39:45 +00007194 "Invalid shuffle!");
7195 unsigned NumElts = cast<PackedType>(V->getType())->getNumElements();
7196
7197 if (isa<UndefValue>(V)) {
7198 Mask.assign(NumElts, UndefValue::get(Type::UIntTy));
7199 return V;
7200 } else if (isa<ConstantAggregateZero>(V)) {
7201 Mask.assign(NumElts, ConstantUInt::get(Type::UIntTy, 0));
7202 return V;
7203 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
7204 // If this is an insert of an extract from some other vector, include it.
7205 Value *VecOp = IEI->getOperand(0);
7206 Value *ScalarOp = IEI->getOperand(1);
7207 Value *IdxOp = IEI->getOperand(2);
7208
7209 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
7210 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
7211 EI->getOperand(0)->getType() == V->getType()) {
7212 unsigned ExtractedIdx =
7213 cast<ConstantInt>(EI->getOperand(1))->getRawValue();
7214 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getRawValue();
7215
7216 // Either the extracted from or inserted into vector must be RHSVec,
7217 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner90951862006-04-16 00:51:47 +00007218 if (EI->getOperand(0) == RHS || RHS == 0) {
7219 RHS = EI->getOperand(0);
7220 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
Chris Lattner39fac442006-04-15 01:39:45 +00007221 Mask[InsertedIdx & (NumElts-1)] =
7222 ConstantUInt::get(Type::UIntTy, NumElts+ExtractedIdx);
7223 return V;
7224 }
7225
Chris Lattner90951862006-04-16 00:51:47 +00007226 if (VecOp == RHS) {
7227 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
Chris Lattner39fac442006-04-15 01:39:45 +00007228 // Everything but the extracted element is replaced with the RHS.
7229 for (unsigned i = 0; i != NumElts; ++i) {
7230 if (i != InsertedIdx)
7231 Mask[i] = ConstantUInt::get(Type::UIntTy, NumElts+i);
7232 }
7233 return V;
7234 }
Chris Lattner90951862006-04-16 00:51:47 +00007235
7236 // If this insertelement is a chain that comes from exactly these two
7237 // vectors, return the vector and the effective shuffle.
7238 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
7239 return EI->getOperand(0);
7240
Chris Lattner39fac442006-04-15 01:39:45 +00007241 }
7242 }
7243 }
Chris Lattner90951862006-04-16 00:51:47 +00007244 // TODO: Handle shufflevector here!
Chris Lattner39fac442006-04-15 01:39:45 +00007245
7246 // Otherwise, can't do anything fancy. Return an identity vector.
7247 for (unsigned i = 0; i != NumElts; ++i)
7248 Mask.push_back(ConstantUInt::get(Type::UIntTy, i));
7249 return V;
7250}
7251
7252Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
7253 Value *VecOp = IE.getOperand(0);
7254 Value *ScalarOp = IE.getOperand(1);
7255 Value *IdxOp = IE.getOperand(2);
7256
7257 // If the inserted element was extracted from some other vector, and if the
7258 // indexes are constant, try to turn this into a shufflevector operation.
7259 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
7260 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
7261 EI->getOperand(0)->getType() == IE.getType()) {
7262 unsigned NumVectorElts = IE.getType()->getNumElements();
7263 unsigned ExtractedIdx=cast<ConstantInt>(EI->getOperand(1))->getRawValue();
7264 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getRawValue();
7265
7266 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
7267 return ReplaceInstUsesWith(IE, VecOp);
7268
7269 if (InsertedIdx >= NumVectorElts) // Out of range insert.
7270 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
7271
7272 // If we are extracting a value from a vector, then inserting it right
7273 // back into the same place, just use the input vector.
7274 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
7275 return ReplaceInstUsesWith(IE, VecOp);
7276
7277 // We could theoretically do this for ANY input. However, doing so could
7278 // turn chains of insertelement instructions into a chain of shufflevector
7279 // instructions, and right now we do not merge shufflevectors. As such,
7280 // only do this in a situation where it is clear that there is benefit.
7281 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
7282 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
7283 // the values of VecOp, except then one read from EIOp0.
7284 // Build a new shuffle mask.
7285 std::vector<Constant*> Mask;
7286 if (isa<UndefValue>(VecOp))
7287 Mask.assign(NumVectorElts, UndefValue::get(Type::UIntTy));
7288 else {
7289 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
7290 Mask.assign(NumVectorElts, ConstantUInt::get(Type::UIntTy,
7291 NumVectorElts));
7292 }
7293 Mask[InsertedIdx] = ConstantUInt::get(Type::UIntTy, ExtractedIdx);
7294 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
7295 ConstantPacked::get(Mask));
7296 }
7297
7298 // If this insertelement isn't used by some other insertelement, turn it
7299 // (and any insertelements it points to), into one big shuffle.
7300 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
7301 std::vector<Constant*> Mask;
Chris Lattner90951862006-04-16 00:51:47 +00007302 Value *RHS = 0;
7303 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
7304 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
7305 // We now have a shuffle of LHS, RHS, Mask.
7306 return new ShuffleVectorInst(LHS, RHS, ConstantPacked::get(Mask));
Chris Lattner39fac442006-04-15 01:39:45 +00007307 }
7308 }
7309 }
7310
7311 return 0;
7312}
7313
7314
Chris Lattnerfbb77a42006-04-10 22:45:52 +00007315Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
7316 Value *LHS = SVI.getOperand(0);
7317 Value *RHS = SVI.getOperand(1);
7318 Constant *Mask = cast<Constant>(SVI.getOperand(2));
7319
7320 bool MadeChange = false;
7321
7322 if (isa<UndefValue>(Mask))
7323 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
7324
Chris Lattner39fac442006-04-15 01:39:45 +00007325 // TODO: If we have shuffle(x, undef, mask) and any elements of mask refer to
7326 // the undef, change them to undefs.
7327
Chris Lattnerfbb77a42006-04-10 22:45:52 +00007328 // Canonicalize shuffle(x,x) -> shuffle(x,undef)
7329 if (LHS == RHS) {
7330 if (isa<UndefValue>(LHS)) {
7331 // shuffle(undef,undef,mask) -> undef.
7332 return ReplaceInstUsesWith(SVI, LHS);
7333 }
7334
7335 if (!isa<ConstantAggregateZero>(Mask)) {
7336 // Remap any references to RHS to use LHS.
7337 ConstantPacked *CP = cast<ConstantPacked>(Mask);
7338 std::vector<Constant*> Elts;
7339 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i) {
7340 Elts.push_back(CP->getOperand(i));
7341 if (isa<UndefValue>(CP->getOperand(i)))
7342 continue;
7343 unsigned MV = cast<ConstantInt>(CP->getOperand(i))->getRawValue();
7344 if (MV >= e)
7345 Elts.back() = ConstantUInt::get(Type::UIntTy, MV & (e-1));
7346 }
7347 Mask = ConstantPacked::get(Elts);
7348 }
7349 SVI.setOperand(1, UndefValue::get(RHS->getType()));
7350 SVI.setOperand(2, Mask);
7351 MadeChange = true;
7352 }
7353
Chris Lattner34cebe72006-04-16 00:03:56 +00007354 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
7355 if (isa<UndefValue>(LHS)) {
7356 // shuffle(undef,x,<0,0,0,0>) -> undef.
7357 if (isa<ConstantAggregateZero>(Mask))
7358 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
7359
7360 ConstantPacked *CPM = cast<ConstantPacked>(Mask);
7361 std::vector<Constant*> Elts;
7362 for (unsigned i = 0, e = CPM->getNumOperands(); i != e; ++i) {
7363 if (isa<UndefValue>(CPM->getOperand(i)))
7364 Elts.push_back(CPM->getOperand(i));
7365 else {
7366 unsigned EltNo = cast<ConstantUInt>(CPM->getOperand(i))->getRawValue();
Chris Lattner90951862006-04-16 00:51:47 +00007367 if (EltNo >= e)
7368 Elts.push_back(ConstantUInt::get(Type::UIntTy, EltNo-e));
Chris Lattner34cebe72006-04-16 00:03:56 +00007369 else // Referring to the undef.
7370 Elts.push_back(UndefValue::get(Type::UIntTy));
7371 }
7372 }
7373 return new ShuffleVectorInst(RHS, LHS, ConstantPacked::get(Elts));
7374 }
7375
Chris Lattnerfbb77a42006-04-10 22:45:52 +00007376 if (ConstantPacked *CP = dyn_cast<ConstantPacked>(Mask)) {
7377 bool isLHSID = true, isRHSID = true;
7378
7379 // Analyze the shuffle.
7380 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i) {
7381 if (isa<UndefValue>(CP->getOperand(i)))
7382 continue;
7383 unsigned MV = cast<ConstantInt>(CP->getOperand(i))->getRawValue();
7384
7385 // Is this an identity shuffle of the LHS value?
7386 isLHSID &= (MV == i);
7387
7388 // Is this an identity shuffle of the RHS value?
7389 isRHSID &= (MV-e == i);
7390 }
7391
7392 // Eliminate identity shuffles.
7393 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
7394 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
7395 }
7396
7397 return MadeChange ? &SVI : 0;
7398}
7399
7400
Robert Bocchinoa8352962006-01-13 22:48:06 +00007401
Chris Lattner99f48c62002-09-02 04:59:56 +00007402void InstCombiner::removeFromWorkList(Instruction *I) {
7403 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
7404 WorkList.end());
7405}
7406
Chris Lattner39c98bb2004-12-08 23:43:58 +00007407
7408/// TryToSinkInstruction - Try to move the specified instruction from its
7409/// current block into the beginning of DestBlock, which can only happen if it's
7410/// safe to move the instruction past all of the instructions between it and the
7411/// end of its block.
7412static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
7413 assert(I->hasOneUse() && "Invariants didn't hold!");
7414
Chris Lattnerc4f67e62005-10-27 17:13:11 +00007415 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
7416 if (isa<PHINode>(I) || I->mayWriteToMemory()) return false;
Misha Brukmanb1c93172005-04-21 23:48:37 +00007417
Chris Lattner39c98bb2004-12-08 23:43:58 +00007418 // Do not sink alloca instructions out of the entry block.
7419 if (isa<AllocaInst>(I) && I->getParent() == &DestBlock->getParent()->front())
7420 return false;
7421
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00007422 // We can only sink load instructions if there is nothing between the load and
7423 // the end of block that could change the value.
7424 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00007425 for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
7426 Scan != E; ++Scan)
7427 if (Scan->mayWriteToMemory())
7428 return false;
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00007429 }
Chris Lattner39c98bb2004-12-08 23:43:58 +00007430
7431 BasicBlock::iterator InsertPos = DestBlock->begin();
7432 while (isa<PHINode>(InsertPos)) ++InsertPos;
7433
Chris Lattner9f269e42005-08-08 19:11:57 +00007434 I->moveBefore(InsertPos);
Chris Lattner39c98bb2004-12-08 23:43:58 +00007435 ++NumSunkInst;
7436 return true;
7437}
7438
Chris Lattner1443bc52006-05-11 17:11:52 +00007439/// OptimizeConstantExpr - Given a constant expression and target data layout
7440/// information, symbolically evaluation the constant expr to something simpler
7441/// if possible.
7442static Constant *OptimizeConstantExpr(ConstantExpr *CE, const TargetData *TD) {
7443 if (!TD) return CE;
7444
7445 Constant *Ptr = CE->getOperand(0);
7446 if (CE->getOpcode() == Instruction::GetElementPtr && Ptr->isNullValue() &&
7447 cast<PointerType>(Ptr->getType())->getElementType()->isSized()) {
7448 // If this is a constant expr gep that is effectively computing an
7449 // "offsetof", fold it into 'cast int Size to T*' instead of 'gep 0, 0, 12'
7450 bool isFoldableGEP = true;
7451 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
7452 if (!isa<ConstantInt>(CE->getOperand(i)))
7453 isFoldableGEP = false;
7454 if (isFoldableGEP) {
7455 std::vector<Value*> Ops(CE->op_begin()+1, CE->op_end());
7456 uint64_t Offset = TD->getIndexedOffset(Ptr->getType(), Ops);
7457 Constant *C = ConstantUInt::get(Type::ULongTy, Offset);
7458 C = ConstantExpr::getCast(C, TD->getIntPtrType());
7459 return ConstantExpr::getCast(C, CE->getType());
7460 }
7461 }
7462
7463 return CE;
7464}
7465
Chris Lattnera36ee4e2006-05-10 19:00:36 +00007466
7467/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
7468/// all reachable code to the worklist.
7469///
7470/// This has a couple of tricks to make the code faster and more powerful. In
7471/// particular, we constant fold and DCE instructions as we go, to avoid adding
7472/// them to the worklist (this significantly speeds up instcombine on code where
7473/// many instructions are dead or constant). Additionally, if we find a branch
7474/// whose condition is a known constant, we only visit the reachable successors.
7475///
7476static void AddReachableCodeToWorklist(BasicBlock *BB,
7477 std::set<BasicBlock*> &Visited,
Chris Lattner1443bc52006-05-11 17:11:52 +00007478 std::vector<Instruction*> &WorkList,
7479 const TargetData *TD) {
Chris Lattnera36ee4e2006-05-10 19:00:36 +00007480 // We have now visited this block! If we've already been here, bail out.
7481 if (!Visited.insert(BB).second) return;
7482
7483 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
7484 Instruction *Inst = BBI++;
7485
7486 // DCE instruction if trivially dead.
7487 if (isInstructionTriviallyDead(Inst)) {
7488 ++NumDeadInst;
7489 DEBUG(std::cerr << "IC: DCE: " << *Inst);
7490 Inst->eraseFromParent();
7491 continue;
7492 }
7493
7494 // ConstantProp instruction if trivially constant.
7495 if (Constant *C = ConstantFoldInstruction(Inst)) {
Chris Lattner1443bc52006-05-11 17:11:52 +00007496 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
7497 C = OptimizeConstantExpr(CE, TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00007498 DEBUG(std::cerr << "IC: ConstFold to: " << *C << " from: " << *Inst);
7499 Inst->replaceAllUsesWith(C);
7500 ++NumConstProp;
7501 Inst->eraseFromParent();
7502 continue;
7503 }
7504
7505 WorkList.push_back(Inst);
7506 }
7507
7508 // Recursively visit successors. If this is a branch or switch on a constant,
7509 // only visit the reachable successor.
7510 TerminatorInst *TI = BB->getTerminator();
7511 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
7512 if (BI->isConditional() && isa<ConstantBool>(BI->getCondition())) {
7513 bool CondVal = cast<ConstantBool>(BI->getCondition())->getValue();
Chris Lattner1443bc52006-05-11 17:11:52 +00007514 AddReachableCodeToWorklist(BI->getSuccessor(!CondVal), Visited, WorkList,
7515 TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00007516 return;
7517 }
7518 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
7519 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
7520 // See if this is an explicit destination.
7521 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
7522 if (SI->getCaseValue(i) == Cond) {
Chris Lattner1443bc52006-05-11 17:11:52 +00007523 AddReachableCodeToWorklist(SI->getSuccessor(i), Visited, WorkList,TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00007524 return;
7525 }
7526
7527 // Otherwise it is the default destination.
Chris Lattner1443bc52006-05-11 17:11:52 +00007528 AddReachableCodeToWorklist(SI->getSuccessor(0), Visited, WorkList, TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00007529 return;
7530 }
7531 }
7532
7533 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
Chris Lattner1443bc52006-05-11 17:11:52 +00007534 AddReachableCodeToWorklist(TI->getSuccessor(i), Visited, WorkList, TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00007535}
7536
Chris Lattner113f4f42002-06-25 16:13:24 +00007537bool InstCombiner::runOnFunction(Function &F) {
Chris Lattner260ab202002-04-18 17:39:14 +00007538 bool Changed = false;
Chris Lattnerf4ad1652003-11-02 05:57:39 +00007539 TD = &getAnalysis<TargetData>();
Chris Lattnerca081252001-12-14 16:52:21 +00007540
Chris Lattner4ed40f72005-07-07 20:40:38 +00007541 {
Chris Lattnera36ee4e2006-05-10 19:00:36 +00007542 // Do a depth-first traversal of the function, populate the worklist with
7543 // the reachable instructions. Ignore blocks that are not reachable. Keep
7544 // track of which blocks we visit.
Chris Lattner4ed40f72005-07-07 20:40:38 +00007545 std::set<BasicBlock*> Visited;
Chris Lattner1443bc52006-05-11 17:11:52 +00007546 AddReachableCodeToWorklist(F.begin(), Visited, WorkList, TD);
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00007547
Chris Lattner4ed40f72005-07-07 20:40:38 +00007548 // Do a quick scan over the function. If we find any blocks that are
7549 // unreachable, remove any instructions inside of them. This prevents
7550 // the instcombine code from having to deal with some bad special cases.
7551 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
7552 if (!Visited.count(BB)) {
7553 Instruction *Term = BB->getTerminator();
7554 while (Term != BB->begin()) { // Remove instrs bottom-up
7555 BasicBlock::iterator I = Term; --I;
Chris Lattner2d3a7a62004-04-27 15:13:33 +00007556
Chris Lattner4ed40f72005-07-07 20:40:38 +00007557 DEBUG(std::cerr << "IC: DCE: " << *I);
7558 ++NumDeadInst;
7559
7560 if (!I->use_empty())
7561 I->replaceAllUsesWith(UndefValue::get(I->getType()));
7562 I->eraseFromParent();
7563 }
7564 }
7565 }
Chris Lattnerca081252001-12-14 16:52:21 +00007566
7567 while (!WorkList.empty()) {
7568 Instruction *I = WorkList.back(); // Get an instruction from the worklist
7569 WorkList.pop_back();
7570
Chris Lattner1443bc52006-05-11 17:11:52 +00007571 // Check to see if we can DCE the instruction.
Chris Lattner99f48c62002-09-02 04:59:56 +00007572 if (isInstructionTriviallyDead(I)) {
Chris Lattner1443bc52006-05-11 17:11:52 +00007573 // Add operands to the worklist.
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00007574 if (I->getNumOperands() < 4)
Chris Lattner51ea1272004-02-28 05:22:00 +00007575 AddUsesToWorkList(*I);
Chris Lattner99f48c62002-09-02 04:59:56 +00007576 ++NumDeadInst;
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00007577
Chris Lattnercd517ff2005-01-28 19:32:01 +00007578 DEBUG(std::cerr << "IC: DCE: " << *I);
7579
7580 I->eraseFromParent();
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00007581 removeFromWorkList(I);
7582 continue;
7583 }
Chris Lattner99f48c62002-09-02 04:59:56 +00007584
Chris Lattner1443bc52006-05-11 17:11:52 +00007585 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattner99f48c62002-09-02 04:59:56 +00007586 if (Constant *C = ConstantFoldInstruction(I)) {
Chris Lattner1443bc52006-05-11 17:11:52 +00007587 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
7588 C = OptimizeConstantExpr(CE, TD);
Chris Lattnercd517ff2005-01-28 19:32:01 +00007589 DEBUG(std::cerr << "IC: ConstFold to: " << *C << " from: " << *I);
7590
Chris Lattner1443bc52006-05-11 17:11:52 +00007591 // Add operands to the worklist.
Chris Lattner51ea1272004-02-28 05:22:00 +00007592 AddUsesToWorkList(*I);
Chris Lattnerc6509f42002-12-05 22:41:53 +00007593 ReplaceInstUsesWith(*I, C);
7594
Chris Lattner99f48c62002-09-02 04:59:56 +00007595 ++NumConstProp;
Chris Lattnera36ee4e2006-05-10 19:00:36 +00007596 I->eraseFromParent();
Chris Lattner800aaaf2003-10-07 15:17:02 +00007597 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00007598 continue;
Chris Lattner99f48c62002-09-02 04:59:56 +00007599 }
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00007600
Chris Lattner39c98bb2004-12-08 23:43:58 +00007601 // See if we can trivially sink this instruction to a successor basic block.
7602 if (I->hasOneUse()) {
7603 BasicBlock *BB = I->getParent();
7604 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
7605 if (UserParent != BB) {
7606 bool UserIsSuccessor = false;
7607 // See if the user is one of our successors.
7608 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
7609 if (*SI == UserParent) {
7610 UserIsSuccessor = true;
7611 break;
7612 }
7613
7614 // If the user is one of our immediate successors, and if that successor
7615 // only has us as a predecessors (we'd have to split the critical edge
7616 // otherwise), we can keep going.
7617 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
7618 next(pred_begin(UserParent)) == pred_end(UserParent))
7619 // Okay, the CFG is simple enough, try to sink this instruction.
7620 Changed |= TryToSinkInstruction(I, UserParent);
7621 }
7622 }
7623
Chris Lattnerca081252001-12-14 16:52:21 +00007624 // Now that we have an instruction, try combining it to simplify it...
Chris Lattnerae7a0d32002-08-02 19:29:35 +00007625 if (Instruction *Result = visit(*I)) {
Chris Lattner0b18c1d2002-05-10 15:38:35 +00007626 ++NumCombined;
Chris Lattner260ab202002-04-18 17:39:14 +00007627 // Should we replace the old instruction with a new one?
Chris Lattner053c0932002-05-14 15:24:07 +00007628 if (Result != I) {
Chris Lattner7d2a5392004-03-13 23:54:27 +00007629 DEBUG(std::cerr << "IC: Old = " << *I
7630 << " New = " << *Result);
7631
Chris Lattner396dbfe2004-06-09 05:08:07 +00007632 // Everything uses the new instruction now.
7633 I->replaceAllUsesWith(Result);
7634
7635 // Push the new instruction and any users onto the worklist.
7636 WorkList.push_back(Result);
7637 AddUsersToWorkList(*Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00007638
7639 // Move the name to the new instruction first...
7640 std::string OldName = I->getName(); I->setName("");
Chris Lattner950fc782003-10-07 22:58:41 +00007641 Result->setName(OldName);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00007642
7643 // Insert the new instruction into the basic block...
7644 BasicBlock *InstParent = I->getParent();
Chris Lattner7515cab2004-11-14 19:13:23 +00007645 BasicBlock::iterator InsertPos = I;
7646
7647 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
7648 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
7649 ++InsertPos;
7650
7651 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00007652
Chris Lattner63d75af2004-05-01 23:27:23 +00007653 // Make sure that we reprocess all operands now that we reduced their
7654 // use counts.
Chris Lattnerb643a9e2004-05-01 23:19:52 +00007655 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
7656 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
7657 WorkList.push_back(OpI);
7658
Chris Lattner396dbfe2004-06-09 05:08:07 +00007659 // Instructions can end up on the worklist more than once. Make sure
7660 // we do not process an instruction that has been deleted.
7661 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00007662
7663 // Erase the old instruction.
7664 InstParent->getInstList().erase(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00007665 } else {
Chris Lattner7d2a5392004-03-13 23:54:27 +00007666 DEBUG(std::cerr << "IC: MOD = " << *I);
7667
Chris Lattnerae7a0d32002-08-02 19:29:35 +00007668 // If the instruction was modified, it's possible that it is now dead.
7669 // if so, remove it.
Chris Lattner63d75af2004-05-01 23:27:23 +00007670 if (isInstructionTriviallyDead(I)) {
7671 // Make sure we process all operands now that we are reducing their
7672 // use counts.
7673 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
7674 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
7675 WorkList.push_back(OpI);
Misha Brukmanb1c93172005-04-21 23:48:37 +00007676
Chris Lattner63d75af2004-05-01 23:27:23 +00007677 // Instructions may end up in the worklist more than once. Erase all
Robert Bocchinoa8352962006-01-13 22:48:06 +00007678 // occurrences of this instruction.
Chris Lattner99f48c62002-09-02 04:59:56 +00007679 removeFromWorkList(I);
Chris Lattner31f486c2005-01-31 05:36:43 +00007680 I->eraseFromParent();
Chris Lattner396dbfe2004-06-09 05:08:07 +00007681 } else {
7682 WorkList.push_back(Result);
7683 AddUsersToWorkList(*Result);
Chris Lattnerae7a0d32002-08-02 19:29:35 +00007684 }
Chris Lattner053c0932002-05-14 15:24:07 +00007685 }
Chris Lattner260ab202002-04-18 17:39:14 +00007686 Changed = true;
Chris Lattnerca081252001-12-14 16:52:21 +00007687 }
7688 }
7689
Chris Lattner260ab202002-04-18 17:39:14 +00007690 return Changed;
Chris Lattner04805fa2002-02-26 21:46:54 +00007691}
7692
Brian Gaeke38b79e82004-07-27 17:43:21 +00007693FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattner260ab202002-04-18 17:39:14 +00007694 return new InstCombiner();
Chris Lattner04805fa2002-02-26 21:46:54 +00007695}
Brian Gaeke960707c2003-11-11 22:41:34 +00007696