blob: 40dfb4163c83da62407ccf5773cb88fd5ed993be [file] [log] [blame]
Chris Lattnere6794492002-08-12 21:17:25 +00001//===- InstructionCombining.cpp - Combine multiple instructions -----------===//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
John Criswell482202a2003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
Misha Brukmanb1c93172005-04-21 23:48:37 +00007//
John Criswell482202a2003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattnerca081252001-12-14 16:52:21 +00009//
10// InstructionCombining - Combine instructions to form fewer, simple
Chris Lattner99f48c62002-09-02 04:59:56 +000011// instructions. This pass does not modify the CFG This pass is where algebraic
12// simplification happens.
Chris Lattnerca081252001-12-14 16:52:21 +000013//
14// This pass combines things like:
Chris Lattnerdd1a86d2004-05-04 15:19:33 +000015// %Y = add int %X, 1
16// %Z = add int %Y, 1
Chris Lattnerca081252001-12-14 16:52:21 +000017// into:
Chris Lattnerdd1a86d2004-05-04 15:19:33 +000018// %Z = add int %X, 2
Chris Lattnerca081252001-12-14 16:52:21 +000019//
20// This is a simple worklist driven algorithm.
21//
Chris Lattner216c7b82003-09-10 05:29:43 +000022// This pass guarantees that the following canonicalizations are performed on
Chris Lattnerbfb1d032003-07-23 21:41:57 +000023// the program:
24// 1. If a binary operator has a constant operand, it is moved to the RHS
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +000025// 2. Bitwise operators with constant operands are always grouped so that
26// shifts are performed first, then or's, then and's, then xor's.
Chris Lattnerbfb1d032003-07-23 21:41:57 +000027// 3. SetCC instructions are converted from <,>,<=,>= to ==,!= if possible
28// 4. All SetCC instructions on boolean values are replaced with logical ops
Chris Lattnerede3fe02003-08-13 04:18:28 +000029// 5. add X, X is represented as (X*2) => (X << 1)
30// 6. Multiplies with a power-of-two constant argument are transformed into
31// shifts.
Chris Lattner7515cab2004-11-14 19:13:23 +000032// ... etc.
Chris Lattnerbfb1d032003-07-23 21:41:57 +000033//
Chris Lattnerca081252001-12-14 16:52:21 +000034//===----------------------------------------------------------------------===//
35
Chris Lattner7d2a5392004-03-13 23:54:27 +000036#define DEBUG_TYPE "instcombine"
Chris Lattnerb4cfa7f2002-05-07 20:03:00 +000037#include "llvm/Transforms/Scalar.h"
Chris Lattner00648e12004-10-12 04:52:52 +000038#include "llvm/IntrinsicInst.h"
Chris Lattner04805fa2002-02-26 21:46:54 +000039#include "llvm/Pass.h"
Chris Lattner1085bdf2002-11-04 16:18:53 +000040#include "llvm/DerivedTypes.h"
Chris Lattner0f1d8a32003-06-26 05:06:25 +000041#include "llvm/GlobalVariable.h"
Chris Lattnerf4ad1652003-11-02 05:57:39 +000042#include "llvm/Target/TargetData.h"
43#include "llvm/Transforms/Utils/BasicBlockUtils.h"
44#include "llvm/Transforms/Utils/Local.h"
Chris Lattner69193f92004-04-05 01:30:19 +000045#include "llvm/Support/CallSite.h"
Chris Lattner39c98bb2004-12-08 23:43:58 +000046#include "llvm/Support/Debug.h"
Chris Lattner69193f92004-04-05 01:30:19 +000047#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner260ab202002-04-18 17:39:14 +000048#include "llvm/Support/InstVisitor.h"
Chris Lattner22d00a82005-08-02 19:16:58 +000049#include "llvm/Support/MathExtras.h"
Chris Lattnerd4252a72004-07-30 07:50:03 +000050#include "llvm/Support/PatternMatch.h"
Chris Lattner3d27be12006-08-27 12:54:02 +000051#include "llvm/Support/Compiler.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000052#include "llvm/ADT/Statistic.h"
Chris Lattner39c98bb2004-12-08 23:43:58 +000053#include "llvm/ADT/STLExtras.h"
Chris Lattner053c0932002-05-14 15:24:07 +000054#include <algorithm>
Chris Lattnerc597b8a2006-01-22 23:32:06 +000055#include <iostream>
Chris Lattner8427bff2003-12-07 01:24:23 +000056using namespace llvm;
Chris Lattnerd4252a72004-07-30 07:50:03 +000057using namespace llvm::PatternMatch;
Brian Gaeke960707c2003-11-11 22:41:34 +000058
Chris Lattner260ab202002-04-18 17:39:14 +000059namespace {
Chris Lattnerbf3a0992002-10-01 22:38:41 +000060 Statistic<> NumCombined ("instcombine", "Number of insts combined");
61 Statistic<> NumConstProp("instcombine", "Number of constant folds");
62 Statistic<> NumDeadInst ("instcombine", "Number of dead inst eliminated");
Chris Lattner5997cf92006-02-08 03:25:32 +000063 Statistic<> NumDeadStore("instcombine", "Number of dead stores eliminated");
Chris Lattner39c98bb2004-12-08 23:43:58 +000064 Statistic<> NumSunkInst ("instcombine", "Number of instructions sunk");
Chris Lattnerbf3a0992002-10-01 22:38:41 +000065
Chris Lattner4a4c7fe2006-06-28 22:08:15 +000066 class VISIBILITY_HIDDEN InstCombiner
67 : public FunctionPass,
68 public InstVisitor<InstCombiner, Instruction*> {
Chris Lattner260ab202002-04-18 17:39:14 +000069 // Worklist of all of the instructions that need to be simplified.
70 std::vector<Instruction*> WorkList;
Chris Lattnerf4ad1652003-11-02 05:57:39 +000071 TargetData *TD;
Chris Lattner260ab202002-04-18 17:39:14 +000072
Chris Lattner51ea1272004-02-28 05:22:00 +000073 /// AddUsersToWorkList - When an instruction is simplified, add all users of
74 /// the instruction to the work lists because they might get more simplified
75 /// now.
76 ///
Chris Lattner2590e512006-02-07 06:56:34 +000077 void AddUsersToWorkList(Value &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +000078 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
Chris Lattner260ab202002-04-18 17:39:14 +000079 UI != UE; ++UI)
80 WorkList.push_back(cast<Instruction>(*UI));
81 }
82
Chris Lattner51ea1272004-02-28 05:22:00 +000083 /// AddUsesToWorkList - When an instruction is simplified, add operands to
84 /// the work lists because they might get more simplified now.
85 ///
86 void AddUsesToWorkList(Instruction &I) {
87 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
88 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i)))
89 WorkList.push_back(Op);
90 }
91
Chris Lattner99f48c62002-09-02 04:59:56 +000092 // removeFromWorkList - remove all instances of I from the worklist.
93 void removeFromWorkList(Instruction *I);
Chris Lattner260ab202002-04-18 17:39:14 +000094 public:
Chris Lattner113f4f42002-06-25 16:13:24 +000095 virtual bool runOnFunction(Function &F);
Chris Lattner260ab202002-04-18 17:39:14 +000096
Chris Lattnerf12cc842002-04-28 21:27:06 +000097 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnerf4ad1652003-11-02 05:57:39 +000098 AU.addRequired<TargetData>();
Owen Andersona6968f82006-07-10 19:03:49 +000099 AU.addPreservedID(LCSSAID);
Chris Lattner820d9712002-10-21 20:00:28 +0000100 AU.setPreservesCFG();
Chris Lattnerf12cc842002-04-28 21:27:06 +0000101 }
102
Chris Lattner69193f92004-04-05 01:30:19 +0000103 TargetData &getTargetData() const { return *TD; }
104
Chris Lattner260ab202002-04-18 17:39:14 +0000105 // Visitation implementation - Implement instruction combining for different
106 // instruction types. The semantics are as follows:
107 // Return Value:
108 // null - No change was made
Chris Lattnere6794492002-08-12 21:17:25 +0000109 // I - Change was made, I is still valid, I may be dead though
Chris Lattner260ab202002-04-18 17:39:14 +0000110 // otherwise - Change was made, replace I with returned instruction
Misha Brukmanb1c93172005-04-21 23:48:37 +0000111 //
Chris Lattner113f4f42002-06-25 16:13:24 +0000112 Instruction *visitAdd(BinaryOperator &I);
113 Instruction *visitSub(BinaryOperator &I);
114 Instruction *visitMul(BinaryOperator &I);
115 Instruction *visitDiv(BinaryOperator &I);
116 Instruction *visitRem(BinaryOperator &I);
117 Instruction *visitAnd(BinaryOperator &I);
118 Instruction *visitOr (BinaryOperator &I);
119 Instruction *visitXor(BinaryOperator &I);
Chris Lattnerd1f46d32005-04-24 06:59:08 +0000120 Instruction *visitSetCondInst(SetCondInst &I);
121 Instruction *visitSetCondInstWithCastAndCast(SetCondInst &SCI);
122
Chris Lattner0798af32005-01-13 20:14:25 +0000123 Instruction *FoldGEPSetCC(User *GEPLHS, Value *RHS,
124 Instruction::BinaryOps Cond, Instruction &I);
Chris Lattnere8d6c602003-03-10 19:16:08 +0000125 Instruction *visitShiftInst(ShiftInst &I);
Chris Lattner14553932006-01-06 07:12:35 +0000126 Instruction *FoldShiftByConstant(Value *Op0, ConstantUInt *Op1,
127 ShiftInst &I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000128 Instruction *visitCastInst(CastInst &CI);
Chris Lattner411336f2005-01-19 21:50:18 +0000129 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
130 Instruction *FI);
Chris Lattnerb909e8b2004-03-12 05:52:32 +0000131 Instruction *visitSelectInst(SelectInst &CI);
Chris Lattner970c33a2003-06-19 17:00:31 +0000132 Instruction *visitCallInst(CallInst &CI);
133 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner113f4f42002-06-25 16:13:24 +0000134 Instruction *visitPHINode(PHINode &PN);
135 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Chris Lattner1085bdf2002-11-04 16:18:53 +0000136 Instruction *visitAllocationInst(AllocationInst &AI);
Chris Lattner8427bff2003-12-07 01:24:23 +0000137 Instruction *visitFreeInst(FreeInst &FI);
Chris Lattner0f1d8a32003-06-26 05:06:25 +0000138 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattner31f486c2005-01-31 05:36:43 +0000139 Instruction *visitStoreInst(StoreInst &SI);
Chris Lattner9eef8a72003-06-04 04:46:00 +0000140 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner4c9c20a2004-07-03 00:26:11 +0000141 Instruction *visitSwitchInst(SwitchInst &SI);
Chris Lattner39fac442006-04-15 01:39:45 +0000142 Instruction *visitInsertElementInst(InsertElementInst &IE);
Robert Bocchinoa8352962006-01-13 22:48:06 +0000143 Instruction *visitExtractElementInst(ExtractElementInst &EI);
Chris Lattnerfbb77a42006-04-10 22:45:52 +0000144 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
Chris Lattner260ab202002-04-18 17:39:14 +0000145
146 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner113f4f42002-06-25 16:13:24 +0000147 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000148
Chris Lattner970c33a2003-06-19 17:00:31 +0000149 private:
Chris Lattneraec3d942003-10-07 22:32:43 +0000150 Instruction *visitCallSite(CallSite CS);
Chris Lattner970c33a2003-06-19 17:00:31 +0000151 bool transformConstExprCastCall(CallSite CS);
152
Chris Lattner69193f92004-04-05 01:30:19 +0000153 public:
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000154 // InsertNewInstBefore - insert an instruction New before instruction Old
155 // in the program. Add the new instruction to the worklist.
156 //
Chris Lattner623826c2004-09-28 21:48:02 +0000157 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattner65217ff2002-08-23 18:32:43 +0000158 assert(New && New->getParent() == 0 &&
159 "New instruction already inserted into a basic block!");
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000160 BasicBlock *BB = Old.getParent();
161 BB->getInstList().insert(&Old, New); // Insert inst
162 WorkList.push_back(New); // Add to worklist
Chris Lattnere79e8542004-02-23 06:38:22 +0000163 return New;
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000164 }
165
Chris Lattner7e794272004-09-24 15:21:34 +0000166 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
167 /// This also adds the cast to the worklist. Finally, this returns the
168 /// cast.
169 Value *InsertCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
170 if (V->getType() == Ty) return V;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000171
Chris Lattnere79d2492006-04-06 19:19:17 +0000172 if (Constant *CV = dyn_cast<Constant>(V))
173 return ConstantExpr::getCast(CV, Ty);
174
Chris Lattner7e794272004-09-24 15:21:34 +0000175 Instruction *C = new CastInst(V, Ty, V->getName(), &Pos);
176 WorkList.push_back(C);
177 return C;
178 }
179
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000180 // ReplaceInstUsesWith - This method is to be used when an instruction is
181 // found to be dead, replacable with another preexisting expression. Here
182 // we add all uses of I to the worklist, replace all uses of I with the new
183 // value, then return I, so that the inst combiner will know that I was
184 // modified.
185 //
186 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattner51ea1272004-02-28 05:22:00 +0000187 AddUsersToWorkList(I); // Add all modified instrs to worklist
Chris Lattner8953b902004-04-05 02:10:19 +0000188 if (&I != V) {
189 I.replaceAllUsesWith(V);
190 return &I;
191 } else {
192 // If we are replacing the instruction with itself, this must be in a
193 // segment of unreachable code, so just clobber the instruction.
Chris Lattner8ba9ec92004-10-18 02:59:09 +0000194 I.replaceAllUsesWith(UndefValue::get(I.getType()));
Chris Lattner8953b902004-04-05 02:10:19 +0000195 return &I;
196 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000197 }
Chris Lattner51ea1272004-02-28 05:22:00 +0000198
Chris Lattner2590e512006-02-07 06:56:34 +0000199 // UpdateValueUsesWith - This method is to be used when an value is
200 // found to be replacable with another preexisting expression or was
201 // updated. Here we add all uses of I to the worklist, replace all uses of
202 // I with the new value (unless the instruction was just updated), then
203 // return true, so that the inst combiner will know that I was modified.
204 //
205 bool UpdateValueUsesWith(Value *Old, Value *New) {
206 AddUsersToWorkList(*Old); // Add all modified instrs to worklist
207 if (Old != New)
208 Old->replaceAllUsesWith(New);
209 if (Instruction *I = dyn_cast<Instruction>(Old))
210 WorkList.push_back(I);
Chris Lattner5b2edb12006-02-12 08:02:11 +0000211 if (Instruction *I = dyn_cast<Instruction>(New))
212 WorkList.push_back(I);
Chris Lattner2590e512006-02-07 06:56:34 +0000213 return true;
214 }
215
Chris Lattner51ea1272004-02-28 05:22:00 +0000216 // EraseInstFromFunction - When dealing with an instruction that has side
217 // effects or produces a void value, we can't rely on DCE to delete the
218 // instruction. Instead, visit methods should return the value returned by
219 // this function.
220 Instruction *EraseInstFromFunction(Instruction &I) {
221 assert(I.use_empty() && "Cannot erase instruction that is used!");
222 AddUsesToWorkList(I);
223 removeFromWorkList(&I);
Chris Lattner95307542004-11-18 21:41:39 +0000224 I.eraseFromParent();
Chris Lattner51ea1272004-02-28 05:22:00 +0000225 return 0; // Don't do anything with FI
226 }
227
Chris Lattner3ac7c262003-08-13 20:16:26 +0000228 private:
Chris Lattnerdfae8be2003-07-24 17:35:25 +0000229 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
230 /// InsertBefore instruction. This is specialized a bit to avoid inserting
231 /// casts that are known to not do anything...
232 ///
233 Value *InsertOperandCastBefore(Value *V, const Type *DestTy,
234 Instruction *InsertBefore);
235
Chris Lattner7fb29e12003-03-11 00:12:48 +0000236 // SimplifyCommutative - This performs a few simplifications for commutative
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000237 // operators.
Chris Lattner7fb29e12003-03-11 00:12:48 +0000238 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerba1cb382003-09-19 17:17:26 +0000239
Chris Lattner0157e7f2006-02-11 09:31:47 +0000240 bool SimplifyDemandedBits(Value *V, uint64_t Mask,
241 uint64_t &KnownZero, uint64_t &KnownOne,
242 unsigned Depth = 0);
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000243
244 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
245 // PHI node as operand #0, see if we can fold the instruction into the PHI
246 // (which is only possible if all operands to the PHI are constants).
247 Instruction *FoldOpIntoPhi(Instruction &I);
248
Chris Lattner7515cab2004-11-14 19:13:23 +0000249 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
250 // operator and they all are only used by the PHI, PHI together their
251 // inputs, and do the operation once, to the result of the PHI.
252 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
253
Chris Lattnerba1cb382003-09-19 17:17:26 +0000254 Instruction *OptAndOp(Instruction *Op, ConstantIntegral *OpRHS,
255 ConstantIntegral *AndRHS, BinaryOperator &TheAnd);
Chris Lattneraf517572005-09-18 04:24:45 +0000256
257 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantIntegral *Mask,
258 bool isSub, Instruction &I);
Chris Lattner6862fbd2004-09-29 17:40:11 +0000259 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
260 bool Inside, Instruction &IB);
Chris Lattner216be912005-10-24 06:03:58 +0000261 Instruction *PromoteCastOfAllocation(CastInst &CI, AllocationInst &AI);
Chris Lattnerc482a9e2006-06-15 19:07:26 +0000262 Instruction *MatchBSwap(BinaryOperator &I);
263
Chris Lattner1ebbe6a2006-05-13 02:06:03 +0000264 Value *EvaluateInDifferentType(Value *V, const Type *Ty);
Chris Lattner260ab202002-04-18 17:39:14 +0000265 };
Chris Lattnerb28b6802002-07-23 18:06:35 +0000266
Chris Lattnerc2d3d312006-08-27 22:42:52 +0000267 RegisterPass<InstCombiner> X("instcombine", "Combine redundant instructions");
Chris Lattner260ab202002-04-18 17:39:14 +0000268}
269
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000270// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattner81a7a232004-10-16 18:11:37 +0000271// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000272static unsigned getComplexity(Value *V) {
273 if (isa<Instruction>(V)) {
274 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
Chris Lattner81a7a232004-10-16 18:11:37 +0000275 return 3;
276 return 4;
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000277 }
Chris Lattner81a7a232004-10-16 18:11:37 +0000278 if (isa<Argument>(V)) return 3;
279 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000280}
Chris Lattner260ab202002-04-18 17:39:14 +0000281
Chris Lattner7fb29e12003-03-11 00:12:48 +0000282// isOnlyUse - Return true if this instruction will be deleted if we stop using
283// it.
284static bool isOnlyUse(Value *V) {
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000285 return V->hasOneUse() || isa<Constant>(V);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000286}
287
Chris Lattnere79e8542004-02-23 06:38:22 +0000288// getPromotedType - Return the specified type promoted as it would be to pass
289// though a va_arg area...
290static const Type *getPromotedType(const Type *Ty) {
Chris Lattner97bfcea2004-06-17 18:16:02 +0000291 switch (Ty->getTypeID()) {
Chris Lattnere79e8542004-02-23 06:38:22 +0000292 case Type::SByteTyID:
293 case Type::ShortTyID: return Type::IntTy;
294 case Type::UByteTyID:
295 case Type::UShortTyID: return Type::UIntTy;
296 case Type::FloatTyID: return Type::DoubleTy;
297 default: return Ty;
298 }
299}
300
Chris Lattner567b81f2005-09-13 00:40:14 +0000301/// isCast - If the specified operand is a CastInst or a constant expr cast,
302/// return the operand value, otherwise return null.
303static Value *isCast(Value *V) {
304 if (CastInst *I = dyn_cast<CastInst>(V))
305 return I->getOperand(0);
306 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
307 if (CE->getOpcode() == Instruction::Cast)
308 return CE->getOperand(0);
309 return 0;
310}
311
Chris Lattner1d441ad2006-05-06 09:00:16 +0000312enum CastType {
313 Noop = 0,
314 Truncate = 1,
315 Signext = 2,
316 Zeroext = 3
317};
318
319/// getCastType - In the future, we will split the cast instruction into these
320/// various types. Until then, we have to do the analysis here.
321static CastType getCastType(const Type *Src, const Type *Dest) {
322 assert(Src->isIntegral() && Dest->isIntegral() &&
323 "Only works on integral types!");
324 unsigned SrcSize = Src->getPrimitiveSizeInBits();
325 unsigned DestSize = Dest->getPrimitiveSizeInBits();
326
327 if (SrcSize == DestSize) return Noop;
328 if (SrcSize > DestSize) return Truncate;
329 if (Src->isSigned()) return Signext;
330 return Zeroext;
331}
332
333
334// isEliminableCastOfCast - Return true if it is valid to eliminate the CI
335// instruction.
336//
337static bool isEliminableCastOfCast(const Type *SrcTy, const Type *MidTy,
338 const Type *DstTy, TargetData *TD) {
339
340 // It is legal to eliminate the instruction if casting A->B->A if the sizes
341 // are identical and the bits don't get reinterpreted (for example
342 // int->float->int would not be allowed).
343 if (SrcTy == DstTy && SrcTy->isLosslesslyConvertibleTo(MidTy))
344 return true;
345
346 // If we are casting between pointer and integer types, treat pointers as
347 // integers of the appropriate size for the code below.
348 if (isa<PointerType>(SrcTy)) SrcTy = TD->getIntPtrType();
349 if (isa<PointerType>(MidTy)) MidTy = TD->getIntPtrType();
350 if (isa<PointerType>(DstTy)) DstTy = TD->getIntPtrType();
351
352 // Allow free casting and conversion of sizes as long as the sign doesn't
353 // change...
354 if (SrcTy->isIntegral() && MidTy->isIntegral() && DstTy->isIntegral()) {
355 CastType FirstCast = getCastType(SrcTy, MidTy);
356 CastType SecondCast = getCastType(MidTy, DstTy);
357
358 // Capture the effect of these two casts. If the result is a legal cast,
359 // the CastType is stored here, otherwise a special code is used.
360 static const unsigned CastResult[] = {
361 // First cast is noop
362 0, 1, 2, 3,
363 // First cast is a truncate
364 1, 1, 4, 4, // trunc->extend is not safe to eliminate
365 // First cast is a sign ext
366 2, 5, 2, 4, // signext->zeroext never ok
367 // First cast is a zero ext
368 3, 5, 3, 3,
369 };
370
371 unsigned Result = CastResult[FirstCast*4+SecondCast];
372 switch (Result) {
373 default: assert(0 && "Illegal table value!");
374 case 0:
375 case 1:
376 case 2:
377 case 3:
378 // FIXME: in the future, when LLVM has explicit sign/zeroextends and
379 // truncates, we could eliminate more casts.
380 return (unsigned)getCastType(SrcTy, DstTy) == Result;
381 case 4:
382 return false; // Not possible to eliminate this here.
383 case 5:
384 // Sign or zero extend followed by truncate is always ok if the result
385 // is a truncate or noop.
386 CastType ResultCast = getCastType(SrcTy, DstTy);
387 if (ResultCast == Noop || ResultCast == Truncate)
388 return true;
389 // Otherwise we are still growing the value, we are only safe if the
390 // result will match the sign/zeroextendness of the result.
391 return ResultCast == FirstCast;
392 }
393 }
394
395 // If this is a cast from 'float -> double -> integer', cast from
396 // 'float -> integer' directly, as the value isn't changed by the
397 // float->double conversion.
398 if (SrcTy->isFloatingPoint() && MidTy->isFloatingPoint() &&
399 DstTy->isIntegral() &&
400 SrcTy->getPrimitiveSize() < MidTy->getPrimitiveSize())
401 return true;
402
403 // Packed type conversions don't modify bits.
404 if (isa<PackedType>(SrcTy) && isa<PackedType>(MidTy) &&isa<PackedType>(DstTy))
405 return true;
406
407 return false;
408}
409
410/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
411/// in any code being generated. It does not require codegen if V is simple
412/// enough or if the cast can be folded into other casts.
413static bool ValueRequiresCast(const Value *V, const Type *Ty, TargetData *TD) {
414 if (V->getType() == Ty || isa<Constant>(V)) return false;
415
416 // If this is a noop cast, it isn't real codegen.
417 if (V->getType()->isLosslesslyConvertibleTo(Ty))
418 return false;
419
Chris Lattner99155be2006-05-25 23:24:33 +0000420 // If this is another cast that can be eliminated, it isn't codegen either.
Chris Lattner1d441ad2006-05-06 09:00:16 +0000421 if (const CastInst *CI = dyn_cast<CastInst>(V))
422 if (isEliminableCastOfCast(CI->getOperand(0)->getType(), CI->getType(), Ty,
423 TD))
424 return false;
425 return true;
426}
427
428/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
429/// InsertBefore instruction. This is specialized a bit to avoid inserting
430/// casts that are known to not do anything...
431///
432Value *InstCombiner::InsertOperandCastBefore(Value *V, const Type *DestTy,
433 Instruction *InsertBefore) {
434 if (V->getType() == DestTy) return V;
435 if (Constant *C = dyn_cast<Constant>(V))
436 return ConstantExpr::getCast(C, DestTy);
437
438 CastInst *CI = new CastInst(V, DestTy, V->getName());
439 InsertNewInstBefore(CI, *InsertBefore);
440 return CI;
441}
442
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000443// SimplifyCommutative - This performs a few simplifications for commutative
444// operators:
Chris Lattner260ab202002-04-18 17:39:14 +0000445//
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000446// 1. Order operands such that they are listed from right (least complex) to
447// left (most complex). This puts constants before unary operators before
448// binary operators.
449//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000450// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
451// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000452//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000453bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000454 bool Changed = false;
455 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
456 Changed = !I.swapOperands();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000457
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000458 if (!I.isAssociative()) return Changed;
459 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattner7fb29e12003-03-11 00:12:48 +0000460 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
461 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
462 if (isa<Constant>(I.getOperand(1))) {
Chris Lattner34428442003-05-27 16:40:51 +0000463 Constant *Folded = ConstantExpr::get(I.getOpcode(),
464 cast<Constant>(I.getOperand(1)),
465 cast<Constant>(Op->getOperand(1)));
Chris Lattner7fb29e12003-03-11 00:12:48 +0000466 I.setOperand(0, Op->getOperand(0));
467 I.setOperand(1, Folded);
468 return true;
469 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
470 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
471 isOnlyUse(Op) && isOnlyUse(Op1)) {
472 Constant *C1 = cast<Constant>(Op->getOperand(1));
473 Constant *C2 = cast<Constant>(Op1->getOperand(1));
474
475 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner34428442003-05-27 16:40:51 +0000476 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000477 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
478 Op1->getOperand(0),
479 Op1->getName(), &I);
480 WorkList.push_back(New);
481 I.setOperand(0, New);
482 I.setOperand(1, Folded);
483 return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000484 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000485 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000486 return Changed;
Chris Lattner260ab202002-04-18 17:39:14 +0000487}
Chris Lattnerca081252001-12-14 16:52:21 +0000488
Chris Lattnerbb74e222003-03-10 23:06:50 +0000489// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
490// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattner9fa53de2002-05-06 16:49:18 +0000491//
Chris Lattnerbb74e222003-03-10 23:06:50 +0000492static inline Value *dyn_castNegVal(Value *V) {
493 if (BinaryOperator::isNeg(V))
Chris Lattnerd6f636a2005-04-24 07:30:14 +0000494 return BinaryOperator::getNegArgument(V);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000495
Chris Lattner9ad0d552004-12-14 20:08:06 +0000496 // Constants can be considered to be negated values if they can be folded.
497 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
498 return ConstantExpr::getNeg(C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000499 return 0;
Chris Lattner9fa53de2002-05-06 16:49:18 +0000500}
501
Chris Lattnerbb74e222003-03-10 23:06:50 +0000502static inline Value *dyn_castNotVal(Value *V) {
503 if (BinaryOperator::isNot(V))
Chris Lattnerd6f636a2005-04-24 07:30:14 +0000504 return BinaryOperator::getNotArgument(V);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000505
506 // Constants can be considered to be not'ed values...
Chris Lattnerdd65d862003-04-30 22:34:06 +0000507 if (ConstantIntegral *C = dyn_cast<ConstantIntegral>(V))
Chris Lattnerc8e7e292004-06-10 02:12:35 +0000508 return ConstantExpr::getNot(C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000509 return 0;
510}
511
Chris Lattner7fb29e12003-03-11 00:12:48 +0000512// dyn_castFoldableMul - If this value is a multiply that can be folded into
513// other computations (because it has a constant operand), return the
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000514// non-constant operand of the multiply, and set CST to point to the multiplier.
515// Otherwise, return null.
Chris Lattner7fb29e12003-03-11 00:12:48 +0000516//
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000517static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000518 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000519 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattner7fb29e12003-03-11 00:12:48 +0000520 if (I->getOpcode() == Instruction::Mul)
Chris Lattner970136362004-11-15 05:54:07 +0000521 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattner7fb29e12003-03-11 00:12:48 +0000522 return I->getOperand(0);
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000523 if (I->getOpcode() == Instruction::Shl)
Chris Lattner970136362004-11-15 05:54:07 +0000524 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000525 // The multiplier is really 1 << CST.
526 Constant *One = ConstantInt::get(V->getType(), 1);
527 CST = cast<ConstantInt>(ConstantExpr::getShl(One, CST));
528 return I->getOperand(0);
529 }
530 }
Chris Lattner7fb29e12003-03-11 00:12:48 +0000531 return 0;
Chris Lattner3082c5a2003-02-18 19:28:33 +0000532}
Chris Lattner31ae8632002-08-14 17:51:49 +0000533
Chris Lattner0798af32005-01-13 20:14:25 +0000534/// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
535/// expression, return it.
536static User *dyn_castGetElementPtr(Value *V) {
537 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
538 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
539 if (CE->getOpcode() == Instruction::GetElementPtr)
540 return cast<User>(V);
541 return false;
542}
543
Chris Lattner623826c2004-09-28 21:48:02 +0000544// AddOne, SubOne - Add or subtract a constant one from an integer constant...
Chris Lattner6862fbd2004-09-29 17:40:11 +0000545static ConstantInt *AddOne(ConstantInt *C) {
546 return cast<ConstantInt>(ConstantExpr::getAdd(C,
547 ConstantInt::get(C->getType(), 1)));
Chris Lattner623826c2004-09-28 21:48:02 +0000548}
Chris Lattner6862fbd2004-09-29 17:40:11 +0000549static ConstantInt *SubOne(ConstantInt *C) {
550 return cast<ConstantInt>(ConstantExpr::getSub(C,
551 ConstantInt::get(C->getType(), 1)));
Chris Lattner623826c2004-09-28 21:48:02 +0000552}
553
Chris Lattner0157e7f2006-02-11 09:31:47 +0000554/// GetConstantInType - Return a ConstantInt with the specified type and value.
555///
Chris Lattneree0f2802006-02-12 02:07:56 +0000556static ConstantIntegral *GetConstantInType(const Type *Ty, uint64_t Val) {
Chris Lattner0157e7f2006-02-11 09:31:47 +0000557 if (Ty->isUnsigned())
558 return ConstantUInt::get(Ty, Val);
Chris Lattneree0f2802006-02-12 02:07:56 +0000559 else if (Ty->getTypeID() == Type::BoolTyID)
560 return ConstantBool::get(Val);
Chris Lattner0157e7f2006-02-11 09:31:47 +0000561 int64_t SVal = Val;
562 SVal <<= 64-Ty->getPrimitiveSizeInBits();
563 SVal >>= 64-Ty->getPrimitiveSizeInBits();
564 return ConstantSInt::get(Ty, SVal);
565}
566
567
Chris Lattner4534dd592006-02-09 07:38:58 +0000568/// ComputeMaskedBits - Determine which of the bits specified in Mask are
569/// known to be either zero or one and return them in the KnownZero/KnownOne
570/// bitsets. This code only analyzes bits in Mask, in order to short-circuit
571/// processing.
572static void ComputeMaskedBits(Value *V, uint64_t Mask, uint64_t &KnownZero,
573 uint64_t &KnownOne, unsigned Depth = 0) {
Chris Lattner0b3557f2005-09-24 23:43:33 +0000574 // Note, we cannot consider 'undef' to be "IsZero" here. The problem is that
575 // we cannot optimize based on the assumption that it is zero without changing
Chris Lattnerc3ebf402006-02-07 07:27:52 +0000576 // it to be an explicit zero. If we don't change it to zero, other code could
Chris Lattner0b3557f2005-09-24 23:43:33 +0000577 // optimized based on the contradictory assumption that it is non-zero.
578 // Because instcombine aggressively folds operations with undef args anyway,
579 // this won't lose us code quality.
Chris Lattner4534dd592006-02-09 07:38:58 +0000580 if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(V)) {
581 // We know all of the bits for a constant!
Chris Lattner0157e7f2006-02-11 09:31:47 +0000582 KnownOne = CI->getZExtValue() & Mask;
Chris Lattner4534dd592006-02-09 07:38:58 +0000583 KnownZero = ~KnownOne & Mask;
584 return;
585 }
586
587 KnownZero = KnownOne = 0; // Don't know anything.
Chris Lattner92a68652006-02-07 08:05:22 +0000588 if (Depth == 6 || Mask == 0)
Chris Lattner4534dd592006-02-09 07:38:58 +0000589 return; // Limit search depth.
590
591 uint64_t KnownZero2, KnownOne2;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000592 Instruction *I = dyn_cast<Instruction>(V);
593 if (!I) return;
594
Chris Lattnerfb296922006-05-04 17:33:35 +0000595 Mask &= V->getType()->getIntegralTypeMask();
596
Chris Lattner0157e7f2006-02-11 09:31:47 +0000597 switch (I->getOpcode()) {
598 case Instruction::And:
599 // If either the LHS or the RHS are Zero, the result is zero.
600 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
601 Mask &= ~KnownZero;
602 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
603 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
604 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
605
606 // Output known-1 bits are only known if set in both the LHS & RHS.
607 KnownOne &= KnownOne2;
608 // Output known-0 are known to be clear if zero in either the LHS | RHS.
609 KnownZero |= KnownZero2;
610 return;
611 case Instruction::Or:
612 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
613 Mask &= ~KnownOne;
614 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
615 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
616 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
617
618 // Output known-0 bits are only known if clear in both the LHS & RHS.
619 KnownZero &= KnownZero2;
620 // Output known-1 are known to be set if set in either the LHS | RHS.
621 KnownOne |= KnownOne2;
622 return;
623 case Instruction::Xor: {
624 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
625 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
626 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
627 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
628
629 // Output known-0 bits are known if clear or set in both the LHS & RHS.
630 uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
631 // Output known-1 are known to be set if set in only one of the LHS, RHS.
632 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
633 KnownZero = KnownZeroOut;
634 return;
635 }
636 case Instruction::Select:
637 ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
638 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
639 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
640 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
641
642 // Only known if known in both the LHS and RHS.
643 KnownOne &= KnownOne2;
644 KnownZero &= KnownZero2;
645 return;
646 case Instruction::Cast: {
647 const Type *SrcTy = I->getOperand(0)->getType();
648 if (!SrcTy->isIntegral()) return;
649
650 // If this is an integer truncate or noop, just look in the input.
651 if (SrcTy->getPrimitiveSizeInBits() >=
652 I->getType()->getPrimitiveSizeInBits()) {
653 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
Chris Lattner4534dd592006-02-09 07:38:58 +0000654 return;
655 }
Chris Lattner4534dd592006-02-09 07:38:58 +0000656
Chris Lattner0157e7f2006-02-11 09:31:47 +0000657 // Sign or Zero extension. Compute the bits in the result that are not
658 // present in the input.
659 uint64_t NotIn = ~SrcTy->getIntegralTypeMask();
660 uint64_t NewBits = I->getType()->getIntegralTypeMask() & NotIn;
Chris Lattner62010c42005-10-09 06:36:35 +0000661
Chris Lattner0157e7f2006-02-11 09:31:47 +0000662 // Handle zero extension.
663 if (!SrcTy->isSigned()) {
664 Mask &= SrcTy->getIntegralTypeMask();
665 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
666 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
667 // The top bits are known to be zero.
668 KnownZero |= NewBits;
669 } else {
670 // Sign extension.
671 Mask &= SrcTy->getIntegralTypeMask();
672 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
673 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattner92a68652006-02-07 08:05:22 +0000674
Chris Lattner0157e7f2006-02-11 09:31:47 +0000675 // If the sign bit of the input is known set or clear, then we know the
676 // top bits of the result.
677 uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
678 if (KnownZero & InSignBit) { // Input sign bit known zero
Chris Lattner4534dd592006-02-09 07:38:58 +0000679 KnownZero |= NewBits;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000680 KnownOne &= ~NewBits;
681 } else if (KnownOne & InSignBit) { // Input sign bit known set
682 KnownOne |= NewBits;
683 KnownZero &= ~NewBits;
684 } else { // Input sign bit unknown
685 KnownZero &= ~NewBits;
686 KnownOne &= ~NewBits;
687 }
688 }
689 return;
690 }
691 case Instruction::Shl:
692 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
693 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1))) {
694 Mask >>= SA->getValue();
695 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
696 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
697 KnownZero <<= SA->getValue();
698 KnownOne <<= SA->getValue();
699 KnownZero |= (1ULL << SA->getValue())-1; // low bits known zero.
700 return;
701 }
702 break;
703 case Instruction::Shr:
704 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
705 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1))) {
706 // Compute the new bits that are at the top now.
707 uint64_t HighBits = (1ULL << SA->getValue())-1;
708 HighBits <<= I->getType()->getPrimitiveSizeInBits()-SA->getValue();
709
710 if (I->getType()->isUnsigned()) { // Unsigned shift right.
711 Mask <<= SA->getValue();
712 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
713 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
714 KnownZero >>= SA->getValue();
715 KnownOne >>= SA->getValue();
716 KnownZero |= HighBits; // high bits known zero.
Chris Lattner4534dd592006-02-09 07:38:58 +0000717 } else {
Chris Lattner0157e7f2006-02-11 09:31:47 +0000718 Mask <<= SA->getValue();
719 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
720 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
721 KnownZero >>= SA->getValue();
722 KnownOne >>= SA->getValue();
723
724 // Handle the sign bits.
725 uint64_t SignBit = 1ULL << (I->getType()->getPrimitiveSizeInBits()-1);
726 SignBit >>= SA->getValue(); // Adjust to where it is now in the mask.
727
728 if (KnownZero & SignBit) { // New bits are known zero.
729 KnownZero |= HighBits;
730 } else if (KnownOne & SignBit) { // New bits are known one.
731 KnownOne |= HighBits;
Chris Lattner4534dd592006-02-09 07:38:58 +0000732 }
733 }
734 return;
Chris Lattner62010c42005-10-09 06:36:35 +0000735 }
Chris Lattner0157e7f2006-02-11 09:31:47 +0000736 break;
Chris Lattner0b3557f2005-09-24 23:43:33 +0000737 }
Chris Lattner92a68652006-02-07 08:05:22 +0000738}
739
740/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
741/// this predicate to simplify operations downstream. Mask is known to be zero
742/// for bits that V cannot have.
743static bool MaskedValueIsZero(Value *V, uint64_t Mask, unsigned Depth = 0) {
Chris Lattner4534dd592006-02-09 07:38:58 +0000744 uint64_t KnownZero, KnownOne;
745 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
746 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
747 return (KnownZero & Mask) == Mask;
Chris Lattner0b3557f2005-09-24 23:43:33 +0000748}
749
Chris Lattner0157e7f2006-02-11 09:31:47 +0000750/// ShrinkDemandedConstant - Check to see if the specified operand of the
751/// specified instruction is a constant integer. If so, check to see if there
752/// are any bits set in the constant that are not demanded. If so, shrink the
753/// constant and return true.
754static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
755 uint64_t Demanded) {
756 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
757 if (!OpC) return false;
758
759 // If there are no bits set that aren't demanded, nothing to do.
760 if ((~Demanded & OpC->getZExtValue()) == 0)
761 return false;
762
763 // This is producing any bits that are not needed, shrink the RHS.
764 uint64_t Val = Demanded & OpC->getZExtValue();
765 I->setOperand(OpNo, GetConstantInType(OpC->getType(), Val));
766 return true;
767}
768
Chris Lattneree0f2802006-02-12 02:07:56 +0000769// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
770// set of known zero and one bits, compute the maximum and minimum values that
771// could have the specified known zero and known one bits, returning them in
772// min/max.
773static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
774 uint64_t KnownZero,
775 uint64_t KnownOne,
776 int64_t &Min, int64_t &Max) {
777 uint64_t TypeBits = Ty->getIntegralTypeMask();
778 uint64_t UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
779
780 uint64_t SignBit = 1ULL << (Ty->getPrimitiveSizeInBits()-1);
781
782 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
783 // bit if it is unknown.
784 Min = KnownOne;
785 Max = KnownOne|UnknownBits;
786
787 if (SignBit & UnknownBits) { // Sign bit is unknown
788 Min |= SignBit;
789 Max &= ~SignBit;
790 }
791
792 // Sign extend the min/max values.
793 int ShAmt = 64-Ty->getPrimitiveSizeInBits();
794 Min = (Min << ShAmt) >> ShAmt;
795 Max = (Max << ShAmt) >> ShAmt;
796}
797
798// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
799// a set of known zero and one bits, compute the maximum and minimum values that
800// could have the specified known zero and known one bits, returning them in
801// min/max.
802static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
803 uint64_t KnownZero,
804 uint64_t KnownOne,
805 uint64_t &Min,
806 uint64_t &Max) {
807 uint64_t TypeBits = Ty->getIntegralTypeMask();
808 uint64_t UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
809
810 // The minimum value is when the unknown bits are all zeros.
811 Min = KnownOne;
812 // The maximum value is when the unknown bits are all ones.
813 Max = KnownOne|UnknownBits;
814}
Chris Lattner0157e7f2006-02-11 09:31:47 +0000815
816
817/// SimplifyDemandedBits - Look at V. At this point, we know that only the
818/// DemandedMask bits of the result of V are ever used downstream. If we can
819/// use this information to simplify V, do so and return true. Otherwise,
820/// analyze the expression and return a mask of KnownOne and KnownZero bits for
821/// the expression (used to simplify the caller). The KnownZero/One bits may
822/// only be accurate for those bits in the DemandedMask.
823bool InstCombiner::SimplifyDemandedBits(Value *V, uint64_t DemandedMask,
824 uint64_t &KnownZero, uint64_t &KnownOne,
Chris Lattner2590e512006-02-07 06:56:34 +0000825 unsigned Depth) {
Chris Lattner0157e7f2006-02-11 09:31:47 +0000826 if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(V)) {
827 // We know all of the bits for a constant!
828 KnownOne = CI->getZExtValue() & DemandedMask;
829 KnownZero = ~KnownOne & DemandedMask;
830 return false;
831 }
832
833 KnownZero = KnownOne = 0;
Chris Lattner2590e512006-02-07 06:56:34 +0000834 if (!V->hasOneUse()) { // Other users may use these bits.
Chris Lattner0157e7f2006-02-11 09:31:47 +0000835 if (Depth != 0) { // Not at the root.
836 // Just compute the KnownZero/KnownOne bits to simplify things downstream.
837 ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
Chris Lattner2590e512006-02-07 06:56:34 +0000838 return false;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000839 }
Chris Lattner2590e512006-02-07 06:56:34 +0000840 // If this is the root being simplified, allow it to have multiple uses,
Chris Lattner0157e7f2006-02-11 09:31:47 +0000841 // just set the DemandedMask to all bits.
842 DemandedMask = V->getType()->getIntegralTypeMask();
843 } else if (DemandedMask == 0) { // Not demanding any bits from V.
Chris Lattner92a68652006-02-07 08:05:22 +0000844 if (V != UndefValue::get(V->getType()))
845 return UpdateValueUsesWith(V, UndefValue::get(V->getType()));
846 return false;
Chris Lattner2590e512006-02-07 06:56:34 +0000847 } else if (Depth == 6) { // Limit search depth.
848 return false;
849 }
850
851 Instruction *I = dyn_cast<Instruction>(V);
852 if (!I) return false; // Only analyze instructions.
853
Chris Lattnerfb296922006-05-04 17:33:35 +0000854 DemandedMask &= V->getType()->getIntegralTypeMask();
855
Chris Lattner0157e7f2006-02-11 09:31:47 +0000856 uint64_t KnownZero2, KnownOne2;
Chris Lattner2590e512006-02-07 06:56:34 +0000857 switch (I->getOpcode()) {
858 default: break;
859 case Instruction::And:
Chris Lattner0157e7f2006-02-11 09:31:47 +0000860 // If either the LHS or the RHS are Zero, the result is zero.
861 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
862 KnownZero, KnownOne, Depth+1))
863 return true;
864 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
865
866 // If something is known zero on the RHS, the bits aren't demanded on the
867 // LHS.
868 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownZero,
869 KnownZero2, KnownOne2, Depth+1))
870 return true;
871 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
872
873 // If all of the demanded bits are known one on one side, return the other.
874 // These bits cannot contribute to the result of the 'and'.
875 if ((DemandedMask & ~KnownZero2 & KnownOne) == (DemandedMask & ~KnownZero2))
876 return UpdateValueUsesWith(I, I->getOperand(0));
877 if ((DemandedMask & ~KnownZero & KnownOne2) == (DemandedMask & ~KnownZero))
878 return UpdateValueUsesWith(I, I->getOperand(1));
Chris Lattner5b2edb12006-02-12 08:02:11 +0000879
880 // If all of the demanded bits in the inputs are known zeros, return zero.
881 if ((DemandedMask & (KnownZero|KnownZero2)) == DemandedMask)
882 return UpdateValueUsesWith(I, Constant::getNullValue(I->getType()));
883
Chris Lattner0157e7f2006-02-11 09:31:47 +0000884 // If the RHS is a constant, see if we can simplify it.
Chris Lattner5b2edb12006-02-12 08:02:11 +0000885 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~KnownZero2))
Chris Lattner0157e7f2006-02-11 09:31:47 +0000886 return UpdateValueUsesWith(I, I);
887
888 // Output known-1 bits are only known if set in both the LHS & RHS.
889 KnownOne &= KnownOne2;
890 // Output known-0 are known to be clear if zero in either the LHS | RHS.
891 KnownZero |= KnownZero2;
892 break;
893 case Instruction::Or:
894 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
895 KnownZero, KnownOne, Depth+1))
896 return true;
897 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
898 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownOne,
899 KnownZero2, KnownOne2, Depth+1))
900 return true;
901 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
902
903 // If all of the demanded bits are known zero on one side, return the other.
904 // These bits cannot contribute to the result of the 'or'.
Jeff Cohen0add83e2006-02-18 03:20:33 +0000905 if ((DemandedMask & ~KnownOne2 & KnownZero) == (DemandedMask & ~KnownOne2))
Chris Lattner0157e7f2006-02-11 09:31:47 +0000906 return UpdateValueUsesWith(I, I->getOperand(0));
Jeff Cohen0add83e2006-02-18 03:20:33 +0000907 if ((DemandedMask & ~KnownOne & KnownZero2) == (DemandedMask & ~KnownOne))
Chris Lattner0157e7f2006-02-11 09:31:47 +0000908 return UpdateValueUsesWith(I, I->getOperand(1));
Chris Lattner5b2edb12006-02-12 08:02:11 +0000909
910 // If all of the potentially set bits on one side are known to be set on
911 // the other side, just use the 'other' side.
912 if ((DemandedMask & (~KnownZero) & KnownOne2) ==
913 (DemandedMask & (~KnownZero)))
914 return UpdateValueUsesWith(I, I->getOperand(0));
Nate Begeman8a77efe2006-02-16 21:11:51 +0000915 if ((DemandedMask & (~KnownZero2) & KnownOne) ==
916 (DemandedMask & (~KnownZero2)))
917 return UpdateValueUsesWith(I, I->getOperand(1));
Chris Lattner0157e7f2006-02-11 09:31:47 +0000918
919 // If the RHS is a constant, see if we can simplify it.
920 if (ShrinkDemandedConstant(I, 1, DemandedMask))
921 return UpdateValueUsesWith(I, I);
922
923 // Output known-0 bits are only known if clear in both the LHS & RHS.
924 KnownZero &= KnownZero2;
925 // Output known-1 are known to be set if set in either the LHS | RHS.
926 KnownOne |= KnownOne2;
927 break;
928 case Instruction::Xor: {
929 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
930 KnownZero, KnownOne, Depth+1))
931 return true;
932 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
933 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
934 KnownZero2, KnownOne2, Depth+1))
935 return true;
936 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
937
938 // If all of the demanded bits are known zero on one side, return the other.
939 // These bits cannot contribute to the result of the 'xor'.
940 if ((DemandedMask & KnownZero) == DemandedMask)
941 return UpdateValueUsesWith(I, I->getOperand(0));
942 if ((DemandedMask & KnownZero2) == DemandedMask)
943 return UpdateValueUsesWith(I, I->getOperand(1));
944
945 // Output known-0 bits are known if clear or set in both the LHS & RHS.
946 uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
947 // Output known-1 are known to be set if set in only one of the LHS, RHS.
948 uint64_t KnownOneOut = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
949
950 // If all of the unknown bits are known to be zero on one side or the other
951 // (but not both) turn this into an *inclusive* or.
Chris Lattner5b2edb12006-02-12 08:02:11 +0000952 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattner0157e7f2006-02-11 09:31:47 +0000953 if (uint64_t UnknownBits = DemandedMask & ~(KnownZeroOut|KnownOneOut)) {
954 if ((UnknownBits & (KnownZero|KnownZero2)) == UnknownBits) {
955 Instruction *Or =
956 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
957 I->getName());
958 InsertNewInstBefore(Or, *I);
959 return UpdateValueUsesWith(I, Or);
Chris Lattner2590e512006-02-07 06:56:34 +0000960 }
961 }
Chris Lattner0157e7f2006-02-11 09:31:47 +0000962
Chris Lattner5b2edb12006-02-12 08:02:11 +0000963 // If all of the demanded bits on one side are known, and all of the set
964 // bits on that side are also known to be set on the other side, turn this
965 // into an AND, as we know the bits will be cleared.
966 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
967 if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask) { // all known
968 if ((KnownOne & KnownOne2) == KnownOne) {
969 Constant *AndC = GetConstantInType(I->getType(),
970 ~KnownOne & DemandedMask);
971 Instruction *And =
972 BinaryOperator::createAnd(I->getOperand(0), AndC, "tmp");
973 InsertNewInstBefore(And, *I);
974 return UpdateValueUsesWith(I, And);
975 }
976 }
977
Chris Lattner0157e7f2006-02-11 09:31:47 +0000978 // If the RHS is a constant, see if we can simplify it.
979 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
980 if (ShrinkDemandedConstant(I, 1, DemandedMask))
981 return UpdateValueUsesWith(I, I);
982
983 KnownZero = KnownZeroOut;
984 KnownOne = KnownOneOut;
985 break;
986 }
987 case Instruction::Select:
988 if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
989 KnownZero, KnownOne, Depth+1))
990 return true;
991 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
992 KnownZero2, KnownOne2, Depth+1))
993 return true;
994 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
995 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
996
997 // If the operands are constants, see if we can simplify them.
998 if (ShrinkDemandedConstant(I, 1, DemandedMask))
999 return UpdateValueUsesWith(I, I);
1000 if (ShrinkDemandedConstant(I, 2, DemandedMask))
1001 return UpdateValueUsesWith(I, I);
1002
1003 // Only known if known in both the LHS and RHS.
1004 KnownOne &= KnownOne2;
1005 KnownZero &= KnownZero2;
1006 break;
Chris Lattner2590e512006-02-07 06:56:34 +00001007 case Instruction::Cast: {
1008 const Type *SrcTy = I->getOperand(0)->getType();
Chris Lattner0157e7f2006-02-11 09:31:47 +00001009 if (!SrcTy->isIntegral()) return false;
Chris Lattner2590e512006-02-07 06:56:34 +00001010
Chris Lattner0157e7f2006-02-11 09:31:47 +00001011 // If this is an integer truncate or noop, just look in the input.
1012 if (SrcTy->getPrimitiveSizeInBits() >=
1013 I->getType()->getPrimitiveSizeInBits()) {
Chris Lattner850465d2006-09-16 03:14:10 +00001014 // Cast to bool is a comparison against 0, which demands all bits. We
1015 // can't propagate anything useful up.
1016 if (I->getType() == Type::BoolTy)
1017 break;
1018
Chris Lattner0157e7f2006-02-11 09:31:47 +00001019 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1020 KnownZero, KnownOne, Depth+1))
1021 return true;
1022 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1023 break;
1024 }
1025
1026 // Sign or Zero extension. Compute the bits in the result that are not
1027 // present in the input.
1028 uint64_t NotIn = ~SrcTy->getIntegralTypeMask();
1029 uint64_t NewBits = I->getType()->getIntegralTypeMask() & NotIn;
1030
1031 // Handle zero extension.
1032 if (!SrcTy->isSigned()) {
1033 DemandedMask &= SrcTy->getIntegralTypeMask();
1034 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1035 KnownZero, KnownOne, Depth+1))
1036 return true;
1037 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1038 // The top bits are known to be zero.
1039 KnownZero |= NewBits;
1040 } else {
1041 // Sign extension.
Chris Lattner7d852282006-02-13 22:41:07 +00001042 uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
1043 int64_t InputDemandedBits = DemandedMask & SrcTy->getIntegralTypeMask();
1044
1045 // If any of the sign extended bits are demanded, we know that the sign
1046 // bit is demanded.
1047 if (NewBits & DemandedMask)
1048 InputDemandedBits |= InSignBit;
1049
1050 if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
Chris Lattner0157e7f2006-02-11 09:31:47 +00001051 KnownZero, KnownOne, Depth+1))
1052 return true;
1053 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1054
1055 // If the sign bit of the input is known set or clear, then we know the
1056 // top bits of the result.
Chris Lattner2590e512006-02-07 06:56:34 +00001057
Chris Lattner0157e7f2006-02-11 09:31:47 +00001058 // If the input sign bit is known zero, or if the NewBits are not demanded
1059 // convert this into a zero extension.
1060 if ((KnownZero & InSignBit) || (NewBits & ~DemandedMask) == NewBits) {
Chris Lattner2590e512006-02-07 06:56:34 +00001061 // Convert to unsigned first.
Chris Lattner44314822006-02-07 19:07:40 +00001062 Instruction *NewVal;
Chris Lattner2590e512006-02-07 06:56:34 +00001063 NewVal = new CastInst(I->getOperand(0), SrcTy->getUnsignedVersion(),
Chris Lattner44314822006-02-07 19:07:40 +00001064 I->getOperand(0)->getName());
1065 InsertNewInstBefore(NewVal, *I);
Chris Lattner0157e7f2006-02-11 09:31:47 +00001066 // Then cast that to the destination type.
Chris Lattner44314822006-02-07 19:07:40 +00001067 NewVal = new CastInst(NewVal, I->getType(), I->getName());
1068 InsertNewInstBefore(NewVal, *I);
Chris Lattner2590e512006-02-07 06:56:34 +00001069 return UpdateValueUsesWith(I, NewVal);
Chris Lattner0157e7f2006-02-11 09:31:47 +00001070 } else if (KnownOne & InSignBit) { // Input sign bit known set
1071 KnownOne |= NewBits;
1072 KnownZero &= ~NewBits;
1073 } else { // Input sign bit unknown
1074 KnownZero &= ~NewBits;
1075 KnownOne &= ~NewBits;
Chris Lattner2590e512006-02-07 06:56:34 +00001076 }
Chris Lattner2590e512006-02-07 06:56:34 +00001077 }
Chris Lattner0157e7f2006-02-11 09:31:47 +00001078 break;
Chris Lattner2590e512006-02-07 06:56:34 +00001079 }
Chris Lattner2590e512006-02-07 06:56:34 +00001080 case Instruction::Shl:
Chris Lattner0157e7f2006-02-11 09:31:47 +00001081 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1))) {
1082 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask >> SA->getValue(),
1083 KnownZero, KnownOne, Depth+1))
1084 return true;
1085 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1086 KnownZero <<= SA->getValue();
1087 KnownOne <<= SA->getValue();
1088 KnownZero |= (1ULL << SA->getValue())-1; // low bits known zero.
1089 }
Chris Lattner2590e512006-02-07 06:56:34 +00001090 break;
1091 case Instruction::Shr:
Chris Lattner420c4bc2006-09-18 04:31:40 +00001092 // If this is an arithmetic shift right and only the low-bit is set, we can
1093 // always convert this into a logical shr, even if the shift amount is
1094 // variable. The low bit of the shift cannot be an input sign bit unless
1095 // the shift amount is >= the size of the datatype, which is undefined.
1096 if (DemandedMask == 1 && I->getType()->isSigned()) {
1097 // Convert the input to unsigned.
1098 Instruction *NewVal = new CastInst(I->getOperand(0),
1099 I->getType()->getUnsignedVersion(),
1100 I->getOperand(0)->getName());
1101 InsertNewInstBefore(NewVal, *I);
1102 // Perform the unsigned shift right.
1103 NewVal = new ShiftInst(Instruction::Shr, NewVal, I->getOperand(1),
1104 I->getName());
1105 InsertNewInstBefore(NewVal, *I);
1106 // Then cast that to the destination type.
1107 NewVal = new CastInst(NewVal, I->getType(), I->getName());
1108 InsertNewInstBefore(NewVal, *I);
1109 return UpdateValueUsesWith(I, NewVal);
1110 }
1111
Chris Lattner0157e7f2006-02-11 09:31:47 +00001112 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1))) {
1113 unsigned ShAmt = SA->getValue();
1114
1115 // Compute the new bits that are at the top now.
1116 uint64_t HighBits = (1ULL << ShAmt)-1;
1117 HighBits <<= I->getType()->getPrimitiveSizeInBits() - ShAmt;
Chris Lattner68e74752006-02-13 06:09:08 +00001118 uint64_t TypeMask = I->getType()->getIntegralTypeMask();
Chris Lattner0157e7f2006-02-11 09:31:47 +00001119 if (I->getType()->isUnsigned()) { // Unsigned shift right.
Chris Lattner68e74752006-02-13 06:09:08 +00001120 if (SimplifyDemandedBits(I->getOperand(0),
1121 (DemandedMask << ShAmt) & TypeMask,
Chris Lattner0157e7f2006-02-11 09:31:47 +00001122 KnownZero, KnownOne, Depth+1))
1123 return true;
1124 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattner68e74752006-02-13 06:09:08 +00001125 KnownZero &= TypeMask;
1126 KnownOne &= TypeMask;
Chris Lattner0157e7f2006-02-11 09:31:47 +00001127 KnownZero >>= ShAmt;
1128 KnownOne >>= ShAmt;
1129 KnownZero |= HighBits; // high bits known zero.
1130 } else { // Signed shift right.
Chris Lattner68e74752006-02-13 06:09:08 +00001131 if (SimplifyDemandedBits(I->getOperand(0),
1132 (DemandedMask << ShAmt) & TypeMask,
Chris Lattner0157e7f2006-02-11 09:31:47 +00001133 KnownZero, KnownOne, Depth+1))
1134 return true;
1135 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattner68e74752006-02-13 06:09:08 +00001136 KnownZero &= TypeMask;
1137 KnownOne &= TypeMask;
Chris Lattner0157e7f2006-02-11 09:31:47 +00001138 KnownZero >>= SA->getValue();
1139 KnownOne >>= SA->getValue();
1140
1141 // Handle the sign bits.
1142 uint64_t SignBit = 1ULL << (I->getType()->getPrimitiveSizeInBits()-1);
1143 SignBit >>= SA->getValue(); // Adjust to where it is now in the mask.
1144
1145 // If the input sign bit is known to be zero, or if none of the top bits
1146 // are demanded, turn this into an unsigned shift right.
1147 if ((KnownZero & SignBit) || (HighBits & ~DemandedMask) == HighBits) {
1148 // Convert the input to unsigned.
1149 Instruction *NewVal;
1150 NewVal = new CastInst(I->getOperand(0),
1151 I->getType()->getUnsignedVersion(),
1152 I->getOperand(0)->getName());
1153 InsertNewInstBefore(NewVal, *I);
1154 // Perform the unsigned shift right.
1155 NewVal = new ShiftInst(Instruction::Shr, NewVal, SA, I->getName());
1156 InsertNewInstBefore(NewVal, *I);
1157 // Then cast that to the destination type.
1158 NewVal = new CastInst(NewVal, I->getType(), I->getName());
1159 InsertNewInstBefore(NewVal, *I);
1160 return UpdateValueUsesWith(I, NewVal);
1161 } else if (KnownOne & SignBit) { // New bits are known one.
1162 KnownOne |= HighBits;
1163 }
Chris Lattner2590e512006-02-07 06:56:34 +00001164 }
Chris Lattner0157e7f2006-02-11 09:31:47 +00001165 }
Chris Lattner2590e512006-02-07 06:56:34 +00001166 break;
1167 }
Chris Lattner0157e7f2006-02-11 09:31:47 +00001168
1169 // If the client is only demanding bits that we know, return the known
1170 // constant.
1171 if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask)
1172 return UpdateValueUsesWith(I, GetConstantInType(I->getType(), KnownOne));
Chris Lattner2590e512006-02-07 06:56:34 +00001173 return false;
1174}
1175
Chris Lattner623826c2004-09-28 21:48:02 +00001176// isTrueWhenEqual - Return true if the specified setcondinst instruction is
1177// true when both operands are equal...
1178//
1179static bool isTrueWhenEqual(Instruction &I) {
1180 return I.getOpcode() == Instruction::SetEQ ||
1181 I.getOpcode() == Instruction::SetGE ||
1182 I.getOpcode() == Instruction::SetLE;
1183}
Chris Lattnerb8b97502003-08-13 19:01:45 +00001184
1185/// AssociativeOpt - Perform an optimization on an associative operator. This
1186/// function is designed to check a chain of associative operators for a
1187/// potential to apply a certain optimization. Since the optimization may be
1188/// applicable if the expression was reassociated, this checks the chain, then
1189/// reassociates the expression as necessary to expose the optimization
1190/// opportunity. This makes use of a special Functor, which must define
1191/// 'shouldApply' and 'apply' methods.
1192///
1193template<typename Functor>
1194Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1195 unsigned Opcode = Root.getOpcode();
1196 Value *LHS = Root.getOperand(0);
1197
1198 // Quick check, see if the immediate LHS matches...
1199 if (F.shouldApply(LHS))
1200 return F.apply(Root);
1201
1202 // Otherwise, if the LHS is not of the same opcode as the root, return.
1203 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001204 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattnerb8b97502003-08-13 19:01:45 +00001205 // Should we apply this transform to the RHS?
1206 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1207
1208 // If not to the RHS, check to see if we should apply to the LHS...
1209 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1210 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1211 ShouldApply = true;
1212 }
1213
1214 // If the functor wants to apply the optimization to the RHS of LHSI,
1215 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1216 if (ShouldApply) {
1217 BasicBlock *BB = Root.getParent();
Misha Brukmanb1c93172005-04-21 23:48:37 +00001218
Chris Lattnerb8b97502003-08-13 19:01:45 +00001219 // Now all of the instructions are in the current basic block, go ahead
1220 // and perform the reassociation.
1221 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1222
1223 // First move the selected RHS to the LHS of the root...
1224 Root.setOperand(0, LHSI->getOperand(1));
1225
1226 // Make what used to be the LHS of the root be the user of the root...
1227 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner284d3b02004-04-16 18:08:07 +00001228 if (&Root == TmpLHSI) {
Chris Lattner8953b902004-04-05 02:10:19 +00001229 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1230 return 0;
1231 }
Chris Lattner284d3b02004-04-16 18:08:07 +00001232 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattnerb8b97502003-08-13 19:01:45 +00001233 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner284d3b02004-04-16 18:08:07 +00001234 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
1235 BasicBlock::iterator ARI = &Root; ++ARI;
1236 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
1237 ARI = Root;
Chris Lattnerb8b97502003-08-13 19:01:45 +00001238
1239 // Now propagate the ExtraOperand down the chain of instructions until we
1240 // get to LHSI.
1241 while (TmpLHSI != LHSI) {
1242 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner284d3b02004-04-16 18:08:07 +00001243 // Move the instruction to immediately before the chain we are
1244 // constructing to avoid breaking dominance properties.
1245 NextLHSI->getParent()->getInstList().remove(NextLHSI);
1246 BB->getInstList().insert(ARI, NextLHSI);
1247 ARI = NextLHSI;
1248
Chris Lattnerb8b97502003-08-13 19:01:45 +00001249 Value *NextOp = NextLHSI->getOperand(1);
1250 NextLHSI->setOperand(1, ExtraOperand);
1251 TmpLHSI = NextLHSI;
1252 ExtraOperand = NextOp;
1253 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001254
Chris Lattnerb8b97502003-08-13 19:01:45 +00001255 // Now that the instructions are reassociated, have the functor perform
1256 // the transformation...
1257 return F.apply(Root);
1258 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001259
Chris Lattnerb8b97502003-08-13 19:01:45 +00001260 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1261 }
1262 return 0;
1263}
1264
1265
1266// AddRHS - Implements: X + X --> X << 1
1267struct AddRHS {
1268 Value *RHS;
1269 AddRHS(Value *rhs) : RHS(rhs) {}
1270 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1271 Instruction *apply(BinaryOperator &Add) const {
1272 return new ShiftInst(Instruction::Shl, Add.getOperand(0),
1273 ConstantInt::get(Type::UByteTy, 1));
1274 }
1275};
1276
1277// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1278// iff C1&C2 == 0
1279struct AddMaskingAnd {
1280 Constant *C2;
1281 AddMaskingAnd(Constant *c) : C2(c) {}
1282 bool shouldApply(Value *LHS) const {
Chris Lattnerd4252a72004-07-30 07:50:03 +00001283 ConstantInt *C1;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001284 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Chris Lattnerd4252a72004-07-30 07:50:03 +00001285 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattnerb8b97502003-08-13 19:01:45 +00001286 }
1287 Instruction *apply(BinaryOperator &Add) const {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001288 return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattnerb8b97502003-08-13 19:01:45 +00001289 }
1290};
1291
Chris Lattner86102b82005-01-01 16:22:27 +00001292static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner183b3362004-04-09 19:05:30 +00001293 InstCombiner *IC) {
Chris Lattner86102b82005-01-01 16:22:27 +00001294 if (isa<CastInst>(I)) {
1295 if (Constant *SOC = dyn_cast<Constant>(SO))
1296 return ConstantExpr::getCast(SOC, I.getType());
Misha Brukmanb1c93172005-04-21 23:48:37 +00001297
Chris Lattner86102b82005-01-01 16:22:27 +00001298 return IC->InsertNewInstBefore(new CastInst(SO, I.getType(),
1299 SO->getName() + ".cast"), I);
1300 }
1301
Chris Lattner183b3362004-04-09 19:05:30 +00001302 // Figure out if the constant is the left or the right argument.
Chris Lattner86102b82005-01-01 16:22:27 +00001303 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1304 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattnerb8b97502003-08-13 19:01:45 +00001305
Chris Lattner183b3362004-04-09 19:05:30 +00001306 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1307 if (ConstIsRHS)
Chris Lattner86102b82005-01-01 16:22:27 +00001308 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1309 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner183b3362004-04-09 19:05:30 +00001310 }
1311
1312 Value *Op0 = SO, *Op1 = ConstOperand;
1313 if (!ConstIsRHS)
1314 std::swap(Op0, Op1);
1315 Instruction *New;
Chris Lattner86102b82005-01-01 16:22:27 +00001316 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1317 New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
1318 else if (ShiftInst *SI = dyn_cast<ShiftInst>(&I))
1319 New = new ShiftInst(SI->getOpcode(), Op0, Op1, SO->getName()+".sh");
Chris Lattnerf9d96652004-04-10 19:15:56 +00001320 else {
Chris Lattner183b3362004-04-09 19:05:30 +00001321 assert(0 && "Unknown binary instruction type!");
Chris Lattnerf9d96652004-04-10 19:15:56 +00001322 abort();
1323 }
Chris Lattner86102b82005-01-01 16:22:27 +00001324 return IC->InsertNewInstBefore(New, I);
1325}
1326
1327// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1328// constant as the other operand, try to fold the binary operator into the
1329// select arguments. This also works for Cast instructions, which obviously do
1330// not have a second operand.
1331static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1332 InstCombiner *IC) {
1333 // Don't modify shared select instructions
1334 if (!SI->hasOneUse()) return 0;
1335 Value *TV = SI->getOperand(1);
1336 Value *FV = SI->getOperand(2);
1337
1338 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner374e6592005-04-21 05:43:13 +00001339 // Bool selects with constant operands can be folded to logical ops.
1340 if (SI->getType() == Type::BoolTy) return 0;
1341
Chris Lattner86102b82005-01-01 16:22:27 +00001342 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1343 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1344
1345 return new SelectInst(SI->getCondition(), SelectTrueVal,
1346 SelectFalseVal);
1347 }
1348 return 0;
Chris Lattner183b3362004-04-09 19:05:30 +00001349}
1350
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001351
1352/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1353/// node as operand #0, see if we can fold the instruction into the PHI (which
1354/// is only possible if all operands to the PHI are constants).
1355Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1356 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattner7515cab2004-11-14 19:13:23 +00001357 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner04689872006-09-09 22:02:56 +00001358 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001359
Chris Lattner04689872006-09-09 22:02:56 +00001360 // Check to see if all of the operands of the PHI are constants. If there is
1361 // one non-constant value, remember the BB it is. If there is more than one
1362 // bail out.
1363 BasicBlock *NonConstBB = 0;
1364 for (unsigned i = 0; i != NumPHIValues; ++i)
1365 if (!isa<Constant>(PN->getIncomingValue(i))) {
1366 if (NonConstBB) return 0; // More than one non-const value.
1367 NonConstBB = PN->getIncomingBlock(i);
1368
1369 // If the incoming non-constant value is in I's block, we have an infinite
1370 // loop.
1371 if (NonConstBB == I.getParent())
1372 return 0;
1373 }
1374
1375 // If there is exactly one non-constant value, we can insert a copy of the
1376 // operation in that block. However, if this is a critical edge, we would be
1377 // inserting the computation one some other paths (e.g. inside a loop). Only
1378 // do this if the pred block is unconditionally branching into the phi block.
1379 if (NonConstBB) {
1380 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1381 if (!BI || !BI->isUnconditional()) return 0;
1382 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001383
1384 // Okay, we can do the transformation: create the new PHI node.
1385 PHINode *NewPN = new PHINode(I.getType(), I.getName());
1386 I.setName("");
Chris Lattnerd8e20182005-01-29 00:39:08 +00001387 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001388 InsertNewInstBefore(NewPN, *PN);
1389
1390 // Next, add all of the operands to the PHI.
1391 if (I.getNumOperands() == 2) {
1392 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattner7515cab2004-11-14 19:13:23 +00001393 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner04689872006-09-09 22:02:56 +00001394 Value *InV;
1395 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1396 InV = ConstantExpr::get(I.getOpcode(), InC, C);
1397 } else {
1398 assert(PN->getIncomingBlock(i) == NonConstBB);
1399 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1400 InV = BinaryOperator::create(BO->getOpcode(),
1401 PN->getIncomingValue(i), C, "phitmp",
1402 NonConstBB->getTerminator());
1403 else if (ShiftInst *SI = dyn_cast<ShiftInst>(&I))
1404 InV = new ShiftInst(SI->getOpcode(),
1405 PN->getIncomingValue(i), C, "phitmp",
1406 NonConstBB->getTerminator());
1407 else
1408 assert(0 && "Unknown binop!");
1409
1410 WorkList.push_back(cast<Instruction>(InV));
1411 }
1412 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001413 }
1414 } else {
1415 assert(isa<CastInst>(I) && "Unary op should be a cast!");
1416 const Type *RetTy = I.getType();
Chris Lattner7515cab2004-11-14 19:13:23 +00001417 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner04689872006-09-09 22:02:56 +00001418 Value *InV;
1419 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1420 InV = ConstantExpr::getCast(InC, RetTy);
1421 } else {
1422 assert(PN->getIncomingBlock(i) == NonConstBB);
1423 InV = new CastInst(PN->getIncomingValue(i), I.getType(), "phitmp",
1424 NonConstBB->getTerminator());
1425 WorkList.push_back(cast<Instruction>(InV));
1426 }
1427 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001428 }
1429 }
1430 return ReplaceInstUsesWith(I, NewPN);
1431}
1432
Chris Lattner113f4f42002-06-25 16:13:24 +00001433Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001434 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00001435 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattner9fa53de2002-05-06 16:49:18 +00001436
Chris Lattnercf4a9962004-04-10 22:01:55 +00001437 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattner81a7a232004-10-16 18:11:37 +00001438 // X + undef -> undef
1439 if (isa<UndefValue>(RHS))
1440 return ReplaceInstUsesWith(I, RHS);
1441
Chris Lattnercf4a9962004-04-10 22:01:55 +00001442 // X + 0 --> X
Chris Lattner7fde91e2005-10-17 17:56:38 +00001443 if (!I.getType()->isFloatingPoint()) { // NOTE: -0 + +0 = +0.
1444 if (RHSC->isNullValue())
1445 return ReplaceInstUsesWith(I, LHS);
Chris Lattnerda1b1522005-10-17 20:18:38 +00001446 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
1447 if (CFP->isExactlyValue(-0.0))
1448 return ReplaceInstUsesWith(I, LHS);
Chris Lattner7fde91e2005-10-17 17:56:38 +00001449 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001450
Chris Lattnercf4a9962004-04-10 22:01:55 +00001451 // X + (signbit) --> X ^ signbit
1452 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattner92a68652006-02-07 08:05:22 +00001453 uint64_t Val = CI->getZExtValue();
Chris Lattner77defba2006-02-07 07:00:41 +00001454 if (Val == (1ULL << (CI->getType()->getPrimitiveSizeInBits()-1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001455 return BinaryOperator::createXor(LHS, RHS);
Chris Lattnercf4a9962004-04-10 22:01:55 +00001456 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001457
1458 if (isa<PHINode>(LHS))
1459 if (Instruction *NV = FoldOpIntoPhi(I))
1460 return NV;
Chris Lattner0b3557f2005-09-24 23:43:33 +00001461
Chris Lattner330628a2006-01-06 17:59:59 +00001462 ConstantInt *XorRHS = 0;
1463 Value *XorLHS = 0;
Chris Lattner0b3557f2005-09-24 23:43:33 +00001464 if (match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
1465 unsigned TySizeBits = I.getType()->getPrimitiveSizeInBits();
1466 int64_t RHSSExt = cast<ConstantInt>(RHSC)->getSExtValue();
1467 uint64_t RHSZExt = cast<ConstantInt>(RHSC)->getZExtValue();
1468
1469 uint64_t C0080Val = 1ULL << 31;
1470 int64_t CFF80Val = -C0080Val;
1471 unsigned Size = 32;
1472 do {
1473 if (TySizeBits > Size) {
1474 bool Found = false;
1475 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
1476 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
1477 if (RHSSExt == CFF80Val) {
1478 if (XorRHS->getZExtValue() == C0080Val)
1479 Found = true;
1480 } else if (RHSZExt == C0080Val) {
1481 if (XorRHS->getSExtValue() == CFF80Val)
1482 Found = true;
1483 }
1484 if (Found) {
1485 // This is a sign extend if the top bits are known zero.
Chris Lattner4534dd592006-02-09 07:38:58 +00001486 uint64_t Mask = ~0ULL;
Chris Lattnerc3ebf402006-02-07 07:27:52 +00001487 Mask <<= 64-(TySizeBits-Size);
Chris Lattner4534dd592006-02-09 07:38:58 +00001488 Mask &= XorLHS->getType()->getIntegralTypeMask();
Chris Lattnerc3ebf402006-02-07 07:27:52 +00001489 if (!MaskedValueIsZero(XorLHS, Mask))
Chris Lattner0b3557f2005-09-24 23:43:33 +00001490 Size = 0; // Not a sign ext, but can't be any others either.
1491 goto FoundSExt;
1492 }
1493 }
1494 Size >>= 1;
1495 C0080Val >>= Size;
1496 CFF80Val >>= Size;
1497 } while (Size >= 8);
1498
1499FoundSExt:
1500 const Type *MiddleType = 0;
1501 switch (Size) {
1502 default: break;
1503 case 32: MiddleType = Type::IntTy; break;
1504 case 16: MiddleType = Type::ShortTy; break;
1505 case 8: MiddleType = Type::SByteTy; break;
1506 }
1507 if (MiddleType) {
1508 Instruction *NewTrunc = new CastInst(XorLHS, MiddleType, "sext");
1509 InsertNewInstBefore(NewTrunc, I);
1510 return new CastInst(NewTrunc, I.getType());
1511 }
1512 }
Chris Lattnercf4a9962004-04-10 22:01:55 +00001513 }
Chris Lattner9fa53de2002-05-06 16:49:18 +00001514
Chris Lattnerb8b97502003-08-13 19:01:45 +00001515 // X + X --> X << 1
Robert Bocchino7b5b86c2004-07-27 21:02:21 +00001516 if (I.getType()->isInteger()) {
Chris Lattnerb8b97502003-08-13 19:01:45 +00001517 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Chris Lattner47060462005-04-07 17:14:51 +00001518
1519 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
1520 if (RHSI->getOpcode() == Instruction::Sub)
1521 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
1522 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
1523 }
1524 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
1525 if (LHSI->getOpcode() == Instruction::Sub)
1526 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
1527 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
1528 }
Robert Bocchino7b5b86c2004-07-27 21:02:21 +00001529 }
Chris Lattnerede3fe02003-08-13 04:18:28 +00001530
Chris Lattner147e9752002-05-08 22:46:53 +00001531 // -A + B --> B - A
Chris Lattnerbb74e222003-03-10 23:06:50 +00001532 if (Value *V = dyn_castNegVal(LHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001533 return BinaryOperator::createSub(RHS, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +00001534
1535 // A + -B --> A - B
Chris Lattnerbb74e222003-03-10 23:06:50 +00001536 if (!isa<Constant>(RHS))
1537 if (Value *V = dyn_castNegVal(RHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001538 return BinaryOperator::createSub(LHS, V);
Chris Lattner260ab202002-04-18 17:39:14 +00001539
Misha Brukmanb1c93172005-04-21 23:48:37 +00001540
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001541 ConstantInt *C2;
1542 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
1543 if (X == RHS) // X*C + X --> X * (C+1)
1544 return BinaryOperator::createMul(RHS, AddOne(C2));
1545
1546 // X*C1 + X*C2 --> X * (C1+C2)
1547 ConstantInt *C1;
1548 if (X == dyn_castFoldableMul(RHS, C1))
1549 return BinaryOperator::createMul(X, ConstantExpr::getAdd(C1, C2));
Chris Lattner57c8d992003-02-18 19:57:07 +00001550 }
1551
1552 // X + X*C --> X * (C+1)
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001553 if (dyn_castFoldableMul(RHS, C2) == LHS)
1554 return BinaryOperator::createMul(LHS, AddOne(C2));
1555
Chris Lattner57c8d992003-02-18 19:57:07 +00001556
Chris Lattnerb8b97502003-08-13 19:01:45 +00001557 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattnerd4252a72004-07-30 07:50:03 +00001558 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattnerb8b97502003-08-13 19:01:45 +00001559 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2))) return R;
Chris Lattner7fb29e12003-03-11 00:12:48 +00001560
Chris Lattnerb9cde762003-10-02 15:11:26 +00001561 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner330628a2006-01-06 17:59:59 +00001562 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00001563 if (match(LHS, m_Not(m_Value(X)))) { // ~X + C --> (C-1) - X
1564 Constant *C= ConstantExpr::getSub(CRHS, ConstantInt::get(I.getType(), 1));
1565 return BinaryOperator::createSub(C, X);
Chris Lattnerb9cde762003-10-02 15:11:26 +00001566 }
Chris Lattnerd4252a72004-07-30 07:50:03 +00001567
Chris Lattnerbff91d92004-10-08 05:07:56 +00001568 // (X & FF00) + xx00 -> (X+xx00) & FF00
1569 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
1570 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
1571 if (Anded == CRHS) {
1572 // See if all bits from the first bit set in the Add RHS up are included
1573 // in the mask. First, get the rightmost bit.
1574 uint64_t AddRHSV = CRHS->getRawValue();
1575
1576 // Form a mask of all bits from the lowest bit added through the top.
1577 uint64_t AddRHSHighBits = ~((AddRHSV & -AddRHSV)-1);
Chris Lattner77defba2006-02-07 07:00:41 +00001578 AddRHSHighBits &= C2->getType()->getIntegralTypeMask();
Chris Lattnerbff91d92004-10-08 05:07:56 +00001579
1580 // See if the and mask includes all of these bits.
1581 uint64_t AddRHSHighBitsAnd = AddRHSHighBits & C2->getRawValue();
Misha Brukmanb1c93172005-04-21 23:48:37 +00001582
Chris Lattnerbff91d92004-10-08 05:07:56 +00001583 if (AddRHSHighBits == AddRHSHighBitsAnd) {
1584 // Okay, the xform is safe. Insert the new add pronto.
1585 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
1586 LHS->getName()), I);
1587 return BinaryOperator::createAnd(NewAdd, C2);
1588 }
1589 }
1590 }
1591
Chris Lattnerd4252a72004-07-30 07:50:03 +00001592 // Try to fold constant add into select arguments.
1593 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner86102b82005-01-01 16:22:27 +00001594 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattnerd4252a72004-07-30 07:50:03 +00001595 return R;
Chris Lattnerb9cde762003-10-02 15:11:26 +00001596 }
1597
Chris Lattner113f4f42002-06-25 16:13:24 +00001598 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +00001599}
1600
Chris Lattnerbdb0ce02003-07-22 21:46:59 +00001601// isSignBit - Return true if the value represented by the constant only has the
1602// highest order bit set.
1603static bool isSignBit(ConstantInt *CI) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001604 unsigned NumBits = CI->getType()->getPrimitiveSizeInBits();
Chris Lattner2f1457f2005-04-24 17:46:05 +00001605 return (CI->getRawValue() & (~0ULL >> (64-NumBits))) == (1ULL << (NumBits-1));
Chris Lattnerbdb0ce02003-07-22 21:46:59 +00001606}
1607
Chris Lattner022167f2004-03-13 00:11:49 +00001608/// RemoveNoopCast - Strip off nonconverting casts from the value.
1609///
1610static Value *RemoveNoopCast(Value *V) {
1611 if (CastInst *CI = dyn_cast<CastInst>(V)) {
1612 const Type *CTy = CI->getType();
1613 const Type *OpTy = CI->getOperand(0)->getType();
1614 if (CTy->isInteger() && OpTy->isInteger()) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001615 if (CTy->getPrimitiveSizeInBits() == OpTy->getPrimitiveSizeInBits())
Chris Lattner022167f2004-03-13 00:11:49 +00001616 return RemoveNoopCast(CI->getOperand(0));
1617 } else if (isa<PointerType>(CTy) && isa<PointerType>(OpTy))
1618 return RemoveNoopCast(CI->getOperand(0));
1619 }
1620 return V;
1621}
1622
Chris Lattner113f4f42002-06-25 16:13:24 +00001623Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +00001624 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001625
Chris Lattnere6794492002-08-12 21:17:25 +00001626 if (Op0 == Op1) // sub X, X -> 0
1627 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner260ab202002-04-18 17:39:14 +00001628
Chris Lattnere6794492002-08-12 21:17:25 +00001629 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattnerbb74e222003-03-10 23:06:50 +00001630 if (Value *V = dyn_castNegVal(Op1))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001631 return BinaryOperator::createAdd(Op0, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +00001632
Chris Lattner81a7a232004-10-16 18:11:37 +00001633 if (isa<UndefValue>(Op0))
1634 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
1635 if (isa<UndefValue>(Op1))
1636 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
1637
Chris Lattner8f2f5982003-11-05 01:06:05 +00001638 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
1639 // Replace (-1 - A) with (~A)...
Chris Lattner3082c5a2003-02-18 19:28:33 +00001640 if (C->isAllOnesValue())
1641 return BinaryOperator::createNot(Op1);
Chris Lattnerad3c4952002-05-09 01:29:19 +00001642
Chris Lattner8f2f5982003-11-05 01:06:05 +00001643 // C - ~X == X + (1+C)
Reid Spencer4fdd96c2005-06-18 17:37:34 +00001644 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00001645 if (match(Op1, m_Not(m_Value(X))))
1646 return BinaryOperator::createAdd(X,
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001647 ConstantExpr::getAdd(C, ConstantInt::get(I.getType(), 1)));
Chris Lattner92295c52004-03-12 23:53:13 +00001648 // -((uint)X >> 31) -> ((int)X >> 31)
1649 // -((int)X >> 31) -> ((uint)X >> 31)
Chris Lattner022167f2004-03-13 00:11:49 +00001650 if (C->isNullValue()) {
1651 Value *NoopCastedRHS = RemoveNoopCast(Op1);
1652 if (ShiftInst *SI = dyn_cast<ShiftInst>(NoopCastedRHS))
Chris Lattner92295c52004-03-12 23:53:13 +00001653 if (SI->getOpcode() == Instruction::Shr)
1654 if (ConstantUInt *CU = dyn_cast<ConstantUInt>(SI->getOperand(1))) {
1655 const Type *NewTy;
Chris Lattner022167f2004-03-13 00:11:49 +00001656 if (SI->getType()->isSigned())
Chris Lattner97bfcea2004-06-17 18:16:02 +00001657 NewTy = SI->getType()->getUnsignedVersion();
Chris Lattner92295c52004-03-12 23:53:13 +00001658 else
Chris Lattner97bfcea2004-06-17 18:16:02 +00001659 NewTy = SI->getType()->getSignedVersion();
Chris Lattner92295c52004-03-12 23:53:13 +00001660 // Check to see if we are shifting out everything but the sign bit.
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001661 if (CU->getValue() == SI->getType()->getPrimitiveSizeInBits()-1) {
Chris Lattner92295c52004-03-12 23:53:13 +00001662 // Ok, the transformation is safe. Insert a cast of the incoming
1663 // value, then the new shift, then the new cast.
1664 Instruction *FirstCast = new CastInst(SI->getOperand(0), NewTy,
1665 SI->getOperand(0)->getName());
1666 Value *InV = InsertNewInstBefore(FirstCast, I);
1667 Instruction *NewShift = new ShiftInst(Instruction::Shr, FirstCast,
1668 CU, SI->getName());
Chris Lattner022167f2004-03-13 00:11:49 +00001669 if (NewShift->getType() == I.getType())
1670 return NewShift;
1671 else {
1672 InV = InsertNewInstBefore(NewShift, I);
1673 return new CastInst(NewShift, I.getType());
1674 }
Chris Lattner92295c52004-03-12 23:53:13 +00001675 }
1676 }
Chris Lattner022167f2004-03-13 00:11:49 +00001677 }
Chris Lattner183b3362004-04-09 19:05:30 +00001678
1679 // Try to fold constant sub into select arguments.
1680 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner86102b82005-01-01 16:22:27 +00001681 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00001682 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001683
1684 if (isa<PHINode>(Op0))
1685 if (Instruction *NV = FoldOpIntoPhi(I))
1686 return NV;
Chris Lattner8f2f5982003-11-05 01:06:05 +00001687 }
1688
Chris Lattnera9be4492005-04-07 16:15:25 +00001689 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
1690 if (Op1I->getOpcode() == Instruction::Add &&
1691 !Op0->getType()->isFloatingPoint()) {
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00001692 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Chris Lattnera9be4492005-04-07 16:15:25 +00001693 return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00001694 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Chris Lattnera9be4492005-04-07 16:15:25 +00001695 return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00001696 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
1697 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
1698 // C1-(X+C2) --> (C1-C2)-X
1699 return BinaryOperator::createSub(ConstantExpr::getSub(CI1, CI2),
1700 Op1I->getOperand(0));
1701 }
Chris Lattnera9be4492005-04-07 16:15:25 +00001702 }
1703
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001704 if (Op1I->hasOneUse()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00001705 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
1706 // is not used by anyone else...
1707 //
Chris Lattnerc2f0aa52004-02-02 20:09:56 +00001708 if (Op1I->getOpcode() == Instruction::Sub &&
1709 !Op1I->getType()->isFloatingPoint()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00001710 // Swap the two operands of the subexpr...
1711 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
1712 Op1I->setOperand(0, IIOp1);
1713 Op1I->setOperand(1, IIOp0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001714
Chris Lattner3082c5a2003-02-18 19:28:33 +00001715 // Create the new top level add instruction...
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001716 return BinaryOperator::createAdd(Op0, Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001717 }
1718
1719 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
1720 //
1721 if (Op1I->getOpcode() == Instruction::And &&
1722 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
1723 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
1724
Chris Lattner396dbfe2004-06-09 05:08:07 +00001725 Value *NewNot =
1726 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001727 return BinaryOperator::createAnd(Op0, NewNot);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001728 }
Chris Lattner57c8d992003-02-18 19:57:07 +00001729
Chris Lattner0aee4b72004-10-06 15:08:25 +00001730 // -(X sdiv C) -> (X sdiv -C)
1731 if (Op1I->getOpcode() == Instruction::Div)
1732 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
Chris Lattnera9be4492005-04-07 16:15:25 +00001733 if (CSI->isNullValue())
Chris Lattner0aee4b72004-10-06 15:08:25 +00001734 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Misha Brukmanb1c93172005-04-21 23:48:37 +00001735 return BinaryOperator::createDiv(Op1I->getOperand(0),
Chris Lattner0aee4b72004-10-06 15:08:25 +00001736 ConstantExpr::getNeg(DivRHS));
1737
Chris Lattner57c8d992003-02-18 19:57:07 +00001738 // X - X*C --> X * (1-C)
Reid Spencer4fdd96c2005-06-18 17:37:34 +00001739 ConstantInt *C2 = 0;
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001740 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00001741 Constant *CP1 =
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001742 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1), C2);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001743 return BinaryOperator::createMul(Op0, CP1);
Chris Lattner57c8d992003-02-18 19:57:07 +00001744 }
Chris Lattnerad3c4952002-05-09 01:29:19 +00001745 }
Chris Lattnera9be4492005-04-07 16:15:25 +00001746 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00001747
Chris Lattner47060462005-04-07 17:14:51 +00001748 if (!Op0->getType()->isFloatingPoint())
1749 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
1750 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner411336f2005-01-19 21:50:18 +00001751 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
1752 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
1753 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
1754 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner47060462005-04-07 17:14:51 +00001755 } else if (Op0I->getOpcode() == Instruction::Sub) {
1756 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
1757 return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
Chris Lattner411336f2005-01-19 21:50:18 +00001758 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001759
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001760 ConstantInt *C1;
1761 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
1762 if (X == Op1) { // X*C - X --> X * (C-1)
1763 Constant *CP1 = ConstantExpr::getSub(C1, ConstantInt::get(I.getType(),1));
1764 return BinaryOperator::createMul(Op1, CP1);
1765 }
Chris Lattner57c8d992003-02-18 19:57:07 +00001766
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001767 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
1768 if (X == dyn_castFoldableMul(Op1, C2))
1769 return BinaryOperator::createMul(Op1, ConstantExpr::getSub(C1, C2));
1770 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001771 return 0;
Chris Lattner260ab202002-04-18 17:39:14 +00001772}
1773
Chris Lattnere79e8542004-02-23 06:38:22 +00001774/// isSignBitCheck - Given an exploded setcc instruction, return true if it is
1775/// really just returns true if the most significant (sign) bit is set.
1776static bool isSignBitCheck(unsigned Opcode, Value *LHS, ConstantInt *RHS) {
1777 if (RHS->getType()->isSigned()) {
1778 // True if source is LHS < 0 or LHS <= -1
1779 return Opcode == Instruction::SetLT && RHS->isNullValue() ||
1780 Opcode == Instruction::SetLE && RHS->isAllOnesValue();
1781 } else {
1782 ConstantUInt *RHSC = cast<ConstantUInt>(RHS);
1783 // True if source is LHS > 127 or LHS >= 128, where the constants depend on
1784 // the size of the integer type.
1785 if (Opcode == Instruction::SetGE)
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001786 return RHSC->getValue() ==
1787 1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1);
Chris Lattnere79e8542004-02-23 06:38:22 +00001788 if (Opcode == Instruction::SetGT)
1789 return RHSC->getValue() ==
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001790 (1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1))-1;
Chris Lattnere79e8542004-02-23 06:38:22 +00001791 }
1792 return false;
1793}
1794
Chris Lattner113f4f42002-06-25 16:13:24 +00001795Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001796 bool Changed = SimplifyCommutative(I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001797 Value *Op0 = I.getOperand(0);
Chris Lattner260ab202002-04-18 17:39:14 +00001798
Chris Lattner81a7a232004-10-16 18:11:37 +00001799 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
1800 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1801
Chris Lattnere6794492002-08-12 21:17:25 +00001802 // Simplify mul instructions with a constant RHS...
Chris Lattner3082c5a2003-02-18 19:28:33 +00001803 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
1804 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerede3fe02003-08-13 04:18:28 +00001805
1806 // ((X << C1)*C2) == (X * (C2 << C1))
1807 if (ShiftInst *SI = dyn_cast<ShiftInst>(Op0))
1808 if (SI->getOpcode() == Instruction::Shl)
1809 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001810 return BinaryOperator::createMul(SI->getOperand(0),
1811 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanb1c93172005-04-21 23:48:37 +00001812
Chris Lattnercce81be2003-09-11 22:24:54 +00001813 if (CI->isNullValue())
1814 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
1815 if (CI->equalsInt(1)) // X * 1 == X
1816 return ReplaceInstUsesWith(I, Op0);
1817 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Chris Lattner35236d82003-06-25 17:09:20 +00001818 return BinaryOperator::createNeg(Op0, I.getName());
Chris Lattner31ba1292002-04-29 22:24:47 +00001819
Chris Lattnercce81be2003-09-11 22:24:54 +00001820 int64_t Val = (int64_t)cast<ConstantInt>(CI)->getRawValue();
Chris Lattner22d00a82005-08-02 19:16:58 +00001821 if (isPowerOf2_64(Val)) { // Replace X*(2^C) with X << C
1822 uint64_t C = Log2_64(Val);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001823 return new ShiftInst(Instruction::Shl, Op0,
1824 ConstantUInt::get(Type::UByteTy, C));
Chris Lattner22d00a82005-08-02 19:16:58 +00001825 }
Robert Bocchino7b5b86c2004-07-27 21:02:21 +00001826 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00001827 if (Op1F->isNullValue())
1828 return ReplaceInstUsesWith(I, Op1);
Chris Lattner31ba1292002-04-29 22:24:47 +00001829
Chris Lattner3082c5a2003-02-18 19:28:33 +00001830 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
1831 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
1832 if (Op1F->getValue() == 1.0)
1833 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
1834 }
Chris Lattner32c01df2006-03-04 06:04:02 +00001835
1836 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
1837 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
1838 isa<ConstantInt>(Op0I->getOperand(1))) {
1839 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
1840 Instruction *Add = BinaryOperator::createMul(Op0I->getOperand(0),
1841 Op1, "tmp");
1842 InsertNewInstBefore(Add, I);
1843 Value *C1C2 = ConstantExpr::getMul(Op1,
1844 cast<Constant>(Op0I->getOperand(1)));
1845 return BinaryOperator::createAdd(Add, C1C2);
1846
1847 }
Chris Lattner183b3362004-04-09 19:05:30 +00001848
1849 // Try to fold constant mul into select arguments.
1850 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00001851 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00001852 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001853
1854 if (isa<PHINode>(Op0))
1855 if (Instruction *NV = FoldOpIntoPhi(I))
1856 return NV;
Chris Lattner260ab202002-04-18 17:39:14 +00001857 }
1858
Chris Lattner934a64cf2003-03-10 23:23:04 +00001859 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
1860 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001861 return BinaryOperator::createMul(Op0v, Op1v);
Chris Lattner934a64cf2003-03-10 23:23:04 +00001862
Chris Lattner2635b522004-02-23 05:39:21 +00001863 // If one of the operands of the multiply is a cast from a boolean value, then
1864 // we know the bool is either zero or one, so this is a 'masking' multiply.
1865 // See if we can simplify things based on how the boolean was originally
1866 // formed.
1867 CastInst *BoolCast = 0;
1868 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(0)))
1869 if (CI->getOperand(0)->getType() == Type::BoolTy)
1870 BoolCast = CI;
1871 if (!BoolCast)
1872 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(1)))
1873 if (CI->getOperand(0)->getType() == Type::BoolTy)
1874 BoolCast = CI;
1875 if (BoolCast) {
1876 if (SetCondInst *SCI = dyn_cast<SetCondInst>(BoolCast->getOperand(0))) {
1877 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
1878 const Type *SCOpTy = SCIOp0->getType();
1879
Chris Lattnere79e8542004-02-23 06:38:22 +00001880 // If the setcc is true iff the sign bit of X is set, then convert this
1881 // multiply into a shift/and combination.
1882 if (isa<ConstantInt>(SCIOp1) &&
1883 isSignBitCheck(SCI->getOpcode(), SCIOp0, cast<ConstantInt>(SCIOp1))) {
Chris Lattner2635b522004-02-23 05:39:21 +00001884 // Shift the X value right to turn it into "all signbits".
1885 Constant *Amt = ConstantUInt::get(Type::UByteTy,
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001886 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattnere79e8542004-02-23 06:38:22 +00001887 if (SCIOp0->getType()->isUnsigned()) {
Chris Lattner97bfcea2004-06-17 18:16:02 +00001888 const Type *NewTy = SCIOp0->getType()->getSignedVersion();
Chris Lattnere79e8542004-02-23 06:38:22 +00001889 SCIOp0 = InsertNewInstBefore(new CastInst(SCIOp0, NewTy,
1890 SCIOp0->getName()), I);
1891 }
1892
1893 Value *V =
1894 InsertNewInstBefore(new ShiftInst(Instruction::Shr, SCIOp0, Amt,
1895 BoolCast->getOperand(0)->getName()+
1896 ".mask"), I);
Chris Lattner2635b522004-02-23 05:39:21 +00001897
1898 // If the multiply type is not the same as the source type, sign extend
1899 // or truncate to the multiply type.
1900 if (I.getType() != V->getType())
Chris Lattnere79e8542004-02-23 06:38:22 +00001901 V = InsertNewInstBefore(new CastInst(V, I.getType(), V->getName()),I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001902
Chris Lattner2635b522004-02-23 05:39:21 +00001903 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001904 return BinaryOperator::createAnd(V, OtherOp);
Chris Lattner2635b522004-02-23 05:39:21 +00001905 }
1906 }
1907 }
1908
Chris Lattner113f4f42002-06-25 16:13:24 +00001909 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +00001910}
1911
Chris Lattner113f4f42002-06-25 16:13:24 +00001912Instruction *InstCombiner::visitDiv(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001913 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner81a7a232004-10-16 18:11:37 +00001914
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001915 if (isa<UndefValue>(Op0)) // undef / X -> 0
1916 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1917 if (isa<UndefValue>(Op1))
1918 return ReplaceInstUsesWith(I, Op1); // X / undef -> undef
1919
1920 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnere20c3342004-04-26 14:01:59 +00001921 // div X, 1 == X
Chris Lattnere6794492002-08-12 21:17:25 +00001922 if (RHS->equalsInt(1))
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001923 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001924
Chris Lattnere20c3342004-04-26 14:01:59 +00001925 // div X, -1 == -X
1926 if (RHS->isAllOnesValue())
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001927 return BinaryOperator::createNeg(Op0);
Chris Lattnere20c3342004-04-26 14:01:59 +00001928
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001929 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
Chris Lattner272d5ca2004-09-28 18:22:15 +00001930 if (LHS->getOpcode() == Instruction::Div)
1931 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Chris Lattner272d5ca2004-09-28 18:22:15 +00001932 // (X / C1) / C2 -> X / (C1*C2)
1933 return BinaryOperator::createDiv(LHS->getOperand(0),
1934 ConstantExpr::getMul(RHS, LHSRHS));
1935 }
1936
Chris Lattner3082c5a2003-02-18 19:28:33 +00001937 // Check to see if this is an unsigned division with an exact power of 2,
1938 // if so, convert to a right shift.
1939 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
1940 if (uint64_t Val = C->getValue()) // Don't break X / 0
Chris Lattner22d00a82005-08-02 19:16:58 +00001941 if (isPowerOf2_64(Val)) {
1942 uint64_t C = Log2_64(Val);
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001943 return new ShiftInst(Instruction::Shr, Op0,
Chris Lattner3082c5a2003-02-18 19:28:33 +00001944 ConstantUInt::get(Type::UByteTy, C));
Chris Lattner22d00a82005-08-02 19:16:58 +00001945 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001946
Chris Lattner4ad08352004-10-09 02:50:40 +00001947 // -X/C -> X/-C
1948 if (RHS->getType()->isSigned())
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001949 if (Value *LHSNeg = dyn_castNegVal(Op0))
Chris Lattner4ad08352004-10-09 02:50:40 +00001950 return BinaryOperator::createDiv(LHSNeg, ConstantExpr::getNeg(RHS));
1951
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001952 if (!RHS->isNullValue()) {
1953 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00001954 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001955 return R;
1956 if (isa<PHINode>(Op0))
1957 if (Instruction *NV = FoldOpIntoPhi(I))
1958 return NV;
1959 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00001960 }
1961
Chris Lattnerd79dc792006-09-09 20:26:32 +00001962 // Handle div X, Cond?Y:Z
1963 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
1964 // div X, (Cond ? 0 : Y) -> div X, Y. If the div and the select are in the
1965 // same basic block, then we replace the select with Y, and the condition of
1966 // the select with false (if the cond value is in the same BB). If the
1967 // select has uses other than the div, this allows them to be simplified
1968 // also.
1969 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
1970 if (ST->isNullValue()) {
1971 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
1972 if (CondI && CondI->getParent() == I.getParent())
1973 UpdateValueUsesWith(CondI, ConstantBool::False);
1974 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
1975 I.setOperand(1, SI->getOperand(2));
1976 else
1977 UpdateValueUsesWith(SI, SI->getOperand(2));
1978 return &I;
1979 }
1980 // Likewise for: div X, (Cond ? Y : 0) -> div X, Y
1981 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
1982 if (ST->isNullValue()) {
1983 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
1984 if (CondI && CondI->getParent() == I.getParent())
1985 UpdateValueUsesWith(CondI, ConstantBool::True);
1986 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
1987 I.setOperand(1, SI->getOperand(1));
1988 else
1989 UpdateValueUsesWith(SI, SI->getOperand(1));
1990 return &I;
1991 }
1992
1993 // If this is 'udiv X, (Cond ? C1, C2)' where C1&C2 are powers of two,
1994 // transform this into: '(Cond ? (udiv X, C1) : (udiv X, C2))'.
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001995 if (ConstantUInt *STO = dyn_cast<ConstantUInt>(SI->getOperand(1)))
1996 if (ConstantUInt *SFO = dyn_cast<ConstantUInt>(SI->getOperand(2))) {
Chris Lattnerd79dc792006-09-09 20:26:32 +00001997 // STO == 0 and SFO == 0 handled above.
Chris Lattner42362612005-04-08 04:03:26 +00001998 uint64_t TVA = STO->getValue(), FVA = SFO->getValue();
Chris Lattner22d00a82005-08-02 19:16:58 +00001999 if (isPowerOf2_64(TVA) && isPowerOf2_64(FVA)) {
2000 unsigned TSA = Log2_64(TVA), FSA = Log2_64(FVA);
Chris Lattner42362612005-04-08 04:03:26 +00002001 Constant *TC = ConstantUInt::get(Type::UByteTy, TSA);
2002 Instruction *TSI = new ShiftInst(Instruction::Shr, Op0,
2003 TC, SI->getName()+".t");
2004 TSI = InsertNewInstBefore(TSI, I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002005
Chris Lattner42362612005-04-08 04:03:26 +00002006 Constant *FC = ConstantUInt::get(Type::UByteTy, FSA);
2007 Instruction *FSI = new ShiftInst(Instruction::Shr, Op0,
2008 FC, SI->getName()+".f");
2009 FSI = InsertNewInstBefore(FSI, I);
2010 return new SelectInst(SI->getOperand(0), TSI, FSI);
2011 }
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002012 }
Chris Lattnerd79dc792006-09-09 20:26:32 +00002013 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002014
Chris Lattner3082c5a2003-02-18 19:28:33 +00002015 // 0 / X == 0, we don't need to preserve faults!
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002016 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattner3082c5a2003-02-18 19:28:33 +00002017 if (LHS->equalsInt(0))
2018 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2019
Chris Lattnerdd0c1742005-11-05 07:40:31 +00002020 if (I.getType()->isSigned()) {
Chris Lattnerc3ebf402006-02-07 07:27:52 +00002021 // If the sign bits of both operands are zero (i.e. we can prove they are
Chris Lattnerdd0c1742005-11-05 07:40:31 +00002022 // unsigned inputs), turn this into a udiv.
Chris Lattnerc3ebf402006-02-07 07:27:52 +00002023 uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
2024 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
Chris Lattnerdd0c1742005-11-05 07:40:31 +00002025 const Type *NTy = Op0->getType()->getUnsignedVersion();
2026 Instruction *LHS = new CastInst(Op0, NTy, Op0->getName());
2027 InsertNewInstBefore(LHS, I);
2028 Value *RHS;
2029 if (Constant *R = dyn_cast<Constant>(Op1))
2030 RHS = ConstantExpr::getCast(R, NTy);
2031 else
2032 RHS = InsertNewInstBefore(new CastInst(Op1, NTy, Op1->getName()), I);
2033 Instruction *Div = BinaryOperator::createDiv(LHS, RHS, I.getName());
2034 InsertNewInstBefore(Div, I);
2035 return new CastInst(Div, I.getType());
2036 }
Chris Lattner2e90b732006-02-05 07:54:04 +00002037 } else {
2038 // Known to be an unsigned division.
2039 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
2040 // Turn A / (C1 << N), where C1 is "1<<C2" into A >> (N+C2) [udiv only].
2041 if (RHSI->getOpcode() == Instruction::Shl &&
2042 isa<ConstantUInt>(RHSI->getOperand(0))) {
2043 unsigned C1 = cast<ConstantUInt>(RHSI->getOperand(0))->getRawValue();
2044 if (isPowerOf2_64(C1)) {
2045 unsigned C2 = Log2_64(C1);
2046 Value *Add = RHSI->getOperand(1);
2047 if (C2) {
2048 Constant *C2V = ConstantUInt::get(Add->getType(), C2);
2049 Add = InsertNewInstBefore(BinaryOperator::createAdd(Add, C2V,
2050 "tmp"), I);
2051 }
2052 return new ShiftInst(Instruction::Shr, Op0, Add);
2053 }
2054 }
2055 }
Chris Lattnerdd0c1742005-11-05 07:40:31 +00002056 }
2057
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002058 return 0;
2059}
2060
2061
Chris Lattner85dda9a2006-03-02 06:50:58 +00002062/// GetFactor - If we can prove that the specified value is at least a multiple
2063/// of some factor, return that factor.
2064static Constant *GetFactor(Value *V) {
2065 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
2066 return CI;
2067
2068 // Unless we can be tricky, we know this is a multiple of 1.
2069 Constant *Result = ConstantInt::get(V->getType(), 1);
2070
2071 Instruction *I = dyn_cast<Instruction>(V);
2072 if (!I) return Result;
2073
2074 if (I->getOpcode() == Instruction::Mul) {
2075 // Handle multiplies by a constant, etc.
2076 return ConstantExpr::getMul(GetFactor(I->getOperand(0)),
2077 GetFactor(I->getOperand(1)));
2078 } else if (I->getOpcode() == Instruction::Shl) {
2079 // (X<<C) -> X * (1 << C)
2080 if (Constant *ShRHS = dyn_cast<Constant>(I->getOperand(1))) {
2081 ShRHS = ConstantExpr::getShl(Result, ShRHS);
2082 return ConstantExpr::getMul(GetFactor(I->getOperand(0)), ShRHS);
2083 }
2084 } else if (I->getOpcode() == Instruction::And) {
2085 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
2086 // X & 0xFFF0 is known to be a multiple of 16.
2087 unsigned Zeros = CountTrailingZeros_64(RHS->getZExtValue());
2088 if (Zeros != V->getType()->getPrimitiveSizeInBits())
2089 return ConstantExpr::getShl(Result,
2090 ConstantUInt::get(Type::UByteTy, Zeros));
2091 }
2092 } else if (I->getOpcode() == Instruction::Cast) {
2093 Value *Op = I->getOperand(0);
2094 // Only handle int->int casts.
2095 if (!Op->getType()->isInteger()) return Result;
2096 return ConstantExpr::getCast(GetFactor(Op), V->getType());
2097 }
2098 return Result;
2099}
2100
Chris Lattner113f4f42002-06-25 16:13:24 +00002101Instruction *InstCombiner::visitRem(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002102 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner0de4a8d2006-02-28 05:30:45 +00002103
2104 // 0 % X == 0, we don't need to preserve faults!
2105 if (Constant *LHS = dyn_cast<Constant>(Op0))
2106 if (LHS->isNullValue())
2107 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2108
2109 if (isa<UndefValue>(Op0)) // undef % X -> 0
2110 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2111 if (isa<UndefValue>(Op1))
2112 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
2113
Chris Lattnere9ff0ea2005-11-05 07:28:37 +00002114 if (I.getType()->isSigned()) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002115 if (Value *RHSNeg = dyn_castNegVal(Op1))
Chris Lattner98c6bdf2004-07-06 07:11:42 +00002116 if (!isa<ConstantSInt>(RHSNeg) ||
Chris Lattner8e726062004-08-09 21:05:48 +00002117 cast<ConstantSInt>(RHSNeg)->getValue() > 0) {
Chris Lattner7fd5f072004-07-06 07:01:22 +00002118 // X % -Y -> X % Y
2119 AddUsesToWorkList(I);
2120 I.setOperand(1, RHSNeg);
2121 return &I;
2122 }
Chris Lattnere9ff0ea2005-11-05 07:28:37 +00002123
2124 // If the top bits of both operands are zero (i.e. we can prove they are
2125 // unsigned inputs), turn this into a urem.
Chris Lattnerc3ebf402006-02-07 07:27:52 +00002126 uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
2127 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
Chris Lattnere9ff0ea2005-11-05 07:28:37 +00002128 const Type *NTy = Op0->getType()->getUnsignedVersion();
2129 Instruction *LHS = new CastInst(Op0, NTy, Op0->getName());
2130 InsertNewInstBefore(LHS, I);
2131 Value *RHS;
2132 if (Constant *R = dyn_cast<Constant>(Op1))
2133 RHS = ConstantExpr::getCast(R, NTy);
2134 else
2135 RHS = InsertNewInstBefore(new CastInst(Op1, NTy, Op1->getName()), I);
2136 Instruction *Rem = BinaryOperator::createRem(LHS, RHS, I.getName());
2137 InsertNewInstBefore(Rem, I);
2138 return new CastInst(Rem, I.getType());
2139 }
2140 }
Chris Lattner7fd5f072004-07-06 07:01:22 +00002141
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002142 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner0de4a8d2006-02-28 05:30:45 +00002143 // X % 0 == undef, we don't need to preserve faults!
2144 if (RHS->equalsInt(0))
2145 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2146
Chris Lattner3082c5a2003-02-18 19:28:33 +00002147 if (RHS->equalsInt(1)) // X % 1 == 0
2148 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2149
2150 // Check to see if this is an unsigned remainder with an exact power of 2,
2151 // if so, convert to a bitwise and.
2152 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
Chris Lattner0de4a8d2006-02-28 05:30:45 +00002153 if (isPowerOf2_64(C->getValue()))
2154 return BinaryOperator::createAnd(Op0, SubOne(C));
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002155
Chris Lattnerb70f1412006-02-28 05:49:21 +00002156 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2157 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2158 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2159 return R;
2160 } else if (isa<PHINode>(Op0I)) {
2161 if (Instruction *NV = FoldOpIntoPhi(I))
2162 return NV;
Chris Lattnerb70f1412006-02-28 05:49:21 +00002163 }
Chris Lattner85dda9a2006-03-02 06:50:58 +00002164
2165 // X*C1%C2 --> 0 iff C1%C2 == 0
2166 if (ConstantExpr::getRem(GetFactor(Op0I), RHS)->isNullValue())
2167 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerb70f1412006-02-28 05:49:21 +00002168 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00002169 }
2170
Chris Lattner2e90b732006-02-05 07:54:04 +00002171 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
2172 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1) [urem only].
2173 if (I.getType()->isUnsigned() &&
2174 RHSI->getOpcode() == Instruction::Shl &&
2175 isa<ConstantUInt>(RHSI->getOperand(0))) {
2176 unsigned C1 = cast<ConstantUInt>(RHSI->getOperand(0))->getRawValue();
2177 if (isPowerOf2_64(C1)) {
2178 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
2179 Value *Add = InsertNewInstBefore(BinaryOperator::createAdd(RHSI, N1,
2180 "tmp"), I);
2181 return BinaryOperator::createAnd(Op0, Add);
2182 }
2183 }
Chris Lattner0de4a8d2006-02-28 05:30:45 +00002184
2185 // If this is 'urem X, (Cond ? C1, C2)' where C1&C2 are powers of two,
2186 // transform this into: '(Cond ? (urem X, C1) : (urem X, C2))'.
Chris Lattnerd79dc792006-09-09 20:26:32 +00002187 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2188 // rem X, (Cond ? 0 : Y) -> rem X, Y. If the rem and the select are in
2189 // the same basic block, then we replace the select with Y, and the
2190 // condition of the select with false (if the cond value is in the same
2191 // BB). If the select has uses other than the div, this allows them to be
2192 // simplified also.
2193 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2194 if (ST->isNullValue()) {
2195 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2196 if (CondI && CondI->getParent() == I.getParent())
2197 UpdateValueUsesWith(CondI, ConstantBool::False);
2198 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2199 I.setOperand(1, SI->getOperand(2));
2200 else
2201 UpdateValueUsesWith(SI, SI->getOperand(2));
2202 return &I;
2203 }
2204 // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
2205 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2206 if (ST->isNullValue()) {
2207 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2208 if (CondI && CondI->getParent() == I.getParent())
2209 UpdateValueUsesWith(CondI, ConstantBool::True);
2210 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2211 I.setOperand(1, SI->getOperand(1));
2212 else
2213 UpdateValueUsesWith(SI, SI->getOperand(1));
2214 return &I;
2215 }
2216
2217
Chris Lattner0de4a8d2006-02-28 05:30:45 +00002218 if (ConstantUInt *STO = dyn_cast<ConstantUInt>(SI->getOperand(1)))
2219 if (ConstantUInt *SFO = dyn_cast<ConstantUInt>(SI->getOperand(2))) {
Chris Lattnerd79dc792006-09-09 20:26:32 +00002220 // STO == 0 and SFO == 0 handled above.
Chris Lattner0de4a8d2006-02-28 05:30:45 +00002221
2222 if (isPowerOf2_64(STO->getValue()) && isPowerOf2_64(SFO->getValue())){
2223 Value *TrueAnd = InsertNewInstBefore(BinaryOperator::createAnd(Op0,
2224 SubOne(STO), SI->getName()+".t"), I);
2225 Value *FalseAnd = InsertNewInstBefore(BinaryOperator::createAnd(Op0,
2226 SubOne(SFO), SI->getName()+".f"), I);
2227 return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
2228 }
2229 }
Chris Lattnerd79dc792006-09-09 20:26:32 +00002230 }
Chris Lattner2e90b732006-02-05 07:54:04 +00002231 }
2232
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002233 return 0;
2234}
2235
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002236// isMaxValueMinusOne - return true if this is Max-1
Chris Lattnere6794492002-08-12 21:17:25 +00002237static bool isMaxValueMinusOne(const ConstantInt *C) {
Chris Lattner77defba2006-02-07 07:00:41 +00002238 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
2239 return CU->getValue() == C->getType()->getIntegralTypeMask()-1;
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002240
2241 const ConstantSInt *CS = cast<ConstantSInt>(C);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002242
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002243 // Calculate 0111111111..11111
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002244 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002245 int64_t Val = INT64_MAX; // All ones
2246 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
2247 return CS->getValue() == Val-1;
2248}
2249
2250// isMinValuePlusOne - return true if this is Min+1
Chris Lattnere6794492002-08-12 21:17:25 +00002251static bool isMinValuePlusOne(const ConstantInt *C) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002252 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
2253 return CU->getValue() == 1;
2254
2255 const ConstantSInt *CS = cast<ConstantSInt>(C);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002256
2257 // Calculate 1111111111000000000000
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002258 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002259 int64_t Val = -1; // All ones
2260 Val <<= TypeBits-1; // Shift over to the right spot
2261 return CS->getValue() == Val+1;
2262}
2263
Chris Lattner35167c32004-06-09 07:59:58 +00002264// isOneBitSet - Return true if there is exactly one bit set in the specified
2265// constant.
2266static bool isOneBitSet(const ConstantInt *CI) {
2267 uint64_t V = CI->getRawValue();
2268 return V && (V & (V-1)) == 0;
2269}
2270
Chris Lattner8fc5af42004-09-23 21:46:38 +00002271#if 0 // Currently unused
2272// isLowOnes - Return true if the constant is of the form 0+1+.
2273static bool isLowOnes(const ConstantInt *CI) {
2274 uint64_t V = CI->getRawValue();
2275
2276 // There won't be bits set in parts that the type doesn't contain.
2277 V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
2278
2279 uint64_t U = V+1; // If it is low ones, this should be a power of two.
2280 return U && V && (U & V) == 0;
2281}
2282#endif
2283
2284// isHighOnes - Return true if the constant is of the form 1+0+.
2285// This is the same as lowones(~X).
2286static bool isHighOnes(const ConstantInt *CI) {
2287 uint64_t V = ~CI->getRawValue();
Chris Lattner2c14cf72005-08-07 07:03:10 +00002288 if (~V == 0) return false; // 0's does not match "1+"
Chris Lattner8fc5af42004-09-23 21:46:38 +00002289
2290 // There won't be bits set in parts that the type doesn't contain.
2291 V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
2292
2293 uint64_t U = V+1; // If it is low ones, this should be a power of two.
2294 return U && V && (U & V) == 0;
2295}
2296
2297
Chris Lattner3ac7c262003-08-13 20:16:26 +00002298/// getSetCondCode - Encode a setcc opcode into a three bit mask. These bits
2299/// are carefully arranged to allow folding of expressions such as:
2300///
2301/// (A < B) | (A > B) --> (A != B)
2302///
2303/// Bit value '4' represents that the comparison is true if A > B, bit value '2'
2304/// represents that the comparison is true if A == B, and bit value '1' is true
2305/// if A < B.
2306///
2307static unsigned getSetCondCode(const SetCondInst *SCI) {
2308 switch (SCI->getOpcode()) {
2309 // False -> 0
2310 case Instruction::SetGT: return 1;
2311 case Instruction::SetEQ: return 2;
2312 case Instruction::SetGE: return 3;
2313 case Instruction::SetLT: return 4;
2314 case Instruction::SetNE: return 5;
2315 case Instruction::SetLE: return 6;
2316 // True -> 7
2317 default:
2318 assert(0 && "Invalid SetCC opcode!");
2319 return 0;
2320 }
2321}
2322
2323/// getSetCCValue - This is the complement of getSetCondCode, which turns an
2324/// opcode and two operands into either a constant true or false, or a brand new
2325/// SetCC instruction.
2326static Value *getSetCCValue(unsigned Opcode, Value *LHS, Value *RHS) {
2327 switch (Opcode) {
2328 case 0: return ConstantBool::False;
2329 case 1: return new SetCondInst(Instruction::SetGT, LHS, RHS);
2330 case 2: return new SetCondInst(Instruction::SetEQ, LHS, RHS);
2331 case 3: return new SetCondInst(Instruction::SetGE, LHS, RHS);
2332 case 4: return new SetCondInst(Instruction::SetLT, LHS, RHS);
2333 case 5: return new SetCondInst(Instruction::SetNE, LHS, RHS);
2334 case 6: return new SetCondInst(Instruction::SetLE, LHS, RHS);
2335 case 7: return ConstantBool::True;
2336 default: assert(0 && "Illegal SetCCCode!"); return 0;
2337 }
2338}
2339
2340// FoldSetCCLogical - Implements (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
2341struct FoldSetCCLogical {
2342 InstCombiner &IC;
2343 Value *LHS, *RHS;
2344 FoldSetCCLogical(InstCombiner &ic, SetCondInst *SCI)
2345 : IC(ic), LHS(SCI->getOperand(0)), RHS(SCI->getOperand(1)) {}
2346 bool shouldApply(Value *V) const {
2347 if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
2348 return (SCI->getOperand(0) == LHS && SCI->getOperand(1) == RHS ||
2349 SCI->getOperand(0) == RHS && SCI->getOperand(1) == LHS);
2350 return false;
2351 }
2352 Instruction *apply(BinaryOperator &Log) const {
2353 SetCondInst *SCI = cast<SetCondInst>(Log.getOperand(0));
2354 if (SCI->getOperand(0) != LHS) {
2355 assert(SCI->getOperand(1) == LHS);
2356 SCI->swapOperands(); // Swap the LHS and RHS of the SetCC
2357 }
2358
2359 unsigned LHSCode = getSetCondCode(SCI);
2360 unsigned RHSCode = getSetCondCode(cast<SetCondInst>(Log.getOperand(1)));
2361 unsigned Code;
2362 switch (Log.getOpcode()) {
2363 case Instruction::And: Code = LHSCode & RHSCode; break;
2364 case Instruction::Or: Code = LHSCode | RHSCode; break;
2365 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner2caaaba2003-09-22 20:33:34 +00002366 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattner3ac7c262003-08-13 20:16:26 +00002367 }
2368
2369 Value *RV = getSetCCValue(Code, LHS, RHS);
2370 if (Instruction *I = dyn_cast<Instruction>(RV))
2371 return I;
2372 // Otherwise, it's a constant boolean value...
2373 return IC.ReplaceInstUsesWith(Log, RV);
2374 }
2375};
2376
Chris Lattnerba1cb382003-09-19 17:17:26 +00002377// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
2378// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
2379// guaranteed to be either a shift instruction or a binary operator.
2380Instruction *InstCombiner::OptAndOp(Instruction *Op,
2381 ConstantIntegral *OpRHS,
2382 ConstantIntegral *AndRHS,
2383 BinaryOperator &TheAnd) {
2384 Value *X = Op->getOperand(0);
Chris Lattnerfcf21a72004-01-12 19:47:05 +00002385 Constant *Together = 0;
2386 if (!isa<ShiftInst>(Op))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002387 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002388
Chris Lattnerba1cb382003-09-19 17:17:26 +00002389 switch (Op->getOpcode()) {
2390 case Instruction::Xor:
Chris Lattner86102b82005-01-01 16:22:27 +00002391 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00002392 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
2393 std::string OpName = Op->getName(); Op->setName("");
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002394 Instruction *And = BinaryOperator::createAnd(X, AndRHS, OpName);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002395 InsertNewInstBefore(And, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002396 return BinaryOperator::createXor(And, Together);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002397 }
2398 break;
2399 case Instruction::Or:
Chris Lattner86102b82005-01-01 16:22:27 +00002400 if (Together == AndRHS) // (X | C) & C --> C
2401 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002402
Chris Lattner86102b82005-01-01 16:22:27 +00002403 if (Op->hasOneUse() && Together != OpRHS) {
2404 // (X | C1) & C2 --> (X | (C1&C2)) & C2
2405 std::string Op0Name = Op->getName(); Op->setName("");
2406 Instruction *Or = BinaryOperator::createOr(X, Together, Op0Name);
2407 InsertNewInstBefore(Or, TheAnd);
2408 return BinaryOperator::createAnd(Or, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002409 }
2410 break;
2411 case Instruction::Add:
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002412 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00002413 // Adding a one to a single bit bit-field should be turned into an XOR
2414 // of the bit. First thing to check is to see if this AND is with a
2415 // single bit constant.
Chris Lattner35167c32004-06-09 07:59:58 +00002416 uint64_t AndRHSV = cast<ConstantInt>(AndRHS)->getRawValue();
Chris Lattnerba1cb382003-09-19 17:17:26 +00002417
2418 // Clear bits that are not part of the constant.
Chris Lattner77defba2006-02-07 07:00:41 +00002419 AndRHSV &= AndRHS->getType()->getIntegralTypeMask();
Chris Lattnerba1cb382003-09-19 17:17:26 +00002420
2421 // If there is only one bit set...
Chris Lattner35167c32004-06-09 07:59:58 +00002422 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00002423 // Ok, at this point, we know that we are masking the result of the
2424 // ADD down to exactly one bit. If the constant we are adding has
2425 // no bits set below this bit, then we can eliminate the ADD.
Chris Lattner35167c32004-06-09 07:59:58 +00002426 uint64_t AddRHS = cast<ConstantInt>(OpRHS)->getRawValue();
Misha Brukmanb1c93172005-04-21 23:48:37 +00002427
Chris Lattnerba1cb382003-09-19 17:17:26 +00002428 // Check to see if any bits below the one bit set in AndRHSV are set.
2429 if ((AddRHS & (AndRHSV-1)) == 0) {
2430 // If not, the only thing that can effect the output of the AND is
2431 // the bit specified by AndRHSV. If that bit is set, the effect of
2432 // the XOR is to toggle the bit. If it is clear, then the ADD has
2433 // no effect.
2434 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
2435 TheAnd.setOperand(0, X);
2436 return &TheAnd;
2437 } else {
2438 std::string Name = Op->getName(); Op->setName("");
2439 // Pull the XOR out of the AND.
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002440 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS, Name);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002441 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002442 return BinaryOperator::createXor(NewAnd, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002443 }
2444 }
2445 }
2446 }
2447 break;
Chris Lattner2da29172003-09-19 19:05:02 +00002448
2449 case Instruction::Shl: {
2450 // We know that the AND will not produce any of the bits shifted in, so if
2451 // the anded constant includes them, clear them now!
2452 //
2453 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner7e794272004-09-24 15:21:34 +00002454 Constant *ShlMask = ConstantExpr::getShl(AllOne, OpRHS);
2455 Constant *CI = ConstantExpr::getAnd(AndRHS, ShlMask);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002456
Chris Lattner7e794272004-09-24 15:21:34 +00002457 if (CI == ShlMask) { // Masking out bits that the shift already masks
2458 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
2459 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner2da29172003-09-19 19:05:02 +00002460 TheAnd.setOperand(1, CI);
2461 return &TheAnd;
2462 }
2463 break;
Misha Brukmanb1c93172005-04-21 23:48:37 +00002464 }
Chris Lattner2da29172003-09-19 19:05:02 +00002465 case Instruction::Shr:
2466 // We know that the AND will not produce any of the bits shifted in, so if
2467 // the anded constant includes them, clear them now! This only applies to
2468 // unsigned shifts, because a signed shr may bring in set bits!
2469 //
2470 if (AndRHS->getType()->isUnsigned()) {
2471 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner7e794272004-09-24 15:21:34 +00002472 Constant *ShrMask = ConstantExpr::getShr(AllOne, OpRHS);
2473 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
2474
2475 if (CI == ShrMask) { // Masking out bits that the shift already masks.
2476 return ReplaceInstUsesWith(TheAnd, Op);
2477 } else if (CI != AndRHS) {
2478 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
Chris Lattner2da29172003-09-19 19:05:02 +00002479 return &TheAnd;
2480 }
Chris Lattner7e794272004-09-24 15:21:34 +00002481 } else { // Signed shr.
2482 // See if this is shifting in some sign extension, then masking it out
2483 // with an and.
2484 if (Op->hasOneUse()) {
2485 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
2486 Constant *ShrMask = ConstantExpr::getUShr(AllOne, OpRHS);
2487 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
Chris Lattner5c3c21e2004-10-22 04:53:16 +00002488 if (CI == AndRHS) { // Masking out bits shifted in.
Chris Lattner7e794272004-09-24 15:21:34 +00002489 // Make the argument unsigned.
2490 Value *ShVal = Op->getOperand(0);
2491 ShVal = InsertCastBefore(ShVal,
2492 ShVal->getType()->getUnsignedVersion(),
2493 TheAnd);
2494 ShVal = InsertNewInstBefore(new ShiftInst(Instruction::Shr, ShVal,
2495 OpRHS, Op->getName()),
2496 TheAnd);
Chris Lattner70c20392004-10-27 05:57:15 +00002497 Value *AndRHS2 = ConstantExpr::getCast(AndRHS, ShVal->getType());
2498 ShVal = InsertNewInstBefore(BinaryOperator::createAnd(ShVal, AndRHS2,
2499 TheAnd.getName()),
2500 TheAnd);
Chris Lattner7e794272004-09-24 15:21:34 +00002501 return new CastInst(ShVal, Op->getType());
2502 }
2503 }
Chris Lattner2da29172003-09-19 19:05:02 +00002504 }
2505 break;
Chris Lattnerba1cb382003-09-19 17:17:26 +00002506 }
2507 return 0;
2508}
2509
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002510
Chris Lattner6862fbd2004-09-29 17:40:11 +00002511/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
2512/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
2513/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. IB is the location to
2514/// insert new instructions.
2515Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
2516 bool Inside, Instruction &IB) {
2517 assert(cast<ConstantBool>(ConstantExpr::getSetLE(Lo, Hi))->getValue() &&
2518 "Lo is not <= Hi in range emission code!");
2519 if (Inside) {
2520 if (Lo == Hi) // Trivially false.
2521 return new SetCondInst(Instruction::SetNE, V, V);
2522 if (cast<ConstantIntegral>(Lo)->isMinValue())
2523 return new SetCondInst(Instruction::SetLT, V, Hi);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002524
Chris Lattner6862fbd2004-09-29 17:40:11 +00002525 Constant *AddCST = ConstantExpr::getNeg(Lo);
2526 Instruction *Add = BinaryOperator::createAdd(V, AddCST,V->getName()+".off");
2527 InsertNewInstBefore(Add, IB);
2528 // Convert to unsigned for the comparison.
2529 const Type *UnsType = Add->getType()->getUnsignedVersion();
2530 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
2531 AddCST = ConstantExpr::getAdd(AddCST, Hi);
2532 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2533 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
2534 }
2535
2536 if (Lo == Hi) // Trivially true.
2537 return new SetCondInst(Instruction::SetEQ, V, V);
2538
2539 Hi = SubOne(cast<ConstantInt>(Hi));
2540 if (cast<ConstantIntegral>(Lo)->isMinValue()) // V < 0 || V >= Hi ->'V > Hi-1'
2541 return new SetCondInst(Instruction::SetGT, V, Hi);
2542
2543 // Emit X-Lo > Hi-Lo-1
2544 Constant *AddCST = ConstantExpr::getNeg(Lo);
2545 Instruction *Add = BinaryOperator::createAdd(V, AddCST, V->getName()+".off");
2546 InsertNewInstBefore(Add, IB);
2547 // Convert to unsigned for the comparison.
2548 const Type *UnsType = Add->getType()->getUnsignedVersion();
2549 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
2550 AddCST = ConstantExpr::getAdd(AddCST, Hi);
2551 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2552 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
2553}
2554
Chris Lattnerb4b25302005-09-18 07:22:02 +00002555// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
2556// any number of 0s on either side. The 1s are allowed to wrap from LSB to
2557// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
2558// not, since all 1s are not contiguous.
2559static bool isRunOfOnes(ConstantIntegral *Val, unsigned &MB, unsigned &ME) {
2560 uint64_t V = Val->getRawValue();
2561 if (!isShiftedMask_64(V)) return false;
2562
2563 // look for the first zero bit after the run of ones
2564 MB = 64-CountLeadingZeros_64((V - 1) ^ V);
2565 // look for the first non-zero bit
2566 ME = 64-CountLeadingZeros_64(V);
2567 return true;
2568}
2569
2570
2571
2572/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
2573/// where isSub determines whether the operator is a sub. If we can fold one of
2574/// the following xforms:
Chris Lattneraf517572005-09-18 04:24:45 +00002575///
2576/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
2577/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
2578/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
2579///
2580/// return (A +/- B).
2581///
2582Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
2583 ConstantIntegral *Mask, bool isSub,
2584 Instruction &I) {
2585 Instruction *LHSI = dyn_cast<Instruction>(LHS);
2586 if (!LHSI || LHSI->getNumOperands() != 2 ||
2587 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
2588
2589 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
2590
2591 switch (LHSI->getOpcode()) {
2592 default: return 0;
2593 case Instruction::And:
Chris Lattnerb4b25302005-09-18 07:22:02 +00002594 if (ConstantExpr::getAnd(N, Mask) == Mask) {
2595 // If the AndRHS is a power of two minus one (0+1+), this is simple.
2596 if ((Mask->getRawValue() & Mask->getRawValue()+1) == 0)
2597 break;
2598
2599 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
2600 // part, we don't need any explicit masks to take them out of A. If that
2601 // is all N is, ignore it.
2602 unsigned MB, ME;
2603 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Chris Lattnerc3ebf402006-02-07 07:27:52 +00002604 uint64_t Mask = RHS->getType()->getIntegralTypeMask();
2605 Mask >>= 64-MB+1;
2606 if (MaskedValueIsZero(RHS, Mask))
Chris Lattnerb4b25302005-09-18 07:22:02 +00002607 break;
2608 }
2609 }
Chris Lattneraf517572005-09-18 04:24:45 +00002610 return 0;
2611 case Instruction::Or:
2612 case Instruction::Xor:
Chris Lattnerb4b25302005-09-18 07:22:02 +00002613 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
2614 if ((Mask->getRawValue() & Mask->getRawValue()+1) == 0 &&
2615 ConstantExpr::getAnd(N, Mask)->isNullValue())
Chris Lattneraf517572005-09-18 04:24:45 +00002616 break;
2617 return 0;
2618 }
2619
2620 Instruction *New;
2621 if (isSub)
2622 New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
2623 else
2624 New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
2625 return InsertNewInstBefore(New, I);
2626}
2627
Chris Lattner113f4f42002-06-25 16:13:24 +00002628Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00002629 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00002630 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002631
Chris Lattner81a7a232004-10-16 18:11:37 +00002632 if (isa<UndefValue>(Op1)) // X & undef -> 0
2633 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2634
Chris Lattner86102b82005-01-01 16:22:27 +00002635 // and X, X = X
2636 if (Op0 == Op1)
Chris Lattnere6794492002-08-12 21:17:25 +00002637 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002638
Chris Lattner5b2edb12006-02-12 08:02:11 +00002639 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner5997cf92006-02-08 03:25:32 +00002640 // purpose is to compute bits we don't care about.
Chris Lattner0157e7f2006-02-11 09:31:47 +00002641 uint64_t KnownZero, KnownOne;
Chris Lattnerd70d9f52006-03-25 21:58:26 +00002642 if (!isa<PackedType>(I.getType()) &&
2643 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
Chris Lattner0157e7f2006-02-11 09:31:47 +00002644 KnownZero, KnownOne))
Chris Lattner5997cf92006-02-08 03:25:32 +00002645 return &I;
2646
Chris Lattner86102b82005-01-01 16:22:27 +00002647 if (ConstantIntegral *AndRHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00002648 uint64_t AndRHSMask = AndRHS->getZExtValue();
2649 uint64_t TypeMask = Op0->getType()->getIntegralTypeMask();
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00002650 uint64_t NotAndRHS = AndRHSMask^TypeMask;
Chris Lattner86102b82005-01-01 16:22:27 +00002651
Chris Lattnerba1cb382003-09-19 17:17:26 +00002652 // Optimize a variety of ((val OP C1) & C2) combinations...
2653 if (isa<BinaryOperator>(Op0) || isa<ShiftInst>(Op0)) {
2654 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner86102b82005-01-01 16:22:27 +00002655 Value *Op0LHS = Op0I->getOperand(0);
2656 Value *Op0RHS = Op0I->getOperand(1);
2657 switch (Op0I->getOpcode()) {
2658 case Instruction::Xor:
2659 case Instruction::Or:
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00002660 // If the mask is only needed on one incoming arm, push it up.
2661 if (Op0I->hasOneUse()) {
2662 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
2663 // Not masking anything out for the LHS, move to RHS.
2664 Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
2665 Op0RHS->getName()+".masked");
2666 InsertNewInstBefore(NewRHS, I);
2667 return BinaryOperator::create(
2668 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002669 }
Chris Lattnerc3ebf402006-02-07 07:27:52 +00002670 if (!isa<Constant>(Op0RHS) &&
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00002671 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
2672 // Not masking anything out for the RHS, move to LHS.
2673 Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
2674 Op0LHS->getName()+".masked");
2675 InsertNewInstBefore(NewLHS, I);
2676 return BinaryOperator::create(
2677 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
2678 }
2679 }
2680
Chris Lattner86102b82005-01-01 16:22:27 +00002681 break;
Chris Lattneraf517572005-09-18 04:24:45 +00002682 case Instruction::Add:
Chris Lattnerb4b25302005-09-18 07:22:02 +00002683 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
2684 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
2685 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
2686 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
2687 return BinaryOperator::createAnd(V, AndRHS);
2688 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
2689 return BinaryOperator::createAnd(V, AndRHS); // Add commutes
Chris Lattneraf517572005-09-18 04:24:45 +00002690 break;
2691
2692 case Instruction::Sub:
Chris Lattnerb4b25302005-09-18 07:22:02 +00002693 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
2694 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
2695 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
2696 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
2697 return BinaryOperator::createAnd(V, AndRHS);
Chris Lattneraf517572005-09-18 04:24:45 +00002698 break;
Chris Lattner86102b82005-01-01 16:22:27 +00002699 }
2700
Chris Lattner16464b32003-07-23 19:25:52 +00002701 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner86102b82005-01-01 16:22:27 +00002702 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerba1cb382003-09-19 17:17:26 +00002703 return Res;
Chris Lattner86102b82005-01-01 16:22:27 +00002704 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
2705 const Type *SrcTy = CI->getOperand(0)->getType();
2706
Chris Lattner2c14cf72005-08-07 07:03:10 +00002707 // If this is an integer truncation or change from signed-to-unsigned, and
2708 // if the source is an and/or with immediate, transform it. This
2709 // frequently occurs for bitfield accesses.
2710 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
2711 if (SrcTy->getPrimitiveSizeInBits() >=
2712 I.getType()->getPrimitiveSizeInBits() &&
2713 CastOp->getNumOperands() == 2)
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00002714 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1)))
Chris Lattner2c14cf72005-08-07 07:03:10 +00002715 if (CastOp->getOpcode() == Instruction::And) {
2716 // Change: and (cast (and X, C1) to T), C2
2717 // into : and (cast X to T), trunc(C1)&C2
2718 // This will folds the two ands together, which may allow other
2719 // simplifications.
2720 Instruction *NewCast =
2721 new CastInst(CastOp->getOperand(0), I.getType(),
2722 CastOp->getName()+".shrunk");
2723 NewCast = InsertNewInstBefore(NewCast, I);
2724
2725 Constant *C3=ConstantExpr::getCast(AndCI, I.getType());//trunc(C1)
2726 C3 = ConstantExpr::getAnd(C3, AndRHS); // trunc(C1)&C2
2727 return BinaryOperator::createAnd(NewCast, C3);
2728 } else if (CastOp->getOpcode() == Instruction::Or) {
2729 // Change: and (cast (or X, C1) to T), C2
2730 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
2731 Constant *C3=ConstantExpr::getCast(AndCI, I.getType());//trunc(C1)
2732 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
2733 return ReplaceInstUsesWith(I, AndRHS);
2734 }
2735 }
Chris Lattner33217db2003-07-23 19:36:21 +00002736 }
Chris Lattner183b3362004-04-09 19:05:30 +00002737
2738 // Try to fold constant and into select arguments.
2739 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00002740 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00002741 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002742 if (isa<PHINode>(Op0))
2743 if (Instruction *NV = FoldOpIntoPhi(I))
2744 return NV;
Chris Lattner49b47ae2003-07-23 17:57:01 +00002745 }
2746
Chris Lattnerbb74e222003-03-10 23:06:50 +00002747 Value *Op0NotVal = dyn_castNotVal(Op0);
2748 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002749
Chris Lattner023a4832004-06-18 06:07:51 +00002750 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
2751 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2752
Misha Brukman9c003d82004-07-30 12:50:08 +00002753 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattnerbb74e222003-03-10 23:06:50 +00002754 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002755 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
2756 I.getName()+".demorgan");
Chris Lattner49b47ae2003-07-23 17:57:01 +00002757 InsertNewInstBefore(Or, I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002758 return BinaryOperator::createNot(Or);
2759 }
Chris Lattner8b10ab32006-02-13 23:07:23 +00002760
2761 {
2762 Value *A = 0, *B = 0;
2763 ConstantInt *C1 = 0, *C2 = 0;
2764 if (match(Op0, m_Or(m_Value(A), m_Value(B))))
2765 if (A == Op1 || B == Op1) // (A | ?) & A --> A
2766 return ReplaceInstUsesWith(I, Op1);
2767 if (match(Op1, m_Or(m_Value(A), m_Value(B))))
2768 if (A == Op0 || B == Op0) // A & (A | ?) --> A
2769 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerdcd07922006-04-01 08:03:55 +00002770
2771 if (Op0->hasOneUse() &&
2772 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
2773 if (A == Op1) { // (A^B)&A -> A&(A^B)
2774 I.swapOperands(); // Simplify below
2775 std::swap(Op0, Op1);
2776 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
2777 cast<BinaryOperator>(Op0)->swapOperands();
2778 I.swapOperands(); // Simplify below
2779 std::swap(Op0, Op1);
2780 }
2781 }
2782 if (Op1->hasOneUse() &&
2783 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
2784 if (B == Op0) { // B&(A^B) -> B&(B^A)
2785 cast<BinaryOperator>(Op1)->swapOperands();
2786 std::swap(A, B);
2787 }
2788 if (A == Op0) { // A&(A^B) -> A & ~B
2789 Instruction *NotB = BinaryOperator::createNot(B, "tmp");
2790 InsertNewInstBefore(NotB, I);
2791 return BinaryOperator::createAnd(A, NotB);
2792 }
2793 }
Chris Lattner8b10ab32006-02-13 23:07:23 +00002794 }
2795
Chris Lattner3082c5a2003-02-18 19:28:33 +00002796
Chris Lattner623826c2004-09-28 21:48:02 +00002797 if (SetCondInst *RHS = dyn_cast<SetCondInst>(Op1)) {
2798 // (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
Chris Lattner3ac7c262003-08-13 20:16:26 +00002799 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
2800 return R;
2801
Chris Lattner623826c2004-09-28 21:48:02 +00002802 Value *LHSVal, *RHSVal;
2803 ConstantInt *LHSCst, *RHSCst;
2804 Instruction::BinaryOps LHSCC, RHSCC;
2805 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
2806 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
2807 if (LHSVal == RHSVal && // Found (X setcc C1) & (X setcc C2)
2808 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
Misha Brukmanb1c93172005-04-21 23:48:37 +00002809 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
Chris Lattner623826c2004-09-28 21:48:02 +00002810 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
2811 // Ensure that the larger constant is on the RHS.
2812 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
2813 SetCondInst *LHS = cast<SetCondInst>(Op0);
2814 if (cast<ConstantBool>(Cmp)->getValue()) {
2815 std::swap(LHS, RHS);
2816 std::swap(LHSCst, RHSCst);
2817 std::swap(LHSCC, RHSCC);
2818 }
2819
2820 // At this point, we know we have have two setcc instructions
2821 // comparing a value against two constants and and'ing the result
2822 // together. Because of the above check, we know that we only have
2823 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
2824 // FoldSetCCLogical check above), that the two constants are not
2825 // equal.
2826 assert(LHSCst != RHSCst && "Compares not folded above?");
2827
2828 switch (LHSCC) {
2829 default: assert(0 && "Unknown integer condition code!");
2830 case Instruction::SetEQ:
2831 switch (RHSCC) {
2832 default: assert(0 && "Unknown integer condition code!");
2833 case Instruction::SetEQ: // (X == 13 & X == 15) -> false
2834 case Instruction::SetGT: // (X == 13 & X > 15) -> false
2835 return ReplaceInstUsesWith(I, ConstantBool::False);
2836 case Instruction::SetNE: // (X == 13 & X != 15) -> X == 13
2837 case Instruction::SetLT: // (X == 13 & X < 15) -> X == 13
2838 return ReplaceInstUsesWith(I, LHS);
2839 }
2840 case Instruction::SetNE:
2841 switch (RHSCC) {
2842 default: assert(0 && "Unknown integer condition code!");
2843 case Instruction::SetLT:
2844 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X < 14) -> X < 13
2845 return new SetCondInst(Instruction::SetLT, LHSVal, LHSCst);
2846 break; // (X != 13 & X < 15) -> no change
2847 case Instruction::SetEQ: // (X != 13 & X == 15) -> X == 15
2848 case Instruction::SetGT: // (X != 13 & X > 15) -> X > 15
2849 return ReplaceInstUsesWith(I, RHS);
2850 case Instruction::SetNE:
2851 if (LHSCst == SubOne(RHSCst)) {// (X != 13 & X != 14) -> X-13 >u 1
2852 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
2853 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
2854 LHSVal->getName()+".off");
2855 InsertNewInstBefore(Add, I);
2856 const Type *UnsType = Add->getType()->getUnsignedVersion();
2857 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
2858 AddCST = ConstantExpr::getSub(RHSCst, LHSCst);
2859 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2860 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
2861 }
2862 break; // (X != 13 & X != 15) -> no change
2863 }
2864 break;
2865 case Instruction::SetLT:
2866 switch (RHSCC) {
2867 default: assert(0 && "Unknown integer condition code!");
2868 case Instruction::SetEQ: // (X < 13 & X == 15) -> false
2869 case Instruction::SetGT: // (X < 13 & X > 15) -> false
2870 return ReplaceInstUsesWith(I, ConstantBool::False);
2871 case Instruction::SetNE: // (X < 13 & X != 15) -> X < 13
2872 case Instruction::SetLT: // (X < 13 & X < 15) -> X < 13
2873 return ReplaceInstUsesWith(I, LHS);
2874 }
2875 case Instruction::SetGT:
2876 switch (RHSCC) {
2877 default: assert(0 && "Unknown integer condition code!");
2878 case Instruction::SetEQ: // (X > 13 & X == 15) -> X > 13
2879 return ReplaceInstUsesWith(I, LHS);
2880 case Instruction::SetGT: // (X > 13 & X > 15) -> X > 15
2881 return ReplaceInstUsesWith(I, RHS);
2882 case Instruction::SetNE:
2883 if (RHSCst == AddOne(LHSCst)) // (X > 13 & X != 14) -> X > 14
2884 return new SetCondInst(Instruction::SetGT, LHSVal, RHSCst);
2885 break; // (X > 13 & X != 15) -> no change
Chris Lattner6862fbd2004-09-29 17:40:11 +00002886 case Instruction::SetLT: // (X > 13 & X < 15) -> (X-14) <u 1
2887 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true, I);
Chris Lattner623826c2004-09-28 21:48:02 +00002888 }
2889 }
2890 }
2891 }
2892
Chris Lattner3af10532006-05-05 06:39:07 +00002893 // fold (and (cast A), (cast B)) -> (cast (and A, B))
2894 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattnere745c7d2006-05-05 20:51:30 +00002895 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner3af10532006-05-05 06:39:07 +00002896 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Chris Lattnere745c7d2006-05-05 20:51:30 +00002897 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegral() &&
Chris Lattner1d441ad2006-05-06 09:00:16 +00002898 // Only do this if the casts both really cause code to be generated.
2899 ValueRequiresCast(Op0C->getOperand(0), I.getType(), TD) &&
2900 ValueRequiresCast(Op1C->getOperand(0), I.getType(), TD)) {
Chris Lattner3af10532006-05-05 06:39:07 +00002901 Instruction *NewOp = BinaryOperator::createAnd(Op0C->getOperand(0),
2902 Op1C->getOperand(0),
2903 I.getName());
2904 InsertNewInstBefore(NewOp, I);
2905 return new CastInst(NewOp, I.getType());
2906 }
2907 }
2908
Chris Lattner113f4f42002-06-25 16:13:24 +00002909 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002910}
2911
Chris Lattnerc482a9e2006-06-15 19:07:26 +00002912/// CollectBSwapParts - Look to see if the specified value defines a single byte
2913/// in the result. If it does, and if the specified byte hasn't been filled in
2914/// yet, fill it in and return false.
2915static bool CollectBSwapParts(Value *V, std::vector<Value*> &ByteValues) {
2916 Instruction *I = dyn_cast<Instruction>(V);
2917 if (I == 0) return true;
2918
2919 // If this is an or instruction, it is an inner node of the bswap.
2920 if (I->getOpcode() == Instruction::Or)
2921 return CollectBSwapParts(I->getOperand(0), ByteValues) ||
2922 CollectBSwapParts(I->getOperand(1), ByteValues);
2923
2924 // If this is a shift by a constant int, and it is "24", then its operand
2925 // defines a byte. We only handle unsigned types here.
2926 if (isa<ShiftInst>(I) && isa<ConstantInt>(I->getOperand(1))) {
2927 // Not shifting the entire input by N-1 bytes?
2928 if (cast<ConstantInt>(I->getOperand(1))->getRawValue() !=
2929 8*(ByteValues.size()-1))
2930 return true;
2931
2932 unsigned DestNo;
2933 if (I->getOpcode() == Instruction::Shl) {
2934 // X << 24 defines the top byte with the lowest of the input bytes.
2935 DestNo = ByteValues.size()-1;
2936 } else {
2937 // X >>u 24 defines the low byte with the highest of the input bytes.
2938 DestNo = 0;
2939 }
2940
2941 // If the destination byte value is already defined, the values are or'd
2942 // together, which isn't a bswap (unless it's an or of the same bits).
2943 if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
2944 return true;
2945 ByteValues[DestNo] = I->getOperand(0);
2946 return false;
2947 }
2948
2949 // Otherwise, we can only handle and(shift X, imm), imm). Bail out of if we
2950 // don't have this.
2951 Value *Shift = 0, *ShiftLHS = 0;
2952 ConstantInt *AndAmt = 0, *ShiftAmt = 0;
2953 if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
2954 !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
2955 return true;
2956 Instruction *SI = cast<Instruction>(Shift);
2957
2958 // Make sure that the shift amount is by a multiple of 8 and isn't too big.
2959 if (ShiftAmt->getRawValue() & 7 ||
2960 ShiftAmt->getRawValue() > 8*ByteValues.size())
2961 return true;
2962
2963 // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
2964 unsigned DestByte;
2965 for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
2966 if (AndAmt->getRawValue() == uint64_t(0xFF) << 8*DestByte)
2967 break;
2968 // Unknown mask for bswap.
2969 if (DestByte == ByteValues.size()) return true;
2970
2971 unsigned ShiftBytes = ShiftAmt->getRawValue()/8;
2972 unsigned SrcByte;
2973 if (SI->getOpcode() == Instruction::Shl)
2974 SrcByte = DestByte - ShiftBytes;
2975 else
2976 SrcByte = DestByte + ShiftBytes;
2977
2978 // If the SrcByte isn't a bswapped value from the DestByte, reject it.
2979 if (SrcByte != ByteValues.size()-DestByte-1)
2980 return true;
2981
2982 // If the destination byte value is already defined, the values are or'd
2983 // together, which isn't a bswap (unless it's an or of the same bits).
2984 if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
2985 return true;
2986 ByteValues[DestByte] = SI->getOperand(0);
2987 return false;
2988}
2989
2990/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
2991/// If so, insert the new bswap intrinsic and return it.
2992Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
2993 // We can only handle bswap of unsigned integers, and cannot bswap one byte.
2994 if (!I.getType()->isUnsigned() || I.getType() == Type::UByteTy)
2995 return 0;
2996
2997 /// ByteValues - For each byte of the result, we keep track of which value
2998 /// defines each byte.
2999 std::vector<Value*> ByteValues;
3000 ByteValues.resize(I.getType()->getPrimitiveSize());
3001
3002 // Try to find all the pieces corresponding to the bswap.
3003 if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
3004 CollectBSwapParts(I.getOperand(1), ByteValues))
3005 return 0;
3006
3007 // Check to see if all of the bytes come from the same value.
3008 Value *V = ByteValues[0];
3009 if (V == 0) return 0; // Didn't find a byte? Must be zero.
3010
3011 // Check to make sure that all of the bytes come from the same value.
3012 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
3013 if (ByteValues[i] != V)
3014 return 0;
3015
3016 // If they do then *success* we can turn this into a bswap. Figure out what
3017 // bswap to make it into.
3018 Module *M = I.getParent()->getParent()->getParent();
Chris Lattner091b6ea2006-07-11 18:31:26 +00003019 const char *FnName = 0;
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003020 if (I.getType() == Type::UShortTy)
3021 FnName = "llvm.bswap.i16";
3022 else if (I.getType() == Type::UIntTy)
3023 FnName = "llvm.bswap.i32";
3024 else if (I.getType() == Type::ULongTy)
3025 FnName = "llvm.bswap.i64";
3026 else
3027 assert(0 && "Unknown integer type!");
3028 Function *F = M->getOrInsertFunction(FnName, I.getType(), I.getType(), NULL);
3029
3030 return new CallInst(F, V);
3031}
3032
3033
Chris Lattner113f4f42002-06-25 16:13:24 +00003034Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003035 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00003036 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003037
Chris Lattner81a7a232004-10-16 18:11:37 +00003038 if (isa<UndefValue>(Op1))
3039 return ReplaceInstUsesWith(I, // X | undef -> -1
3040 ConstantIntegral::getAllOnesValue(I.getType()));
3041
Chris Lattner5b2edb12006-02-12 08:02:11 +00003042 // or X, X = X
3043 if (Op0 == Op1)
Chris Lattnere6794492002-08-12 21:17:25 +00003044 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003045
Chris Lattner5b2edb12006-02-12 08:02:11 +00003046 // See if we can simplify any instructions used by the instruction whose sole
3047 // purpose is to compute bits we don't care about.
3048 uint64_t KnownZero, KnownOne;
Chris Lattnerd70d9f52006-03-25 21:58:26 +00003049 if (!isa<PackedType>(I.getType()) &&
3050 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
Chris Lattner5b2edb12006-02-12 08:02:11 +00003051 KnownZero, KnownOne))
3052 return &I;
3053
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003054 // or X, -1 == -1
Chris Lattner8f0d1562003-07-23 18:29:44 +00003055 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner330628a2006-01-06 17:59:59 +00003056 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00003057 // (X & C1) | C2 --> (X | C2) & (C1|C2)
3058 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Chris Lattnerb62f5082005-05-09 04:58:36 +00003059 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0->getName());
3060 Op0->setName("");
Chris Lattnerd4252a72004-07-30 07:50:03 +00003061 InsertNewInstBefore(Or, I);
3062 return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, C1));
3063 }
Chris Lattner8f0d1562003-07-23 18:29:44 +00003064
Chris Lattnerd4252a72004-07-30 07:50:03 +00003065 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
3066 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
3067 std::string Op0Name = Op0->getName(); Op0->setName("");
3068 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
3069 InsertNewInstBefore(Or, I);
3070 return BinaryOperator::createXor(Or,
3071 ConstantExpr::getAnd(C1, ConstantExpr::getNot(RHS)));
Chris Lattner8f0d1562003-07-23 18:29:44 +00003072 }
Chris Lattner183b3362004-04-09 19:05:30 +00003073
3074 // Try to fold constant and into select arguments.
3075 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00003076 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00003077 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00003078 if (isa<PHINode>(Op0))
3079 if (Instruction *NV = FoldOpIntoPhi(I))
3080 return NV;
Chris Lattner8f0d1562003-07-23 18:29:44 +00003081 }
3082
Chris Lattner330628a2006-01-06 17:59:59 +00003083 Value *A = 0, *B = 0;
3084 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattner4294cec2005-05-07 23:49:08 +00003085
3086 if (match(Op0, m_And(m_Value(A), m_Value(B))))
3087 if (A == Op1 || B == Op1) // (A & ?) | A --> A
3088 return ReplaceInstUsesWith(I, Op1);
3089 if (match(Op1, m_And(m_Value(A), m_Value(B))))
3090 if (A == Op0 || B == Op0) // A | (A & ?) --> A
3091 return ReplaceInstUsesWith(I, Op0);
3092
Chris Lattnerb7845d62006-07-10 20:25:24 +00003093 // (A | B) | C and A | (B | C) -> bswap if possible.
3094 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003095 if (match(Op0, m_Or(m_Value(), m_Value())) ||
Chris Lattnerb7845d62006-07-10 20:25:24 +00003096 match(Op1, m_Or(m_Value(), m_Value())) ||
3097 (match(Op0, m_Shift(m_Value(), m_Value())) &&
3098 match(Op1, m_Shift(m_Value(), m_Value())))) {
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003099 if (Instruction *BSwap = MatchBSwap(I))
3100 return BSwap;
3101 }
3102
Chris Lattnerb62f5082005-05-09 04:58:36 +00003103 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
3104 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003105 MaskedValueIsZero(Op1, C1->getZExtValue())) {
Chris Lattnerb62f5082005-05-09 04:58:36 +00003106 Instruction *NOr = BinaryOperator::createOr(A, Op1, Op0->getName());
3107 Op0->setName("");
3108 return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
3109 }
3110
3111 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
3112 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003113 MaskedValueIsZero(Op0, C1->getZExtValue())) {
Chris Lattnerb62f5082005-05-09 04:58:36 +00003114 Instruction *NOr = BinaryOperator::createOr(A, Op0, Op1->getName());
3115 Op0->setName("");
3116 return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
3117 }
3118
Chris Lattner15212982005-09-18 03:42:07 +00003119 // (A & C1)|(B & C2)
Chris Lattnerd4252a72004-07-30 07:50:03 +00003120 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattner15212982005-09-18 03:42:07 +00003121 match(Op1, m_And(m_Value(B), m_ConstantInt(C2)))) {
3122
3123 if (A == B) // (A & C1)|(A & C2) == A & (C1|C2)
3124 return BinaryOperator::createAnd(A, ConstantExpr::getOr(C1, C2));
3125
3126
Chris Lattner01f56c62005-09-18 06:02:59 +00003127 // If we have: ((V + N) & C1) | (V & C2)
3128 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
3129 // replace with V+N.
3130 if (C1 == ConstantExpr::getNot(C2)) {
Chris Lattner330628a2006-01-06 17:59:59 +00003131 Value *V1 = 0, *V2 = 0;
Chris Lattner01f56c62005-09-18 06:02:59 +00003132 if ((C2->getRawValue() & (C2->getRawValue()+1)) == 0 && // C2 == 0+1+
3133 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
3134 // Add commutes, try both ways.
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003135 if (V1 == B && MaskedValueIsZero(V2, C2->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003136 return ReplaceInstUsesWith(I, A);
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003137 if (V2 == B && MaskedValueIsZero(V1, C2->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003138 return ReplaceInstUsesWith(I, A);
3139 }
3140 // Or commutes, try both ways.
3141 if ((C1->getRawValue() & (C1->getRawValue()+1)) == 0 &&
3142 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
3143 // Add commutes, try both ways.
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003144 if (V1 == A && MaskedValueIsZero(V2, C1->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003145 return ReplaceInstUsesWith(I, B);
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003146 if (V2 == A && MaskedValueIsZero(V1, C1->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003147 return ReplaceInstUsesWith(I, B);
Chris Lattner15212982005-09-18 03:42:07 +00003148 }
3149 }
3150 }
Chris Lattner812aab72003-08-12 19:11:07 +00003151
Chris Lattnerd4252a72004-07-30 07:50:03 +00003152 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
3153 if (A == Op1) // ~A | A == -1
Misha Brukmanb1c93172005-04-21 23:48:37 +00003154 return ReplaceInstUsesWith(I,
Chris Lattnerd4252a72004-07-30 07:50:03 +00003155 ConstantIntegral::getAllOnesValue(I.getType()));
3156 } else {
3157 A = 0;
3158 }
Chris Lattner4294cec2005-05-07 23:49:08 +00003159 // Note, A is still live here!
Chris Lattnerd4252a72004-07-30 07:50:03 +00003160 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
3161 if (Op0 == B)
Misha Brukmanb1c93172005-04-21 23:48:37 +00003162 return ReplaceInstUsesWith(I,
Chris Lattnerd4252a72004-07-30 07:50:03 +00003163 ConstantIntegral::getAllOnesValue(I.getType()));
Chris Lattner3e327a42003-03-10 23:13:59 +00003164
Misha Brukman9c003d82004-07-30 12:50:08 +00003165 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattnerd4252a72004-07-30 07:50:03 +00003166 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3167 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
3168 I.getName()+".demorgan"), I);
3169 return BinaryOperator::createNot(And);
3170 }
Chris Lattner3e327a42003-03-10 23:13:59 +00003171 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00003172
Chris Lattner3ac7c262003-08-13 20:16:26 +00003173 // (setcc1 A, B) | (setcc2 A, B) --> (setcc3 A, B)
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003174 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1))) {
Chris Lattner3ac7c262003-08-13 20:16:26 +00003175 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
3176 return R;
3177
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003178 Value *LHSVal, *RHSVal;
3179 ConstantInt *LHSCst, *RHSCst;
3180 Instruction::BinaryOps LHSCC, RHSCC;
3181 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3182 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3183 if (LHSVal == RHSVal && // Found (X setcc C1) | (X setcc C2)
3184 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
Misha Brukmanb1c93172005-04-21 23:48:37 +00003185 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003186 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
3187 // Ensure that the larger constant is on the RHS.
3188 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
3189 SetCondInst *LHS = cast<SetCondInst>(Op0);
3190 if (cast<ConstantBool>(Cmp)->getValue()) {
3191 std::swap(LHS, RHS);
3192 std::swap(LHSCst, RHSCst);
3193 std::swap(LHSCC, RHSCC);
3194 }
3195
3196 // At this point, we know we have have two setcc instructions
3197 // comparing a value against two constants and or'ing the result
3198 // together. Because of the above check, we know that we only have
3199 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
3200 // FoldSetCCLogical check above), that the two constants are not
3201 // equal.
3202 assert(LHSCst != RHSCst && "Compares not folded above?");
3203
3204 switch (LHSCC) {
3205 default: assert(0 && "Unknown integer condition code!");
3206 case Instruction::SetEQ:
3207 switch (RHSCC) {
3208 default: assert(0 && "Unknown integer condition code!");
3209 case Instruction::SetEQ:
3210 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
3211 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3212 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3213 LHSVal->getName()+".off");
3214 InsertNewInstBefore(Add, I);
3215 const Type *UnsType = Add->getType()->getUnsignedVersion();
3216 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
3217 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
3218 AddCST = ConstantExpr::getCast(AddCST, UnsType);
3219 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
3220 }
3221 break; // (X == 13 | X == 15) -> no change
3222
Chris Lattner5c219462005-04-19 06:04:18 +00003223 case Instruction::SetGT: // (X == 13 | X > 14) -> no change
3224 break;
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003225 case Instruction::SetNE: // (X == 13 | X != 15) -> X != 15
3226 case Instruction::SetLT: // (X == 13 | X < 15) -> X < 15
3227 return ReplaceInstUsesWith(I, RHS);
3228 }
3229 break;
3230 case Instruction::SetNE:
3231 switch (RHSCC) {
3232 default: assert(0 && "Unknown integer condition code!");
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003233 case Instruction::SetEQ: // (X != 13 | X == 15) -> X != 13
3234 case Instruction::SetGT: // (X != 13 | X > 15) -> X != 13
3235 return ReplaceInstUsesWith(I, LHS);
3236 case Instruction::SetNE: // (X != 13 | X != 15) -> true
Chris Lattner2ceb6ee2005-06-17 03:59:17 +00003237 case Instruction::SetLT: // (X != 13 | X < 15) -> true
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003238 return ReplaceInstUsesWith(I, ConstantBool::True);
3239 }
3240 break;
3241 case Instruction::SetLT:
3242 switch (RHSCC) {
3243 default: assert(0 && "Unknown integer condition code!");
3244 case Instruction::SetEQ: // (X < 13 | X == 14) -> no change
3245 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00003246 case Instruction::SetGT: // (X < 13 | X > 15) -> (X-13) > 2
3247 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false, I);
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003248 case Instruction::SetNE: // (X < 13 | X != 15) -> X != 15
3249 case Instruction::SetLT: // (X < 13 | X < 15) -> X < 15
3250 return ReplaceInstUsesWith(I, RHS);
3251 }
3252 break;
3253 case Instruction::SetGT:
3254 switch (RHSCC) {
3255 default: assert(0 && "Unknown integer condition code!");
3256 case Instruction::SetEQ: // (X > 13 | X == 15) -> X > 13
3257 case Instruction::SetGT: // (X > 13 | X > 15) -> X > 13
3258 return ReplaceInstUsesWith(I, LHS);
3259 case Instruction::SetNE: // (X > 13 | X != 15) -> true
3260 case Instruction::SetLT: // (X > 13 | X < 15) -> true
3261 return ReplaceInstUsesWith(I, ConstantBool::True);
3262 }
3263 }
3264 }
3265 }
Chris Lattner3af10532006-05-05 06:39:07 +00003266
3267 // fold (or (cast A), (cast B)) -> (cast (or A, B))
3268 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattnere745c7d2006-05-05 20:51:30 +00003269 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner3af10532006-05-05 06:39:07 +00003270 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Chris Lattnere745c7d2006-05-05 20:51:30 +00003271 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegral() &&
Chris Lattner1d441ad2006-05-06 09:00:16 +00003272 // Only do this if the casts both really cause code to be generated.
3273 ValueRequiresCast(Op0C->getOperand(0), I.getType(), TD) &&
3274 ValueRequiresCast(Op1C->getOperand(0), I.getType(), TD)) {
Chris Lattner3af10532006-05-05 06:39:07 +00003275 Instruction *NewOp = BinaryOperator::createOr(Op0C->getOperand(0),
3276 Op1C->getOperand(0),
3277 I.getName());
3278 InsertNewInstBefore(NewOp, I);
3279 return new CastInst(NewOp, I.getType());
3280 }
3281 }
3282
Chris Lattner15212982005-09-18 03:42:07 +00003283
Chris Lattner113f4f42002-06-25 16:13:24 +00003284 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003285}
3286
Chris Lattnerc2076352004-02-16 01:20:27 +00003287// XorSelf - Implements: X ^ X --> 0
3288struct XorSelf {
3289 Value *RHS;
3290 XorSelf(Value *rhs) : RHS(rhs) {}
3291 bool shouldApply(Value *LHS) const { return LHS == RHS; }
3292 Instruction *apply(BinaryOperator &Xor) const {
3293 return &Xor;
3294 }
3295};
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003296
3297
Chris Lattner113f4f42002-06-25 16:13:24 +00003298Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003299 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00003300 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003301
Chris Lattner81a7a232004-10-16 18:11:37 +00003302 if (isa<UndefValue>(Op1))
3303 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
3304
Chris Lattnerc2076352004-02-16 01:20:27 +00003305 // xor X, X = 0, even if X is nested in a sequence of Xor's.
3306 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
3307 assert(Result == &I && "AssociativeOpt didn't work?");
Chris Lattnere6794492002-08-12 21:17:25 +00003308 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc2076352004-02-16 01:20:27 +00003309 }
Chris Lattner5b2edb12006-02-12 08:02:11 +00003310
3311 // See if we can simplify any instructions used by the instruction whose sole
3312 // purpose is to compute bits we don't care about.
3313 uint64_t KnownZero, KnownOne;
Chris Lattnerd70d9f52006-03-25 21:58:26 +00003314 if (!isa<PackedType>(I.getType()) &&
3315 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
Chris Lattner5b2edb12006-02-12 08:02:11 +00003316 KnownZero, KnownOne))
3317 return &I;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003318
Chris Lattner97638592003-07-23 21:37:07 +00003319 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner97638592003-07-23 21:37:07 +00003320 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerb8d6e402002-08-20 18:24:26 +00003321 // xor (setcc A, B), true = not (setcc A, B) = setncc A, B
Chris Lattner97638592003-07-23 21:37:07 +00003322 if (SetCondInst *SCI = dyn_cast<SetCondInst>(Op0I))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00003323 if (RHS == ConstantBool::True && SCI->hasOneUse())
Chris Lattnerb8d6e402002-08-20 18:24:26 +00003324 return new SetCondInst(SCI->getInverseCondition(),
3325 SCI->getOperand(0), SCI->getOperand(1));
Chris Lattnere5806662003-11-04 23:50:51 +00003326
Chris Lattner8f2f5982003-11-05 01:06:05 +00003327 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003328 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
3329 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003330 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
3331 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003332 ConstantInt::get(I.getType(), 1));
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003333 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003334 }
Chris Lattner023a4832004-06-18 06:07:51 +00003335
3336 // ~(~X & Y) --> (X | ~Y)
3337 if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
3338 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
3339 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
3340 Instruction *NotY =
Misha Brukmanb1c93172005-04-21 23:48:37 +00003341 BinaryOperator::createNot(Op0I->getOperand(1),
Chris Lattner023a4832004-06-18 06:07:51 +00003342 Op0I->getOperand(1)->getName()+".not");
3343 InsertNewInstBefore(NotY, I);
3344 return BinaryOperator::createOr(Op0NotVal, NotY);
3345 }
3346 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003347
Chris Lattner97638592003-07-23 21:37:07 +00003348 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner5b2edb12006-02-12 08:02:11 +00003349 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner0f68fa62003-11-04 23:37:10 +00003350 // ~(X-c) --> (-c-1)-X
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003351 if (RHS->isAllOnesValue()) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003352 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
3353 return BinaryOperator::createSub(
3354 ConstantExpr::getSub(NegOp0CI,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003355 ConstantInt::get(I.getType(), 1)),
Chris Lattner0f68fa62003-11-04 23:37:10 +00003356 Op0I->getOperand(0));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003357 }
Chris Lattnerf78df7c2006-02-26 19:57:54 +00003358 } else if (Op0I->getOpcode() == Instruction::Or) {
3359 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
3360 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getZExtValue())) {
3361 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
3362 // Anything in both C1 and C2 is known to be zero, remove it from
3363 // NewRHS.
3364 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
3365 NewRHS = ConstantExpr::getAnd(NewRHS,
3366 ConstantExpr::getNot(CommonBits));
3367 WorkList.push_back(Op0I);
3368 I.setOperand(0, Op0I->getOperand(0));
3369 I.setOperand(1, NewRHS);
3370 return &I;
3371 }
Chris Lattner97638592003-07-23 21:37:07 +00003372 }
Chris Lattnerb8d6e402002-08-20 18:24:26 +00003373 }
Chris Lattner183b3362004-04-09 19:05:30 +00003374
3375 // Try to fold constant and into select arguments.
3376 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00003377 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00003378 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00003379 if (isa<PHINode>(Op0))
3380 if (Instruction *NV = FoldOpIntoPhi(I))
3381 return NV;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003382 }
3383
Chris Lattnerbb74e222003-03-10 23:06:50 +00003384 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00003385 if (X == Op1)
3386 return ReplaceInstUsesWith(I,
3387 ConstantIntegral::getAllOnesValue(I.getType()));
3388
Chris Lattnerbb74e222003-03-10 23:06:50 +00003389 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00003390 if (X == Op0)
3391 return ReplaceInstUsesWith(I,
3392 ConstantIntegral::getAllOnesValue(I.getType()));
3393
Chris Lattnerdcd07922006-04-01 08:03:55 +00003394 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1))
Chris Lattnerb36d9082004-02-16 03:54:20 +00003395 if (Op1I->getOpcode() == Instruction::Or) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003396 if (Op1I->getOperand(0) == Op0) { // B^(B|A) == (A|B)^B
Chris Lattnerdcd07922006-04-01 08:03:55 +00003397 Op1I->swapOperands();
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003398 I.swapOperands();
3399 std::swap(Op0, Op1);
3400 } else if (Op1I->getOperand(1) == Op0) { // B^(A|B) == (A|B)^B
Chris Lattnerdcd07922006-04-01 08:03:55 +00003401 I.swapOperands(); // Simplified below.
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003402 std::swap(Op0, Op1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003403 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00003404 } else if (Op1I->getOpcode() == Instruction::Xor) {
3405 if (Op0 == Op1I->getOperand(0)) // A^(A^B) == B
3406 return ReplaceInstUsesWith(I, Op1I->getOperand(1));
3407 else if (Op0 == Op1I->getOperand(1)) // A^(B^A) == B
3408 return ReplaceInstUsesWith(I, Op1I->getOperand(0));
Chris Lattnerdcd07922006-04-01 08:03:55 +00003409 } else if (Op1I->getOpcode() == Instruction::And && Op1I->hasOneUse()) {
3410 if (Op1I->getOperand(0) == Op0) // A^(A&B) -> A^(B&A)
3411 Op1I->swapOperands();
3412 if (Op0 == Op1I->getOperand(1)) { // A^(B&A) -> (B&A)^A
3413 I.swapOperands(); // Simplified below.
3414 std::swap(Op0, Op1);
3415 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00003416 }
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003417
Chris Lattnerdcd07922006-04-01 08:03:55 +00003418 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00003419 if (Op0I->getOpcode() == Instruction::Or && Op0I->hasOneUse()) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003420 if (Op0I->getOperand(0) == Op1) // (B|A)^B == (A|B)^B
Chris Lattnerdcd07922006-04-01 08:03:55 +00003421 Op0I->swapOperands();
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003422 if (Op0I->getOperand(1) == Op1) { // (A|B)^B == A & ~B
Chris Lattnerdcd07922006-04-01 08:03:55 +00003423 Instruction *NotB = BinaryOperator::createNot(Op1, "tmp");
3424 InsertNewInstBefore(NotB, I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003425 return BinaryOperator::createAnd(Op0I->getOperand(0), NotB);
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003426 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00003427 } else if (Op0I->getOpcode() == Instruction::Xor) {
3428 if (Op1 == Op0I->getOperand(0)) // (A^B)^A == B
3429 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
3430 else if (Op1 == Op0I->getOperand(1)) // (B^A)^A == B
3431 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattnerdcd07922006-04-01 08:03:55 +00003432 } else if (Op0I->getOpcode() == Instruction::And && Op0I->hasOneUse()) {
3433 if (Op0I->getOperand(0) == Op1) // (A&B)^A -> (B&A)^A
3434 Op0I->swapOperands();
Chris Lattner6cf49142006-04-01 22:05:01 +00003435 if (Op0I->getOperand(1) == Op1 && // (B&A)^A == ~B & A
3436 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattnerdcd07922006-04-01 08:03:55 +00003437 Instruction *N = BinaryOperator::createNot(Op0I->getOperand(0), "tmp");
3438 InsertNewInstBefore(N, I);
3439 return BinaryOperator::createAnd(N, Op1);
3440 }
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003441 }
3442
Chris Lattner3ac7c262003-08-13 20:16:26 +00003443 // (setcc1 A, B) ^ (setcc2 A, B) --> (setcc3 A, B)
3444 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
3445 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
3446 return R;
3447
Chris Lattner3af10532006-05-05 06:39:07 +00003448 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
3449 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattnere745c7d2006-05-05 20:51:30 +00003450 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner3af10532006-05-05 06:39:07 +00003451 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Chris Lattnere745c7d2006-05-05 20:51:30 +00003452 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegral() &&
Chris Lattner1d441ad2006-05-06 09:00:16 +00003453 // Only do this if the casts both really cause code to be generated.
3454 ValueRequiresCast(Op0C->getOperand(0), I.getType(), TD) &&
3455 ValueRequiresCast(Op1C->getOperand(0), I.getType(), TD)) {
Chris Lattner3af10532006-05-05 06:39:07 +00003456 Instruction *NewOp = BinaryOperator::createXor(Op0C->getOperand(0),
3457 Op1C->getOperand(0),
3458 I.getName());
3459 InsertNewInstBefore(NewOp, I);
3460 return new CastInst(NewOp, I.getType());
3461 }
3462 }
3463
Chris Lattner113f4f42002-06-25 16:13:24 +00003464 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003465}
3466
Chris Lattner6862fbd2004-09-29 17:40:11 +00003467/// MulWithOverflow - Compute Result = In1*In2, returning true if the result
3468/// overflowed for this type.
3469static bool MulWithOverflow(ConstantInt *&Result, ConstantInt *In1,
3470 ConstantInt *In2) {
3471 Result = cast<ConstantInt>(ConstantExpr::getMul(In1, In2));
3472 return !In2->isNullValue() && ConstantExpr::getDiv(Result, In2) != In1;
3473}
3474
3475static bool isPositive(ConstantInt *C) {
3476 return cast<ConstantSInt>(C)->getValue() >= 0;
3477}
3478
3479/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
3480/// overflowed for this type.
3481static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
3482 ConstantInt *In2) {
3483 Result = cast<ConstantInt>(ConstantExpr::getAdd(In1, In2));
3484
3485 if (In1->getType()->isUnsigned())
3486 return cast<ConstantUInt>(Result)->getValue() <
3487 cast<ConstantUInt>(In1)->getValue();
3488 if (isPositive(In1) != isPositive(In2))
3489 return false;
3490 if (isPositive(In1))
3491 return cast<ConstantSInt>(Result)->getValue() <
3492 cast<ConstantSInt>(In1)->getValue();
3493 return cast<ConstantSInt>(Result)->getValue() >
3494 cast<ConstantSInt>(In1)->getValue();
3495}
3496
Chris Lattner0798af32005-01-13 20:14:25 +00003497/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
3498/// code necessary to compute the offset from the base pointer (without adding
3499/// in the base pointer). Return the result as a signed integer of intptr size.
3500static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
3501 TargetData &TD = IC.getTargetData();
3502 gep_type_iterator GTI = gep_type_begin(GEP);
3503 const Type *UIntPtrTy = TD.getIntPtrType();
3504 const Type *SIntPtrTy = UIntPtrTy->getSignedVersion();
3505 Value *Result = Constant::getNullValue(SIntPtrTy);
3506
3507 // Build a mask for high order bits.
Chris Lattner77defba2006-02-07 07:00:41 +00003508 uint64_t PtrSizeMask = ~0ULL >> (64-TD.getPointerSize()*8);
Chris Lattner0798af32005-01-13 20:14:25 +00003509
Chris Lattner0798af32005-01-13 20:14:25 +00003510 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
3511 Value *Op = GEP->getOperand(i);
Chris Lattnerd35d2102005-01-13 23:26:48 +00003512 uint64_t Size = TD.getTypeSize(GTI.getIndexedType()) & PtrSizeMask;
Chris Lattner0798af32005-01-13 20:14:25 +00003513 Constant *Scale = ConstantExpr::getCast(ConstantUInt::get(UIntPtrTy, Size),
3514 SIntPtrTy);
3515 if (Constant *OpC = dyn_cast<Constant>(Op)) {
3516 if (!OpC->isNullValue()) {
Chris Lattner4cb9fa32005-01-13 20:40:58 +00003517 OpC = ConstantExpr::getCast(OpC, SIntPtrTy);
Chris Lattner0798af32005-01-13 20:14:25 +00003518 Scale = ConstantExpr::getMul(OpC, Scale);
3519 if (Constant *RC = dyn_cast<Constant>(Result))
3520 Result = ConstantExpr::getAdd(RC, Scale);
3521 else {
3522 // Emit an add instruction.
3523 Result = IC.InsertNewInstBefore(
3524 BinaryOperator::createAdd(Result, Scale,
3525 GEP->getName()+".offs"), I);
3526 }
3527 }
3528 } else {
Chris Lattner7aa41cf2005-01-14 17:17:59 +00003529 // Convert to correct type.
3530 Op = IC.InsertNewInstBefore(new CastInst(Op, SIntPtrTy,
3531 Op->getName()+".c"), I);
3532 if (Size != 1)
Chris Lattner4cb9fa32005-01-13 20:40:58 +00003533 // We'll let instcombine(mul) convert this to a shl if possible.
3534 Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
3535 GEP->getName()+".idx"), I);
Chris Lattner0798af32005-01-13 20:14:25 +00003536
3537 // Emit an add instruction.
Chris Lattner4cb9fa32005-01-13 20:40:58 +00003538 Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
Chris Lattner0798af32005-01-13 20:14:25 +00003539 GEP->getName()+".offs"), I);
3540 }
3541 }
3542 return Result;
3543}
3544
3545/// FoldGEPSetCC - Fold comparisons between a GEP instruction and something
3546/// else. At this point we know that the GEP is on the LHS of the comparison.
3547Instruction *InstCombiner::FoldGEPSetCC(User *GEPLHS, Value *RHS,
3548 Instruction::BinaryOps Cond,
3549 Instruction &I) {
3550 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattner81e84172005-01-13 22:25:21 +00003551
3552 if (CastInst *CI = dyn_cast<CastInst>(RHS))
3553 if (isa<PointerType>(CI->getOperand(0)->getType()))
3554 RHS = CI->getOperand(0);
3555
Chris Lattner0798af32005-01-13 20:14:25 +00003556 Value *PtrBase = GEPLHS->getOperand(0);
3557 if (PtrBase == RHS) {
3558 // As an optimization, we don't actually have to compute the actual value of
3559 // OFFSET if this is a seteq or setne comparison, just return whether each
3560 // index is zero or not.
Chris Lattner81e84172005-01-13 22:25:21 +00003561 if (Cond == Instruction::SetEQ || Cond == Instruction::SetNE) {
3562 Instruction *InVal = 0;
Chris Lattnercd517ff2005-01-28 19:32:01 +00003563 gep_type_iterator GTI = gep_type_begin(GEPLHS);
3564 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i, ++GTI) {
Chris Lattner81e84172005-01-13 22:25:21 +00003565 bool EmitIt = true;
3566 if (Constant *C = dyn_cast<Constant>(GEPLHS->getOperand(i))) {
3567 if (isa<UndefValue>(C)) // undef index -> undef.
3568 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
3569 if (C->isNullValue())
3570 EmitIt = false;
Chris Lattnercd517ff2005-01-28 19:32:01 +00003571 else if (TD->getTypeSize(GTI.getIndexedType()) == 0) {
3572 EmitIt = false; // This is indexing into a zero sized array?
Misha Brukmanb1c93172005-04-21 23:48:37 +00003573 } else if (isa<ConstantInt>(C))
Chris Lattner81e84172005-01-13 22:25:21 +00003574 return ReplaceInstUsesWith(I, // No comparison is needed here.
3575 ConstantBool::get(Cond == Instruction::SetNE));
3576 }
3577
3578 if (EmitIt) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00003579 Instruction *Comp =
Chris Lattner81e84172005-01-13 22:25:21 +00003580 new SetCondInst(Cond, GEPLHS->getOperand(i),
3581 Constant::getNullValue(GEPLHS->getOperand(i)->getType()));
3582 if (InVal == 0)
3583 InVal = Comp;
3584 else {
3585 InVal = InsertNewInstBefore(InVal, I);
3586 InsertNewInstBefore(Comp, I);
3587 if (Cond == Instruction::SetNE) // True if any are unequal
3588 InVal = BinaryOperator::createOr(InVal, Comp);
3589 else // True if all are equal
3590 InVal = BinaryOperator::createAnd(InVal, Comp);
3591 }
3592 }
3593 }
3594
3595 if (InVal)
3596 return InVal;
3597 else
3598 ReplaceInstUsesWith(I, // No comparison is needed here, all indexes = 0
3599 ConstantBool::get(Cond == Instruction::SetEQ));
3600 }
Chris Lattner0798af32005-01-13 20:14:25 +00003601
3602 // Only lower this if the setcc is the only user of the GEP or if we expect
3603 // the result to fold to a constant!
3604 if (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) {
3605 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
3606 Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
3607 return new SetCondInst(Cond, Offset,
3608 Constant::getNullValue(Offset->getType()));
3609 }
3610 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
Chris Lattnera21bf8d2005-04-25 20:17:30 +00003611 // If the base pointers are different, but the indices are the same, just
3612 // compare the base pointer.
3613 if (PtrBase != GEPRHS->getOperand(0)) {
3614 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00003615 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattnerbd43b9d2005-04-26 14:40:41 +00003616 GEPRHS->getOperand(0)->getType();
Chris Lattnera21bf8d2005-04-25 20:17:30 +00003617 if (IndicesTheSame)
3618 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
3619 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
3620 IndicesTheSame = false;
3621 break;
3622 }
3623
3624 // If all indices are the same, just compare the base pointers.
3625 if (IndicesTheSame)
3626 return new SetCondInst(Cond, GEPLHS->getOperand(0),
3627 GEPRHS->getOperand(0));
3628
3629 // Otherwise, the base pointers are different and the indices are
3630 // different, bail out.
Chris Lattner0798af32005-01-13 20:14:25 +00003631 return 0;
Chris Lattnera21bf8d2005-04-25 20:17:30 +00003632 }
Chris Lattner0798af32005-01-13 20:14:25 +00003633
Chris Lattner81e84172005-01-13 22:25:21 +00003634 // If one of the GEPs has all zero indices, recurse.
3635 bool AllZeros = true;
3636 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
3637 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
3638 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
3639 AllZeros = false;
3640 break;
3641 }
3642 if (AllZeros)
3643 return FoldGEPSetCC(GEPRHS, GEPLHS->getOperand(0),
3644 SetCondInst::getSwappedCondition(Cond), I);
Chris Lattner4fa89822005-01-14 00:20:05 +00003645
3646 // If the other GEP has all zero indices, recurse.
Chris Lattner81e84172005-01-13 22:25:21 +00003647 AllZeros = true;
3648 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
3649 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
3650 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
3651 AllZeros = false;
3652 break;
3653 }
3654 if (AllZeros)
3655 return FoldGEPSetCC(GEPLHS, GEPRHS->getOperand(0), Cond, I);
3656
Chris Lattner4fa89822005-01-14 00:20:05 +00003657 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
3658 // If the GEPs only differ by one index, compare it.
3659 unsigned NumDifferences = 0; // Keep track of # differences.
3660 unsigned DiffOperand = 0; // The operand that differs.
3661 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
3662 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003663 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
3664 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattnerfc4429e2005-01-21 23:06:49 +00003665 // Irreconcilable differences.
Chris Lattner4fa89822005-01-14 00:20:05 +00003666 NumDifferences = 2;
3667 break;
3668 } else {
3669 if (NumDifferences++) break;
3670 DiffOperand = i;
3671 }
3672 }
3673
3674 if (NumDifferences == 0) // SAME GEP?
3675 return ReplaceInstUsesWith(I, // No comparison is needed here.
3676 ConstantBool::get(Cond == Instruction::SetEQ));
3677 else if (NumDifferences == 1) {
Chris Lattnerfc4429e2005-01-21 23:06:49 +00003678 Value *LHSV = GEPLHS->getOperand(DiffOperand);
3679 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Chris Lattner247aef82005-07-18 23:07:33 +00003680
3681 // Convert the operands to signed values to make sure to perform a
3682 // signed comparison.
3683 const Type *NewTy = LHSV->getType()->getSignedVersion();
3684 if (LHSV->getType() != NewTy)
3685 LHSV = InsertNewInstBefore(new CastInst(LHSV, NewTy,
3686 LHSV->getName()), I);
3687 if (RHSV->getType() != NewTy)
3688 RHSV = InsertNewInstBefore(new CastInst(RHSV, NewTy,
3689 RHSV->getName()), I);
3690 return new SetCondInst(Cond, LHSV, RHSV);
Chris Lattner4fa89822005-01-14 00:20:05 +00003691 }
3692 }
3693
Chris Lattner0798af32005-01-13 20:14:25 +00003694 // Only lower this if the setcc is the only user of the GEP or if we expect
3695 // the result to fold to a constant!
3696 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
3697 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
3698 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
3699 Value *L = EmitGEPOffset(GEPLHS, I, *this);
3700 Value *R = EmitGEPOffset(GEPRHS, I, *this);
3701 return new SetCondInst(Cond, L, R);
3702 }
3703 }
3704 return 0;
3705}
3706
3707
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003708Instruction *InstCombiner::visitSetCondInst(SetCondInst &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003709 bool Changed = SimplifyCommutative(I);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003710 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3711 const Type *Ty = Op0->getType();
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003712
3713 // setcc X, X
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003714 if (Op0 == Op1)
3715 return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
Chris Lattner1fc23f32002-05-09 20:11:54 +00003716
Chris Lattner81a7a232004-10-16 18:11:37 +00003717 if (isa<UndefValue>(Op1)) // X setcc undef -> undef
3718 return ReplaceInstUsesWith(I, UndefValue::get(Type::BoolTy));
3719
Chris Lattner15ff1e12004-11-14 07:33:16 +00003720 // setcc <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
3721 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanb1c93172005-04-21 23:48:37 +00003722 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
3723 isa<ConstantPointerNull>(Op0)) &&
3724 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner15ff1e12004-11-14 07:33:16 +00003725 isa<ConstantPointerNull>(Op1)))
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003726 return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
3727
3728 // setcc's with boolean values can always be turned into bitwise operations
3729 if (Ty == Type::BoolTy) {
Chris Lattner4456da62004-08-11 00:50:51 +00003730 switch (I.getOpcode()) {
3731 default: assert(0 && "Invalid setcc instruction!");
3732 case Instruction::SetEQ: { // seteq bool %A, %B -> ~(A^B)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003733 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003734 InsertNewInstBefore(Xor, I);
Chris Lattner16930792003-11-03 04:25:02 +00003735 return BinaryOperator::createNot(Xor);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003736 }
Chris Lattner4456da62004-08-11 00:50:51 +00003737 case Instruction::SetNE:
3738 return BinaryOperator::createXor(Op0, Op1);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003739
Chris Lattner4456da62004-08-11 00:50:51 +00003740 case Instruction::SetGT:
3741 std::swap(Op0, Op1); // Change setgt -> setlt
3742 // FALL THROUGH
3743 case Instruction::SetLT: { // setlt bool A, B -> ~X & Y
3744 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
3745 InsertNewInstBefore(Not, I);
3746 return BinaryOperator::createAnd(Not, Op1);
3747 }
3748 case Instruction::SetGE:
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003749 std::swap(Op0, Op1); // Change setge -> setle
Chris Lattner4456da62004-08-11 00:50:51 +00003750 // FALL THROUGH
3751 case Instruction::SetLE: { // setle bool %A, %B -> ~A | B
3752 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
3753 InsertNewInstBefore(Not, I);
3754 return BinaryOperator::createOr(Not, Op1);
3755 }
3756 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003757 }
3758
Chris Lattner2dd01742004-06-09 04:24:29 +00003759 // See if we are doing a comparison between a constant and an instruction that
3760 // can be folded into the comparison.
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003761 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner6862fbd2004-09-29 17:40:11 +00003762 // Check to see if we are comparing against the minimum or maximum value...
3763 if (CI->isMinValue()) {
3764 if (I.getOpcode() == Instruction::SetLT) // A < MIN -> FALSE
3765 return ReplaceInstUsesWith(I, ConstantBool::False);
3766 if (I.getOpcode() == Instruction::SetGE) // A >= MIN -> TRUE
3767 return ReplaceInstUsesWith(I, ConstantBool::True);
3768 if (I.getOpcode() == Instruction::SetLE) // A <= MIN -> A == MIN
3769 return BinaryOperator::createSetEQ(Op0, Op1);
3770 if (I.getOpcode() == Instruction::SetGT) // A > MIN -> A != MIN
3771 return BinaryOperator::createSetNE(Op0, Op1);
3772
3773 } else if (CI->isMaxValue()) {
3774 if (I.getOpcode() == Instruction::SetGT) // A > MAX -> FALSE
3775 return ReplaceInstUsesWith(I, ConstantBool::False);
3776 if (I.getOpcode() == Instruction::SetLE) // A <= MAX -> TRUE
3777 return ReplaceInstUsesWith(I, ConstantBool::True);
3778 if (I.getOpcode() == Instruction::SetGE) // A >= MAX -> A == MAX
3779 return BinaryOperator::createSetEQ(Op0, Op1);
3780 if (I.getOpcode() == Instruction::SetLT) // A < MAX -> A != MAX
3781 return BinaryOperator::createSetNE(Op0, Op1);
3782
3783 // Comparing against a value really close to min or max?
3784 } else if (isMinValuePlusOne(CI)) {
3785 if (I.getOpcode() == Instruction::SetLT) // A < MIN+1 -> A == MIN
3786 return BinaryOperator::createSetEQ(Op0, SubOne(CI));
3787 if (I.getOpcode() == Instruction::SetGE) // A >= MIN-1 -> A != MIN
3788 return BinaryOperator::createSetNE(Op0, SubOne(CI));
3789
3790 } else if (isMaxValueMinusOne(CI)) {
3791 if (I.getOpcode() == Instruction::SetGT) // A > MAX-1 -> A == MAX
3792 return BinaryOperator::createSetEQ(Op0, AddOne(CI));
3793 if (I.getOpcode() == Instruction::SetLE) // A <= MAX-1 -> A != MAX
3794 return BinaryOperator::createSetNE(Op0, AddOne(CI));
3795 }
3796
3797 // If we still have a setle or setge instruction, turn it into the
3798 // appropriate setlt or setgt instruction. Since the border cases have
3799 // already been handled above, this requires little checking.
3800 //
3801 if (I.getOpcode() == Instruction::SetLE)
3802 return BinaryOperator::createSetLT(Op0, AddOne(CI));
3803 if (I.getOpcode() == Instruction::SetGE)
3804 return BinaryOperator::createSetGT(Op0, SubOne(CI));
3805
Chris Lattneree0f2802006-02-12 02:07:56 +00003806
3807 // See if we can fold the comparison based on bits known to be zero or one
3808 // in the input.
3809 uint64_t KnownZero, KnownOne;
3810 if (SimplifyDemandedBits(Op0, Ty->getIntegralTypeMask(),
3811 KnownZero, KnownOne, 0))
3812 return &I;
3813
3814 // Given the known and unknown bits, compute a range that the LHS could be
3815 // in.
3816 if (KnownOne | KnownZero) {
3817 if (Ty->isUnsigned()) { // Unsigned comparison.
3818 uint64_t Min, Max;
3819 uint64_t RHSVal = CI->getZExtValue();
3820 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne,
3821 Min, Max);
3822 switch (I.getOpcode()) { // LE/GE have been folded already.
3823 default: assert(0 && "Unknown setcc opcode!");
3824 case Instruction::SetEQ:
3825 if (Max < RHSVal || Min > RHSVal)
3826 return ReplaceInstUsesWith(I, ConstantBool::False);
3827 break;
3828 case Instruction::SetNE:
3829 if (Max < RHSVal || Min > RHSVal)
3830 return ReplaceInstUsesWith(I, ConstantBool::True);
3831 break;
3832 case Instruction::SetLT:
3833 if (Max < RHSVal) return ReplaceInstUsesWith(I, ConstantBool::True);
3834 if (Min > RHSVal) return ReplaceInstUsesWith(I, ConstantBool::False);
3835 break;
3836 case Instruction::SetGT:
3837 if (Min > RHSVal) return ReplaceInstUsesWith(I, ConstantBool::True);
3838 if (Max < RHSVal) return ReplaceInstUsesWith(I, ConstantBool::False);
3839 break;
3840 }
3841 } else { // Signed comparison.
3842 int64_t Min, Max;
3843 int64_t RHSVal = CI->getSExtValue();
3844 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne,
3845 Min, Max);
3846 switch (I.getOpcode()) { // LE/GE have been folded already.
3847 default: assert(0 && "Unknown setcc opcode!");
3848 case Instruction::SetEQ:
3849 if (Max < RHSVal || Min > RHSVal)
3850 return ReplaceInstUsesWith(I, ConstantBool::False);
3851 break;
3852 case Instruction::SetNE:
3853 if (Max < RHSVal || Min > RHSVal)
3854 return ReplaceInstUsesWith(I, ConstantBool::True);
3855 break;
3856 case Instruction::SetLT:
3857 if (Max < RHSVal) return ReplaceInstUsesWith(I, ConstantBool::True);
3858 if (Min > RHSVal) return ReplaceInstUsesWith(I, ConstantBool::False);
3859 break;
3860 case Instruction::SetGT:
3861 if (Min > RHSVal) return ReplaceInstUsesWith(I, ConstantBool::True);
3862 if (Max < RHSVal) return ReplaceInstUsesWith(I, ConstantBool::False);
3863 break;
3864 }
3865 }
3866 }
3867
3868
Chris Lattnere1e10e12004-05-25 06:32:08 +00003869 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00003870 switch (LHSI->getOpcode()) {
3871 case Instruction::And:
3872 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
3873 LHSI->getOperand(0)->hasOneUse()) {
Chris Lattner4922a0e2006-09-18 05:27:43 +00003874 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
3875
3876 // If an operand is an AND of a truncating cast, we can widen the
3877 // and/compare to be the input width without changing the value
3878 // produced, eliminating a cast.
3879 if (CastInst *Cast = dyn_cast<CastInst>(LHSI->getOperand(0))) {
3880 // We can do this transformation if either the AND constant does not
3881 // have its sign bit set or if it is an equality comparison.
3882 // Extending a relational comparison when we're checking the sign
3883 // bit would not work.
3884 if (Cast->hasOneUse() && Cast->isTruncIntCast() &&
3885 (I.isEquality() ||
3886 (AndCST->getZExtValue() == (uint64_t)AndCST->getSExtValue()) &&
3887 (CI->getZExtValue() == (uint64_t)CI->getSExtValue()))) {
3888 ConstantInt *NewCST;
3889 ConstantInt *NewCI;
3890 if (Cast->getOperand(0)->getType()->isSigned()) {
3891 NewCST = ConstantSInt::get(Cast->getOperand(0)->getType(),
3892 AndCST->getZExtValue());
3893 NewCI = ConstantSInt::get(Cast->getOperand(0)->getType(),
3894 CI->getZExtValue());
3895 } else {
3896 NewCST = ConstantUInt::get(Cast->getOperand(0)->getType(),
3897 AndCST->getZExtValue());
3898 NewCI = ConstantUInt::get(Cast->getOperand(0)->getType(),
3899 CI->getZExtValue());
3900 }
3901 Instruction *NewAnd =
3902 BinaryOperator::createAnd(Cast->getOperand(0), NewCST,
3903 LHSI->getName());
3904 InsertNewInstBefore(NewAnd, I);
3905 return new SetCondInst(I.getOpcode(), NewAnd, NewCI);
3906 }
3907 }
3908
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00003909 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
3910 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
3911 // happens a LOT in code produced by the C front-end, for bitfield
3912 // access.
3913 ShiftInst *Shift = dyn_cast<ShiftInst>(LHSI->getOperand(0));
Chris Lattneree0f2802006-02-12 02:07:56 +00003914
3915 // Check to see if there is a noop-cast between the shift and the and.
3916 if (!Shift) {
3917 if (CastInst *CI = dyn_cast<CastInst>(LHSI->getOperand(0)))
3918 if (CI->getOperand(0)->getType()->isIntegral() &&
3919 CI->getOperand(0)->getType()->getPrimitiveSizeInBits() ==
3920 CI->getType()->getPrimitiveSizeInBits())
3921 Shift = dyn_cast<ShiftInst>(CI->getOperand(0));
3922 }
Chris Lattnerb3f24c92006-09-18 04:22:48 +00003923
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00003924 ConstantUInt *ShAmt;
3925 ShAmt = Shift ? dyn_cast<ConstantUInt>(Shift->getOperand(1)) : 0;
Chris Lattneree0f2802006-02-12 02:07:56 +00003926 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
3927 const Type *AndTy = AndCST->getType(); // Type of the and.
Misha Brukmanb1c93172005-04-21 23:48:37 +00003928
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00003929 // We can fold this as long as we can't shift unknown bits
3930 // into the mask. This can only happen with signed shift
3931 // rights, as they sign-extend.
3932 if (ShAmt) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00003933 bool CanFold = Shift->isLogicalShift();
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00003934 if (!CanFold) {
3935 // To test for the bad case of the signed shr, see if any
3936 // of the bits shifted in could be tested after the mask.
Chris Lattnerc53cb9d2005-06-17 01:29:28 +00003937 int ShAmtVal = Ty->getPrimitiveSizeInBits()-ShAmt->getValue();
3938 if (ShAmtVal < 0) ShAmtVal = 0; // Out of range shift.
3939
3940 Constant *OShAmt = ConstantUInt::get(Type::UByteTy, ShAmtVal);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003941 Constant *ShVal =
Chris Lattneree0f2802006-02-12 02:07:56 +00003942 ConstantExpr::getShl(ConstantInt::getAllOnesValue(AndTy),
3943 OShAmt);
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00003944 if (ConstantExpr::getAnd(ShVal, AndCST)->isNullValue())
3945 CanFold = true;
3946 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003947
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00003948 if (CanFold) {
Chris Lattner6afc02f2004-09-28 17:54:07 +00003949 Constant *NewCst;
3950 if (Shift->getOpcode() == Instruction::Shl)
3951 NewCst = ConstantExpr::getUShr(CI, ShAmt);
3952 else
3953 NewCst = ConstantExpr::getShl(CI, ShAmt);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00003954
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00003955 // Check to see if we are shifting out any of the bits being
3956 // compared.
3957 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != CI){
3958 // If we shifted bits out, the fold is not going to work out.
3959 // As a special case, check to see if this means that the
3960 // result is always true or false now.
3961 if (I.getOpcode() == Instruction::SetEQ)
3962 return ReplaceInstUsesWith(I, ConstantBool::False);
3963 if (I.getOpcode() == Instruction::SetNE)
3964 return ReplaceInstUsesWith(I, ConstantBool::True);
3965 } else {
3966 I.setOperand(1, NewCst);
Chris Lattner6afc02f2004-09-28 17:54:07 +00003967 Constant *NewAndCST;
3968 if (Shift->getOpcode() == Instruction::Shl)
3969 NewAndCST = ConstantExpr::getUShr(AndCST, ShAmt);
3970 else
3971 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
3972 LHSI->setOperand(1, NewAndCST);
Chris Lattneree0f2802006-02-12 02:07:56 +00003973 if (AndTy == Ty)
3974 LHSI->setOperand(0, Shift->getOperand(0));
3975 else {
3976 Value *NewCast = InsertCastBefore(Shift->getOperand(0), AndTy,
3977 *Shift);
3978 LHSI->setOperand(0, NewCast);
3979 }
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00003980 WorkList.push_back(Shift); // Shift is dead.
3981 AddUsesToWorkList(I);
3982 return &I;
Chris Lattner1638de42004-07-21 19:50:44 +00003983 }
3984 }
Chris Lattner35167c32004-06-09 07:59:58 +00003985 }
Chris Lattnerb3f24c92006-09-18 04:22:48 +00003986
3987 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
3988 // preferable because it allows the C<<Y expression to be hoisted out
3989 // of a loop if Y is invariant and X is not.
3990 if (Shift && Shift->hasOneUse() && CI->isNullValue() &&
Chris Lattnerde077922006-09-18 18:27:05 +00003991 I.isEquality() && !Shift->isArithmeticShift() &&
3992 isa<Instruction>(Shift->getOperand(0))) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00003993 // Compute C << Y.
3994 Value *NS;
3995 if (Shift->getOpcode() == Instruction::Shr) {
3996 NS = new ShiftInst(Instruction::Shl, AndCST, Shift->getOperand(1),
3997 "tmp");
3998 } else {
3999 // Make sure we insert a logical shift.
Chris Lattner4922a0e2006-09-18 05:27:43 +00004000 Constant *NewAndCST = AndCST;
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004001 if (AndCST->getType()->isSigned())
Chris Lattner4922a0e2006-09-18 05:27:43 +00004002 NewAndCST = ConstantExpr::getCast(AndCST,
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004003 AndCST->getType()->getUnsignedVersion());
Chris Lattner4922a0e2006-09-18 05:27:43 +00004004 NS = new ShiftInst(Instruction::Shr, NewAndCST,
4005 Shift->getOperand(1), "tmp");
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004006 }
4007 InsertNewInstBefore(cast<Instruction>(NS), I);
4008
4009 // If C's sign doesn't agree with the and, insert a cast now.
4010 if (NS->getType() != LHSI->getType())
4011 NS = InsertCastBefore(NS, LHSI->getType(), I);
4012
4013 Value *ShiftOp = Shift->getOperand(0);
4014 if (ShiftOp->getType() != LHSI->getType())
4015 ShiftOp = InsertCastBefore(ShiftOp, LHSI->getType(), I);
4016
4017 // Compute X & (C << Y).
4018 Instruction *NewAnd =
4019 BinaryOperator::createAnd(ShiftOp, NS, LHSI->getName());
4020 InsertNewInstBefore(NewAnd, I);
4021
4022 I.setOperand(0, NewAnd);
4023 return &I;
4024 }
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004025 }
4026 break;
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004027
Chris Lattner272d5ca2004-09-28 18:22:15 +00004028 case Instruction::Shl: // (setcc (shl X, ShAmt), CI)
4029 if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004030 if (I.isEquality()) {
Chris Lattner19b57f52005-06-15 20:53:31 +00004031 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
4032
4033 // Check that the shift amount is in range. If not, don't perform
4034 // undefined shifts. When the shift is visited it will be
4035 // simplified.
4036 if (ShAmt->getValue() >= TypeBits)
4037 break;
4038
Chris Lattner272d5ca2004-09-28 18:22:15 +00004039 // If we are comparing against bits always shifted out, the
4040 // comparison cannot succeed.
Misha Brukmanb1c93172005-04-21 23:48:37 +00004041 Constant *Comp =
Chris Lattner272d5ca2004-09-28 18:22:15 +00004042 ConstantExpr::getShl(ConstantExpr::getShr(CI, ShAmt), ShAmt);
4043 if (Comp != CI) {// Comparing against a bit that we know is zero.
4044 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
4045 Constant *Cst = ConstantBool::get(IsSetNE);
4046 return ReplaceInstUsesWith(I, Cst);
4047 }
4048
4049 if (LHSI->hasOneUse()) {
4050 // Otherwise strength reduce the shift into an and.
Chris Lattnerfdfe3e492005-01-08 19:42:22 +00004051 unsigned ShAmtVal = (unsigned)ShAmt->getValue();
Chris Lattner272d5ca2004-09-28 18:22:15 +00004052 uint64_t Val = (1ULL << (TypeBits-ShAmtVal))-1;
4053
4054 Constant *Mask;
4055 if (CI->getType()->isUnsigned()) {
4056 Mask = ConstantUInt::get(CI->getType(), Val);
4057 } else if (ShAmtVal != 0) {
4058 Mask = ConstantSInt::get(CI->getType(), Val);
4059 } else {
4060 Mask = ConstantInt::getAllOnesValue(CI->getType());
4061 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004062
Chris Lattner272d5ca2004-09-28 18:22:15 +00004063 Instruction *AndI =
4064 BinaryOperator::createAnd(LHSI->getOperand(0),
4065 Mask, LHSI->getName()+".mask");
4066 Value *And = InsertNewInstBefore(AndI, I);
4067 return new SetCondInst(I.getOpcode(), And,
4068 ConstantExpr::getUShr(CI, ShAmt));
4069 }
4070 }
Chris Lattner272d5ca2004-09-28 18:22:15 +00004071 }
4072 break;
4073
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004074 case Instruction::Shr: // (setcc (shr X, ShAmt), CI)
Chris Lattner1023b872004-09-27 16:18:50 +00004075 if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004076 if (I.isEquality()) {
Chris Lattner19b57f52005-06-15 20:53:31 +00004077 // Check that the shift amount is in range. If not, don't perform
4078 // undefined shifts. When the shift is visited it will be
4079 // simplified.
Chris Lattner104002b2005-06-16 01:52:07 +00004080 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
Chris Lattner19b57f52005-06-15 20:53:31 +00004081 if (ShAmt->getValue() >= TypeBits)
4082 break;
4083
Chris Lattner1023b872004-09-27 16:18:50 +00004084 // If we are comparing against bits always shifted out, the
4085 // comparison cannot succeed.
Misha Brukmanb1c93172005-04-21 23:48:37 +00004086 Constant *Comp =
Chris Lattner1023b872004-09-27 16:18:50 +00004087 ConstantExpr::getShr(ConstantExpr::getShl(CI, ShAmt), ShAmt);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004088
Chris Lattner1023b872004-09-27 16:18:50 +00004089 if (Comp != CI) {// Comparing against a bit that we know is zero.
4090 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
4091 Constant *Cst = ConstantBool::get(IsSetNE);
4092 return ReplaceInstUsesWith(I, Cst);
4093 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004094
Chris Lattner1023b872004-09-27 16:18:50 +00004095 if (LHSI->hasOneUse() || CI->isNullValue()) {
Chris Lattnerfdfe3e492005-01-08 19:42:22 +00004096 unsigned ShAmtVal = (unsigned)ShAmt->getValue();
Chris Lattner272d5ca2004-09-28 18:22:15 +00004097
Chris Lattner1023b872004-09-27 16:18:50 +00004098 // Otherwise strength reduce the shift into an and.
4099 uint64_t Val = ~0ULL; // All ones.
4100 Val <<= ShAmtVal; // Shift over to the right spot.
4101
4102 Constant *Mask;
4103 if (CI->getType()->isUnsigned()) {
Chris Lattner2f1457f2005-04-24 17:46:05 +00004104 Val &= ~0ULL >> (64-TypeBits);
Chris Lattner1023b872004-09-27 16:18:50 +00004105 Mask = ConstantUInt::get(CI->getType(), Val);
4106 } else {
4107 Mask = ConstantSInt::get(CI->getType(), Val);
4108 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004109
Chris Lattner1023b872004-09-27 16:18:50 +00004110 Instruction *AndI =
4111 BinaryOperator::createAnd(LHSI->getOperand(0),
4112 Mask, LHSI->getName()+".mask");
4113 Value *And = InsertNewInstBefore(AndI, I);
4114 return new SetCondInst(I.getOpcode(), And,
4115 ConstantExpr::getShl(CI, ShAmt));
4116 }
Chris Lattner1023b872004-09-27 16:18:50 +00004117 }
4118 }
4119 break;
Chris Lattner7e794272004-09-24 15:21:34 +00004120
Chris Lattner6862fbd2004-09-29 17:40:11 +00004121 case Instruction::Div:
4122 // Fold: (div X, C1) op C2 -> range check
4123 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
4124 // Fold this div into the comparison, producing a range check.
4125 // Determine, based on the divide type, what the range is being
4126 // checked. If there is an overflow on the low or high side, remember
4127 // it, otherwise compute the range [low, hi) bounding the new value.
4128 bool LoOverflow = false, HiOverflow = 0;
4129 ConstantInt *LoBound = 0, *HiBound = 0;
4130
4131 ConstantInt *Prod;
4132 bool ProdOV = MulWithOverflow(Prod, CI, DivRHS);
4133
Chris Lattnera92af962004-10-11 19:40:04 +00004134 Instruction::BinaryOps Opcode = I.getOpcode();
4135
Chris Lattner6862fbd2004-09-29 17:40:11 +00004136 if (DivRHS->isNullValue()) { // Don't hack on divide by zeros.
4137 } else if (LHSI->getType()->isUnsigned()) { // udiv
4138 LoBound = Prod;
4139 LoOverflow = ProdOV;
4140 HiOverflow = ProdOV || AddWithOverflow(HiBound, LoBound, DivRHS);
4141 } else if (isPositive(DivRHS)) { // Divisor is > 0.
4142 if (CI->isNullValue()) { // (X / pos) op 0
4143 // Can't overflow.
4144 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
4145 HiBound = DivRHS;
4146 } else if (isPositive(CI)) { // (X / pos) op pos
4147 LoBound = Prod;
4148 LoOverflow = ProdOV;
4149 HiOverflow = ProdOV || AddWithOverflow(HiBound, Prod, DivRHS);
4150 } else { // (X / pos) op neg
4151 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
4152 LoOverflow = AddWithOverflow(LoBound, Prod,
4153 cast<ConstantInt>(DivRHSH));
4154 HiBound = Prod;
4155 HiOverflow = ProdOV;
4156 }
4157 } else { // Divisor is < 0.
4158 if (CI->isNullValue()) { // (X / neg) op 0
4159 LoBound = AddOne(DivRHS);
4160 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner73bcba52005-06-17 02:05:55 +00004161 if (HiBound == DivRHS)
4162 LoBound = 0; // - INTMIN = INTMIN
Chris Lattner6862fbd2004-09-29 17:40:11 +00004163 } else if (isPositive(CI)) { // (X / neg) op pos
4164 HiOverflow = LoOverflow = ProdOV;
4165 if (!LoOverflow)
4166 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS));
4167 HiBound = AddOne(Prod);
4168 } else { // (X / neg) op neg
4169 LoBound = Prod;
4170 LoOverflow = HiOverflow = ProdOV;
4171 HiBound = cast<ConstantInt>(ConstantExpr::getSub(Prod, DivRHS));
4172 }
Chris Lattner0b41e862004-10-08 19:15:44 +00004173
Chris Lattnera92af962004-10-11 19:40:04 +00004174 // Dividing by a negate swaps the condition.
4175 Opcode = SetCondInst::getSwappedCondition(Opcode);
Chris Lattner6862fbd2004-09-29 17:40:11 +00004176 }
4177
4178 if (LoBound) {
4179 Value *X = LHSI->getOperand(0);
Chris Lattnera92af962004-10-11 19:40:04 +00004180 switch (Opcode) {
Chris Lattner6862fbd2004-09-29 17:40:11 +00004181 default: assert(0 && "Unhandled setcc opcode!");
4182 case Instruction::SetEQ:
4183 if (LoOverflow && HiOverflow)
4184 return ReplaceInstUsesWith(I, ConstantBool::False);
4185 else if (HiOverflow)
4186 return new SetCondInst(Instruction::SetGE, X, LoBound);
4187 else if (LoOverflow)
4188 return new SetCondInst(Instruction::SetLT, X, HiBound);
4189 else
4190 return InsertRangeTest(X, LoBound, HiBound, true, I);
4191 case Instruction::SetNE:
4192 if (LoOverflow && HiOverflow)
4193 return ReplaceInstUsesWith(I, ConstantBool::True);
4194 else if (HiOverflow)
4195 return new SetCondInst(Instruction::SetLT, X, LoBound);
4196 else if (LoOverflow)
4197 return new SetCondInst(Instruction::SetGE, X, HiBound);
4198 else
4199 return InsertRangeTest(X, LoBound, HiBound, false, I);
4200 case Instruction::SetLT:
4201 if (LoOverflow)
4202 return ReplaceInstUsesWith(I, ConstantBool::False);
4203 return new SetCondInst(Instruction::SetLT, X, LoBound);
4204 case Instruction::SetGT:
4205 if (HiOverflow)
4206 return ReplaceInstUsesWith(I, ConstantBool::False);
4207 return new SetCondInst(Instruction::SetGE, X, HiBound);
4208 }
4209 }
4210 }
4211 break;
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004212 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004213
Chris Lattnerd492a0b2003-07-23 17:02:11 +00004214 // Simplify seteq and setne instructions...
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004215 if (I.isEquality()) {
Chris Lattnerd492a0b2003-07-23 17:02:11 +00004216 bool isSetNE = I.getOpcode() == Instruction::SetNE;
4217
Chris Lattnercfbce7c2003-07-23 17:26:36 +00004218 // If the first operand is (and|or|xor) with a constant, and the second
Chris Lattnerd492a0b2003-07-23 17:02:11 +00004219 // operand is a constant, simplify a bit.
Chris Lattnerc992add2003-08-13 05:33:12 +00004220 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
4221 switch (BO->getOpcode()) {
Chris Lattner23b47b62004-07-06 07:38:18 +00004222 case Instruction::Rem:
4223 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
4224 if (CI->isNullValue() && isa<ConstantSInt>(BO->getOperand(1)) &&
4225 BO->hasOneUse() &&
Chris Lattner22d00a82005-08-02 19:16:58 +00004226 cast<ConstantSInt>(BO->getOperand(1))->getValue() > 1) {
4227 int64_t V = cast<ConstantSInt>(BO->getOperand(1))->getValue();
4228 if (isPowerOf2_64(V)) {
4229 unsigned L2 = Log2_64(V);
Chris Lattner23b47b62004-07-06 07:38:18 +00004230 const Type *UTy = BO->getType()->getUnsignedVersion();
4231 Value *NewX = InsertNewInstBefore(new CastInst(BO->getOperand(0),
4232 UTy, "tmp"), I);
4233 Constant *RHSCst = ConstantUInt::get(UTy, 1ULL << L2);
4234 Value *NewRem =InsertNewInstBefore(BinaryOperator::createRem(NewX,
4235 RHSCst, BO->getName()), I);
4236 return BinaryOperator::create(I.getOpcode(), NewRem,
4237 Constant::getNullValue(UTy));
4238 }
Chris Lattner22d00a82005-08-02 19:16:58 +00004239 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004240 break;
Chris Lattner23b47b62004-07-06 07:38:18 +00004241
Chris Lattnerc992add2003-08-13 05:33:12 +00004242 case Instruction::Add:
Chris Lattner6e079362004-06-27 22:51:36 +00004243 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
4244 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerb121ae12004-09-21 21:35:23 +00004245 if (BO->hasOneUse())
4246 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
4247 ConstantExpr::getSub(CI, BOp1C));
Chris Lattner6e079362004-06-27 22:51:36 +00004248 } else if (CI->isNullValue()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00004249 // Replace ((add A, B) != 0) with (A != -B) if A or B is
4250 // efficiently invertible, or if the add has just this one use.
4251 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004252
Chris Lattnerc992add2003-08-13 05:33:12 +00004253 if (Value *NegVal = dyn_castNegVal(BOp1))
4254 return new SetCondInst(I.getOpcode(), BOp0, NegVal);
4255 else if (Value *NegVal = dyn_castNegVal(BOp0))
4256 return new SetCondInst(I.getOpcode(), NegVal, BOp1);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00004257 else if (BO->hasOneUse()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00004258 Instruction *Neg = BinaryOperator::createNeg(BOp1, BO->getName());
4259 BO->setName("");
4260 InsertNewInstBefore(Neg, I);
4261 return new SetCondInst(I.getOpcode(), BOp0, Neg);
4262 }
4263 }
4264 break;
4265 case Instruction::Xor:
4266 // For the xor case, we can xor two constants together, eliminating
4267 // the explicit xor.
4268 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
4269 return BinaryOperator::create(I.getOpcode(), BO->getOperand(0),
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004270 ConstantExpr::getXor(CI, BOC));
Chris Lattnerc992add2003-08-13 05:33:12 +00004271
4272 // FALLTHROUGH
4273 case Instruction::Sub:
4274 // Replace (([sub|xor] A, B) != 0) with (A != B)
4275 if (CI->isNullValue())
4276 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
4277 BO->getOperand(1));
4278 break;
4279
4280 case Instruction::Or:
4281 // If bits are being or'd in that are not present in the constant we
4282 // are comparing against, then the comparison could never succeed!
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00004283 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Chris Lattnerc8e7e292004-06-10 02:12:35 +00004284 Constant *NotCI = ConstantExpr::getNot(CI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004285 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Chris Lattnerd492a0b2003-07-23 17:02:11 +00004286 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00004287 }
Chris Lattnerc992add2003-08-13 05:33:12 +00004288 break;
4289
4290 case Instruction::And:
4291 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerd492a0b2003-07-23 17:02:11 +00004292 // If bits are being compared against that are and'd out, then the
4293 // comparison can never succeed!
Chris Lattnerc8e7e292004-06-10 02:12:35 +00004294 if (!ConstantExpr::getAnd(CI,
4295 ConstantExpr::getNot(BOC))->isNullValue())
Chris Lattnerd492a0b2003-07-23 17:02:11 +00004296 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattnerc992add2003-08-13 05:33:12 +00004297
Chris Lattner35167c32004-06-09 07:59:58 +00004298 // If we have ((X & C) == C), turn it into ((X & C) != 0).
Chris Lattneree59d4b2004-06-10 02:33:20 +00004299 if (CI == BOC && isOneBitSet(CI))
Chris Lattner35167c32004-06-09 07:59:58 +00004300 return new SetCondInst(isSetNE ? Instruction::SetEQ :
4301 Instruction::SetNE, Op0,
4302 Constant::getNullValue(CI->getType()));
Chris Lattner35167c32004-06-09 07:59:58 +00004303
Chris Lattnerc992add2003-08-13 05:33:12 +00004304 // Replace (and X, (1 << size(X)-1) != 0) with x < 0, converting X
4305 // to be a signed value as appropriate.
4306 if (isSignBit(BOC)) {
4307 Value *X = BO->getOperand(0);
4308 // If 'X' is not signed, insert a cast now...
4309 if (!BOC->getType()->isSigned()) {
Chris Lattner97bfcea2004-06-17 18:16:02 +00004310 const Type *DestTy = BOC->getType()->getSignedVersion();
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004311 X = InsertCastBefore(X, DestTy, I);
Chris Lattnerc992add2003-08-13 05:33:12 +00004312 }
4313 return new SetCondInst(isSetNE ? Instruction::SetLT :
4314 Instruction::SetGE, X,
4315 Constant::getNullValue(X->getType()));
4316 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004317
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004318 // ((X & ~7) == 0) --> X < 8
Chris Lattner8fc5af42004-09-23 21:46:38 +00004319 if (CI->isNullValue() && isHighOnes(BOC)) {
4320 Value *X = BO->getOperand(0);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004321 Constant *NegX = ConstantExpr::getNeg(BOC);
Chris Lattner8fc5af42004-09-23 21:46:38 +00004322
4323 // If 'X' is signed, insert a cast now.
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004324 if (NegX->getType()->isSigned()) {
4325 const Type *DestTy = NegX->getType()->getUnsignedVersion();
4326 X = InsertCastBefore(X, DestTy, I);
4327 NegX = ConstantExpr::getCast(NegX, DestTy);
Chris Lattner8fc5af42004-09-23 21:46:38 +00004328 }
4329
4330 return new SetCondInst(isSetNE ? Instruction::SetGE :
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004331 Instruction::SetLT, X, NegX);
Chris Lattner8fc5af42004-09-23 21:46:38 +00004332 }
4333
Chris Lattnerd492a0b2003-07-23 17:02:11 +00004334 }
Chris Lattnerc992add2003-08-13 05:33:12 +00004335 default: break;
4336 }
4337 }
Chris Lattner2b55ea32004-02-23 07:16:20 +00004338 } else { // Not a SetEQ/SetNE
Misha Brukmanb1c93172005-04-21 23:48:37 +00004339 // If the LHS is a cast from an integral value of the same size,
Chris Lattner2b55ea32004-02-23 07:16:20 +00004340 if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
4341 Value *CastOp = Cast->getOperand(0);
4342 const Type *SrcTy = CastOp->getType();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004343 unsigned SrcTySize = SrcTy->getPrimitiveSizeInBits();
Chris Lattner2b55ea32004-02-23 07:16:20 +00004344 if (SrcTy != Cast->getType() && SrcTy->isInteger() &&
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004345 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00004346 assert((SrcTy->isSigned() ^ Cast->getType()->isSigned()) &&
Chris Lattner2b55ea32004-02-23 07:16:20 +00004347 "Source and destination signednesses should differ!");
4348 if (Cast->getType()->isSigned()) {
4349 // If this is a signed comparison, check for comparisons in the
4350 // vicinity of zero.
4351 if (I.getOpcode() == Instruction::SetLT && CI->isNullValue())
4352 // X < 0 => x > 127
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004353 return BinaryOperator::createSetGT(CastOp,
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004354 ConstantUInt::get(SrcTy, (1ULL << (SrcTySize-1))-1));
Chris Lattner2b55ea32004-02-23 07:16:20 +00004355 else if (I.getOpcode() == Instruction::SetGT &&
4356 cast<ConstantSInt>(CI)->getValue() == -1)
4357 // X > -1 => x < 128
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004358 return BinaryOperator::createSetLT(CastOp,
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004359 ConstantUInt::get(SrcTy, 1ULL << (SrcTySize-1)));
Chris Lattner2b55ea32004-02-23 07:16:20 +00004360 } else {
4361 ConstantUInt *CUI = cast<ConstantUInt>(CI);
4362 if (I.getOpcode() == Instruction::SetLT &&
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004363 CUI->getValue() == 1ULL << (SrcTySize-1))
Chris Lattner2b55ea32004-02-23 07:16:20 +00004364 // X < 128 => X > -1
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004365 return BinaryOperator::createSetGT(CastOp,
4366 ConstantSInt::get(SrcTy, -1));
Chris Lattner2b55ea32004-02-23 07:16:20 +00004367 else if (I.getOpcode() == Instruction::SetGT &&
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004368 CUI->getValue() == (1ULL << (SrcTySize-1))-1)
Chris Lattner2b55ea32004-02-23 07:16:20 +00004369 // X > 127 => X < 0
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004370 return BinaryOperator::createSetLT(CastOp,
4371 Constant::getNullValue(SrcTy));
Chris Lattner2b55ea32004-02-23 07:16:20 +00004372 }
4373 }
4374 }
Chris Lattnere967b342003-06-04 05:10:11 +00004375 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004376 }
4377
Chris Lattner77c32c32005-04-23 15:31:55 +00004378 // Handle setcc with constant RHS's that can be integer, FP or pointer.
4379 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
4380 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4381 switch (LHSI->getOpcode()) {
Chris Lattnera816eee2005-05-01 04:42:15 +00004382 case Instruction::GetElementPtr:
4383 if (RHSC->isNullValue()) {
4384 // Transform setcc GEP P, int 0, int 0, int 0, null -> setcc P, null
4385 bool isAllZeros = true;
4386 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
4387 if (!isa<Constant>(LHSI->getOperand(i)) ||
4388 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
4389 isAllZeros = false;
4390 break;
4391 }
4392 if (isAllZeros)
4393 return new SetCondInst(I.getOpcode(), LHSI->getOperand(0),
4394 Constant::getNullValue(LHSI->getOperand(0)->getType()));
4395 }
4396 break;
4397
Chris Lattner77c32c32005-04-23 15:31:55 +00004398 case Instruction::PHI:
4399 if (Instruction *NV = FoldOpIntoPhi(I))
4400 return NV;
4401 break;
4402 case Instruction::Select:
4403 // If either operand of the select is a constant, we can fold the
4404 // comparison into the select arms, which will cause one to be
4405 // constant folded and the select turned into a bitwise or.
4406 Value *Op1 = 0, *Op2 = 0;
4407 if (LHSI->hasOneUse()) {
4408 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
4409 // Fold the known value into the constant operand.
4410 Op1 = ConstantExpr::get(I.getOpcode(), C, RHSC);
4411 // Insert a new SetCC of the other select operand.
4412 Op2 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
4413 LHSI->getOperand(2), RHSC,
4414 I.getName()), I);
4415 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
4416 // Fold the known value into the constant operand.
4417 Op2 = ConstantExpr::get(I.getOpcode(), C, RHSC);
4418 // Insert a new SetCC of the other select operand.
4419 Op1 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
4420 LHSI->getOperand(1), RHSC,
4421 I.getName()), I);
4422 }
4423 }
Jeff Cohen82639852005-04-23 21:38:35 +00004424
Chris Lattner77c32c32005-04-23 15:31:55 +00004425 if (Op1)
4426 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
4427 break;
4428 }
4429 }
4430
Chris Lattner0798af32005-01-13 20:14:25 +00004431 // If we can optimize a 'setcc GEP, P' or 'setcc P, GEP', do so now.
4432 if (User *GEP = dyn_castGetElementPtr(Op0))
4433 if (Instruction *NI = FoldGEPSetCC(GEP, Op1, I.getOpcode(), I))
4434 return NI;
4435 if (User *GEP = dyn_castGetElementPtr(Op1))
4436 if (Instruction *NI = FoldGEPSetCC(GEP, Op0,
4437 SetCondInst::getSwappedCondition(I.getOpcode()), I))
4438 return NI;
4439
Chris Lattner16930792003-11-03 04:25:02 +00004440 // Test to see if the operands of the setcc are casted versions of other
4441 // values. If the cast can be stripped off both arguments, we do so now.
Chris Lattner6444c372003-11-03 05:17:03 +00004442 if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
4443 Value *CastOp0 = CI->getOperand(0);
4444 if (CastOp0->getType()->isLosslesslyConvertibleTo(CI->getType()) &&
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004445 (isa<Constant>(Op1) || isa<CastInst>(Op1)) && I.isEquality()) {
Chris Lattner16930792003-11-03 04:25:02 +00004446 // We keep moving the cast from the left operand over to the right
4447 // operand, where it can often be eliminated completely.
Chris Lattner6444c372003-11-03 05:17:03 +00004448 Op0 = CastOp0;
Misha Brukmanb1c93172005-04-21 23:48:37 +00004449
Chris Lattner16930792003-11-03 04:25:02 +00004450 // If operand #1 is a cast instruction, see if we can eliminate it as
4451 // well.
Chris Lattner6444c372003-11-03 05:17:03 +00004452 if (CastInst *CI2 = dyn_cast<CastInst>(Op1))
4453 if (CI2->getOperand(0)->getType()->isLosslesslyConvertibleTo(
Chris Lattner16930792003-11-03 04:25:02 +00004454 Op0->getType()))
Chris Lattner6444c372003-11-03 05:17:03 +00004455 Op1 = CI2->getOperand(0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004456
Chris Lattner16930792003-11-03 04:25:02 +00004457 // If Op1 is a constant, we can fold the cast into the constant.
4458 if (Op1->getType() != Op0->getType())
4459 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
4460 Op1 = ConstantExpr::getCast(Op1C, Op0->getType());
4461 } else {
4462 // Otherwise, cast the RHS right before the setcc
4463 Op1 = new CastInst(Op1, Op0->getType(), Op1->getName());
4464 InsertNewInstBefore(cast<Instruction>(Op1), I);
4465 }
4466 return BinaryOperator::create(I.getOpcode(), Op0, Op1);
4467 }
4468
Chris Lattner6444c372003-11-03 05:17:03 +00004469 // Handle the special case of: setcc (cast bool to X), <cst>
4470 // This comes up when you have code like
4471 // int X = A < B;
4472 // if (X) ...
4473 // For generality, we handle any zero-extension of any operand comparison
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004474 // with a constant or another cast from the same type.
4475 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
4476 if (Instruction *R = visitSetCondInstWithCastAndCast(I))
4477 return R;
Chris Lattner6444c372003-11-03 05:17:03 +00004478 }
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00004479
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004480 if (I.isEquality()) {
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00004481 Value *A, *B;
4482 if (match(Op0, m_Xor(m_Value(A), m_Value(B))) &&
4483 (A == Op1 || B == Op1)) {
4484 // (A^B) == A -> B == 0
4485 Value *OtherVal = A == Op1 ? B : A;
4486 return BinaryOperator::create(I.getOpcode(), OtherVal,
4487 Constant::getNullValue(A->getType()));
4488 } else if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
4489 (A == Op0 || B == Op0)) {
4490 // A == (A^B) -> B == 0
4491 Value *OtherVal = A == Op0 ? B : A;
4492 return BinaryOperator::create(I.getOpcode(), OtherVal,
4493 Constant::getNullValue(A->getType()));
4494 } else if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
4495 // (A-B) == A -> B == 0
4496 return BinaryOperator::create(I.getOpcode(), B,
4497 Constant::getNullValue(B->getType()));
4498 } else if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
4499 // A == (A-B) -> B == 0
4500 return BinaryOperator::create(I.getOpcode(), B,
4501 Constant::getNullValue(B->getType()));
4502 }
4503 }
Chris Lattner113f4f42002-06-25 16:13:24 +00004504 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004505}
4506
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004507// visitSetCondInstWithCastAndCast - Handle setcond (cast x to y), (cast/cst).
4508// We only handle extending casts so far.
4509//
4510Instruction *InstCombiner::visitSetCondInstWithCastAndCast(SetCondInst &SCI) {
4511 Value *LHSCIOp = cast<CastInst>(SCI.getOperand(0))->getOperand(0);
4512 const Type *SrcTy = LHSCIOp->getType();
4513 const Type *DestTy = SCI.getOperand(0)->getType();
4514 Value *RHSCIOp;
4515
4516 if (!DestTy->isIntegral() || !SrcTy->isIntegral())
Chris Lattner03f06f12005-01-17 03:20:02 +00004517 return 0;
4518
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004519 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
4520 unsigned DestBits = DestTy->getPrimitiveSizeInBits();
4521 if (SrcBits >= DestBits) return 0; // Only handle extending cast.
4522
4523 // Is this a sign or zero extension?
4524 bool isSignSrc = SrcTy->isSigned();
4525 bool isSignDest = DestTy->isSigned();
4526
4527 if (CastInst *CI = dyn_cast<CastInst>(SCI.getOperand(1))) {
4528 // Not an extension from the same type?
4529 RHSCIOp = CI->getOperand(0);
4530 if (RHSCIOp->getType() != LHSCIOp->getType()) return 0;
4531 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(SCI.getOperand(1))) {
4532 // Compute the constant that would happen if we truncated to SrcTy then
4533 // reextended to DestTy.
4534 Constant *Res = ConstantExpr::getCast(CI, SrcTy);
4535
4536 if (ConstantExpr::getCast(Res, DestTy) == CI) {
4537 RHSCIOp = Res;
4538 } else {
4539 // If the value cannot be represented in the shorter type, we cannot emit
4540 // a simple comparison.
4541 if (SCI.getOpcode() == Instruction::SetEQ)
4542 return ReplaceInstUsesWith(SCI, ConstantBool::False);
4543 if (SCI.getOpcode() == Instruction::SetNE)
4544 return ReplaceInstUsesWith(SCI, ConstantBool::True);
4545
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004546 // Evaluate the comparison for LT.
4547 Value *Result;
4548 if (DestTy->isSigned()) {
4549 // We're performing a signed comparison.
4550 if (isSignSrc) {
4551 // Signed extend and signed comparison.
4552 if (cast<ConstantSInt>(CI)->getValue() < 0) // X < (small) --> false
4553 Result = ConstantBool::False;
4554 else
4555 Result = ConstantBool::True; // X < (large) --> true
4556 } else {
4557 // Unsigned extend and signed comparison.
4558 if (cast<ConstantSInt>(CI)->getValue() < 0)
4559 Result = ConstantBool::False;
4560 else
4561 Result = ConstantBool::True;
4562 }
4563 } else {
4564 // We're performing an unsigned comparison.
4565 if (!isSignSrc) {
4566 // Unsigned extend & compare -> always true.
4567 Result = ConstantBool::True;
4568 } else {
4569 // We're performing an unsigned comp with a sign extended value.
4570 // This is true if the input is >= 0. [aka >s -1]
4571 Constant *NegOne = ConstantIntegral::getAllOnesValue(SrcTy);
4572 Result = InsertNewInstBefore(BinaryOperator::createSetGT(LHSCIOp,
4573 NegOne, SCI.getName()), SCI);
4574 }
Reid Spencer279fa252004-11-28 21:31:15 +00004575 }
Chris Lattner03f06f12005-01-17 03:20:02 +00004576
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00004577 // Finally, return the value computed.
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004578 if (SCI.getOpcode() == Instruction::SetLT) {
4579 return ReplaceInstUsesWith(SCI, Result);
4580 } else {
4581 assert(SCI.getOpcode()==Instruction::SetGT &&"SetCC should be folded!");
4582 if (Constant *CI = dyn_cast<Constant>(Result))
4583 return ReplaceInstUsesWith(SCI, ConstantExpr::getNot(CI));
4584 else
4585 return BinaryOperator::createNot(Result);
4586 }
Chris Lattner03f06f12005-01-17 03:20:02 +00004587 }
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004588 } else {
4589 return 0;
Reid Spencer279fa252004-11-28 21:31:15 +00004590 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004591
Chris Lattner252a8452005-06-16 03:00:08 +00004592 // Okay, just insert a compare of the reduced operands now!
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004593 return BinaryOperator::create(SCI.getOpcode(), LHSCIOp, RHSCIOp);
4594}
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004595
Chris Lattnere8d6c602003-03-10 19:16:08 +00004596Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +00004597 assert(I.getOperand(1)->getType() == Type::UByteTy);
4598 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00004599 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004600
4601 // shl X, 0 == X and shr X, 0 == X
4602 // shl 0, X == 0 and shr 0, X == 0
4603 if (Op1 == Constant::getNullValue(Type::UByteTy) ||
Chris Lattnere6794492002-08-12 21:17:25 +00004604 Op0 == Constant::getNullValue(Op0->getType()))
4605 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf5b4ef72006-02-12 08:07:37 +00004606
Chris Lattner81a7a232004-10-16 18:11:37 +00004607 if (isa<UndefValue>(Op0)) { // undef >>s X -> undef
4608 if (!isLeftShift && I.getType()->isSigned())
Chris Lattner67f05452004-10-16 23:28:04 +00004609 return ReplaceInstUsesWith(I, Op0);
Chris Lattner81a7a232004-10-16 18:11:37 +00004610 else // undef << X -> 0 AND undef >>u X -> 0
4611 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4612 }
4613 if (isa<UndefValue>(Op1)) {
Chris Lattner18aa4d82005-07-20 18:49:28 +00004614 if (isLeftShift || I.getType()->isUnsigned())// X << undef, X >>u undef -> 0
Chris Lattner81a7a232004-10-16 18:11:37 +00004615 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4616 else
4617 return ReplaceInstUsesWith(I, Op0); // X >>s undef -> X
4618 }
4619
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00004620 // shr int -1, X = -1 (for any arithmetic shift rights of ~0)
4621 if (!isLeftShift)
4622 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
4623 if (CSI->isAllOnesValue())
4624 return ReplaceInstUsesWith(I, CSI);
4625
Chris Lattner183b3362004-04-09 19:05:30 +00004626 // Try to fold constant and into select arguments.
4627 if (isa<Constant>(Op0))
4628 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner86102b82005-01-01 16:22:27 +00004629 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00004630 return R;
4631
Chris Lattnerb18dbbf2005-05-08 17:34:56 +00004632 // See if we can turn a signed shr into an unsigned shr.
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004633 if (I.isArithmeticShift()) {
Chris Lattnerc3ebf402006-02-07 07:27:52 +00004634 if (MaskedValueIsZero(Op0,
4635 1ULL << (I.getType()->getPrimitiveSizeInBits()-1))) {
Chris Lattnerb18dbbf2005-05-08 17:34:56 +00004636 Value *V = InsertCastBefore(Op0, I.getType()->getUnsignedVersion(), I);
4637 V = InsertNewInstBefore(new ShiftInst(Instruction::Shr, V, Op1,
4638 I.getName()), I);
4639 return new CastInst(V, I.getType());
4640 }
4641 }
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00004642
Chris Lattner14553932006-01-06 07:12:35 +00004643 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op1))
4644 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
4645 return Res;
4646 return 0;
4647}
4648
4649Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantUInt *Op1,
4650 ShiftInst &I) {
4651 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattnerb3309392006-01-06 07:22:22 +00004652 bool isSignedShift = Op0->getType()->isSigned();
4653 bool isUnsignedShift = !isSignedShift;
Chris Lattner14553932006-01-06 07:12:35 +00004654
Chris Lattnerf5b4ef72006-02-12 08:07:37 +00004655 // See if we can simplify any instructions used by the instruction whose sole
4656 // purpose is to compute bits we don't care about.
4657 uint64_t KnownZero, KnownOne;
4658 if (SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
4659 KnownZero, KnownOne))
4660 return &I;
4661
Chris Lattner14553932006-01-06 07:12:35 +00004662 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
4663 // of a signed value.
4664 //
4665 unsigned TypeBits = Op0->getType()->getPrimitiveSizeInBits();
4666 if (Op1->getValue() >= TypeBits) {
Chris Lattnerb3309392006-01-06 07:22:22 +00004667 if (isUnsignedShift || isLeftShift)
Chris Lattner14553932006-01-06 07:12:35 +00004668 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
4669 else {
4670 I.setOperand(1, ConstantUInt::get(Type::UByteTy, TypeBits-1));
4671 return &I;
Chris Lattnerf5ce2542004-02-23 20:30:06 +00004672 }
Chris Lattner14553932006-01-06 07:12:35 +00004673 }
4674
4675 // ((X*C1) << C2) == (X * (C1 << C2))
4676 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
4677 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
4678 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
4679 return BinaryOperator::createMul(BO->getOperand(0),
4680 ConstantExpr::getShl(BOOp, Op1));
4681
4682 // Try to fold constant and into select arguments.
4683 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4684 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4685 return R;
4686 if (isa<PHINode>(Op0))
4687 if (Instruction *NV = FoldOpIntoPhi(I))
4688 return NV;
4689
4690 if (Op0->hasOneUse()) {
Chris Lattner14553932006-01-06 07:12:35 +00004691 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
4692 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
4693 Value *V1, *V2;
4694 ConstantInt *CC;
4695 switch (Op0BO->getOpcode()) {
Chris Lattner27cb9db2005-09-18 05:12:10 +00004696 default: break;
4697 case Instruction::Add:
4698 case Instruction::And:
4699 case Instruction::Or:
4700 case Instruction::Xor:
4701 // These operators commute.
4702 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner797dee72005-09-18 06:30:59 +00004703 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
4704 match(Op0BO->getOperand(1),
Chris Lattner14553932006-01-06 07:12:35 +00004705 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Chris Lattner797dee72005-09-18 06:30:59 +00004706 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00004707 Op0BO->getOperand(0), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00004708 Op0BO->getName());
4709 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner24cd2fa2006-02-09 07:41:14 +00004710 Instruction *X =
4711 BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
4712 Op0BO->getOperand(1)->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00004713 InsertNewInstBefore(X, I); // (X + (Y << C))
4714 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
Chris Lattner14553932006-01-06 07:12:35 +00004715 C2 = ConstantExpr::getShl(C2, Op1);
Chris Lattner797dee72005-09-18 06:30:59 +00004716 return BinaryOperator::createAnd(X, C2);
4717 }
Chris Lattner14553932006-01-06 07:12:35 +00004718
Chris Lattner797dee72005-09-18 06:30:59 +00004719 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
4720 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
4721 match(Op0BO->getOperand(1),
4722 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner14553932006-01-06 07:12:35 +00004723 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner24cd2fa2006-02-09 07:41:14 +00004724 cast<BinaryOperator>(Op0BO->getOperand(1))->getOperand(0)->hasOneUse()) {
Chris Lattner797dee72005-09-18 06:30:59 +00004725 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00004726 Op0BO->getOperand(0), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00004727 Op0BO->getName());
4728 InsertNewInstBefore(YS, I); // (Y << C)
4729 Instruction *XM =
Chris Lattner14553932006-01-06 07:12:35 +00004730 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner797dee72005-09-18 06:30:59 +00004731 V1->getName()+".mask");
4732 InsertNewInstBefore(XM, I); // X & (CC << C)
4733
4734 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
4735 }
Chris Lattner14553932006-01-06 07:12:35 +00004736
Chris Lattner797dee72005-09-18 06:30:59 +00004737 // FALL THROUGH.
Chris Lattner27cb9db2005-09-18 05:12:10 +00004738 case Instruction::Sub:
4739 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner797dee72005-09-18 06:30:59 +00004740 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
4741 match(Op0BO->getOperand(0),
Chris Lattner14553932006-01-06 07:12:35 +00004742 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Chris Lattner797dee72005-09-18 06:30:59 +00004743 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00004744 Op0BO->getOperand(1), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00004745 Op0BO->getName());
4746 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner24cd2fa2006-02-09 07:41:14 +00004747 Instruction *X =
Chris Lattner1df0e982006-05-31 21:14:00 +00004748 BinaryOperator::create(Op0BO->getOpcode(), V1, YS,
Chris Lattner24cd2fa2006-02-09 07:41:14 +00004749 Op0BO->getOperand(0)->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00004750 InsertNewInstBefore(X, I); // (X + (Y << C))
4751 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
Chris Lattner14553932006-01-06 07:12:35 +00004752 C2 = ConstantExpr::getShl(C2, Op1);
Chris Lattner797dee72005-09-18 06:30:59 +00004753 return BinaryOperator::createAnd(X, C2);
4754 }
Chris Lattner14553932006-01-06 07:12:35 +00004755
Chris Lattner1df0e982006-05-31 21:14:00 +00004756 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner797dee72005-09-18 06:30:59 +00004757 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
4758 match(Op0BO->getOperand(0),
4759 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner14553932006-01-06 07:12:35 +00004760 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner24cd2fa2006-02-09 07:41:14 +00004761 cast<BinaryOperator>(Op0BO->getOperand(0))
4762 ->getOperand(0)->hasOneUse()) {
Chris Lattner797dee72005-09-18 06:30:59 +00004763 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00004764 Op0BO->getOperand(1), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00004765 Op0BO->getName());
4766 InsertNewInstBefore(YS, I); // (Y << C)
4767 Instruction *XM =
Chris Lattner14553932006-01-06 07:12:35 +00004768 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner797dee72005-09-18 06:30:59 +00004769 V1->getName()+".mask");
4770 InsertNewInstBefore(XM, I); // X & (CC << C)
4771
Chris Lattner1df0e982006-05-31 21:14:00 +00004772 return BinaryOperator::create(Op0BO->getOpcode(), XM, YS);
Chris Lattner797dee72005-09-18 06:30:59 +00004773 }
Chris Lattner14553932006-01-06 07:12:35 +00004774
Chris Lattner27cb9db2005-09-18 05:12:10 +00004775 break;
Chris Lattner14553932006-01-06 07:12:35 +00004776 }
4777
4778
4779 // If the operand is an bitwise operator with a constant RHS, and the
4780 // shift is the only use, we can pull it out of the shift.
4781 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
4782 bool isValid = true; // Valid only for And, Or, Xor
4783 bool highBitSet = false; // Transform if high bit of constant set?
4784
4785 switch (Op0BO->getOpcode()) {
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00004786 default: isValid = false; break; // Do not perform transform!
Chris Lattner44bd3922004-10-08 03:46:20 +00004787 case Instruction::Add:
4788 isValid = isLeftShift;
4789 break;
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00004790 case Instruction::Or:
4791 case Instruction::Xor:
4792 highBitSet = false;
4793 break;
4794 case Instruction::And:
4795 highBitSet = true;
4796 break;
Chris Lattner14553932006-01-06 07:12:35 +00004797 }
4798
4799 // If this is a signed shift right, and the high bit is modified
4800 // by the logical operation, do not perform the transformation.
4801 // The highBitSet boolean indicates the value of the high bit of
4802 // the constant which would cause it to be modified for this
4803 // operation.
4804 //
Chris Lattnerb3309392006-01-06 07:22:22 +00004805 if (isValid && !isLeftShift && isSignedShift) {
Chris Lattner14553932006-01-06 07:12:35 +00004806 uint64_t Val = Op0C->getRawValue();
4807 isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
4808 }
4809
4810 if (isValid) {
4811 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
4812
4813 Instruction *NewShift =
4814 new ShiftInst(I.getOpcode(), Op0BO->getOperand(0), Op1,
4815 Op0BO->getName());
4816 Op0BO->setName("");
4817 InsertNewInstBefore(NewShift, I);
4818
4819 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
4820 NewRHS);
4821 }
4822 }
4823 }
4824 }
4825
Chris Lattnereb372a02006-01-06 07:52:12 +00004826 // Find out if this is a shift of a shift by a constant.
4827 ShiftInst *ShiftOp = 0;
Chris Lattner14553932006-01-06 07:12:35 +00004828 if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0))
Chris Lattnereb372a02006-01-06 07:52:12 +00004829 ShiftOp = Op0SI;
4830 else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
4831 // If this is a noop-integer case of a shift instruction, use the shift.
4832 if (CI->getOperand(0)->getType()->isInteger() &&
4833 CI->getOperand(0)->getType()->getPrimitiveSizeInBits() ==
4834 CI->getType()->getPrimitiveSizeInBits() &&
4835 isa<ShiftInst>(CI->getOperand(0))) {
4836 ShiftOp = cast<ShiftInst>(CI->getOperand(0));
4837 }
4838 }
4839
4840 if (ShiftOp && isa<ConstantUInt>(ShiftOp->getOperand(1))) {
4841 // Find the operands and properties of the input shift. Note that the
4842 // signedness of the input shift may differ from the current shift if there
4843 // is a noop cast between the two.
4844 bool isShiftOfLeftShift = ShiftOp->getOpcode() == Instruction::Shl;
4845 bool isShiftOfSignedShift = ShiftOp->getType()->isSigned();
Chris Lattner9cbfbc22006-01-07 01:32:28 +00004846 bool isShiftOfUnsignedShift = !isShiftOfSignedShift;
Chris Lattnereb372a02006-01-06 07:52:12 +00004847
4848 ConstantUInt *ShiftAmt1C = cast<ConstantUInt>(ShiftOp->getOperand(1));
4849
4850 unsigned ShiftAmt1 = (unsigned)ShiftAmt1C->getValue();
4851 unsigned ShiftAmt2 = (unsigned)Op1->getValue();
4852
4853 // Check for (A << c1) << c2 and (A >> c1) >> c2.
4854 if (isLeftShift == isShiftOfLeftShift) {
4855 // Do not fold these shifts if the first one is signed and the second one
4856 // is unsigned and this is a right shift. Further, don't do any folding
4857 // on them.
4858 if (isShiftOfSignedShift && isUnsignedShift && !isLeftShift)
4859 return 0;
Chris Lattner14553932006-01-06 07:12:35 +00004860
Chris Lattnereb372a02006-01-06 07:52:12 +00004861 unsigned Amt = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
4862 if (Amt > Op0->getType()->getPrimitiveSizeInBits())
4863 Amt = Op0->getType()->getPrimitiveSizeInBits();
Chris Lattner14553932006-01-06 07:12:35 +00004864
Chris Lattnereb372a02006-01-06 07:52:12 +00004865 Value *Op = ShiftOp->getOperand(0);
4866 if (isShiftOfSignedShift != isSignedShift)
4867 Op = InsertNewInstBefore(new CastInst(Op, I.getType(), "tmp"), I);
4868 return new ShiftInst(I.getOpcode(), Op,
4869 ConstantUInt::get(Type::UByteTy, Amt));
4870 }
4871
4872 // Check for (A << c1) >> c2 or (A >> c1) << c2. If we are dealing with
4873 // signed types, we can only support the (A >> c1) << c2 configuration,
4874 // because it can not turn an arbitrary bit of A into a sign bit.
4875 if (isUnsignedShift || isLeftShift) {
4876 // Calculate bitmask for what gets shifted off the edge.
4877 Constant *C = ConstantIntegral::getAllOnesValue(I.getType());
4878 if (isLeftShift)
4879 C = ConstantExpr::getShl(C, ShiftAmt1C);
4880 else
Chris Lattner9cbfbc22006-01-07 01:32:28 +00004881 C = ConstantExpr::getUShr(C, ShiftAmt1C);
Chris Lattnereb372a02006-01-06 07:52:12 +00004882
4883 Value *Op = ShiftOp->getOperand(0);
4884 if (isShiftOfSignedShift != isSignedShift)
4885 Op = InsertNewInstBefore(new CastInst(Op, I.getType(),Op->getName()),I);
4886
4887 Instruction *Mask =
4888 BinaryOperator::createAnd(Op, C, Op->getName()+".mask");
4889 InsertNewInstBefore(Mask, I);
4890
4891 // Figure out what flavor of shift we should use...
Chris Lattner9cbfbc22006-01-07 01:32:28 +00004892 if (ShiftAmt1 == ShiftAmt2) {
Chris Lattnereb372a02006-01-06 07:52:12 +00004893 return ReplaceInstUsesWith(I, Mask); // (A << c) >> c === A & c2
Chris Lattner9cbfbc22006-01-07 01:32:28 +00004894 } else if (ShiftAmt1 < ShiftAmt2) {
Chris Lattnereb372a02006-01-06 07:52:12 +00004895 return new ShiftInst(I.getOpcode(), Mask,
4896 ConstantUInt::get(Type::UByteTy, ShiftAmt2-ShiftAmt1));
Chris Lattner9cbfbc22006-01-07 01:32:28 +00004897 } else if (isShiftOfUnsignedShift || isShiftOfLeftShift) {
4898 if (isShiftOfUnsignedShift && !isShiftOfLeftShift && isSignedShift) {
4899 // Make sure to emit an unsigned shift right, not a signed one.
4900 Mask = InsertNewInstBefore(new CastInst(Mask,
4901 Mask->getType()->getUnsignedVersion(),
4902 Op->getName()), I);
4903 Mask = new ShiftInst(Instruction::Shr, Mask,
Chris Lattnereb372a02006-01-06 07:52:12 +00004904 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
Chris Lattner9cbfbc22006-01-07 01:32:28 +00004905 InsertNewInstBefore(Mask, I);
4906 return new CastInst(Mask, I.getType());
4907 } else {
4908 return new ShiftInst(ShiftOp->getOpcode(), Mask,
4909 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
4910 }
4911 } else {
4912 // (X >>s C1) << C2 where C1 > C2 === (X >>s (C1-C2)) & mask
4913 Op = InsertNewInstBefore(new CastInst(Mask,
4914 I.getType()->getSignedVersion(),
4915 Mask->getName()), I);
4916 Instruction *Shift =
4917 new ShiftInst(ShiftOp->getOpcode(), Op,
4918 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
4919 InsertNewInstBefore(Shift, I);
4920
4921 C = ConstantIntegral::getAllOnesValue(Shift->getType());
4922 C = ConstantExpr::getShl(C, Op1);
4923 Mask = BinaryOperator::createAnd(Shift, C, Op->getName()+".mask");
4924 InsertNewInstBefore(Mask, I);
4925 return new CastInst(Mask, I.getType());
Chris Lattnereb372a02006-01-06 07:52:12 +00004926 }
4927 } else {
Chris Lattner9cbfbc22006-01-07 01:32:28 +00004928 // We can handle signed (X << C1) >>s C2 if it's a sign extend. In
Chris Lattnereb372a02006-01-06 07:52:12 +00004929 // this case, C1 == C2 and C1 is 8, 16, or 32.
4930 if (ShiftAmt1 == ShiftAmt2) {
4931 const Type *SExtType = 0;
Chris Lattner655d08f2006-04-28 22:21:41 +00004932 switch (Op0->getType()->getPrimitiveSizeInBits() - ShiftAmt1) {
Chris Lattnereb372a02006-01-06 07:52:12 +00004933 case 8 : SExtType = Type::SByteTy; break;
4934 case 16: SExtType = Type::ShortTy; break;
4935 case 32: SExtType = Type::IntTy; break;
4936 }
4937
4938 if (SExtType) {
4939 Instruction *NewTrunc = new CastInst(ShiftOp->getOperand(0),
4940 SExtType, "sext");
4941 InsertNewInstBefore(NewTrunc, I);
4942 return new CastInst(NewTrunc, I.getType());
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00004943 }
Chris Lattner27cb9db2005-09-18 05:12:10 +00004944 }
Chris Lattner86102b82005-01-01 16:22:27 +00004945 }
Chris Lattnereb372a02006-01-06 07:52:12 +00004946 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004947 return 0;
4948}
4949
Chris Lattner48a44f72002-05-02 17:06:02 +00004950
Chris Lattner8f663e82005-10-29 04:36:15 +00004951/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
4952/// expression. If so, decompose it, returning some value X, such that Val is
4953/// X*Scale+Offset.
4954///
4955static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
4956 unsigned &Offset) {
4957 assert(Val->getType() == Type::UIntTy && "Unexpected allocation size type!");
4958 if (ConstantUInt *CI = dyn_cast<ConstantUInt>(Val)) {
4959 Offset = CI->getValue();
4960 Scale = 1;
4961 return ConstantUInt::get(Type::UIntTy, 0);
4962 } else if (Instruction *I = dyn_cast<Instruction>(Val)) {
4963 if (I->getNumOperands() == 2) {
4964 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(I->getOperand(1))) {
4965 if (I->getOpcode() == Instruction::Shl) {
4966 // This is a value scaled by '1 << the shift amt'.
4967 Scale = 1U << CUI->getValue();
4968 Offset = 0;
4969 return I->getOperand(0);
4970 } else if (I->getOpcode() == Instruction::Mul) {
4971 // This value is scaled by 'CUI'.
4972 Scale = CUI->getValue();
4973 Offset = 0;
4974 return I->getOperand(0);
4975 } else if (I->getOpcode() == Instruction::Add) {
4976 // We have X+C. Check to see if we really have (X*C2)+C1, where C1 is
4977 // divisible by C2.
4978 unsigned SubScale;
4979 Value *SubVal = DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
4980 Offset);
4981 Offset += CUI->getValue();
4982 if (SubScale > 1 && (Offset % SubScale == 0)) {
4983 Scale = SubScale;
4984 return SubVal;
4985 }
4986 }
4987 }
4988 }
4989 }
4990
4991 // Otherwise, we can't look past this.
4992 Scale = 1;
4993 Offset = 0;
4994 return Val;
4995}
4996
4997
Chris Lattner216be912005-10-24 06:03:58 +00004998/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
4999/// try to eliminate the cast by moving the type information into the alloc.
5000Instruction *InstCombiner::PromoteCastOfAllocation(CastInst &CI,
5001 AllocationInst &AI) {
5002 const PointerType *PTy = dyn_cast<PointerType>(CI.getType());
Chris Lattnerbb171802005-10-27 05:53:56 +00005003 if (!PTy) return 0; // Not casting the allocation to a pointer type.
Chris Lattner216be912005-10-24 06:03:58 +00005004
Chris Lattnerac87beb2005-10-24 06:22:12 +00005005 // Remove any uses of AI that are dead.
5006 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
5007 std::vector<Instruction*> DeadUsers;
5008 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
5009 Instruction *User = cast<Instruction>(*UI++);
5010 if (isInstructionTriviallyDead(User)) {
5011 while (UI != E && *UI == User)
5012 ++UI; // If this instruction uses AI more than once, don't break UI.
5013
5014 // Add operands to the worklist.
5015 AddUsesToWorkList(*User);
5016 ++NumDeadInst;
5017 DEBUG(std::cerr << "IC: DCE: " << *User);
5018
5019 User->eraseFromParent();
5020 removeFromWorkList(User);
5021 }
5022 }
5023
Chris Lattner216be912005-10-24 06:03:58 +00005024 // Get the type really allocated and the type casted to.
5025 const Type *AllocElTy = AI.getAllocatedType();
5026 const Type *CastElTy = PTy->getElementType();
5027 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner355ecc02005-10-24 06:26:18 +00005028
5029 unsigned AllocElTyAlign = TD->getTypeSize(AllocElTy);
5030 unsigned CastElTyAlign = TD->getTypeSize(CastElTy);
5031 if (CastElTyAlign < AllocElTyAlign) return 0;
5032
Chris Lattner46705b22005-10-24 06:35:18 +00005033 // If the allocation has multiple uses, only promote it if we are strictly
5034 // increasing the alignment of the resultant allocation. If we keep it the
5035 // same, we open the door to infinite loops of various kinds.
5036 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
5037
Chris Lattner216be912005-10-24 06:03:58 +00005038 uint64_t AllocElTySize = TD->getTypeSize(AllocElTy);
5039 uint64_t CastElTySize = TD->getTypeSize(CastElTy);
Chris Lattnerbb171802005-10-27 05:53:56 +00005040 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner355ecc02005-10-24 06:26:18 +00005041
Chris Lattner8270c332005-10-29 03:19:53 +00005042 // See if we can satisfy the modulus by pulling a scale out of the array
5043 // size argument.
Chris Lattner8f663e82005-10-29 04:36:15 +00005044 unsigned ArraySizeScale, ArrayOffset;
5045 Value *NumElements = // See if the array size is a decomposable linear expr.
5046 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
5047
Chris Lattner8270c332005-10-29 03:19:53 +00005048 // If we can now satisfy the modulus, by using a non-1 scale, we really can
5049 // do the xform.
Chris Lattner8f663e82005-10-29 04:36:15 +00005050 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
5051 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattnerb3ecf962005-10-27 06:12:00 +00005052
Chris Lattner8270c332005-10-29 03:19:53 +00005053 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
5054 Value *Amt = 0;
5055 if (Scale == 1) {
5056 Amt = NumElements;
5057 } else {
5058 Amt = ConstantUInt::get(Type::UIntTy, Scale);
5059 if (ConstantUInt *CI = dyn_cast<ConstantUInt>(NumElements))
5060 Amt = ConstantExpr::getMul(CI, cast<ConstantUInt>(Amt));
5061 else if (Scale != 1) {
5062 Instruction *Tmp = BinaryOperator::createMul(Amt, NumElements, "tmp");
5063 Amt = InsertNewInstBefore(Tmp, AI);
Chris Lattnerb3ecf962005-10-27 06:12:00 +00005064 }
Chris Lattnerbb171802005-10-27 05:53:56 +00005065 }
5066
Chris Lattner8f663e82005-10-29 04:36:15 +00005067 if (unsigned Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
5068 Value *Off = ConstantUInt::get(Type::UIntTy, Offset);
5069 Instruction *Tmp = BinaryOperator::createAdd(Amt, Off, "tmp");
5070 Amt = InsertNewInstBefore(Tmp, AI);
5071 }
5072
Chris Lattner216be912005-10-24 06:03:58 +00005073 std::string Name = AI.getName(); AI.setName("");
5074 AllocationInst *New;
5075 if (isa<MallocInst>(AI))
Nate Begeman848622f2005-11-05 09:21:28 +00005076 New = new MallocInst(CastElTy, Amt, AI.getAlignment(), Name);
Chris Lattner216be912005-10-24 06:03:58 +00005077 else
Nate Begeman848622f2005-11-05 09:21:28 +00005078 New = new AllocaInst(CastElTy, Amt, AI.getAlignment(), Name);
Chris Lattner216be912005-10-24 06:03:58 +00005079 InsertNewInstBefore(New, AI);
Chris Lattner46705b22005-10-24 06:35:18 +00005080
5081 // If the allocation has multiple uses, insert a cast and change all things
5082 // that used it to use the new cast. This will also hack on CI, but it will
5083 // die soon.
5084 if (!AI.hasOneUse()) {
5085 AddUsesToWorkList(AI);
5086 CastInst *NewCast = new CastInst(New, AI.getType(), "tmpcast");
5087 InsertNewInstBefore(NewCast, AI);
5088 AI.replaceAllUsesWith(NewCast);
5089 }
Chris Lattner216be912005-10-24 06:03:58 +00005090 return ReplaceInstUsesWith(CI, New);
5091}
5092
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005093/// CanEvaluateInDifferentType - Return true if we can take the specified value
5094/// and return it without inserting any new casts. This is used by code that
5095/// tries to decide whether promoting or shrinking integer operations to wider
5096/// or smaller types will allow us to eliminate a truncate or extend.
5097static bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
5098 int &NumCastsRemoved) {
5099 if (isa<Constant>(V)) return true;
5100
5101 Instruction *I = dyn_cast<Instruction>(V);
5102 if (!I || !I->hasOneUse()) return false;
5103
5104 switch (I->getOpcode()) {
5105 case Instruction::And:
5106 case Instruction::Or:
5107 case Instruction::Xor:
5108 // These operators can all arbitrarily be extended or truncated.
5109 return CanEvaluateInDifferentType(I->getOperand(0), Ty, NumCastsRemoved) &&
5110 CanEvaluateInDifferentType(I->getOperand(1), Ty, NumCastsRemoved);
5111 case Instruction::Cast:
5112 // If this is a cast from the destination type, we can trivially eliminate
5113 // it, and this will remove a cast overall.
5114 if (I->getOperand(0)->getType() == Ty) {
Chris Lattner3fda3862006-06-28 17:34:50 +00005115 // If the first operand is itself a cast, and is eliminable, do not count
5116 // this as an eliminable cast. We would prefer to eliminate those two
5117 // casts first.
5118 if (CastInst *OpCast = dyn_cast<CastInst>(I->getOperand(0)))
5119 return true;
5120
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005121 ++NumCastsRemoved;
5122 return true;
5123 }
5124 // TODO: Can handle more cases here.
5125 break;
5126 }
5127
5128 return false;
5129}
5130
5131/// EvaluateInDifferentType - Given an expression that
5132/// CanEvaluateInDifferentType returns true for, actually insert the code to
5133/// evaluate the expression.
5134Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty) {
5135 if (Constant *C = dyn_cast<Constant>(V))
5136 return ConstantExpr::getCast(C, Ty);
5137
5138 // Otherwise, it must be an instruction.
5139 Instruction *I = cast<Instruction>(V);
Chris Lattnerd0622b62006-05-20 23:14:03 +00005140 Instruction *Res = 0;
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005141 switch (I->getOpcode()) {
5142 case Instruction::And:
5143 case Instruction::Or:
5144 case Instruction::Xor: {
5145 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty);
5146 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty);
5147 Res = BinaryOperator::create((Instruction::BinaryOps)I->getOpcode(),
5148 LHS, RHS, I->getName());
5149 break;
5150 }
5151 case Instruction::Cast:
5152 // If this is a cast from the destination type, return the input.
5153 if (I->getOperand(0)->getType() == Ty)
5154 return I->getOperand(0);
5155
5156 // TODO: Can handle more cases here.
5157 assert(0 && "Unreachable!");
5158 break;
5159 }
5160
5161 return InsertNewInstBefore(Res, *I);
5162}
5163
Chris Lattner216be912005-10-24 06:03:58 +00005164
Chris Lattner48a44f72002-05-02 17:06:02 +00005165// CastInst simplification
Chris Lattner260ab202002-04-18 17:39:14 +00005166//
Chris Lattner113f4f42002-06-25 16:13:24 +00005167Instruction *InstCombiner::visitCastInst(CastInst &CI) {
Chris Lattner55d4bda2003-06-23 21:59:52 +00005168 Value *Src = CI.getOperand(0);
5169
Chris Lattner48a44f72002-05-02 17:06:02 +00005170 // If the user is casting a value to the same type, eliminate this cast
5171 // instruction...
Chris Lattner55d4bda2003-06-23 21:59:52 +00005172 if (CI.getType() == Src->getType())
5173 return ReplaceInstUsesWith(CI, Src);
Chris Lattner48a44f72002-05-02 17:06:02 +00005174
Chris Lattner81a7a232004-10-16 18:11:37 +00005175 if (isa<UndefValue>(Src)) // cast undef -> undef
5176 return ReplaceInstUsesWith(CI, UndefValue::get(CI.getType()));
5177
Chris Lattner48a44f72002-05-02 17:06:02 +00005178 // If casting the result of another cast instruction, try to eliminate this
5179 // one!
5180 //
Chris Lattner86102b82005-01-01 16:22:27 +00005181 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
5182 Value *A = CSrc->getOperand(0);
5183 if (isEliminableCastOfCast(A->getType(), CSrc->getType(),
5184 CI.getType(), TD)) {
Chris Lattner48a44f72002-05-02 17:06:02 +00005185 // This instruction now refers directly to the cast's src operand. This
5186 // has a good chance of making CSrc dead.
Chris Lattner113f4f42002-06-25 16:13:24 +00005187 CI.setOperand(0, CSrc->getOperand(0));
5188 return &CI;
Chris Lattner48a44f72002-05-02 17:06:02 +00005189 }
5190
Chris Lattner650b6da2002-08-02 20:00:25 +00005191 // If this is an A->B->A cast, and we are dealing with integral types, try
5192 // to convert this into a logical 'and' instruction.
5193 //
Misha Brukmanb1c93172005-04-21 23:48:37 +00005194 if (A->getType()->isInteger() &&
Chris Lattnerb0b412e2002-09-03 01:08:28 +00005195 CI.getType()->isInteger() && CSrc->getType()->isInteger() &&
Chris Lattner86102b82005-01-01 16:22:27 +00005196 CSrc->getType()->isUnsigned() && // B->A cast must zero extend
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005197 CSrc->getType()->getPrimitiveSizeInBits() <
5198 CI.getType()->getPrimitiveSizeInBits()&&
5199 A->getType()->getPrimitiveSizeInBits() ==
5200 CI.getType()->getPrimitiveSizeInBits()) {
Chris Lattner650b6da2002-08-02 20:00:25 +00005201 assert(CSrc->getType() != Type::ULongTy &&
5202 "Cannot have type bigger than ulong!");
Chris Lattner77defba2006-02-07 07:00:41 +00005203 uint64_t AndValue = CSrc->getType()->getIntegralTypeMask();
Chris Lattner86102b82005-01-01 16:22:27 +00005204 Constant *AndOp = ConstantUInt::get(A->getType()->getUnsignedVersion(),
5205 AndValue);
5206 AndOp = ConstantExpr::getCast(AndOp, A->getType());
5207 Instruction *And = BinaryOperator::createAnd(CSrc->getOperand(0), AndOp);
5208 if (And->getType() != CI.getType()) {
5209 And->setName(CSrc->getName()+".mask");
5210 InsertNewInstBefore(And, CI);
5211 And = new CastInst(And, CI.getType());
5212 }
5213 return And;
Chris Lattner650b6da2002-08-02 20:00:25 +00005214 }
5215 }
Chris Lattner2590e512006-02-07 06:56:34 +00005216
Chris Lattner03841652004-05-25 04:29:21 +00005217 // If this is a cast to bool, turn it into the appropriate setne instruction.
5218 if (CI.getType() == Type::BoolTy)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00005219 return BinaryOperator::createSetNE(CI.getOperand(0),
Chris Lattner03841652004-05-25 04:29:21 +00005220 Constant::getNullValue(CI.getOperand(0)->getType()));
5221
Chris Lattner2590e512006-02-07 06:56:34 +00005222 // See if we can simplify any instructions used by the LHS whose sole
5223 // purpose is to compute bits we don't care about.
Chris Lattner0157e7f2006-02-11 09:31:47 +00005224 if (CI.getType()->isInteger() && CI.getOperand(0)->getType()->isIntegral()) {
5225 uint64_t KnownZero, KnownOne;
5226 if (SimplifyDemandedBits(&CI, CI.getType()->getIntegralTypeMask(),
5227 KnownZero, KnownOne))
5228 return &CI;
5229 }
Chris Lattner2590e512006-02-07 06:56:34 +00005230
Chris Lattnerd0d51602003-06-21 23:12:02 +00005231 // If casting the result of a getelementptr instruction with no offset, turn
5232 // this into a cast of the original pointer!
5233 //
Chris Lattner55d4bda2003-06-23 21:59:52 +00005234 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattnerd0d51602003-06-21 23:12:02 +00005235 bool AllZeroOperands = true;
5236 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
5237 if (!isa<Constant>(GEP->getOperand(i)) ||
5238 !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
5239 AllZeroOperands = false;
5240 break;
5241 }
5242 if (AllZeroOperands) {
5243 CI.setOperand(0, GEP->getOperand(0));
5244 return &CI;
5245 }
5246 }
5247
Chris Lattnerf4ad1652003-11-02 05:57:39 +00005248 // If we are casting a malloc or alloca to a pointer to a type of the same
5249 // size, rewrite the allocation instruction to allocate the "right" type.
5250 //
5251 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
Chris Lattner216be912005-10-24 06:03:58 +00005252 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
5253 return V;
Chris Lattnerf4ad1652003-11-02 05:57:39 +00005254
Chris Lattner86102b82005-01-01 16:22:27 +00005255 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
5256 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
5257 return NV;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00005258 if (isa<PHINode>(Src))
5259 if (Instruction *NV = FoldOpIntoPhi(CI))
5260 return NV;
Chris Lattnerb19a5c62006-04-12 18:09:35 +00005261
5262 // If the source and destination are pointers, and this cast is equivalent to
5263 // a getelementptr X, 0, 0, 0... turn it into the appropriate getelementptr.
5264 // This can enhance SROA and other transforms that want type-safe pointers.
5265 if (const PointerType *DstPTy = dyn_cast<PointerType>(CI.getType()))
5266 if (const PointerType *SrcPTy = dyn_cast<PointerType>(Src->getType())) {
5267 const Type *DstTy = DstPTy->getElementType();
5268 const Type *SrcTy = SrcPTy->getElementType();
5269
5270 Constant *ZeroUInt = Constant::getNullValue(Type::UIntTy);
5271 unsigned NumZeros = 0;
5272 while (SrcTy != DstTy &&
Chris Lattnerd2862702006-09-11 21:43:16 +00005273 isa<CompositeType>(SrcTy) && !isa<PointerType>(SrcTy) &&
5274 SrcTy->getNumContainedTypes() /* not "{}" */) {
Chris Lattnerb19a5c62006-04-12 18:09:35 +00005275 SrcTy = cast<CompositeType>(SrcTy)->getTypeAtIndex(ZeroUInt);
5276 ++NumZeros;
5277 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00005278
Chris Lattnerb19a5c62006-04-12 18:09:35 +00005279 // If we found a path from the src to dest, create the getelementptr now.
5280 if (SrcTy == DstTy) {
5281 std::vector<Value*> Idxs(NumZeros+1, ZeroUInt);
5282 return new GetElementPtrInst(Src, Idxs);
5283 }
5284 }
5285
Chris Lattnerdfae8be2003-07-24 17:35:25 +00005286 // If the source value is an instruction with only this use, we can attempt to
5287 // propagate the cast into the instruction. Also, only handle integral types
5288 // for now.
Chris Lattner99155be2006-05-25 23:24:33 +00005289 if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
Chris Lattnerf95d9b92003-10-15 16:48:29 +00005290 if (SrcI->hasOneUse() && Src->getType()->isIntegral() &&
Chris Lattnerdfae8be2003-07-24 17:35:25 +00005291 CI.getType()->isInteger()) { // Don't mess with casts to bool here
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005292
5293 int NumCastsRemoved = 0;
5294 if (CanEvaluateInDifferentType(SrcI, CI.getType(), NumCastsRemoved)) {
5295 // If this cast is a truncate, evaluting in a different type always
5296 // eliminates the cast, so it is always a win. If this is a noop-cast
5297 // this just removes a noop cast which isn't pointful, but simplifies
5298 // the code. If this is a zero-extension, we need to do an AND to
5299 // maintain the clear top-part of the computation, so we require that
5300 // the input have eliminated at least one cast. If this is a sign
5301 // extension, we insert two new casts (to do the extension) so we
5302 // require that two casts have been eliminated.
5303 bool DoXForm;
5304 switch (getCastType(Src->getType(), CI.getType())) {
5305 default: assert(0 && "Unknown cast type!");
5306 case Noop:
5307 case Truncate:
5308 DoXForm = true;
5309 break;
5310 case Zeroext:
5311 DoXForm = NumCastsRemoved >= 1;
5312 break;
5313 case Signext:
5314 DoXForm = NumCastsRemoved >= 2;
5315 break;
5316 }
5317
5318 if (DoXForm) {
5319 Value *Res = EvaluateInDifferentType(SrcI, CI.getType());
5320 assert(Res->getType() == CI.getType());
5321 switch (getCastType(Src->getType(), CI.getType())) {
5322 default: assert(0 && "Unknown cast type!");
5323 case Noop:
5324 case Truncate:
5325 // Just replace this cast with the result.
5326 return ReplaceInstUsesWith(CI, Res);
5327 case Zeroext: {
5328 // We need to emit an AND to clear the high bits.
5329 unsigned SrcBitSize = Src->getType()->getPrimitiveSizeInBits();
5330 unsigned DestBitSize = CI.getType()->getPrimitiveSizeInBits();
5331 assert(SrcBitSize < DestBitSize && "Not a zext?");
5332 Constant *C = ConstantUInt::get(Type::ULongTy, (1 << SrcBitSize)-1);
5333 C = ConstantExpr::getCast(C, CI.getType());
5334 return BinaryOperator::createAnd(Res, C);
5335 }
5336 case Signext:
5337 // We need to emit a cast to truncate, then a cast to sext.
5338 return new CastInst(InsertCastBefore(Res, Src->getType(), CI),
5339 CI.getType());
5340 }
5341 }
5342 }
5343
Chris Lattnerdfae8be2003-07-24 17:35:25 +00005344 const Type *DestTy = CI.getType();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005345 unsigned SrcBitSize = Src->getType()->getPrimitiveSizeInBits();
5346 unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
Chris Lattnerdfae8be2003-07-24 17:35:25 +00005347
5348 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
5349 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
5350
5351 switch (SrcI->getOpcode()) {
5352 case Instruction::Add:
5353 case Instruction::Mul:
5354 case Instruction::And:
5355 case Instruction::Or:
5356 case Instruction::Xor:
5357 // If we are discarding information, or just changing the sign, rewrite.
5358 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
5359 // Don't insert two casts if they cannot be eliminated. We allow two
5360 // casts to be inserted if the sizes are the same. This could only be
5361 // converting signedness, which is a noop.
Chris Lattner11ffd592004-07-20 05:21:00 +00005362 if (DestBitSize == SrcBitSize || !ValueRequiresCast(Op1, DestTy,TD) ||
5363 !ValueRequiresCast(Op0, DestTy, TD)) {
Chris Lattnerdfae8be2003-07-24 17:35:25 +00005364 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
5365 Value *Op1c = InsertOperandCastBefore(Op1, DestTy, SrcI);
5366 return BinaryOperator::create(cast<BinaryOperator>(SrcI)
5367 ->getOpcode(), Op0c, Op1c);
5368 }
5369 }
Chris Lattner72086162005-05-06 02:07:39 +00005370
5371 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
5372 if (SrcBitSize == 1 && SrcI->getOpcode() == Instruction::Xor &&
5373 Op1 == ConstantBool::True &&
5374 (!Op0->hasOneUse() || !isa<SetCondInst>(Op0))) {
5375 Value *New = InsertOperandCastBefore(Op0, DestTy, &CI);
5376 return BinaryOperator::createXor(New,
5377 ConstantInt::get(CI.getType(), 1));
5378 }
Chris Lattnerdfae8be2003-07-24 17:35:25 +00005379 break;
5380 case Instruction::Shl:
5381 // Allow changing the sign of the source operand. Do not allow changing
5382 // the size of the shift, UNLESS the shift amount is a constant. We
5383 // mush not change variable sized shifts to a smaller size, because it
5384 // is undefined to shift more bits out than exist in the value.
5385 if (DestBitSize == SrcBitSize ||
5386 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
5387 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
5388 return new ShiftInst(Instruction::Shl, Op0c, Op1);
5389 }
5390 break;
Chris Lattner87380412005-05-06 04:18:52 +00005391 case Instruction::Shr:
5392 // If this is a signed shr, and if all bits shifted in are about to be
5393 // truncated off, turn it into an unsigned shr to allow greater
5394 // simplifications.
5395 if (DestBitSize < SrcBitSize && Src->getType()->isSigned() &&
5396 isa<ConstantInt>(Op1)) {
5397 unsigned ShiftAmt = cast<ConstantUInt>(Op1)->getValue();
5398 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
5399 // Convert to unsigned.
5400 Value *N1 = InsertOperandCastBefore(Op0,
5401 Op0->getType()->getUnsignedVersion(), &CI);
5402 // Insert the new shift, which is now unsigned.
5403 N1 = InsertNewInstBefore(new ShiftInst(Instruction::Shr, N1,
5404 Op1, Src->getName()), CI);
5405 return new CastInst(N1, CI.getType());
5406 }
5407 }
5408 break;
5409
Chris Lattnerc7bfed02006-02-27 02:38:23 +00005410 case Instruction::SetEQ:
Chris Lattner809dfac2005-05-04 19:10:26 +00005411 case Instruction::SetNE:
Chris Lattnerc7bfed02006-02-27 02:38:23 +00005412 // We if we are just checking for a seteq of a single bit and casting it
5413 // to an integer. If so, shift the bit to the appropriate place then
5414 // cast to integer to avoid the comparison.
Chris Lattner809dfac2005-05-04 19:10:26 +00005415 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerc7bfed02006-02-27 02:38:23 +00005416 uint64_t Op1CV = Op1C->getZExtValue();
5417 // cast (X == 0) to int --> X^1 iff X has only the low bit set.
5418 // cast (X == 0) to int --> (X>>1)^1 iff X has only the 2nd bit set.
5419 // cast (X == 1) to int --> X iff X has only the low bit set.
5420 // cast (X == 2) to int --> X>>1 iff X has only the 2nd bit set.
5421 // cast (X != 0) to int --> X iff X has only the low bit set.
5422 // cast (X != 0) to int --> X>>1 iff X has only the 2nd bit set.
5423 // cast (X != 1) to int --> X^1 iff X has only the low bit set.
5424 // cast (X != 2) to int --> (X>>1)^1 iff X has only the 2nd bit set.
5425 if (Op1CV == 0 || isPowerOf2_64(Op1CV)) {
5426 // If Op1C some other power of two, convert:
5427 uint64_t KnownZero, KnownOne;
5428 uint64_t TypeMask = Op1->getType()->getIntegralTypeMask();
5429 ComputeMaskedBits(Op0, TypeMask, KnownZero, KnownOne);
5430
5431 if (isPowerOf2_64(KnownZero^TypeMask)) { // Exactly one possible 1?
5432 bool isSetNE = SrcI->getOpcode() == Instruction::SetNE;
5433 if (Op1CV && (Op1CV != (KnownZero^TypeMask))) {
5434 // (X&4) == 2 --> false
5435 // (X&4) != 2 --> true
Chris Lattnerc5b6c9a2006-02-28 19:47:20 +00005436 Constant *Res = ConstantBool::get(isSetNE);
5437 Res = ConstantExpr::getCast(Res, CI.getType());
5438 return ReplaceInstUsesWith(CI, Res);
Chris Lattnerc7bfed02006-02-27 02:38:23 +00005439 }
5440
5441 unsigned ShiftAmt = Log2_64(KnownZero^TypeMask);
5442 Value *In = Op0;
5443 if (ShiftAmt) {
Chris Lattner4c2d3782005-05-06 01:53:19 +00005444 // Perform an unsigned shr by shiftamt. Convert input to
5445 // unsigned if it is signed.
Chris Lattner4c2d3782005-05-06 01:53:19 +00005446 if (In->getType()->isSigned())
5447 In = InsertNewInstBefore(new CastInst(In,
5448 In->getType()->getUnsignedVersion(), In->getName()),CI);
5449 // Insert the shift to put the result in the low bit.
5450 In = InsertNewInstBefore(new ShiftInst(Instruction::Shr, In,
Chris Lattnerc7bfed02006-02-27 02:38:23 +00005451 ConstantInt::get(Type::UByteTy, ShiftAmt),
5452 In->getName()+".lobit"), CI);
Chris Lattner4c2d3782005-05-06 01:53:19 +00005453 }
Chris Lattnerc7bfed02006-02-27 02:38:23 +00005454
5455 if ((Op1CV != 0) == isSetNE) { // Toggle the low bit.
5456 Constant *One = ConstantInt::get(In->getType(), 1);
5457 In = BinaryOperator::createXor(In, One, "tmp");
5458 InsertNewInstBefore(cast<Instruction>(In), CI);
Chris Lattner4c2d3782005-05-06 01:53:19 +00005459 }
Chris Lattnerc7bfed02006-02-27 02:38:23 +00005460
5461 if (CI.getType() == In->getType())
5462 return ReplaceInstUsesWith(CI, In);
5463 else
5464 return new CastInst(In, CI.getType());
Chris Lattner4c2d3782005-05-06 01:53:19 +00005465 }
Chris Lattner809dfac2005-05-04 19:10:26 +00005466 }
5467 }
5468 break;
Chris Lattnerdfae8be2003-07-24 17:35:25 +00005469 }
5470 }
Chris Lattner99155be2006-05-25 23:24:33 +00005471
5472 if (SrcI->hasOneUse()) {
5473 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(SrcI)) {
5474 // Okay, we have (cast (shuffle ..)). We know this cast is a bitconvert
5475 // because the inputs are known to be a vector. Check to see if this is
5476 // a cast to a vector with the same # elts.
5477 if (isa<PackedType>(CI.getType()) &&
5478 cast<PackedType>(CI.getType())->getNumElements() ==
5479 SVI->getType()->getNumElements()) {
5480 CastInst *Tmp;
5481 // If either of the operands is a cast from CI.getType(), then
5482 // evaluating the shuffle in the casted destination's type will allow
5483 // us to eliminate at least one cast.
5484 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
5485 Tmp->getOperand(0)->getType() == CI.getType()) ||
5486 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
Chris Lattner95cebb02006-06-06 22:26:02 +00005487 Tmp->getOperand(0)->getType() == CI.getType())) {
Chris Lattner99155be2006-05-25 23:24:33 +00005488 Value *LHS = InsertOperandCastBefore(SVI->getOperand(0),
5489 CI.getType(), &CI);
5490 Value *RHS = InsertOperandCastBefore(SVI->getOperand(1),
5491 CI.getType(), &CI);
5492 // Return a new shuffle vector. Use the same element ID's, as we
5493 // know the vector types match #elts.
5494 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
5495 }
5496 }
5497 }
5498 }
5499 }
Chris Lattnerbb171802005-10-27 05:53:56 +00005500
Chris Lattner260ab202002-04-18 17:39:14 +00005501 return 0;
Chris Lattnerca081252001-12-14 16:52:21 +00005502}
5503
Chris Lattner56e4d3d2004-04-09 23:46:01 +00005504/// GetSelectFoldableOperands - We want to turn code that looks like this:
5505/// %C = or %A, %B
5506/// %D = select %cond, %C, %A
5507/// into:
5508/// %C = select %cond, %B, 0
5509/// %D = or %A, %C
5510///
5511/// Assuming that the specified instruction is an operand to the select, return
5512/// a bitmask indicating which operands of this instruction are foldable if they
5513/// equal the other incoming value of the select.
5514///
5515static unsigned GetSelectFoldableOperands(Instruction *I) {
5516 switch (I->getOpcode()) {
5517 case Instruction::Add:
5518 case Instruction::Mul:
5519 case Instruction::And:
5520 case Instruction::Or:
5521 case Instruction::Xor:
5522 return 3; // Can fold through either operand.
5523 case Instruction::Sub: // Can only fold on the amount subtracted.
5524 case Instruction::Shl: // Can only fold on the shift amount.
5525 case Instruction::Shr:
Misha Brukmanb1c93172005-04-21 23:48:37 +00005526 return 1;
Chris Lattner56e4d3d2004-04-09 23:46:01 +00005527 default:
5528 return 0; // Cannot fold
5529 }
5530}
5531
5532/// GetSelectFoldableConstant - For the same transformation as the previous
5533/// function, return the identity constant that goes into the select.
5534static Constant *GetSelectFoldableConstant(Instruction *I) {
5535 switch (I->getOpcode()) {
5536 default: assert(0 && "This cannot happen!"); abort();
5537 case Instruction::Add:
5538 case Instruction::Sub:
5539 case Instruction::Or:
5540 case Instruction::Xor:
5541 return Constant::getNullValue(I->getType());
5542 case Instruction::Shl:
5543 case Instruction::Shr:
5544 return Constant::getNullValue(Type::UByteTy);
5545 case Instruction::And:
5546 return ConstantInt::getAllOnesValue(I->getType());
5547 case Instruction::Mul:
5548 return ConstantInt::get(I->getType(), 1);
5549 }
5550}
5551
Chris Lattner411336f2005-01-19 21:50:18 +00005552/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
5553/// have the same opcode and only one use each. Try to simplify this.
5554Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
5555 Instruction *FI) {
5556 if (TI->getNumOperands() == 1) {
5557 // If this is a non-volatile load or a cast from the same type,
5558 // merge.
5559 if (TI->getOpcode() == Instruction::Cast) {
5560 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
5561 return 0;
5562 } else {
5563 return 0; // unknown unary op.
5564 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00005565
Chris Lattner411336f2005-01-19 21:50:18 +00005566 // Fold this by inserting a select from the input values.
5567 SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
5568 FI->getOperand(0), SI.getName()+".v");
5569 InsertNewInstBefore(NewSI, SI);
5570 return new CastInst(NewSI, TI->getType());
5571 }
5572
5573 // Only handle binary operators here.
5574 if (!isa<ShiftInst>(TI) && !isa<BinaryOperator>(TI))
5575 return 0;
5576
5577 // Figure out if the operations have any operands in common.
5578 Value *MatchOp, *OtherOpT, *OtherOpF;
5579 bool MatchIsOpZero;
5580 if (TI->getOperand(0) == FI->getOperand(0)) {
5581 MatchOp = TI->getOperand(0);
5582 OtherOpT = TI->getOperand(1);
5583 OtherOpF = FI->getOperand(1);
5584 MatchIsOpZero = true;
5585 } else if (TI->getOperand(1) == FI->getOperand(1)) {
5586 MatchOp = TI->getOperand(1);
5587 OtherOpT = TI->getOperand(0);
5588 OtherOpF = FI->getOperand(0);
5589 MatchIsOpZero = false;
5590 } else if (!TI->isCommutative()) {
5591 return 0;
5592 } else if (TI->getOperand(0) == FI->getOperand(1)) {
5593 MatchOp = TI->getOperand(0);
5594 OtherOpT = TI->getOperand(1);
5595 OtherOpF = FI->getOperand(0);
5596 MatchIsOpZero = true;
5597 } else if (TI->getOperand(1) == FI->getOperand(0)) {
5598 MatchOp = TI->getOperand(1);
5599 OtherOpT = TI->getOperand(0);
5600 OtherOpF = FI->getOperand(1);
5601 MatchIsOpZero = true;
5602 } else {
5603 return 0;
5604 }
5605
5606 // If we reach here, they do have operations in common.
5607 SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
5608 OtherOpF, SI.getName()+".v");
5609 InsertNewInstBefore(NewSI, SI);
5610
5611 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
5612 if (MatchIsOpZero)
5613 return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
5614 else
5615 return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
5616 } else {
5617 if (MatchIsOpZero)
5618 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), MatchOp, NewSI);
5619 else
5620 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), NewSI, MatchOp);
5621 }
5622}
5623
Chris Lattnerb909e8b2004-03-12 05:52:32 +00005624Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattner533bc492004-03-30 19:37:13 +00005625 Value *CondVal = SI.getCondition();
5626 Value *TrueVal = SI.getTrueValue();
5627 Value *FalseVal = SI.getFalseValue();
5628
5629 // select true, X, Y -> X
5630 // select false, X, Y -> Y
5631 if (ConstantBool *C = dyn_cast<ConstantBool>(CondVal))
Chris Lattnerb909e8b2004-03-12 05:52:32 +00005632 if (C == ConstantBool::True)
Chris Lattner533bc492004-03-30 19:37:13 +00005633 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattnerb909e8b2004-03-12 05:52:32 +00005634 else {
5635 assert(C == ConstantBool::False);
Chris Lattner533bc492004-03-30 19:37:13 +00005636 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattnerb909e8b2004-03-12 05:52:32 +00005637 }
Chris Lattner533bc492004-03-30 19:37:13 +00005638
5639 // select C, X, X -> X
5640 if (TrueVal == FalseVal)
5641 return ReplaceInstUsesWith(SI, TrueVal);
5642
Chris Lattner81a7a232004-10-16 18:11:37 +00005643 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
5644 return ReplaceInstUsesWith(SI, FalseVal);
5645 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
5646 return ReplaceInstUsesWith(SI, TrueVal);
5647 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
5648 if (isa<Constant>(TrueVal))
5649 return ReplaceInstUsesWith(SI, TrueVal);
5650 else
5651 return ReplaceInstUsesWith(SI, FalseVal);
5652 }
5653
Chris Lattner1c631e82004-04-08 04:43:23 +00005654 if (SI.getType() == Type::BoolTy)
5655 if (ConstantBool *C = dyn_cast<ConstantBool>(TrueVal)) {
5656 if (C == ConstantBool::True) {
5657 // Change: A = select B, true, C --> A = or B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00005658 return BinaryOperator::createOr(CondVal, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00005659 } else {
5660 // Change: A = select B, false, C --> A = and !B, C
5661 Value *NotCond =
5662 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
5663 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00005664 return BinaryOperator::createAnd(NotCond, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00005665 }
5666 } else if (ConstantBool *C = dyn_cast<ConstantBool>(FalseVal)) {
5667 if (C == ConstantBool::False) {
5668 // Change: A = select B, C, false --> A = and B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00005669 return BinaryOperator::createAnd(CondVal, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00005670 } else {
5671 // Change: A = select B, C, true --> A = or !B, C
5672 Value *NotCond =
5673 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
5674 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00005675 return BinaryOperator::createOr(NotCond, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00005676 }
5677 }
5678
Chris Lattner183b3362004-04-09 19:05:30 +00005679 // Selecting between two integer constants?
5680 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
5681 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
5682 // select C, 1, 0 -> cast C to int
5683 if (FalseValC->isNullValue() && TrueValC->getRawValue() == 1) {
5684 return new CastInst(CondVal, SI.getType());
5685 } else if (TrueValC->isNullValue() && FalseValC->getRawValue() == 1) {
5686 // select C, 0, 1 -> cast !C to int
5687 Value *NotCond =
5688 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
Chris Lattnercf7baf32004-04-09 18:19:44 +00005689 "not."+CondVal->getName()), SI);
Chris Lattner183b3362004-04-09 19:05:30 +00005690 return new CastInst(NotCond, SI.getType());
Chris Lattnercf7baf32004-04-09 18:19:44 +00005691 }
Chris Lattner35167c32004-06-09 07:59:58 +00005692
Chris Lattner12f52fa2006-09-19 06:18:21 +00005693 if (SetCondInst *IC = dyn_cast<SetCondInst>(SI.getCondition())) {
5694
5695 // (x <s 0) ? -1 : 0 -> sra x, 31
5696 // (x >u 2147483647) ? -1 : 0 -> sra x, 31
5697 if (TrueValC->isAllOnesValue() && FalseValC->isNullValue())
5698 if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
5699 bool CanXForm = false;
5700 if (CmpCst->getType()->isSigned())
5701 CanXForm = CmpCst->isNullValue() &&
5702 IC->getOpcode() == Instruction::SetLT;
5703 else {
5704 unsigned Bits = CmpCst->getType()->getPrimitiveSizeInBits();
5705 CanXForm = (CmpCst->getRawValue() == ~0ULL >> (64-Bits+1)) &&
5706 IC->getOpcode() == Instruction::SetGT;
5707 }
5708
5709 // The comparison constant and the result are not neccessarily the
5710 // same width. In any case, the first step to do is make sure that
5711 // X is signed.
5712 Value *X = IC->getOperand(0);
5713 if (!X->getType()->isSigned())
5714 X = InsertCastBefore(X, X->getType()->getSignedVersion(), SI);
5715
5716 // Now that X is signed, we have to make the all ones value. Do
5717 // this by inserting a new SRA.
5718 unsigned Bits = X->getType()->getPrimitiveSizeInBits();
5719 Constant *ShAmt = ConstantUInt::get(Type::UByteTy, Bits-1);
5720 Instruction *SRA = new ShiftInst(Instruction::Shr, X, ShAmt,"ones");
5721 InsertNewInstBefore(SRA, SI);
5722
5723 // Finally, convert to the type of the select RHS. If this is
5724 // smaller than the compare value, it will truncate the ones to fit.
5725 // If it is larger, it will sext the ones to fit.
5726 return new CastInst(SRA, SI.getType());
5727 }
5728
5729
5730 // If one of the constants is zero (we know they can't both be) and we
5731 // have a setcc instruction with zero, and we have an 'and' with the
5732 // non-constant value, eliminate this whole mess. This corresponds to
5733 // cases like this: ((X & 27) ? 27 : 0)
5734 if (TrueValC->isNullValue() || FalseValC->isNullValue())
Chris Lattnerb3f24c92006-09-18 04:22:48 +00005735 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner35167c32004-06-09 07:59:58 +00005736 cast<Constant>(IC->getOperand(1))->isNullValue())
5737 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
5738 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00005739 isa<ConstantInt>(ICA->getOperand(1)) &&
5740 (ICA->getOperand(1) == TrueValC ||
5741 ICA->getOperand(1) == FalseValC) &&
Chris Lattner35167c32004-06-09 07:59:58 +00005742 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
5743 // Okay, now we know that everything is set up, we just don't
5744 // know whether we have a setne or seteq and whether the true or
5745 // false val is the zero.
5746 bool ShouldNotVal = !TrueValC->isNullValue();
5747 ShouldNotVal ^= IC->getOpcode() == Instruction::SetNE;
5748 Value *V = ICA;
5749 if (ShouldNotVal)
5750 V = InsertNewInstBefore(BinaryOperator::create(
5751 Instruction::Xor, V, ICA->getOperand(1)), SI);
5752 return ReplaceInstUsesWith(SI, V);
5753 }
Chris Lattner12f52fa2006-09-19 06:18:21 +00005754 }
Chris Lattner533bc492004-03-30 19:37:13 +00005755 }
Chris Lattner623fba12004-04-10 22:21:27 +00005756
5757 // See if we are selecting two values based on a comparison of the two values.
5758 if (SetCondInst *SCI = dyn_cast<SetCondInst>(CondVal)) {
5759 if (SCI->getOperand(0) == TrueVal && SCI->getOperand(1) == FalseVal) {
5760 // Transform (X == Y) ? X : Y -> Y
5761 if (SCI->getOpcode() == Instruction::SetEQ)
5762 return ReplaceInstUsesWith(SI, FalseVal);
5763 // Transform (X != Y) ? X : Y -> X
5764 if (SCI->getOpcode() == Instruction::SetNE)
5765 return ReplaceInstUsesWith(SI, TrueVal);
5766 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
5767
5768 } else if (SCI->getOperand(0) == FalseVal && SCI->getOperand(1) == TrueVal){
5769 // Transform (X == Y) ? Y : X -> X
5770 if (SCI->getOpcode() == Instruction::SetEQ)
Chris Lattner24cf0202004-04-11 01:39:19 +00005771 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattner623fba12004-04-10 22:21:27 +00005772 // Transform (X != Y) ? Y : X -> Y
5773 if (SCI->getOpcode() == Instruction::SetNE)
Chris Lattner24cf0202004-04-11 01:39:19 +00005774 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattner623fba12004-04-10 22:21:27 +00005775 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
5776 }
5777 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00005778
Chris Lattnera04c9042005-01-13 22:52:24 +00005779 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
5780 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
5781 if (TI->hasOneUse() && FI->hasOneUse()) {
5782 bool isInverse = false;
5783 Instruction *AddOp = 0, *SubOp = 0;
5784
Chris Lattner411336f2005-01-19 21:50:18 +00005785 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
5786 if (TI->getOpcode() == FI->getOpcode())
5787 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
5788 return IV;
5789
5790 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
5791 // even legal for FP.
Chris Lattnera04c9042005-01-13 22:52:24 +00005792 if (TI->getOpcode() == Instruction::Sub &&
5793 FI->getOpcode() == Instruction::Add) {
5794 AddOp = FI; SubOp = TI;
5795 } else if (FI->getOpcode() == Instruction::Sub &&
5796 TI->getOpcode() == Instruction::Add) {
5797 AddOp = TI; SubOp = FI;
5798 }
5799
5800 if (AddOp) {
5801 Value *OtherAddOp = 0;
5802 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
5803 OtherAddOp = AddOp->getOperand(1);
5804 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
5805 OtherAddOp = AddOp->getOperand(0);
5806 }
5807
5808 if (OtherAddOp) {
Chris Lattnerb580d262006-02-24 18:05:58 +00005809 // So at this point we know we have (Y -> OtherAddOp):
5810 // select C, (add X, Y), (sub X, Z)
5811 Value *NegVal; // Compute -Z
5812 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
5813 NegVal = ConstantExpr::getNeg(C);
5814 } else {
5815 NegVal = InsertNewInstBefore(
5816 BinaryOperator::createNeg(SubOp->getOperand(1), "tmp"), SI);
Chris Lattnera04c9042005-01-13 22:52:24 +00005817 }
Chris Lattnerb580d262006-02-24 18:05:58 +00005818
5819 Value *NewTrueOp = OtherAddOp;
5820 Value *NewFalseOp = NegVal;
5821 if (AddOp != TI)
5822 std::swap(NewTrueOp, NewFalseOp);
5823 Instruction *NewSel =
5824 new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
5825
5826 NewSel = InsertNewInstBefore(NewSel, SI);
5827 return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
Chris Lattnera04c9042005-01-13 22:52:24 +00005828 }
5829 }
5830 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00005831
Chris Lattner56e4d3d2004-04-09 23:46:01 +00005832 // See if we can fold the select into one of our operands.
5833 if (SI.getType()->isInteger()) {
5834 // See the comment above GetSelectFoldableOperands for a description of the
5835 // transformation we are doing here.
5836 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
5837 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
5838 !isa<Constant>(FalseVal))
5839 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
5840 unsigned OpToFold = 0;
5841 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
5842 OpToFold = 1;
5843 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
5844 OpToFold = 2;
5845 }
5846
5847 if (OpToFold) {
5848 Constant *C = GetSelectFoldableConstant(TVI);
5849 std::string Name = TVI->getName(); TVI->setName("");
5850 Instruction *NewSel =
5851 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C,
5852 Name);
5853 InsertNewInstBefore(NewSel, SI);
5854 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
5855 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
5856 else if (ShiftInst *SI = dyn_cast<ShiftInst>(TVI))
5857 return new ShiftInst(SI->getOpcode(), FalseVal, NewSel);
5858 else {
5859 assert(0 && "Unknown instruction!!");
5860 }
5861 }
5862 }
Chris Lattner6862fbd2004-09-29 17:40:11 +00005863
Chris Lattner56e4d3d2004-04-09 23:46:01 +00005864 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
5865 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
5866 !isa<Constant>(TrueVal))
5867 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
5868 unsigned OpToFold = 0;
5869 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
5870 OpToFold = 1;
5871 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
5872 OpToFold = 2;
5873 }
5874
5875 if (OpToFold) {
5876 Constant *C = GetSelectFoldableConstant(FVI);
5877 std::string Name = FVI->getName(); FVI->setName("");
5878 Instruction *NewSel =
5879 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold),
5880 Name);
5881 InsertNewInstBefore(NewSel, SI);
5882 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
5883 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
5884 else if (ShiftInst *SI = dyn_cast<ShiftInst>(FVI))
5885 return new ShiftInst(SI->getOpcode(), TrueVal, NewSel);
5886 else {
5887 assert(0 && "Unknown instruction!!");
5888 }
5889 }
5890 }
5891 }
Chris Lattnerd6f636a2005-04-24 07:30:14 +00005892
5893 if (BinaryOperator::isNot(CondVal)) {
5894 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
5895 SI.setOperand(1, FalseVal);
5896 SI.setOperand(2, TrueVal);
5897 return &SI;
5898 }
5899
Chris Lattnerb909e8b2004-03-12 05:52:32 +00005900 return 0;
5901}
5902
Chris Lattner82f2ef22006-03-06 20:18:44 +00005903/// GetKnownAlignment - If the specified pointer has an alignment that we can
5904/// determine, return it, otherwise return 0.
5905static unsigned GetKnownAlignment(Value *V, TargetData *TD) {
5906 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
5907 unsigned Align = GV->getAlignment();
5908 if (Align == 0 && TD)
5909 Align = TD->getTypeAlignment(GV->getType()->getElementType());
5910 return Align;
5911 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
5912 unsigned Align = AI->getAlignment();
5913 if (Align == 0 && TD) {
5914 if (isa<AllocaInst>(AI))
5915 Align = TD->getTypeAlignment(AI->getType()->getElementType());
5916 else if (isa<MallocInst>(AI)) {
5917 // Malloc returns maximally aligned memory.
5918 Align = TD->getTypeAlignment(AI->getType()->getElementType());
5919 Align = std::max(Align, (unsigned)TD->getTypeAlignment(Type::DoubleTy));
5920 Align = std::max(Align, (unsigned)TD->getTypeAlignment(Type::LongTy));
5921 }
5922 }
5923 return Align;
Chris Lattner53ef5a02006-03-07 01:28:57 +00005924 } else if (isa<CastInst>(V) ||
5925 (isa<ConstantExpr>(V) &&
5926 cast<ConstantExpr>(V)->getOpcode() == Instruction::Cast)) {
5927 User *CI = cast<User>(V);
Chris Lattner82f2ef22006-03-06 20:18:44 +00005928 if (isa<PointerType>(CI->getOperand(0)->getType()))
5929 return GetKnownAlignment(CI->getOperand(0), TD);
5930 return 0;
Chris Lattner53ef5a02006-03-07 01:28:57 +00005931 } else if (isa<GetElementPtrInst>(V) ||
5932 (isa<ConstantExpr>(V) &&
5933 cast<ConstantExpr>(V)->getOpcode()==Instruction::GetElementPtr)) {
5934 User *GEPI = cast<User>(V);
Chris Lattner82f2ef22006-03-06 20:18:44 +00005935 unsigned BaseAlignment = GetKnownAlignment(GEPI->getOperand(0), TD);
5936 if (BaseAlignment == 0) return 0;
5937
5938 // If all indexes are zero, it is just the alignment of the base pointer.
5939 bool AllZeroOperands = true;
5940 for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
5941 if (!isa<Constant>(GEPI->getOperand(i)) ||
5942 !cast<Constant>(GEPI->getOperand(i))->isNullValue()) {
5943 AllZeroOperands = false;
5944 break;
5945 }
5946 if (AllZeroOperands)
5947 return BaseAlignment;
5948
5949 // Otherwise, if the base alignment is >= the alignment we expect for the
5950 // base pointer type, then we know that the resultant pointer is aligned at
5951 // least as much as its type requires.
5952 if (!TD) return 0;
5953
5954 const Type *BasePtrTy = GEPI->getOperand(0)->getType();
5955 if (TD->getTypeAlignment(cast<PointerType>(BasePtrTy)->getElementType())
Chris Lattner53ef5a02006-03-07 01:28:57 +00005956 <= BaseAlignment) {
5957 const Type *GEPTy = GEPI->getType();
5958 return TD->getTypeAlignment(cast<PointerType>(GEPTy)->getElementType());
5959 }
Chris Lattner82f2ef22006-03-06 20:18:44 +00005960 return 0;
5961 }
5962 return 0;
5963}
5964
Chris Lattnerb909e8b2004-03-12 05:52:32 +00005965
Chris Lattnerc66b2232006-01-13 20:11:04 +00005966/// visitCallInst - CallInst simplification. This mostly only handles folding
5967/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
5968/// the heavy lifting.
5969///
Chris Lattner970c33a2003-06-19 17:00:31 +00005970Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattnerc66b2232006-01-13 20:11:04 +00005971 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
5972 if (!II) return visitCallSite(&CI);
5973
Chris Lattner51ea1272004-02-28 05:22:00 +00005974 // Intrinsics cannot occur in an invoke, so handle them here instead of in
5975 // visitCallSite.
Chris Lattnerc66b2232006-01-13 20:11:04 +00005976 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner00648e12004-10-12 04:52:52 +00005977 bool Changed = false;
5978
5979 // memmove/cpy/set of zero bytes is a noop.
5980 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
5981 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
5982
Chris Lattner00648e12004-10-12 04:52:52 +00005983 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
5984 if (CI->getRawValue() == 1) {
5985 // Replace the instruction with just byte operations. We would
5986 // transform other cases to loads/stores, but we don't know if
5987 // alignment is sufficient.
5988 }
Chris Lattner51ea1272004-02-28 05:22:00 +00005989 }
5990
Chris Lattner00648e12004-10-12 04:52:52 +00005991 // If we have a memmove and the source operation is a constant global,
5992 // then the source and dest pointers can't alias, so we can change this
5993 // into a call to memcpy.
Chris Lattner82f2ef22006-03-06 20:18:44 +00005994 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(II)) {
Chris Lattner00648e12004-10-12 04:52:52 +00005995 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
5996 if (GVSrc->isConstant()) {
5997 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner681ef2f2006-03-03 01:34:17 +00005998 const char *Name;
5999 if (CI.getCalledFunction()->getFunctionType()->getParamType(3) ==
6000 Type::UIntTy)
6001 Name = "llvm.memcpy.i32";
6002 else
6003 Name = "llvm.memcpy.i64";
6004 Function *MemCpy = M->getOrInsertFunction(Name,
Chris Lattner00648e12004-10-12 04:52:52 +00006005 CI.getCalledFunction()->getFunctionType());
6006 CI.setOperand(0, MemCpy);
6007 Changed = true;
6008 }
Chris Lattner82f2ef22006-03-06 20:18:44 +00006009 }
Chris Lattner00648e12004-10-12 04:52:52 +00006010
Chris Lattner82f2ef22006-03-06 20:18:44 +00006011 // If we can determine a pointer alignment that is bigger than currently
6012 // set, update the alignment.
6013 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
6014 unsigned Alignment1 = GetKnownAlignment(MI->getOperand(1), TD);
6015 unsigned Alignment2 = GetKnownAlignment(MI->getOperand(2), TD);
6016 unsigned Align = std::min(Alignment1, Alignment2);
6017 if (MI->getAlignment()->getRawValue() < Align) {
6018 MI->setAlignment(ConstantUInt::get(Type::UIntTy, Align));
6019 Changed = true;
6020 }
6021 } else if (isa<MemSetInst>(MI)) {
6022 unsigned Alignment = GetKnownAlignment(MI->getDest(), TD);
6023 if (MI->getAlignment()->getRawValue() < Alignment) {
6024 MI->setAlignment(ConstantUInt::get(Type::UIntTy, Alignment));
6025 Changed = true;
6026 }
6027 }
6028
Chris Lattnerc66b2232006-01-13 20:11:04 +00006029 if (Changed) return II;
Chris Lattner503221f2006-01-13 21:28:09 +00006030 } else {
6031 switch (II->getIntrinsicID()) {
6032 default: break;
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00006033 case Intrinsic::ppc_altivec_lvx:
6034 case Intrinsic::ppc_altivec_lvxl:
Chris Lattner36dd7c92006-04-17 22:26:56 +00006035 case Intrinsic::x86_sse_loadu_ps:
6036 case Intrinsic::x86_sse2_loadu_pd:
6037 case Intrinsic::x86_sse2_loadu_dq:
6038 // Turn PPC lvx -> load if the pointer is known aligned.
6039 // Turn X86 loadups -> load if the pointer is known aligned.
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00006040 if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
Chris Lattnere79d2492006-04-06 19:19:17 +00006041 Value *Ptr = InsertCastBefore(II->getOperand(1),
6042 PointerType::get(II->getType()), CI);
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00006043 return new LoadInst(Ptr);
6044 }
6045 break;
6046 case Intrinsic::ppc_altivec_stvx:
6047 case Intrinsic::ppc_altivec_stvxl:
6048 // Turn stvx -> store if the pointer is known aligned.
6049 if (GetKnownAlignment(II->getOperand(2), TD) >= 16) {
Chris Lattnere79d2492006-04-06 19:19:17 +00006050 const Type *OpPtrTy = PointerType::get(II->getOperand(1)->getType());
6051 Value *Ptr = InsertCastBefore(II->getOperand(2), OpPtrTy, CI);
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00006052 return new StoreInst(II->getOperand(1), Ptr);
6053 }
6054 break;
Chris Lattner36dd7c92006-04-17 22:26:56 +00006055 case Intrinsic::x86_sse_storeu_ps:
6056 case Intrinsic::x86_sse2_storeu_pd:
6057 case Intrinsic::x86_sse2_storeu_dq:
6058 case Intrinsic::x86_sse2_storel_dq:
6059 // Turn X86 storeu -> store if the pointer is known aligned.
6060 if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
6061 const Type *OpPtrTy = PointerType::get(II->getOperand(2)->getType());
6062 Value *Ptr = InsertCastBefore(II->getOperand(1), OpPtrTy, CI);
6063 return new StoreInst(II->getOperand(2), Ptr);
6064 }
6065 break;
Chris Lattnere79d2492006-04-06 19:19:17 +00006066 case Intrinsic::ppc_altivec_vperm:
6067 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
6068 if (ConstantPacked *Mask = dyn_cast<ConstantPacked>(II->getOperand(3))) {
6069 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
6070
6071 // Check that all of the elements are integer constants or undefs.
6072 bool AllEltsOk = true;
6073 for (unsigned i = 0; i != 16; ++i) {
6074 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
6075 !isa<UndefValue>(Mask->getOperand(i))) {
6076 AllEltsOk = false;
6077 break;
6078 }
6079 }
6080
6081 if (AllEltsOk) {
6082 // Cast the input vectors to byte vectors.
6083 Value *Op0 = InsertCastBefore(II->getOperand(1), Mask->getType(), CI);
6084 Value *Op1 = InsertCastBefore(II->getOperand(2), Mask->getType(), CI);
6085 Value *Result = UndefValue::get(Op0->getType());
6086
6087 // Only extract each element once.
6088 Value *ExtractedElts[32];
6089 memset(ExtractedElts, 0, sizeof(ExtractedElts));
6090
6091 for (unsigned i = 0; i != 16; ++i) {
6092 if (isa<UndefValue>(Mask->getOperand(i)))
6093 continue;
6094 unsigned Idx =cast<ConstantInt>(Mask->getOperand(i))->getRawValue();
6095 Idx &= 31; // Match the hardware behavior.
6096
6097 if (ExtractedElts[Idx] == 0) {
6098 Instruction *Elt =
6099 new ExtractElementInst(Idx < 16 ? Op0 : Op1,
6100 ConstantUInt::get(Type::UIntTy, Idx&15),
6101 "tmp");
6102 InsertNewInstBefore(Elt, CI);
6103 ExtractedElts[Idx] = Elt;
6104 }
6105
6106 // Insert this value into the result vector.
6107 Result = new InsertElementInst(Result, ExtractedElts[Idx],
6108 ConstantUInt::get(Type::UIntTy, i),
6109 "tmp");
6110 InsertNewInstBefore(cast<Instruction>(Result), CI);
6111 }
6112 return new CastInst(Result, CI.getType());
6113 }
6114 }
6115 break;
6116
Chris Lattner503221f2006-01-13 21:28:09 +00006117 case Intrinsic::stackrestore: {
6118 // If the save is right next to the restore, remove the restore. This can
6119 // happen when variable allocas are DCE'd.
6120 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
6121 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
6122 BasicBlock::iterator BI = SS;
6123 if (&*++BI == II)
6124 return EraseInstFromFunction(CI);
6125 }
6126 }
6127
6128 // If the stack restore is in a return/unwind block and if there are no
6129 // allocas or calls between the restore and the return, nuke the restore.
6130 TerminatorInst *TI = II->getParent()->getTerminator();
6131 if (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)) {
6132 BasicBlock::iterator BI = II;
6133 bool CannotRemove = false;
6134 for (++BI; &*BI != TI; ++BI) {
6135 if (isa<AllocaInst>(BI) ||
6136 (isa<CallInst>(BI) && !isa<IntrinsicInst>(BI))) {
6137 CannotRemove = true;
6138 break;
6139 }
6140 }
6141 if (!CannotRemove)
6142 return EraseInstFromFunction(CI);
6143 }
6144 break;
6145 }
6146 }
Chris Lattner00648e12004-10-12 04:52:52 +00006147 }
6148
Chris Lattnerc66b2232006-01-13 20:11:04 +00006149 return visitCallSite(II);
Chris Lattner970c33a2003-06-19 17:00:31 +00006150}
6151
6152// InvokeInst simplification
6153//
6154Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattneraec3d942003-10-07 22:32:43 +00006155 return visitCallSite(&II);
Chris Lattner970c33a2003-06-19 17:00:31 +00006156}
6157
Chris Lattneraec3d942003-10-07 22:32:43 +00006158// visitCallSite - Improvements for call and invoke instructions.
6159//
6160Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner75b4d1d2003-10-07 22:54:13 +00006161 bool Changed = false;
6162
6163 // If the callee is a constexpr cast of a function, attempt to move the cast
6164 // to the arguments of the call/invoke.
Chris Lattneraec3d942003-10-07 22:32:43 +00006165 if (transformConstExprCastCall(CS)) return 0;
6166
Chris Lattner75b4d1d2003-10-07 22:54:13 +00006167 Value *Callee = CS.getCalledValue();
Chris Lattner81a7a232004-10-16 18:11:37 +00006168
Chris Lattner61d9d812005-05-13 07:09:09 +00006169 if (Function *CalleeF = dyn_cast<Function>(Callee))
6170 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
6171 Instruction *OldCall = CS.getInstruction();
6172 // If the call and callee calling conventions don't match, this call must
6173 // be unreachable, as the call is undefined.
6174 new StoreInst(ConstantBool::True,
6175 UndefValue::get(PointerType::get(Type::BoolTy)), OldCall);
6176 if (!OldCall->use_empty())
6177 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
6178 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
6179 return EraseInstFromFunction(*OldCall);
6180 return 0;
6181 }
6182
Chris Lattner8ba9ec92004-10-18 02:59:09 +00006183 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
6184 // This instruction is not reachable, just remove it. We insert a store to
6185 // undef so that we know that this code is not reachable, despite the fact
6186 // that we can't modify the CFG here.
6187 new StoreInst(ConstantBool::True,
6188 UndefValue::get(PointerType::get(Type::BoolTy)),
6189 CS.getInstruction());
6190
6191 if (!CS.getInstruction()->use_empty())
6192 CS.getInstruction()->
6193 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
6194
6195 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
6196 // Don't break the CFG, insert a dummy cond branch.
6197 new BranchInst(II->getNormalDest(), II->getUnwindDest(),
6198 ConstantBool::True, II);
Chris Lattner81a7a232004-10-16 18:11:37 +00006199 }
Chris Lattner8ba9ec92004-10-18 02:59:09 +00006200 return EraseInstFromFunction(*CS.getInstruction());
6201 }
Chris Lattner81a7a232004-10-16 18:11:37 +00006202
Chris Lattner75b4d1d2003-10-07 22:54:13 +00006203 const PointerType *PTy = cast<PointerType>(Callee->getType());
6204 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
6205 if (FTy->isVarArg()) {
6206 // See if we can optimize any arguments passed through the varargs area of
6207 // the call.
6208 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
6209 E = CS.arg_end(); I != E; ++I)
6210 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
6211 // If this cast does not effect the value passed through the varargs
6212 // area, we can eliminate the use of the cast.
6213 Value *Op = CI->getOperand(0);
6214 if (CI->getType()->isLosslesslyConvertibleTo(Op->getType())) {
6215 *I = Op;
6216 Changed = true;
6217 }
6218 }
6219 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00006220
Chris Lattner75b4d1d2003-10-07 22:54:13 +00006221 return Changed ? CS.getInstruction() : 0;
Chris Lattneraec3d942003-10-07 22:32:43 +00006222}
6223
Chris Lattner970c33a2003-06-19 17:00:31 +00006224// transformConstExprCastCall - If the callee is a constexpr cast of a function,
6225// attempt to move the cast to the arguments of the call/invoke.
6226//
6227bool InstCombiner::transformConstExprCastCall(CallSite CS) {
6228 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
6229 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Chris Lattnerf3edc492004-07-18 18:59:44 +00006230 if (CE->getOpcode() != Instruction::Cast || !isa<Function>(CE->getOperand(0)))
Chris Lattner970c33a2003-06-19 17:00:31 +00006231 return false;
Reid Spencer87436872004-07-18 00:38:32 +00006232 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner970c33a2003-06-19 17:00:31 +00006233 Instruction *Caller = CS.getInstruction();
6234
6235 // Okay, this is a cast from a function to a different type. Unless doing so
6236 // would cause a type conversion of one of our arguments, change this call to
6237 // be a direct call with arguments casted to the appropriate types.
6238 //
6239 const FunctionType *FT = Callee->getFunctionType();
6240 const Type *OldRetTy = Caller->getType();
6241
Chris Lattner1f7942f2004-01-14 06:06:08 +00006242 // Check to see if we are changing the return type...
6243 if (OldRetTy != FT->getReturnType()) {
6244 if (Callee->isExternal() &&
Andrew Lenharth61eae292006-04-20 14:56:47 +00006245 !(OldRetTy->isLosslesslyConvertibleTo(FT->getReturnType()) ||
6246 (isa<PointerType>(FT->getReturnType()) &&
Andrew Lenharthf89e6302006-04-20 15:41:37 +00006247 TD->getIntPtrType()->isLosslesslyConvertibleTo(OldRetTy)))
Andrew Lenharth61eae292006-04-20 14:56:47 +00006248 && !Caller->use_empty())
Chris Lattner1f7942f2004-01-14 06:06:08 +00006249 return false; // Cannot transform this return value...
6250
6251 // If the callsite is an invoke instruction, and the return value is used by
6252 // a PHI node in a successor, we cannot change the return type of the call
6253 // because there is no place to put the cast instruction (without breaking
6254 // the critical edge). Bail out in this case.
6255 if (!Caller->use_empty())
6256 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
6257 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
6258 UI != E; ++UI)
6259 if (PHINode *PN = dyn_cast<PHINode>(*UI))
6260 if (PN->getParent() == II->getNormalDest() ||
Chris Lattnerfae8ab32004-02-08 21:44:31 +00006261 PN->getParent() == II->getUnwindDest())
Chris Lattner1f7942f2004-01-14 06:06:08 +00006262 return false;
6263 }
Chris Lattner970c33a2003-06-19 17:00:31 +00006264
6265 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
6266 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanb1c93172005-04-21 23:48:37 +00006267
Chris Lattner970c33a2003-06-19 17:00:31 +00006268 CallSite::arg_iterator AI = CS.arg_begin();
6269 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
6270 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthebfa24e2006-06-28 01:01:52 +00006271 const Type *ActTy = (*AI)->getType();
6272 ConstantSInt* c = dyn_cast<ConstantSInt>(*AI);
6273 //Either we can cast directly, or we can upconvert the argument
6274 bool isConvertible = ActTy->isLosslesslyConvertibleTo(ParamTy) ||
6275 (ParamTy->isIntegral() && ActTy->isIntegral() &&
6276 ParamTy->isSigned() == ActTy->isSigned() &&
6277 ParamTy->getPrimitiveSize() >= ActTy->getPrimitiveSize()) ||
6278 (c && ParamTy->getPrimitiveSize() >= ActTy->getPrimitiveSize() &&
6279 c->getValue() > 0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00006280 if (Callee->isExternal() && !isConvertible) return false;
Chris Lattner970c33a2003-06-19 17:00:31 +00006281 }
6282
6283 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
6284 Callee->isExternal())
6285 return false; // Do not delete arguments unless we have a function body...
6286
6287 // Okay, we decided that this is a safe thing to do: go ahead and start
6288 // inserting cast instructions as necessary...
6289 std::vector<Value*> Args;
6290 Args.reserve(NumActualArgs);
6291
6292 AI = CS.arg_begin();
6293 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
6294 const Type *ParamTy = FT->getParamType(i);
6295 if ((*AI)->getType() == ParamTy) {
6296 Args.push_back(*AI);
6297 } else {
Chris Lattner1c631e82004-04-08 04:43:23 +00006298 Args.push_back(InsertNewInstBefore(new CastInst(*AI, ParamTy, "tmp"),
6299 *Caller));
Chris Lattner970c33a2003-06-19 17:00:31 +00006300 }
6301 }
6302
6303 // If the function takes more arguments than the call was taking, add them
6304 // now...
6305 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
6306 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
6307
6308 // If we are removing arguments to the function, emit an obnoxious warning...
6309 if (FT->getNumParams() < NumActualArgs)
6310 if (!FT->isVarArg()) {
6311 std::cerr << "WARNING: While resolving call to function '"
6312 << Callee->getName() << "' arguments were dropped!\n";
6313 } else {
6314 // Add all of the arguments in their promoted form to the arg list...
6315 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
6316 const Type *PTy = getPromotedType((*AI)->getType());
6317 if (PTy != (*AI)->getType()) {
6318 // Must promote to pass through va_arg area!
6319 Instruction *Cast = new CastInst(*AI, PTy, "tmp");
6320 InsertNewInstBefore(Cast, *Caller);
6321 Args.push_back(Cast);
6322 } else {
6323 Args.push_back(*AI);
6324 }
6325 }
6326 }
6327
6328 if (FT->getReturnType() == Type::VoidTy)
6329 Caller->setName(""); // Void type should not have a name...
6330
6331 Instruction *NC;
6332 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Chris Lattnerfae8ab32004-02-08 21:44:31 +00006333 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
Chris Lattner970c33a2003-06-19 17:00:31 +00006334 Args, Caller->getName(), Caller);
Chris Lattner05c703e2005-05-14 12:25:32 +00006335 cast<InvokeInst>(II)->setCallingConv(II->getCallingConv());
Chris Lattner970c33a2003-06-19 17:00:31 +00006336 } else {
6337 NC = new CallInst(Callee, Args, Caller->getName(), Caller);
Chris Lattner6aacb0f2005-05-06 06:48:21 +00006338 if (cast<CallInst>(Caller)->isTailCall())
6339 cast<CallInst>(NC)->setTailCall();
Chris Lattner05c703e2005-05-14 12:25:32 +00006340 cast<CallInst>(NC)->setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Chris Lattner970c33a2003-06-19 17:00:31 +00006341 }
6342
6343 // Insert a cast of the return type as necessary...
6344 Value *NV = NC;
6345 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
6346 if (NV->getType() != Type::VoidTy) {
6347 NV = NC = new CastInst(NC, Caller->getType(), "tmp");
Chris Lattner686767f2003-10-30 00:46:41 +00006348
6349 // If this is an invoke instruction, we should insert it after the first
6350 // non-phi, instruction in the normal successor block.
6351 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
6352 BasicBlock::iterator I = II->getNormalDest()->begin();
6353 while (isa<PHINode>(I)) ++I;
6354 InsertNewInstBefore(NC, *I);
6355 } else {
6356 // Otherwise, it's a call, just insert cast right after the call instr
6357 InsertNewInstBefore(NC, *Caller);
6358 }
Chris Lattner51ea1272004-02-28 05:22:00 +00006359 AddUsersToWorkList(*Caller);
Chris Lattner970c33a2003-06-19 17:00:31 +00006360 } else {
Chris Lattnere29d6342004-10-17 21:22:38 +00006361 NV = UndefValue::get(Caller->getType());
Chris Lattner970c33a2003-06-19 17:00:31 +00006362 }
6363 }
6364
6365 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
6366 Caller->replaceAllUsesWith(NV);
6367 Caller->getParent()->getInstList().erase(Caller);
6368 removeFromWorkList(Caller);
6369 return true;
6370}
6371
6372
Chris Lattner7515cab2004-11-14 19:13:23 +00006373// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
6374// operator and they all are only used by the PHI, PHI together their
6375// inputs, and do the operation once, to the result of the PHI.
6376Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
6377 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
6378
6379 // Scan the instruction, looking for input operations that can be folded away.
6380 // If all input operands to the phi are the same instruction (e.g. a cast from
6381 // the same type or "+42") we can pull the operation through the PHI, reducing
6382 // code size and simplifying code.
6383 Constant *ConstantOp = 0;
6384 const Type *CastSrcTy = 0;
6385 if (isa<CastInst>(FirstInst)) {
6386 CastSrcTy = FirstInst->getOperand(0)->getType();
6387 } else if (isa<BinaryOperator>(FirstInst) || isa<ShiftInst>(FirstInst)) {
6388 // Can fold binop or shift if the RHS is a constant.
6389 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
6390 if (ConstantOp == 0) return 0;
6391 } else {
6392 return 0; // Cannot fold this operation.
6393 }
6394
6395 // Check to see if all arguments are the same operation.
6396 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
6397 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
6398 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
6399 if (!I->hasOneUse() || I->getOpcode() != FirstInst->getOpcode())
6400 return 0;
6401 if (CastSrcTy) {
6402 if (I->getOperand(0)->getType() != CastSrcTy)
6403 return 0; // Cast operation must match.
6404 } else if (I->getOperand(1) != ConstantOp) {
6405 return 0;
6406 }
6407 }
6408
6409 // Okay, they are all the same operation. Create a new PHI node of the
6410 // correct type, and PHI together all of the LHS's of the instructions.
6411 PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
6412 PN.getName()+".in");
Chris Lattnerd8e20182005-01-29 00:39:08 +00006413 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattner46dd5a62004-11-14 19:29:34 +00006414
6415 Value *InVal = FirstInst->getOperand(0);
6416 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattner7515cab2004-11-14 19:13:23 +00006417
6418 // Add all operands to the new PHI.
Chris Lattner46dd5a62004-11-14 19:29:34 +00006419 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
6420 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
6421 if (NewInVal != InVal)
6422 InVal = 0;
6423 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
6424 }
6425
6426 Value *PhiVal;
6427 if (InVal) {
6428 // The new PHI unions all of the same values together. This is really
6429 // common, so we handle it intelligently here for compile-time speed.
6430 PhiVal = InVal;
6431 delete NewPN;
6432 } else {
6433 InsertNewInstBefore(NewPN, PN);
6434 PhiVal = NewPN;
6435 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00006436
Chris Lattner7515cab2004-11-14 19:13:23 +00006437 // Insert and return the new operation.
6438 if (isa<CastInst>(FirstInst))
Chris Lattner46dd5a62004-11-14 19:29:34 +00006439 return new CastInst(PhiVal, PN.getType());
Chris Lattner7515cab2004-11-14 19:13:23 +00006440 else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattner46dd5a62004-11-14 19:29:34 +00006441 return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattner7515cab2004-11-14 19:13:23 +00006442 else
6443 return new ShiftInst(cast<ShiftInst>(FirstInst)->getOpcode(),
Chris Lattner46dd5a62004-11-14 19:29:34 +00006444 PhiVal, ConstantOp);
Chris Lattner7515cab2004-11-14 19:13:23 +00006445}
Chris Lattner48a44f72002-05-02 17:06:02 +00006446
Chris Lattner71536432005-01-17 05:10:15 +00006447/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
6448/// that is dead.
6449static bool DeadPHICycle(PHINode *PN, std::set<PHINode*> &PotentiallyDeadPHIs) {
6450 if (PN->use_empty()) return true;
6451 if (!PN->hasOneUse()) return false;
6452
6453 // Remember this node, and if we find the cycle, return.
6454 if (!PotentiallyDeadPHIs.insert(PN).second)
6455 return true;
6456
6457 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
6458 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanb1c93172005-04-21 23:48:37 +00006459
Chris Lattner71536432005-01-17 05:10:15 +00006460 return false;
6461}
6462
Chris Lattnerbbbdd852002-05-06 18:06:38 +00006463// PHINode simplification
6464//
Chris Lattner113f4f42002-06-25 16:13:24 +00006465Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonbbf89902006-07-10 22:15:25 +00006466 // If LCSSA is around, don't mess with Phi nodes
6467 if (mustPreserveAnalysisID(LCSSAID)) return 0;
Owen Andersona6968f82006-07-10 19:03:49 +00006468
Owen Andersonae8aa642006-07-10 22:03:18 +00006469 if (Value *V = PN.hasConstantValue())
6470 return ReplaceInstUsesWith(PN, V);
6471
6472 // If the only user of this instruction is a cast instruction, and all of the
6473 // incoming values are constants, change this PHI to merge together the casted
6474 // constants.
6475 if (PN.hasOneUse())
6476 if (CastInst *CI = dyn_cast<CastInst>(PN.use_back()))
6477 if (CI->getType() != PN.getType()) { // noop casts will be folded
6478 bool AllConstant = true;
6479 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
6480 if (!isa<Constant>(PN.getIncomingValue(i))) {
6481 AllConstant = false;
6482 break;
6483 }
6484 if (AllConstant) {
6485 // Make a new PHI with all casted values.
6486 PHINode *New = new PHINode(CI->getType(), PN.getName(), &PN);
6487 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
6488 Constant *OldArg = cast<Constant>(PN.getIncomingValue(i));
6489 New->addIncoming(ConstantExpr::getCast(OldArg, New->getType()),
6490 PN.getIncomingBlock(i));
6491 }
6492
6493 // Update the cast instruction.
6494 CI->setOperand(0, New);
6495 WorkList.push_back(CI); // revisit the cast instruction to fold.
6496 WorkList.push_back(New); // Make sure to revisit the new Phi
6497 return &PN; // PN is now dead!
6498 }
6499 }
6500
6501 // If all PHI operands are the same operation, pull them through the PHI,
6502 // reducing code size.
6503 if (isa<Instruction>(PN.getIncomingValue(0)) &&
6504 PN.getIncomingValue(0)->hasOneUse())
6505 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
6506 return Result;
6507
6508 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
6509 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
6510 // PHI)... break the cycle.
6511 if (PN.hasOneUse())
6512 if (PHINode *PU = dyn_cast<PHINode>(PN.use_back())) {
6513 std::set<PHINode*> PotentiallyDeadPHIs;
6514 PotentiallyDeadPHIs.insert(&PN);
6515 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
6516 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
6517 }
6518
Chris Lattner91daeb52003-12-19 05:58:40 +00006519 return 0;
Chris Lattnerbbbdd852002-05-06 18:06:38 +00006520}
6521
Chris Lattner69193f92004-04-05 01:30:19 +00006522static Value *InsertSignExtendToPtrTy(Value *V, const Type *DTy,
6523 Instruction *InsertPoint,
6524 InstCombiner *IC) {
6525 unsigned PS = IC->getTargetData().getPointerSize();
6526 const Type *VTy = V->getType();
Chris Lattner69193f92004-04-05 01:30:19 +00006527 if (!VTy->isSigned() && VTy->getPrimitiveSize() < PS)
6528 // We must insert a cast to ensure we sign-extend.
6529 V = IC->InsertNewInstBefore(new CastInst(V, VTy->getSignedVersion(),
6530 V->getName()), *InsertPoint);
6531 return IC->InsertNewInstBefore(new CastInst(V, DTy, V->getName()),
6532 *InsertPoint);
6533}
6534
Chris Lattner48a44f72002-05-02 17:06:02 +00006535
Chris Lattner113f4f42002-06-25 16:13:24 +00006536Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner5f667a62004-05-07 22:09:22 +00006537 Value *PtrOp = GEP.getOperand(0);
Chris Lattner471bd762003-05-22 19:07:21 +00006538 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
Chris Lattner113f4f42002-06-25 16:13:24 +00006539 // If so, eliminate the noop.
Chris Lattner8d0bacb2004-02-22 05:25:17 +00006540 if (GEP.getNumOperands() == 1)
Chris Lattner5f667a62004-05-07 22:09:22 +00006541 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner8d0bacb2004-02-22 05:25:17 +00006542
Chris Lattner81a7a232004-10-16 18:11:37 +00006543 if (isa<UndefValue>(GEP.getOperand(0)))
6544 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
6545
Chris Lattner8d0bacb2004-02-22 05:25:17 +00006546 bool HasZeroPointerIndex = false;
6547 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
6548 HasZeroPointerIndex = C->isNullValue();
6549
6550 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner5f667a62004-05-07 22:09:22 +00006551 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner48a44f72002-05-02 17:06:02 +00006552
Chris Lattner69193f92004-04-05 01:30:19 +00006553 // Eliminate unneeded casts for indices.
6554 bool MadeChange = false;
Chris Lattner2b2412d2004-04-07 18:38:20 +00006555 gep_type_iterator GTI = gep_type_begin(GEP);
6556 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI)
6557 if (isa<SequentialType>(*GTI)) {
6558 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
6559 Value *Src = CI->getOperand(0);
6560 const Type *SrcTy = Src->getType();
6561 const Type *DestTy = CI->getType();
6562 if (Src->getType()->isInteger()) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00006563 if (SrcTy->getPrimitiveSizeInBits() ==
6564 DestTy->getPrimitiveSizeInBits()) {
Chris Lattner2b2412d2004-04-07 18:38:20 +00006565 // We can always eliminate a cast from ulong or long to the other.
6566 // We can always eliminate a cast from uint to int or the other on
6567 // 32-bit pointer platforms.
Chris Lattnerd1f46d32005-04-24 06:59:08 +00006568 if (DestTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()){
Chris Lattner2b2412d2004-04-07 18:38:20 +00006569 MadeChange = true;
6570 GEP.setOperand(i, Src);
6571 }
6572 } else if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
6573 SrcTy->getPrimitiveSize() == 4) {
6574 // We can always eliminate a cast from int to [u]long. We can
6575 // eliminate a cast from uint to [u]long iff the target is a 32-bit
6576 // pointer target.
Misha Brukmanb1c93172005-04-21 23:48:37 +00006577 if (SrcTy->isSigned() ||
Chris Lattnerd1f46d32005-04-24 06:59:08 +00006578 SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
Chris Lattner2b2412d2004-04-07 18:38:20 +00006579 MadeChange = true;
6580 GEP.setOperand(i, Src);
6581 }
Chris Lattner69193f92004-04-05 01:30:19 +00006582 }
6583 }
6584 }
Chris Lattner2b2412d2004-04-07 18:38:20 +00006585 // If we are using a wider index than needed for this platform, shrink it
6586 // to what we need. If the incoming value needs a cast instruction,
6587 // insert it. This explicit cast can make subsequent optimizations more
6588 // obvious.
6589 Value *Op = GEP.getOperand(i);
6590 if (Op->getType()->getPrimitiveSize() > TD->getPointerSize())
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00006591 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner44d0b952004-07-20 01:48:15 +00006592 GEP.setOperand(i, ConstantExpr::getCast(C,
6593 TD->getIntPtrType()->getSignedVersion()));
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00006594 MadeChange = true;
6595 } else {
Chris Lattner2b2412d2004-04-07 18:38:20 +00006596 Op = InsertNewInstBefore(new CastInst(Op, TD->getIntPtrType(),
6597 Op->getName()), GEP);
6598 GEP.setOperand(i, Op);
6599 MadeChange = true;
6600 }
Chris Lattner44d0b952004-07-20 01:48:15 +00006601
6602 // If this is a constant idx, make sure to canonicalize it to be a signed
6603 // operand, otherwise CSE and other optimizations are pessimized.
6604 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op)) {
6605 GEP.setOperand(i, ConstantExpr::getCast(CUI,
6606 CUI->getType()->getSignedVersion()));
6607 MadeChange = true;
6608 }
Chris Lattner69193f92004-04-05 01:30:19 +00006609 }
6610 if (MadeChange) return &GEP;
6611
Chris Lattnerae7a0d32002-08-02 19:29:35 +00006612 // Combine Indices - If the source pointer to this getelementptr instruction
6613 // is a getelementptr instruction, combine the indices of the two
6614 // getelementptr instructions into a single instruction.
6615 //
Chris Lattner57c67b02004-03-25 22:59:29 +00006616 std::vector<Value*> SrcGEPOperands;
Chris Lattner0798af32005-01-13 20:14:25 +00006617 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattner57c67b02004-03-25 22:59:29 +00006618 SrcGEPOperands.assign(Src->op_begin(), Src->op_end());
Chris Lattner57c67b02004-03-25 22:59:29 +00006619
6620 if (!SrcGEPOperands.empty()) {
Chris Lattner5f667a62004-05-07 22:09:22 +00006621 // Note that if our source is a gep chain itself that we wait for that
6622 // chain to be resolved before we perform this transformation. This
6623 // avoids us creating a TON of code in some cases.
6624 //
6625 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
6626 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
6627 return 0; // Wait until our source is folded to completion.
6628
Chris Lattnerae7a0d32002-08-02 19:29:35 +00006629 std::vector<Value *> Indices;
Chris Lattner5f667a62004-05-07 22:09:22 +00006630
6631 // Find out whether the last index in the source GEP is a sequential idx.
6632 bool EndsWithSequential = false;
6633 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
6634 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattner8ec5f882004-05-08 22:41:42 +00006635 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00006636
Chris Lattnerae7a0d32002-08-02 19:29:35 +00006637 // Can we combine the two pointer arithmetics offsets?
Chris Lattner5f667a62004-05-07 22:09:22 +00006638 if (EndsWithSequential) {
Chris Lattner235af562003-03-05 22:33:14 +00006639 // Replace: gep (gep %P, long B), long A, ...
6640 // With: T = long A+B; gep %P, T, ...
6641 //
Chris Lattner5f667a62004-05-07 22:09:22 +00006642 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner69193f92004-04-05 01:30:19 +00006643 if (SO1 == Constant::getNullValue(SO1->getType())) {
6644 Sum = GO1;
6645 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
6646 Sum = SO1;
6647 } else {
6648 // If they aren't the same type, convert both to an integer of the
6649 // target's pointer size.
6650 if (SO1->getType() != GO1->getType()) {
6651 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
6652 SO1 = ConstantExpr::getCast(SO1C, GO1->getType());
6653 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
6654 GO1 = ConstantExpr::getCast(GO1C, SO1->getType());
6655 } else {
6656 unsigned PS = TD->getPointerSize();
Chris Lattner69193f92004-04-05 01:30:19 +00006657 if (SO1->getType()->getPrimitiveSize() == PS) {
6658 // Convert GO1 to SO1's type.
6659 GO1 = InsertSignExtendToPtrTy(GO1, SO1->getType(), &GEP, this);
6660
6661 } else if (GO1->getType()->getPrimitiveSize() == PS) {
6662 // Convert SO1 to GO1's type.
6663 SO1 = InsertSignExtendToPtrTy(SO1, GO1->getType(), &GEP, this);
6664 } else {
6665 const Type *PT = TD->getIntPtrType();
6666 SO1 = InsertSignExtendToPtrTy(SO1, PT, &GEP, this);
6667 GO1 = InsertSignExtendToPtrTy(GO1, PT, &GEP, this);
6668 }
6669 }
6670 }
Chris Lattner5f667a62004-05-07 22:09:22 +00006671 if (isa<Constant>(SO1) && isa<Constant>(GO1))
6672 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
6673 else {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00006674 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
6675 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner5f667a62004-05-07 22:09:22 +00006676 }
Chris Lattner69193f92004-04-05 01:30:19 +00006677 }
Chris Lattner5f667a62004-05-07 22:09:22 +00006678
6679 // Recycle the GEP we already have if possible.
6680 if (SrcGEPOperands.size() == 2) {
6681 GEP.setOperand(0, SrcGEPOperands[0]);
6682 GEP.setOperand(1, Sum);
6683 return &GEP;
6684 } else {
6685 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
6686 SrcGEPOperands.end()-1);
6687 Indices.push_back(Sum);
6688 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
6689 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00006690 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner69193f92004-04-05 01:30:19 +00006691 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00006692 SrcGEPOperands.size() != 1) {
Chris Lattnerae7a0d32002-08-02 19:29:35 +00006693 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattner57c67b02004-03-25 22:59:29 +00006694 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
6695 SrcGEPOperands.end());
Chris Lattnerae7a0d32002-08-02 19:29:35 +00006696 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
6697 }
6698
6699 if (!Indices.empty())
Chris Lattner57c67b02004-03-25 22:59:29 +00006700 return new GetElementPtrInst(SrcGEPOperands[0], Indices, GEP.getName());
Chris Lattnerc59af1d2002-08-17 22:21:59 +00006701
Chris Lattner5f667a62004-05-07 22:09:22 +00006702 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattnerc59af1d2002-08-17 22:21:59 +00006703 // GEP of global variable. If all of the indices for this GEP are
6704 // constants, we can promote this to a constexpr instead of an instruction.
6705
6706 // Scan for nonconstants...
6707 std::vector<Constant*> Indices;
6708 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
6709 for (; I != E && isa<Constant>(*I); ++I)
6710 Indices.push_back(cast<Constant>(*I));
6711
6712 if (I == E) { // If they are all constants...
Chris Lattnerf3edc492004-07-18 18:59:44 +00006713 Constant *CE = ConstantExpr::getGetElementPtr(GV, Indices);
Chris Lattnerc59af1d2002-08-17 22:21:59 +00006714
6715 // Replace all uses of the GEP with the new constexpr...
6716 return ReplaceInstUsesWith(GEP, CE);
6717 }
Chris Lattner567b81f2005-09-13 00:40:14 +00006718 } else if (Value *X = isCast(PtrOp)) { // Is the operand a cast?
6719 if (!isa<PointerType>(X->getType())) {
6720 // Not interesting. Source pointer must be a cast from pointer.
6721 } else if (HasZeroPointerIndex) {
6722 // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
6723 // into : GEP [10 x ubyte]* X, long 0, ...
6724 //
6725 // This occurs when the program declares an array extern like "int X[];"
6726 //
6727 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
6728 const PointerType *XTy = cast<PointerType>(X->getType());
6729 if (const ArrayType *XATy =
6730 dyn_cast<ArrayType>(XTy->getElementType()))
6731 if (const ArrayType *CATy =
6732 dyn_cast<ArrayType>(CPTy->getElementType()))
6733 if (CATy->getElementType() == XATy->getElementType()) {
6734 // At this point, we know that the cast source type is a pointer
6735 // to an array of the same type as the destination pointer
6736 // array. Because the array type is never stepped over (there
6737 // is a leading zero) we can fold the cast into this GEP.
6738 GEP.setOperand(0, X);
6739 return &GEP;
6740 }
6741 } else if (GEP.getNumOperands() == 2) {
6742 // Transform things like:
Chris Lattner2a893292005-09-13 18:36:04 +00006743 // %t = getelementptr ubyte* cast ([2 x int]* %str to uint*), uint %V
6744 // into: %t1 = getelementptr [2 x int*]* %str, int 0, uint %V; cast
Chris Lattner567b81f2005-09-13 00:40:14 +00006745 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
6746 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
6747 if (isa<ArrayType>(SrcElTy) &&
6748 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
6749 TD->getTypeSize(ResElTy)) {
6750 Value *V = InsertNewInstBefore(
6751 new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
6752 GEP.getOperand(1), GEP.getName()), GEP);
6753 return new CastInst(V, GEP.getType());
Chris Lattner8d0bacb2004-02-22 05:25:17 +00006754 }
Chris Lattner2a893292005-09-13 18:36:04 +00006755
6756 // Transform things like:
6757 // getelementptr sbyte* cast ([100 x double]* X to sbyte*), int %tmp
6758 // (where tmp = 8*tmp2) into:
6759 // getelementptr [100 x double]* %arr, int 0, int %tmp.2
6760
6761 if (isa<ArrayType>(SrcElTy) &&
6762 (ResElTy == Type::SByteTy || ResElTy == Type::UByteTy)) {
6763 uint64_t ArrayEltSize =
6764 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType());
6765
6766 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
6767 // allow either a mul, shift, or constant here.
6768 Value *NewIdx = 0;
6769 ConstantInt *Scale = 0;
6770 if (ArrayEltSize == 1) {
6771 NewIdx = GEP.getOperand(1);
6772 Scale = ConstantInt::get(NewIdx->getType(), 1);
6773 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Chris Lattnera393e4d2005-09-14 17:32:56 +00006774 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner2a893292005-09-13 18:36:04 +00006775 Scale = CI;
6776 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
6777 if (Inst->getOpcode() == Instruction::Shl &&
6778 isa<ConstantInt>(Inst->getOperand(1))) {
6779 unsigned ShAmt =cast<ConstantUInt>(Inst->getOperand(1))->getValue();
6780 if (Inst->getType()->isSigned())
6781 Scale = ConstantSInt::get(Inst->getType(), 1ULL << ShAmt);
6782 else
6783 Scale = ConstantUInt::get(Inst->getType(), 1ULL << ShAmt);
6784 NewIdx = Inst->getOperand(0);
6785 } else if (Inst->getOpcode() == Instruction::Mul &&
6786 isa<ConstantInt>(Inst->getOperand(1))) {
6787 Scale = cast<ConstantInt>(Inst->getOperand(1));
6788 NewIdx = Inst->getOperand(0);
6789 }
6790 }
6791
6792 // If the index will be to exactly the right offset with the scale taken
6793 // out, perform the transformation.
6794 if (Scale && Scale->getRawValue() % ArrayEltSize == 0) {
6795 if (ConstantSInt *C = dyn_cast<ConstantSInt>(Scale))
6796 Scale = ConstantSInt::get(C->getType(),
Chris Lattnera393e4d2005-09-14 17:32:56 +00006797 (int64_t)C->getRawValue() /
6798 (int64_t)ArrayEltSize);
Chris Lattner2a893292005-09-13 18:36:04 +00006799 else
6800 Scale = ConstantUInt::get(Scale->getType(),
6801 Scale->getRawValue() / ArrayEltSize);
6802 if (Scale->getRawValue() != 1) {
6803 Constant *C = ConstantExpr::getCast(Scale, NewIdx->getType());
6804 Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
6805 NewIdx = InsertNewInstBefore(Sc, GEP);
6806 }
6807
6808 // Insert the new GEP instruction.
6809 Instruction *Idx =
6810 new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
6811 NewIdx, GEP.getName());
6812 Idx = InsertNewInstBefore(Idx, GEP);
6813 return new CastInst(Idx, GEP.getType());
6814 }
6815 }
Chris Lattner8d0bacb2004-02-22 05:25:17 +00006816 }
Chris Lattnerca081252001-12-14 16:52:21 +00006817 }
6818
Chris Lattnerca081252001-12-14 16:52:21 +00006819 return 0;
6820}
6821
Chris Lattner1085bdf2002-11-04 16:18:53 +00006822Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
6823 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
6824 if (AI.isArrayAllocation()) // Check C != 1
6825 if (const ConstantUInt *C = dyn_cast<ConstantUInt>(AI.getArraySize())) {
6826 const Type *NewTy = ArrayType::get(AI.getAllocatedType(), C->getValue());
Chris Lattnera2620ac2002-11-09 00:49:43 +00006827 AllocationInst *New = 0;
Chris Lattner1085bdf2002-11-04 16:18:53 +00006828
6829 // Create and insert the replacement instruction...
6830 if (isa<MallocInst>(AI))
Nate Begeman848622f2005-11-05 09:21:28 +00006831 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00006832 else {
6833 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Nate Begeman848622f2005-11-05 09:21:28 +00006834 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00006835 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00006836
6837 InsertNewInstBefore(New, AI);
Misha Brukmanb1c93172005-04-21 23:48:37 +00006838
Chris Lattner1085bdf2002-11-04 16:18:53 +00006839 // Scan to the end of the allocation instructions, to skip over a block of
6840 // allocas if possible...
6841 //
6842 BasicBlock::iterator It = New;
6843 while (isa<AllocationInst>(*It)) ++It;
6844
6845 // Now that I is pointing to the first non-allocation-inst in the block,
6846 // insert our getelementptr instruction...
6847 //
Chris Lattner809dfac2005-05-04 19:10:26 +00006848 Value *NullIdx = Constant::getNullValue(Type::IntTy);
6849 Value *V = new GetElementPtrInst(New, NullIdx, NullIdx,
6850 New->getName()+".sub", It);
Chris Lattner1085bdf2002-11-04 16:18:53 +00006851
6852 // Now make everything use the getelementptr instead of the original
6853 // allocation.
Chris Lattnerabb77c92004-03-19 06:08:10 +00006854 return ReplaceInstUsesWith(AI, V);
Chris Lattner81a7a232004-10-16 18:11:37 +00006855 } else if (isa<UndefValue>(AI.getArraySize())) {
6856 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner1085bdf2002-11-04 16:18:53 +00006857 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00006858
6859 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
6860 // Note that we only do this for alloca's, because malloc should allocate and
6861 // return a unique pointer, even for a zero byte allocation.
Misha Brukmanb1c93172005-04-21 23:48:37 +00006862 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
Chris Lattner49df6ce2004-07-02 22:55:47 +00006863 TD->getTypeSize(AI.getAllocatedType()) == 0)
Chris Lattnerabb77c92004-03-19 06:08:10 +00006864 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
6865
Chris Lattner1085bdf2002-11-04 16:18:53 +00006866 return 0;
6867}
6868
Chris Lattner8427bff2003-12-07 01:24:23 +00006869Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
6870 Value *Op = FI.getOperand(0);
6871
6872 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
6873 if (CastInst *CI = dyn_cast<CastInst>(Op))
6874 if (isa<PointerType>(CI->getOperand(0)->getType())) {
6875 FI.setOperand(0, CI->getOperand(0));
6876 return &FI;
6877 }
6878
Chris Lattner8ba9ec92004-10-18 02:59:09 +00006879 // free undef -> unreachable.
6880 if (isa<UndefValue>(Op)) {
6881 // Insert a new store to null because we cannot modify the CFG here.
6882 new StoreInst(ConstantBool::True,
6883 UndefValue::get(PointerType::get(Type::BoolTy)), &FI);
6884 return EraseInstFromFunction(FI);
6885 }
6886
Chris Lattnerf3a36602004-02-28 04:57:37 +00006887 // If we have 'free null' delete the instruction. This can happen in stl code
6888 // when lots of inlining happens.
Chris Lattner8ba9ec92004-10-18 02:59:09 +00006889 if (isa<ConstantPointerNull>(Op))
Chris Lattner51ea1272004-02-28 05:22:00 +00006890 return EraseInstFromFunction(FI);
Chris Lattnerf3a36602004-02-28 04:57:37 +00006891
Chris Lattner8427bff2003-12-07 01:24:23 +00006892 return 0;
6893}
6894
6895
Chris Lattner72684fe2005-01-31 05:51:45 +00006896/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Chris Lattner35e24772004-07-13 01:49:43 +00006897static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
6898 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00006899 Value *CastOp = CI->getOperand(0);
Chris Lattner35e24772004-07-13 01:49:43 +00006900
6901 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00006902 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Chris Lattner35e24772004-07-13 01:49:43 +00006903 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00006904
Chris Lattnerebca4762006-04-02 05:37:12 +00006905 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
6906 isa<PackedType>(DestPTy)) {
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00006907 // If the source is an array, the code below will not succeed. Check to
6908 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
6909 // constants.
6910 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
6911 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
6912 if (ASrcTy->getNumElements() != 0) {
6913 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
6914 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
6915 SrcTy = cast<PointerType>(CastOp->getType());
6916 SrcPTy = SrcTy->getElementType();
6917 }
6918
Chris Lattnerebca4762006-04-02 05:37:12 +00006919 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
6920 isa<PackedType>(SrcPTy)) &&
Chris Lattnerecfa9b52005-03-29 06:37:47 +00006921 // Do not allow turning this into a load of an integer, which is then
6922 // casted to a pointer, this pessimizes pointer analysis a lot.
6923 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00006924 IC.getTargetData().getTypeSize(SrcPTy) ==
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00006925 IC.getTargetData().getTypeSize(DestPTy)) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00006926
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00006927 // Okay, we are casting from one integer or pointer type to another of
6928 // the same size. Instead of casting the pointer before the load, cast
6929 // the result of the loaded value.
6930 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
6931 CI->getName(),
6932 LI.isVolatile()),LI);
6933 // Now cast the result of the load.
6934 return new CastInst(NewLoad, LI.getType());
6935 }
Chris Lattner35e24772004-07-13 01:49:43 +00006936 }
6937 }
6938 return 0;
6939}
6940
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00006941/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattnere6f13092004-09-19 19:18:10 +00006942/// from this value cannot trap. If it is not obviously safe to load from the
6943/// specified pointer, we do a quick local scan of the basic block containing
6944/// ScanFrom, to determine if the address is already accessed.
6945static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
6946 // If it is an alloca or global variable, it is always safe to load from.
6947 if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
6948
6949 // Otherwise, be a little bit agressive by scanning the local block where we
6950 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00006951 // from/to. If so, the previous load or store would have already trapped,
6952 // so there is no harm doing an extra load (also, CSE will later eliminate
6953 // the load entirely).
Chris Lattnere6f13092004-09-19 19:18:10 +00006954 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
6955
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00006956 while (BBI != E) {
Chris Lattnere6f13092004-09-19 19:18:10 +00006957 --BBI;
6958
6959 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
6960 if (LI->getOperand(0) == V) return true;
6961 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
6962 if (SI->getOperand(1) == V) return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +00006963
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00006964 }
Chris Lattnere6f13092004-09-19 19:18:10 +00006965 return false;
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00006966}
6967
Chris Lattner0f1d8a32003-06-26 05:06:25 +00006968Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
6969 Value *Op = LI.getOperand(0);
Chris Lattner7e8af382004-01-12 04:13:56 +00006970
Chris Lattnera9d84e32005-05-01 04:24:53 +00006971 // load (cast X) --> cast (load X) iff safe
6972 if (CastInst *CI = dyn_cast<CastInst>(Op))
6973 if (Instruction *Res = InstCombineLoadCast(*this, LI))
6974 return Res;
6975
6976 // None of the following transforms are legal for volatile loads.
6977 if (LI.isVolatile()) return 0;
Chris Lattnerb990f7d2005-09-12 22:00:15 +00006978
Chris Lattnerb990f7d2005-09-12 22:00:15 +00006979 if (&LI.getParent()->front() != &LI) {
6980 BasicBlock::iterator BBI = &LI; --BBI;
Chris Lattnere0bfdf12005-09-12 22:21:03 +00006981 // If the instruction immediately before this is a store to the same
6982 // address, do a simple form of store->load forwarding.
Chris Lattnerb990f7d2005-09-12 22:00:15 +00006983 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
6984 if (SI->getOperand(1) == LI.getOperand(0))
6985 return ReplaceInstUsesWith(LI, SI->getOperand(0));
Chris Lattnere0bfdf12005-09-12 22:21:03 +00006986 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
6987 if (LIB->getOperand(0) == LI.getOperand(0))
6988 return ReplaceInstUsesWith(LI, LIB);
Chris Lattnerb990f7d2005-09-12 22:00:15 +00006989 }
Chris Lattnera9d84e32005-05-01 04:24:53 +00006990
6991 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op))
6992 if (isa<ConstantPointerNull>(GEPI->getOperand(0)) ||
6993 isa<UndefValue>(GEPI->getOperand(0))) {
6994 // Insert a new store to null instruction before the load to indicate
6995 // that this code is not reachable. We do this instead of inserting
6996 // an unreachable instruction directly because we cannot modify the
6997 // CFG.
6998 new StoreInst(UndefValue::get(LI.getType()),
6999 Constant::getNullValue(Op->getType()), &LI);
7000 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
7001 }
7002
Chris Lattner81a7a232004-10-16 18:11:37 +00007003 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattnera9d84e32005-05-01 04:24:53 +00007004 // load null/undef -> undef
7005 if ((C->isNullValue() || isa<UndefValue>(C))) {
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007006 // Insert a new store to null instruction before the load to indicate that
7007 // this code is not reachable. We do this instead of inserting an
7008 // unreachable instruction directly because we cannot modify the CFG.
Chris Lattnera9d84e32005-05-01 04:24:53 +00007009 new StoreInst(UndefValue::get(LI.getType()),
7010 Constant::getNullValue(Op->getType()), &LI);
Chris Lattner81a7a232004-10-16 18:11:37 +00007011 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007012 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00007013
Chris Lattner81a7a232004-10-16 18:11:37 +00007014 // Instcombine load (constant global) into the value loaded.
7015 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
7016 if (GV->isConstant() && !GV->isExternal())
7017 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanb1c93172005-04-21 23:48:37 +00007018
Chris Lattner81a7a232004-10-16 18:11:37 +00007019 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
7020 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
7021 if (CE->getOpcode() == Instruction::GetElementPtr) {
7022 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
7023 if (GV->isConstant() && !GV->isExternal())
Chris Lattner0b011ec2005-09-26 05:28:06 +00007024 if (Constant *V =
7025 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
Chris Lattner81a7a232004-10-16 18:11:37 +00007026 return ReplaceInstUsesWith(LI, V);
Chris Lattnera9d84e32005-05-01 04:24:53 +00007027 if (CE->getOperand(0)->isNullValue()) {
7028 // Insert a new store to null instruction before the load to indicate
7029 // that this code is not reachable. We do this instead of inserting
7030 // an unreachable instruction directly because we cannot modify the
7031 // CFG.
7032 new StoreInst(UndefValue::get(LI.getType()),
7033 Constant::getNullValue(Op->getType()), &LI);
7034 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
7035 }
7036
Chris Lattner81a7a232004-10-16 18:11:37 +00007037 } else if (CE->getOpcode() == Instruction::Cast) {
7038 if (Instruction *Res = InstCombineLoadCast(*this, LI))
7039 return Res;
7040 }
7041 }
Chris Lattnere228ee52004-04-08 20:39:49 +00007042
Chris Lattnera9d84e32005-05-01 04:24:53 +00007043 if (Op->hasOneUse()) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00007044 // Change select and PHI nodes to select values instead of addresses: this
7045 // helps alias analysis out a lot, allows many others simplifications, and
7046 // exposes redundancy in the code.
7047 //
7048 // Note that we cannot do the transformation unless we know that the
7049 // introduced loads cannot trap! Something like this is valid as long as
7050 // the condition is always false: load (select bool %C, int* null, int* %G),
7051 // but it would not be valid if we transformed it to load from null
7052 // unconditionally.
7053 //
7054 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
7055 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattnere6f13092004-09-19 19:18:10 +00007056 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
7057 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00007058 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner42618552004-09-20 10:15:10 +00007059 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00007060 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner42618552004-09-20 10:15:10 +00007061 SI->getOperand(2)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00007062 return new SelectInst(SI->getCondition(), V1, V2);
7063 }
7064
Chris Lattnerbdcf41a2004-09-23 15:46:00 +00007065 // load (select (cond, null, P)) -> load P
7066 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
7067 if (C->isNullValue()) {
7068 LI.setOperand(0, SI->getOperand(2));
7069 return &LI;
7070 }
7071
7072 // load (select (cond, P, null)) -> load P
7073 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
7074 if (C->isNullValue()) {
7075 LI.setOperand(0, SI->getOperand(1));
7076 return &LI;
7077 }
7078
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00007079 } else if (PHINode *PN = dyn_cast<PHINode>(Op)) {
7080 // load (phi (&V1, &V2, &V3)) --> phi(load &V1, load &V2, load &V3)
Chris Lattner42618552004-09-20 10:15:10 +00007081 bool Safe = PN->getParent() == LI.getParent();
7082
7083 // Scan all of the instructions between the PHI and the load to make
7084 // sure there are no instructions that might possibly alter the value
7085 // loaded from the PHI.
7086 if (Safe) {
7087 BasicBlock::iterator I = &LI;
7088 for (--I; !isa<PHINode>(I); --I)
7089 if (isa<StoreInst>(I) || isa<CallInst>(I)) {
7090 Safe = false;
7091 break;
7092 }
7093 }
7094
7095 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e && Safe; ++i)
Chris Lattnere6f13092004-09-19 19:18:10 +00007096 if (!isSafeToLoadUnconditionally(PN->getIncomingValue(i),
Chris Lattner42618552004-09-20 10:15:10 +00007097 PN->getIncomingBlock(i)->getTerminator()))
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00007098 Safe = false;
Chris Lattner42618552004-09-20 10:15:10 +00007099
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00007100 if (Safe) {
7101 // Create the PHI.
7102 PHINode *NewPN = new PHINode(LI.getType(), PN->getName());
7103 InsertNewInstBefore(NewPN, *PN);
7104 std::map<BasicBlock*,Value*> LoadMap; // Don't insert duplicate loads
7105
7106 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
7107 BasicBlock *BB = PN->getIncomingBlock(i);
7108 Value *&TheLoad = LoadMap[BB];
7109 if (TheLoad == 0) {
7110 Value *InVal = PN->getIncomingValue(i);
7111 TheLoad = InsertNewInstBefore(new LoadInst(InVal,
7112 InVal->getName()+".val"),
7113 *BB->getTerminator());
7114 }
7115 NewPN->addIncoming(TheLoad, BB);
7116 }
7117 return ReplaceInstUsesWith(LI, NewPN);
7118 }
7119 }
7120 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00007121 return 0;
7122}
7123
Chris Lattner72684fe2005-01-31 05:51:45 +00007124/// InstCombineStoreToCast - Fold 'store V, (cast P)' -> store (cast V), P'
7125/// when possible.
7126static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
7127 User *CI = cast<User>(SI.getOperand(1));
7128 Value *CastOp = CI->getOperand(0);
7129
7130 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
7131 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
7132 const Type *SrcPTy = SrcTy->getElementType();
7133
7134 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
7135 // If the source is an array, the code below will not succeed. Check to
7136 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
7137 // constants.
7138 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
7139 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
7140 if (ASrcTy->getNumElements() != 0) {
7141 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
7142 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
7143 SrcTy = cast<PointerType>(CastOp->getType());
7144 SrcPTy = SrcTy->getElementType();
7145 }
7146
7147 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00007148 IC.getTargetData().getTypeSize(SrcPTy) ==
Chris Lattner72684fe2005-01-31 05:51:45 +00007149 IC.getTargetData().getTypeSize(DestPTy)) {
7150
7151 // Okay, we are casting from one integer or pointer type to another of
7152 // the same size. Instead of casting the pointer before the store, cast
7153 // the value to be stored.
7154 Value *NewCast;
7155 if (Constant *C = dyn_cast<Constant>(SI.getOperand(0)))
7156 NewCast = ConstantExpr::getCast(C, SrcPTy);
7157 else
7158 NewCast = IC.InsertNewInstBefore(new CastInst(SI.getOperand(0),
7159 SrcPTy,
7160 SI.getOperand(0)->getName()+".c"), SI);
7161
7162 return new StoreInst(NewCast, CastOp);
7163 }
7164 }
7165 }
7166 return 0;
7167}
7168
Chris Lattner31f486c2005-01-31 05:36:43 +00007169Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
7170 Value *Val = SI.getOperand(0);
7171 Value *Ptr = SI.getOperand(1);
7172
7173 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner5997cf92006-02-08 03:25:32 +00007174 EraseInstFromFunction(SI);
Chris Lattner31f486c2005-01-31 05:36:43 +00007175 ++NumCombined;
7176 return 0;
7177 }
7178
Chris Lattner5997cf92006-02-08 03:25:32 +00007179 // Do really simple DSE, to catch cases where there are several consequtive
7180 // stores to the same location, separated by a few arithmetic operations. This
7181 // situation often occurs with bitfield accesses.
7182 BasicBlock::iterator BBI = &SI;
7183 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
7184 --ScanInsts) {
7185 --BBI;
7186
7187 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
7188 // Prev store isn't volatile, and stores to the same location?
7189 if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
7190 ++NumDeadStore;
7191 ++BBI;
7192 EraseInstFromFunction(*PrevSI);
7193 continue;
7194 }
7195 break;
7196 }
7197
Chris Lattnerdab43b22006-05-26 19:19:20 +00007198 // If this is a load, we have to stop. However, if the loaded value is from
7199 // the pointer we're loading and is producing the pointer we're storing,
7200 // then *this* store is dead (X = load P; store X -> P).
7201 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
7202 if (LI == Val && LI->getOperand(0) == Ptr) {
7203 EraseInstFromFunction(SI);
7204 ++NumCombined;
7205 return 0;
7206 }
7207 // Otherwise, this is a load from some other location. Stores before it
7208 // may not be dead.
7209 break;
7210 }
7211
Chris Lattner5997cf92006-02-08 03:25:32 +00007212 // Don't skip over loads or things that can modify memory.
Chris Lattnerdab43b22006-05-26 19:19:20 +00007213 if (BBI->mayWriteToMemory())
Chris Lattner5997cf92006-02-08 03:25:32 +00007214 break;
7215 }
7216
7217
7218 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner31f486c2005-01-31 05:36:43 +00007219
7220 // store X, null -> turns into 'unreachable' in SimplifyCFG
7221 if (isa<ConstantPointerNull>(Ptr)) {
7222 if (!isa<UndefValue>(Val)) {
7223 SI.setOperand(0, UndefValue::get(Val->getType()));
7224 if (Instruction *U = dyn_cast<Instruction>(Val))
7225 WorkList.push_back(U); // Dropped a use.
7226 ++NumCombined;
7227 }
7228 return 0; // Do not modify these!
7229 }
7230
7231 // store undef, Ptr -> noop
7232 if (isa<UndefValue>(Val)) {
Chris Lattner5997cf92006-02-08 03:25:32 +00007233 EraseInstFromFunction(SI);
Chris Lattner31f486c2005-01-31 05:36:43 +00007234 ++NumCombined;
7235 return 0;
7236 }
7237
Chris Lattner72684fe2005-01-31 05:51:45 +00007238 // If the pointer destination is a cast, see if we can fold the cast into the
7239 // source instead.
7240 if (CastInst *CI = dyn_cast<CastInst>(Ptr))
7241 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
7242 return Res;
7243 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
7244 if (CE->getOpcode() == Instruction::Cast)
7245 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
7246 return Res;
7247
Chris Lattner219175c2005-09-12 23:23:25 +00007248
7249 // If this store is the last instruction in the basic block, and if the block
7250 // ends with an unconditional branch, try to move it to the successor block.
Chris Lattner5997cf92006-02-08 03:25:32 +00007251 BBI = &SI; ++BBI;
Chris Lattner219175c2005-09-12 23:23:25 +00007252 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
7253 if (BI->isUnconditional()) {
7254 // Check to see if the successor block has exactly two incoming edges. If
7255 // so, see if the other predecessor contains a store to the same location.
7256 // if so, insert a PHI node (if needed) and move the stores down.
7257 BasicBlock *Dest = BI->getSuccessor(0);
7258
7259 pred_iterator PI = pred_begin(Dest);
7260 BasicBlock *Other = 0;
7261 if (*PI != BI->getParent())
7262 Other = *PI;
7263 ++PI;
7264 if (PI != pred_end(Dest)) {
7265 if (*PI != BI->getParent())
7266 if (Other)
7267 Other = 0;
7268 else
7269 Other = *PI;
7270 if (++PI != pred_end(Dest))
7271 Other = 0;
7272 }
7273 if (Other) { // If only one other pred...
7274 BBI = Other->getTerminator();
7275 // Make sure this other block ends in an unconditional branch and that
7276 // there is an instruction before the branch.
7277 if (isa<BranchInst>(BBI) && cast<BranchInst>(BBI)->isUnconditional() &&
7278 BBI != Other->begin()) {
7279 --BBI;
7280 StoreInst *OtherStore = dyn_cast<StoreInst>(BBI);
7281
7282 // If this instruction is a store to the same location.
7283 if (OtherStore && OtherStore->getOperand(1) == SI.getOperand(1)) {
7284 // Okay, we know we can perform this transformation. Insert a PHI
7285 // node now if we need it.
7286 Value *MergedVal = OtherStore->getOperand(0);
7287 if (MergedVal != SI.getOperand(0)) {
7288 PHINode *PN = new PHINode(MergedVal->getType(), "storemerge");
7289 PN->reserveOperandSpace(2);
7290 PN->addIncoming(SI.getOperand(0), SI.getParent());
7291 PN->addIncoming(OtherStore->getOperand(0), Other);
7292 MergedVal = InsertNewInstBefore(PN, Dest->front());
7293 }
7294
7295 // Advance to a place where it is safe to insert the new store and
7296 // insert it.
7297 BBI = Dest->begin();
7298 while (isa<PHINode>(BBI)) ++BBI;
7299 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
7300 OtherStore->isVolatile()), *BBI);
7301
7302 // Nuke the old stores.
Chris Lattner5997cf92006-02-08 03:25:32 +00007303 EraseInstFromFunction(SI);
7304 EraseInstFromFunction(*OtherStore);
Chris Lattner219175c2005-09-12 23:23:25 +00007305 ++NumCombined;
7306 return 0;
7307 }
7308 }
7309 }
7310 }
7311
Chris Lattner31f486c2005-01-31 05:36:43 +00007312 return 0;
7313}
7314
7315
Chris Lattner9eef8a72003-06-04 04:46:00 +00007316Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
7317 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4fdd96c2005-06-18 17:37:34 +00007318 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00007319 BasicBlock *TrueDest;
7320 BasicBlock *FalseDest;
7321 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
7322 !isa<Constant>(X)) {
7323 // Swap Destinations and condition...
7324 BI.setCondition(X);
7325 BI.setSuccessor(0, FalseDest);
7326 BI.setSuccessor(1, TrueDest);
7327 return &BI;
7328 }
7329
7330 // Cannonicalize setne -> seteq
7331 Instruction::BinaryOps Op; Value *Y;
7332 if (match(&BI, m_Br(m_SetCond(Op, m_Value(X), m_Value(Y)),
7333 TrueDest, FalseDest)))
7334 if ((Op == Instruction::SetNE || Op == Instruction::SetLE ||
7335 Op == Instruction::SetGE) && BI.getCondition()->hasOneUse()) {
7336 SetCondInst *I = cast<SetCondInst>(BI.getCondition());
7337 std::string Name = I->getName(); I->setName("");
7338 Instruction::BinaryOps NewOpcode = SetCondInst::getInverseCondition(Op);
7339 Value *NewSCC = BinaryOperator::create(NewOpcode, X, Y, Name, I);
Chris Lattnere967b342003-06-04 05:10:11 +00007340 // Swap Destinations and condition...
Chris Lattnerd4252a72004-07-30 07:50:03 +00007341 BI.setCondition(NewSCC);
Chris Lattnere967b342003-06-04 05:10:11 +00007342 BI.setSuccessor(0, FalseDest);
7343 BI.setSuccessor(1, TrueDest);
Chris Lattnerd4252a72004-07-30 07:50:03 +00007344 removeFromWorkList(I);
7345 I->getParent()->getInstList().erase(I);
7346 WorkList.push_back(cast<Instruction>(NewSCC));
Chris Lattnere967b342003-06-04 05:10:11 +00007347 return &BI;
7348 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00007349
Chris Lattner9eef8a72003-06-04 04:46:00 +00007350 return 0;
7351}
Chris Lattner1085bdf2002-11-04 16:18:53 +00007352
Chris Lattner4c9c20a2004-07-03 00:26:11 +00007353Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
7354 Value *Cond = SI.getCondition();
7355 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
7356 if (I->getOpcode() == Instruction::Add)
7357 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7358 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
7359 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattner81a7a232004-10-16 18:11:37 +00007360 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner4c9c20a2004-07-03 00:26:11 +00007361 AddRHS));
7362 SI.setOperand(0, I->getOperand(0));
7363 WorkList.push_back(I);
7364 return &SI;
7365 }
7366 }
7367 return 0;
7368}
7369
Chris Lattner6bc98652006-03-05 00:22:33 +00007370/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
7371/// is to leave as a vector operation.
7372static bool CheapToScalarize(Value *V, bool isConstant) {
7373 if (isa<ConstantAggregateZero>(V))
7374 return true;
7375 if (ConstantPacked *C = dyn_cast<ConstantPacked>(V)) {
7376 if (isConstant) return true;
7377 // If all elts are the same, we can extract.
7378 Constant *Op0 = C->getOperand(0);
7379 for (unsigned i = 1; i < C->getNumOperands(); ++i)
7380 if (C->getOperand(i) != Op0)
7381 return false;
7382 return true;
7383 }
7384 Instruction *I = dyn_cast<Instruction>(V);
7385 if (!I) return false;
7386
7387 // Insert element gets simplified to the inserted element or is deleted if
7388 // this is constant idx extract element and its a constant idx insertelt.
7389 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
7390 isa<ConstantInt>(I->getOperand(2)))
7391 return true;
7392 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
7393 return true;
7394 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
7395 if (BO->hasOneUse() &&
7396 (CheapToScalarize(BO->getOperand(0), isConstant) ||
7397 CheapToScalarize(BO->getOperand(1), isConstant)))
7398 return true;
7399
7400 return false;
7401}
7402
Chris Lattner12249be2006-05-25 23:48:38 +00007403/// getShuffleMask - Read and decode a shufflevector mask. It turns undef
7404/// elements into values that are larger than the #elts in the input.
7405static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
7406 unsigned NElts = SVI->getType()->getNumElements();
7407 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
7408 return std::vector<unsigned>(NElts, 0);
7409 if (isa<UndefValue>(SVI->getOperand(2)))
7410 return std::vector<unsigned>(NElts, 2*NElts);
7411
7412 std::vector<unsigned> Result;
7413 const ConstantPacked *CP = cast<ConstantPacked>(SVI->getOperand(2));
7414 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
7415 if (isa<UndefValue>(CP->getOperand(i)))
7416 Result.push_back(NElts*2); // undef -> 8
7417 else
7418 Result.push_back(cast<ConstantUInt>(CP->getOperand(i))->getValue());
7419 return Result;
7420}
7421
Chris Lattner8d1d8d32006-03-31 23:01:56 +00007422/// FindScalarElement - Given a vector and an element number, see if the scalar
7423/// value is already around as a register, for example if it were inserted then
7424/// extracted from the vector.
7425static Value *FindScalarElement(Value *V, unsigned EltNo) {
7426 assert(isa<PackedType>(V->getType()) && "Not looking at a vector?");
7427 const PackedType *PTy = cast<PackedType>(V->getType());
Chris Lattner2d37f922006-04-10 23:06:36 +00007428 unsigned Width = PTy->getNumElements();
7429 if (EltNo >= Width) // Out of range access.
Chris Lattner8d1d8d32006-03-31 23:01:56 +00007430 return UndefValue::get(PTy->getElementType());
7431
7432 if (isa<UndefValue>(V))
7433 return UndefValue::get(PTy->getElementType());
7434 else if (isa<ConstantAggregateZero>(V))
7435 return Constant::getNullValue(PTy->getElementType());
7436 else if (ConstantPacked *CP = dyn_cast<ConstantPacked>(V))
7437 return CP->getOperand(EltNo);
7438 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
7439 // If this is an insert to a variable element, we don't know what it is.
7440 if (!isa<ConstantUInt>(III->getOperand(2))) return 0;
7441 unsigned IIElt = cast<ConstantUInt>(III->getOperand(2))->getValue();
7442
7443 // If this is an insert to the element we are looking for, return the
7444 // inserted value.
7445 if (EltNo == IIElt) return III->getOperand(1);
7446
7447 // Otherwise, the insertelement doesn't modify the value, recurse on its
7448 // vector input.
7449 return FindScalarElement(III->getOperand(0), EltNo);
Chris Lattner2d37f922006-04-10 23:06:36 +00007450 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Chris Lattner12249be2006-05-25 23:48:38 +00007451 unsigned InEl = getShuffleMask(SVI)[EltNo];
7452 if (InEl < Width)
7453 return FindScalarElement(SVI->getOperand(0), InEl);
7454 else if (InEl < Width*2)
7455 return FindScalarElement(SVI->getOperand(1), InEl - Width);
7456 else
7457 return UndefValue::get(PTy->getElementType());
Chris Lattner8d1d8d32006-03-31 23:01:56 +00007458 }
7459
7460 // Otherwise, we don't know.
7461 return 0;
7462}
7463
Robert Bocchinoa8352962006-01-13 22:48:06 +00007464Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Chris Lattner8d1d8d32006-03-31 23:01:56 +00007465
Chris Lattner92346c32006-03-31 18:25:14 +00007466 // If packed val is undef, replace extract with scalar undef.
7467 if (isa<UndefValue>(EI.getOperand(0)))
7468 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
7469
7470 // If packed val is constant 0, replace extract with scalar 0.
7471 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
7472 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
7473
Robert Bocchinoa8352962006-01-13 22:48:06 +00007474 if (ConstantPacked *C = dyn_cast<ConstantPacked>(EI.getOperand(0))) {
7475 // If packed val is constant with uniform operands, replace EI
7476 // with that operand
Chris Lattner6bc98652006-03-05 00:22:33 +00007477 Constant *op0 = C->getOperand(0);
Robert Bocchinoa8352962006-01-13 22:48:06 +00007478 for (unsigned i = 1; i < C->getNumOperands(); ++i)
Chris Lattner6bc98652006-03-05 00:22:33 +00007479 if (C->getOperand(i) != op0) {
7480 op0 = 0;
7481 break;
7482 }
7483 if (op0)
7484 return ReplaceInstUsesWith(EI, op0);
Robert Bocchinoa8352962006-01-13 22:48:06 +00007485 }
Chris Lattner6bc98652006-03-05 00:22:33 +00007486
Chris Lattner8d1d8d32006-03-31 23:01:56 +00007487 // If extracting a specified index from the vector, see if we can recursively
7488 // find a previously computed scalar that was inserted into the vector.
Chris Lattner2d37f922006-04-10 23:06:36 +00007489 if (ConstantUInt *IdxC = dyn_cast<ConstantUInt>(EI.getOperand(1))) {
Chris Lattner8d1d8d32006-03-31 23:01:56 +00007490 if (Value *Elt = FindScalarElement(EI.getOperand(0), IdxC->getValue()))
7491 return ReplaceInstUsesWith(EI, Elt);
Chris Lattner2d37f922006-04-10 23:06:36 +00007492 }
Chris Lattner8d1d8d32006-03-31 23:01:56 +00007493
Chris Lattner83f65782006-05-25 22:53:38 +00007494 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Robert Bocchinoa8352962006-01-13 22:48:06 +00007495 if (I->hasOneUse()) {
7496 // Push extractelement into predecessor operation if legal and
7497 // profitable to do so
7498 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Chris Lattner6bc98652006-03-05 00:22:33 +00007499 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
7500 if (CheapToScalarize(BO, isConstantElt)) {
7501 ExtractElementInst *newEI0 =
7502 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
7503 EI.getName()+".lhs");
7504 ExtractElementInst *newEI1 =
7505 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
7506 EI.getName()+".rhs");
7507 InsertNewInstBefore(newEI0, EI);
7508 InsertNewInstBefore(newEI1, EI);
7509 return BinaryOperator::create(BO->getOpcode(), newEI0, newEI1);
7510 }
7511 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Robert Bocchinoa8352962006-01-13 22:48:06 +00007512 Value *Ptr = InsertCastBefore(I->getOperand(0),
7513 PointerType::get(EI.getType()), EI);
7514 GetElementPtrInst *GEP =
7515 new GetElementPtrInst(Ptr, EI.getOperand(1),
7516 I->getName() + ".gep");
7517 InsertNewInstBefore(GEP, EI);
7518 return new LoadInst(GEP);
Chris Lattner83f65782006-05-25 22:53:38 +00007519 }
7520 }
7521 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
7522 // Extracting the inserted element?
7523 if (IE->getOperand(2) == EI.getOperand(1))
7524 return ReplaceInstUsesWith(EI, IE->getOperand(1));
7525 // If the inserted and extracted elements are constants, they must not
7526 // be the same value, extract from the pre-inserted value instead.
7527 if (isa<Constant>(IE->getOperand(2)) &&
7528 isa<Constant>(EI.getOperand(1))) {
7529 AddUsesToWorkList(EI);
7530 EI.setOperand(0, IE->getOperand(0));
7531 return &EI;
7532 }
7533 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
7534 // If this is extracting an element from a shufflevector, figure out where
7535 // it came from and extract from the appropriate input element instead.
7536 if (ConstantUInt *Elt = dyn_cast<ConstantUInt>(EI.getOperand(1))) {
Chris Lattner12249be2006-05-25 23:48:38 +00007537 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getValue()];
7538 Value *Src;
7539 if (SrcIdx < SVI->getType()->getNumElements())
7540 Src = SVI->getOperand(0);
7541 else if (SrcIdx < SVI->getType()->getNumElements()*2) {
7542 SrcIdx -= SVI->getType()->getNumElements();
7543 Src = SVI->getOperand(1);
7544 } else {
7545 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattner612fa8e2006-03-30 22:02:40 +00007546 }
Chris Lattner12249be2006-05-25 23:48:38 +00007547 return new ExtractElementInst(Src,
7548 ConstantUInt::get(Type::UIntTy, SrcIdx));
Robert Bocchinoa8352962006-01-13 22:48:06 +00007549 }
7550 }
Chris Lattner83f65782006-05-25 22:53:38 +00007551 }
Robert Bocchinoa8352962006-01-13 22:48:06 +00007552 return 0;
7553}
7554
Chris Lattner90951862006-04-16 00:51:47 +00007555/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
7556/// elements from either LHS or RHS, return the shuffle mask and true.
7557/// Otherwise, return false.
7558static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
7559 std::vector<Constant*> &Mask) {
7560 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
7561 "Invalid CollectSingleShuffleElements");
7562 unsigned NumElts = cast<PackedType>(V->getType())->getNumElements();
7563
7564 if (isa<UndefValue>(V)) {
7565 Mask.assign(NumElts, UndefValue::get(Type::UIntTy));
7566 return true;
7567 } else if (V == LHS) {
7568 for (unsigned i = 0; i != NumElts; ++i)
7569 Mask.push_back(ConstantUInt::get(Type::UIntTy, i));
7570 return true;
7571 } else if (V == RHS) {
7572 for (unsigned i = 0; i != NumElts; ++i)
7573 Mask.push_back(ConstantUInt::get(Type::UIntTy, i+NumElts));
7574 return true;
7575 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
7576 // If this is an insert of an extract from some other vector, include it.
7577 Value *VecOp = IEI->getOperand(0);
7578 Value *ScalarOp = IEI->getOperand(1);
7579 Value *IdxOp = IEI->getOperand(2);
7580
Chris Lattnerb6cb64b2006-04-27 21:14:21 +00007581 if (!isa<ConstantInt>(IdxOp))
7582 return false;
7583 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getRawValue();
7584
7585 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
7586 // Okay, we can handle this if the vector we are insertinting into is
7587 // transitively ok.
7588 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
7589 // If so, update the mask to reflect the inserted undef.
7590 Mask[InsertedIdx] = UndefValue::get(Type::UIntTy);
7591 return true;
7592 }
7593 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
7594 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner90951862006-04-16 00:51:47 +00007595 EI->getOperand(0)->getType() == V->getType()) {
7596 unsigned ExtractedIdx =
7597 cast<ConstantInt>(EI->getOperand(1))->getRawValue();
Chris Lattner90951862006-04-16 00:51:47 +00007598
7599 // This must be extracting from either LHS or RHS.
7600 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
7601 // Okay, we can handle this if the vector we are insertinting into is
7602 // transitively ok.
7603 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
7604 // If so, update the mask to reflect the inserted value.
7605 if (EI->getOperand(0) == LHS) {
7606 Mask[InsertedIdx & (NumElts-1)] =
7607 ConstantUInt::get(Type::UIntTy, ExtractedIdx);
7608 } else {
7609 assert(EI->getOperand(0) == RHS);
7610 Mask[InsertedIdx & (NumElts-1)] =
7611 ConstantUInt::get(Type::UIntTy, ExtractedIdx+NumElts);
7612
7613 }
7614 return true;
7615 }
7616 }
7617 }
7618 }
7619 }
7620 // TODO: Handle shufflevector here!
7621
7622 return false;
7623}
7624
7625/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
7626/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
7627/// that computes V and the LHS value of the shuffle.
Chris Lattner39fac442006-04-15 01:39:45 +00007628static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Chris Lattner90951862006-04-16 00:51:47 +00007629 Value *&RHS) {
7630 assert(isa<PackedType>(V->getType()) &&
7631 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattner39fac442006-04-15 01:39:45 +00007632 "Invalid shuffle!");
7633 unsigned NumElts = cast<PackedType>(V->getType())->getNumElements();
7634
7635 if (isa<UndefValue>(V)) {
7636 Mask.assign(NumElts, UndefValue::get(Type::UIntTy));
7637 return V;
7638 } else if (isa<ConstantAggregateZero>(V)) {
7639 Mask.assign(NumElts, ConstantUInt::get(Type::UIntTy, 0));
7640 return V;
7641 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
7642 // If this is an insert of an extract from some other vector, include it.
7643 Value *VecOp = IEI->getOperand(0);
7644 Value *ScalarOp = IEI->getOperand(1);
7645 Value *IdxOp = IEI->getOperand(2);
7646
7647 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
7648 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
7649 EI->getOperand(0)->getType() == V->getType()) {
7650 unsigned ExtractedIdx =
7651 cast<ConstantInt>(EI->getOperand(1))->getRawValue();
7652 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getRawValue();
7653
7654 // Either the extracted from or inserted into vector must be RHSVec,
7655 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner90951862006-04-16 00:51:47 +00007656 if (EI->getOperand(0) == RHS || RHS == 0) {
7657 RHS = EI->getOperand(0);
7658 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
Chris Lattner39fac442006-04-15 01:39:45 +00007659 Mask[InsertedIdx & (NumElts-1)] =
7660 ConstantUInt::get(Type::UIntTy, NumElts+ExtractedIdx);
7661 return V;
7662 }
7663
Chris Lattner90951862006-04-16 00:51:47 +00007664 if (VecOp == RHS) {
7665 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
Chris Lattner39fac442006-04-15 01:39:45 +00007666 // Everything but the extracted element is replaced with the RHS.
7667 for (unsigned i = 0; i != NumElts; ++i) {
7668 if (i != InsertedIdx)
7669 Mask[i] = ConstantUInt::get(Type::UIntTy, NumElts+i);
7670 }
7671 return V;
7672 }
Chris Lattner90951862006-04-16 00:51:47 +00007673
7674 // If this insertelement is a chain that comes from exactly these two
7675 // vectors, return the vector and the effective shuffle.
7676 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
7677 return EI->getOperand(0);
7678
Chris Lattner39fac442006-04-15 01:39:45 +00007679 }
7680 }
7681 }
Chris Lattner90951862006-04-16 00:51:47 +00007682 // TODO: Handle shufflevector here!
Chris Lattner39fac442006-04-15 01:39:45 +00007683
7684 // Otherwise, can't do anything fancy. Return an identity vector.
7685 for (unsigned i = 0; i != NumElts; ++i)
7686 Mask.push_back(ConstantUInt::get(Type::UIntTy, i));
7687 return V;
7688}
7689
7690Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
7691 Value *VecOp = IE.getOperand(0);
7692 Value *ScalarOp = IE.getOperand(1);
7693 Value *IdxOp = IE.getOperand(2);
7694
7695 // If the inserted element was extracted from some other vector, and if the
7696 // indexes are constant, try to turn this into a shufflevector operation.
7697 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
7698 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
7699 EI->getOperand(0)->getType() == IE.getType()) {
7700 unsigned NumVectorElts = IE.getType()->getNumElements();
7701 unsigned ExtractedIdx=cast<ConstantInt>(EI->getOperand(1))->getRawValue();
7702 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getRawValue();
7703
7704 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
7705 return ReplaceInstUsesWith(IE, VecOp);
7706
7707 if (InsertedIdx >= NumVectorElts) // Out of range insert.
7708 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
7709
7710 // If we are extracting a value from a vector, then inserting it right
7711 // back into the same place, just use the input vector.
7712 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
7713 return ReplaceInstUsesWith(IE, VecOp);
7714
7715 // We could theoretically do this for ANY input. However, doing so could
7716 // turn chains of insertelement instructions into a chain of shufflevector
7717 // instructions, and right now we do not merge shufflevectors. As such,
7718 // only do this in a situation where it is clear that there is benefit.
7719 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
7720 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
7721 // the values of VecOp, except then one read from EIOp0.
7722 // Build a new shuffle mask.
7723 std::vector<Constant*> Mask;
7724 if (isa<UndefValue>(VecOp))
7725 Mask.assign(NumVectorElts, UndefValue::get(Type::UIntTy));
7726 else {
7727 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
7728 Mask.assign(NumVectorElts, ConstantUInt::get(Type::UIntTy,
7729 NumVectorElts));
7730 }
7731 Mask[InsertedIdx] = ConstantUInt::get(Type::UIntTy, ExtractedIdx);
7732 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
7733 ConstantPacked::get(Mask));
7734 }
7735
7736 // If this insertelement isn't used by some other insertelement, turn it
7737 // (and any insertelements it points to), into one big shuffle.
7738 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
7739 std::vector<Constant*> Mask;
Chris Lattner90951862006-04-16 00:51:47 +00007740 Value *RHS = 0;
7741 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
7742 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
7743 // We now have a shuffle of LHS, RHS, Mask.
7744 return new ShuffleVectorInst(LHS, RHS, ConstantPacked::get(Mask));
Chris Lattner39fac442006-04-15 01:39:45 +00007745 }
7746 }
7747 }
7748
7749 return 0;
7750}
7751
7752
Chris Lattnerfbb77a42006-04-10 22:45:52 +00007753Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
7754 Value *LHS = SVI.getOperand(0);
7755 Value *RHS = SVI.getOperand(1);
Chris Lattner12249be2006-05-25 23:48:38 +00007756 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnerfbb77a42006-04-10 22:45:52 +00007757
7758 bool MadeChange = false;
7759
Chris Lattner12249be2006-05-25 23:48:38 +00007760 if (isa<UndefValue>(SVI.getOperand(2)))
Chris Lattnerfbb77a42006-04-10 22:45:52 +00007761 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
7762
Chris Lattner39fac442006-04-15 01:39:45 +00007763 // TODO: If we have shuffle(x, undef, mask) and any elements of mask refer to
7764 // the undef, change them to undefs.
7765
Chris Lattner12249be2006-05-25 23:48:38 +00007766 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
7767 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
7768 if (LHS == RHS || isa<UndefValue>(LHS)) {
7769 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnerfbb77a42006-04-10 22:45:52 +00007770 // shuffle(undef,undef,mask) -> undef.
7771 return ReplaceInstUsesWith(SVI, LHS);
7772 }
7773
Chris Lattner12249be2006-05-25 23:48:38 +00007774 // Remap any references to RHS to use LHS.
7775 std::vector<Constant*> Elts;
7776 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner0e477162006-05-26 00:29:06 +00007777 if (Mask[i] >= 2*e)
Chris Lattner12249be2006-05-25 23:48:38 +00007778 Elts.push_back(UndefValue::get(Type::UIntTy));
Chris Lattner0e477162006-05-26 00:29:06 +00007779 else {
7780 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
7781 (Mask[i] < e && isa<UndefValue>(LHS)))
7782 Mask[i] = 2*e; // Turn into undef.
7783 else
7784 Mask[i] &= (e-1); // Force to LHS.
7785 Elts.push_back(ConstantUInt::get(Type::UIntTy, Mask[i]));
7786 }
Chris Lattnerfbb77a42006-04-10 22:45:52 +00007787 }
Chris Lattner12249be2006-05-25 23:48:38 +00007788 SVI.setOperand(0, SVI.getOperand(1));
Chris Lattnerfbb77a42006-04-10 22:45:52 +00007789 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Chris Lattner12249be2006-05-25 23:48:38 +00007790 SVI.setOperand(2, ConstantPacked::get(Elts));
Chris Lattner0e477162006-05-26 00:29:06 +00007791 LHS = SVI.getOperand(0);
7792 RHS = SVI.getOperand(1);
Chris Lattnerfbb77a42006-04-10 22:45:52 +00007793 MadeChange = true;
7794 }
7795
Chris Lattner0e477162006-05-26 00:29:06 +00007796 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner12249be2006-05-25 23:48:38 +00007797 bool isLHSID = true, isRHSID = true;
Chris Lattner34cebe72006-04-16 00:03:56 +00007798
Chris Lattner12249be2006-05-25 23:48:38 +00007799 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
7800 if (Mask[i] >= e*2) continue; // Ignore undef values.
7801 // Is this an identity shuffle of the LHS value?
7802 isLHSID &= (Mask[i] == i);
7803
7804 // Is this an identity shuffle of the RHS value?
7805 isRHSID &= (Mask[i]-e == i);
Chris Lattner34cebe72006-04-16 00:03:56 +00007806 }
Chris Lattnerfbb77a42006-04-10 22:45:52 +00007807
Chris Lattner12249be2006-05-25 23:48:38 +00007808 // Eliminate identity shuffles.
7809 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
7810 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnerfbb77a42006-04-10 22:45:52 +00007811
Chris Lattner0e477162006-05-26 00:29:06 +00007812 // If the LHS is a shufflevector itself, see if we can combine it with this
7813 // one without producing an unusual shuffle. Here we are really conservative:
7814 // we are absolutely afraid of producing a shuffle mask not in the input
7815 // program, because the code gen may not be smart enough to turn a merged
7816 // shuffle into two specific shuffles: it may produce worse code. As such,
7817 // we only merge two shuffles if the result is one of the two input shuffle
7818 // masks. In this case, merging the shuffles just removes one instruction,
7819 // which we know is safe. This is good for things like turning:
7820 // (splat(splat)) -> splat.
7821 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
7822 if (isa<UndefValue>(RHS)) {
7823 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
7824
7825 std::vector<unsigned> NewMask;
7826 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
7827 if (Mask[i] >= 2*e)
7828 NewMask.push_back(2*e);
7829 else
7830 NewMask.push_back(LHSMask[Mask[i]]);
7831
7832 // If the result mask is equal to the src shuffle or this shuffle mask, do
7833 // the replacement.
7834 if (NewMask == LHSMask || NewMask == Mask) {
7835 std::vector<Constant*> Elts;
7836 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
7837 if (NewMask[i] >= e*2) {
7838 Elts.push_back(UndefValue::get(Type::UIntTy));
7839 } else {
7840 Elts.push_back(ConstantUInt::get(Type::UIntTy, NewMask[i]));
7841 }
7842 }
7843 return new ShuffleVectorInst(LHSSVI->getOperand(0),
7844 LHSSVI->getOperand(1),
7845 ConstantPacked::get(Elts));
7846 }
7847 }
7848 }
7849
Chris Lattnerfbb77a42006-04-10 22:45:52 +00007850 return MadeChange ? &SVI : 0;
7851}
7852
7853
Robert Bocchinoa8352962006-01-13 22:48:06 +00007854
Chris Lattner99f48c62002-09-02 04:59:56 +00007855void InstCombiner::removeFromWorkList(Instruction *I) {
7856 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
7857 WorkList.end());
7858}
7859
Chris Lattner39c98bb2004-12-08 23:43:58 +00007860
7861/// TryToSinkInstruction - Try to move the specified instruction from its
7862/// current block into the beginning of DestBlock, which can only happen if it's
7863/// safe to move the instruction past all of the instructions between it and the
7864/// end of its block.
7865static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
7866 assert(I->hasOneUse() && "Invariants didn't hold!");
7867
Chris Lattnerc4f67e62005-10-27 17:13:11 +00007868 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
7869 if (isa<PHINode>(I) || I->mayWriteToMemory()) return false;
Misha Brukmanb1c93172005-04-21 23:48:37 +00007870
Chris Lattner39c98bb2004-12-08 23:43:58 +00007871 // Do not sink alloca instructions out of the entry block.
7872 if (isa<AllocaInst>(I) && I->getParent() == &DestBlock->getParent()->front())
7873 return false;
7874
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00007875 // We can only sink load instructions if there is nothing between the load and
7876 // the end of block that could change the value.
7877 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00007878 for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
7879 Scan != E; ++Scan)
7880 if (Scan->mayWriteToMemory())
7881 return false;
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00007882 }
Chris Lattner39c98bb2004-12-08 23:43:58 +00007883
7884 BasicBlock::iterator InsertPos = DestBlock->begin();
7885 while (isa<PHINode>(InsertPos)) ++InsertPos;
7886
Chris Lattner9f269e42005-08-08 19:11:57 +00007887 I->moveBefore(InsertPos);
Chris Lattner39c98bb2004-12-08 23:43:58 +00007888 ++NumSunkInst;
7889 return true;
7890}
7891
Chris Lattner1443bc52006-05-11 17:11:52 +00007892/// OptimizeConstantExpr - Given a constant expression and target data layout
7893/// information, symbolically evaluation the constant expr to something simpler
7894/// if possible.
7895static Constant *OptimizeConstantExpr(ConstantExpr *CE, const TargetData *TD) {
7896 if (!TD) return CE;
7897
7898 Constant *Ptr = CE->getOperand(0);
7899 if (CE->getOpcode() == Instruction::GetElementPtr && Ptr->isNullValue() &&
7900 cast<PointerType>(Ptr->getType())->getElementType()->isSized()) {
7901 // If this is a constant expr gep that is effectively computing an
7902 // "offsetof", fold it into 'cast int Size to T*' instead of 'gep 0, 0, 12'
7903 bool isFoldableGEP = true;
7904 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
7905 if (!isa<ConstantInt>(CE->getOperand(i)))
7906 isFoldableGEP = false;
7907 if (isFoldableGEP) {
7908 std::vector<Value*> Ops(CE->op_begin()+1, CE->op_end());
7909 uint64_t Offset = TD->getIndexedOffset(Ptr->getType(), Ops);
7910 Constant *C = ConstantUInt::get(Type::ULongTy, Offset);
7911 C = ConstantExpr::getCast(C, TD->getIntPtrType());
7912 return ConstantExpr::getCast(C, CE->getType());
7913 }
7914 }
7915
7916 return CE;
7917}
7918
Chris Lattnera36ee4e2006-05-10 19:00:36 +00007919
7920/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
7921/// all reachable code to the worklist.
7922///
7923/// This has a couple of tricks to make the code faster and more powerful. In
7924/// particular, we constant fold and DCE instructions as we go, to avoid adding
7925/// them to the worklist (this significantly speeds up instcombine on code where
7926/// many instructions are dead or constant). Additionally, if we find a branch
7927/// whose condition is a known constant, we only visit the reachable successors.
7928///
7929static void AddReachableCodeToWorklist(BasicBlock *BB,
7930 std::set<BasicBlock*> &Visited,
Chris Lattner1443bc52006-05-11 17:11:52 +00007931 std::vector<Instruction*> &WorkList,
7932 const TargetData *TD) {
Chris Lattnera36ee4e2006-05-10 19:00:36 +00007933 // We have now visited this block! If we've already been here, bail out.
7934 if (!Visited.insert(BB).second) return;
7935
7936 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
7937 Instruction *Inst = BBI++;
7938
7939 // DCE instruction if trivially dead.
7940 if (isInstructionTriviallyDead(Inst)) {
7941 ++NumDeadInst;
7942 DEBUG(std::cerr << "IC: DCE: " << *Inst);
7943 Inst->eraseFromParent();
7944 continue;
7945 }
7946
7947 // ConstantProp instruction if trivially constant.
7948 if (Constant *C = ConstantFoldInstruction(Inst)) {
Chris Lattner1443bc52006-05-11 17:11:52 +00007949 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
7950 C = OptimizeConstantExpr(CE, TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00007951 DEBUG(std::cerr << "IC: ConstFold to: " << *C << " from: " << *Inst);
7952 Inst->replaceAllUsesWith(C);
7953 ++NumConstProp;
7954 Inst->eraseFromParent();
7955 continue;
7956 }
7957
7958 WorkList.push_back(Inst);
7959 }
7960
7961 // Recursively visit successors. If this is a branch or switch on a constant,
7962 // only visit the reachable successor.
7963 TerminatorInst *TI = BB->getTerminator();
7964 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
7965 if (BI->isConditional() && isa<ConstantBool>(BI->getCondition())) {
7966 bool CondVal = cast<ConstantBool>(BI->getCondition())->getValue();
Chris Lattner1443bc52006-05-11 17:11:52 +00007967 AddReachableCodeToWorklist(BI->getSuccessor(!CondVal), Visited, WorkList,
7968 TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00007969 return;
7970 }
7971 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
7972 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
7973 // See if this is an explicit destination.
7974 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
7975 if (SI->getCaseValue(i) == Cond) {
Chris Lattner1443bc52006-05-11 17:11:52 +00007976 AddReachableCodeToWorklist(SI->getSuccessor(i), Visited, WorkList,TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00007977 return;
7978 }
7979
7980 // Otherwise it is the default destination.
Chris Lattner1443bc52006-05-11 17:11:52 +00007981 AddReachableCodeToWorklist(SI->getSuccessor(0), Visited, WorkList, TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00007982 return;
7983 }
7984 }
7985
7986 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
Chris Lattner1443bc52006-05-11 17:11:52 +00007987 AddReachableCodeToWorklist(TI->getSuccessor(i), Visited, WorkList, TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00007988}
7989
Chris Lattner113f4f42002-06-25 16:13:24 +00007990bool InstCombiner::runOnFunction(Function &F) {
Chris Lattner260ab202002-04-18 17:39:14 +00007991 bool Changed = false;
Chris Lattnerf4ad1652003-11-02 05:57:39 +00007992 TD = &getAnalysis<TargetData>();
Chris Lattnerca081252001-12-14 16:52:21 +00007993
Chris Lattner4ed40f72005-07-07 20:40:38 +00007994 {
Chris Lattnera36ee4e2006-05-10 19:00:36 +00007995 // Do a depth-first traversal of the function, populate the worklist with
7996 // the reachable instructions. Ignore blocks that are not reachable. Keep
7997 // track of which blocks we visit.
Chris Lattner4ed40f72005-07-07 20:40:38 +00007998 std::set<BasicBlock*> Visited;
Chris Lattner1443bc52006-05-11 17:11:52 +00007999 AddReachableCodeToWorklist(F.begin(), Visited, WorkList, TD);
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00008000
Chris Lattner4ed40f72005-07-07 20:40:38 +00008001 // Do a quick scan over the function. If we find any blocks that are
8002 // unreachable, remove any instructions inside of them. This prevents
8003 // the instcombine code from having to deal with some bad special cases.
8004 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
8005 if (!Visited.count(BB)) {
8006 Instruction *Term = BB->getTerminator();
8007 while (Term != BB->begin()) { // Remove instrs bottom-up
8008 BasicBlock::iterator I = Term; --I;
Chris Lattner2d3a7a62004-04-27 15:13:33 +00008009
Chris Lattner4ed40f72005-07-07 20:40:38 +00008010 DEBUG(std::cerr << "IC: DCE: " << *I);
8011 ++NumDeadInst;
8012
8013 if (!I->use_empty())
8014 I->replaceAllUsesWith(UndefValue::get(I->getType()));
8015 I->eraseFromParent();
8016 }
8017 }
8018 }
Chris Lattnerca081252001-12-14 16:52:21 +00008019
8020 while (!WorkList.empty()) {
8021 Instruction *I = WorkList.back(); // Get an instruction from the worklist
8022 WorkList.pop_back();
8023
Chris Lattner1443bc52006-05-11 17:11:52 +00008024 // Check to see if we can DCE the instruction.
Chris Lattner99f48c62002-09-02 04:59:56 +00008025 if (isInstructionTriviallyDead(I)) {
Chris Lattner1443bc52006-05-11 17:11:52 +00008026 // Add operands to the worklist.
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00008027 if (I->getNumOperands() < 4)
Chris Lattner51ea1272004-02-28 05:22:00 +00008028 AddUsesToWorkList(*I);
Chris Lattner99f48c62002-09-02 04:59:56 +00008029 ++NumDeadInst;
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00008030
Chris Lattnercd517ff2005-01-28 19:32:01 +00008031 DEBUG(std::cerr << "IC: DCE: " << *I);
8032
8033 I->eraseFromParent();
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00008034 removeFromWorkList(I);
8035 continue;
8036 }
Chris Lattner99f48c62002-09-02 04:59:56 +00008037
Chris Lattner1443bc52006-05-11 17:11:52 +00008038 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattner99f48c62002-09-02 04:59:56 +00008039 if (Constant *C = ConstantFoldInstruction(I)) {
Chris Lattner1443bc52006-05-11 17:11:52 +00008040 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
8041 C = OptimizeConstantExpr(CE, TD);
Chris Lattnercd517ff2005-01-28 19:32:01 +00008042 DEBUG(std::cerr << "IC: ConstFold to: " << *C << " from: " << *I);
8043
Chris Lattner1443bc52006-05-11 17:11:52 +00008044 // Add operands to the worklist.
Chris Lattner51ea1272004-02-28 05:22:00 +00008045 AddUsesToWorkList(*I);
Chris Lattnerc6509f42002-12-05 22:41:53 +00008046 ReplaceInstUsesWith(*I, C);
8047
Chris Lattner99f48c62002-09-02 04:59:56 +00008048 ++NumConstProp;
Chris Lattnera36ee4e2006-05-10 19:00:36 +00008049 I->eraseFromParent();
Chris Lattner800aaaf2003-10-07 15:17:02 +00008050 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00008051 continue;
Chris Lattner99f48c62002-09-02 04:59:56 +00008052 }
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00008053
Chris Lattner39c98bb2004-12-08 23:43:58 +00008054 // See if we can trivially sink this instruction to a successor basic block.
8055 if (I->hasOneUse()) {
8056 BasicBlock *BB = I->getParent();
8057 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
8058 if (UserParent != BB) {
8059 bool UserIsSuccessor = false;
8060 // See if the user is one of our successors.
8061 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
8062 if (*SI == UserParent) {
8063 UserIsSuccessor = true;
8064 break;
8065 }
8066
8067 // If the user is one of our immediate successors, and if that successor
8068 // only has us as a predecessors (we'd have to split the critical edge
8069 // otherwise), we can keep going.
8070 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
8071 next(pred_begin(UserParent)) == pred_end(UserParent))
8072 // Okay, the CFG is simple enough, try to sink this instruction.
8073 Changed |= TryToSinkInstruction(I, UserParent);
8074 }
8075 }
8076
Chris Lattnerca081252001-12-14 16:52:21 +00008077 // Now that we have an instruction, try combining it to simplify it...
Chris Lattnerae7a0d32002-08-02 19:29:35 +00008078 if (Instruction *Result = visit(*I)) {
Chris Lattner0b18c1d2002-05-10 15:38:35 +00008079 ++NumCombined;
Chris Lattner260ab202002-04-18 17:39:14 +00008080 // Should we replace the old instruction with a new one?
Chris Lattner053c0932002-05-14 15:24:07 +00008081 if (Result != I) {
Chris Lattner7d2a5392004-03-13 23:54:27 +00008082 DEBUG(std::cerr << "IC: Old = " << *I
8083 << " New = " << *Result);
8084
Chris Lattner396dbfe2004-06-09 05:08:07 +00008085 // Everything uses the new instruction now.
8086 I->replaceAllUsesWith(Result);
8087
8088 // Push the new instruction and any users onto the worklist.
8089 WorkList.push_back(Result);
8090 AddUsersToWorkList(*Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00008091
8092 // Move the name to the new instruction first...
8093 std::string OldName = I->getName(); I->setName("");
Chris Lattner950fc782003-10-07 22:58:41 +00008094 Result->setName(OldName);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00008095
8096 // Insert the new instruction into the basic block...
8097 BasicBlock *InstParent = I->getParent();
Chris Lattner7515cab2004-11-14 19:13:23 +00008098 BasicBlock::iterator InsertPos = I;
8099
8100 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
8101 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
8102 ++InsertPos;
8103
8104 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00008105
Chris Lattner63d75af2004-05-01 23:27:23 +00008106 // Make sure that we reprocess all operands now that we reduced their
8107 // use counts.
Chris Lattnerb643a9e2004-05-01 23:19:52 +00008108 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
8109 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
8110 WorkList.push_back(OpI);
8111
Chris Lattner396dbfe2004-06-09 05:08:07 +00008112 // Instructions can end up on the worklist more than once. Make sure
8113 // we do not process an instruction that has been deleted.
8114 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00008115
8116 // Erase the old instruction.
8117 InstParent->getInstList().erase(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00008118 } else {
Chris Lattner7d2a5392004-03-13 23:54:27 +00008119 DEBUG(std::cerr << "IC: MOD = " << *I);
8120
Chris Lattnerae7a0d32002-08-02 19:29:35 +00008121 // If the instruction was modified, it's possible that it is now dead.
8122 // if so, remove it.
Chris Lattner63d75af2004-05-01 23:27:23 +00008123 if (isInstructionTriviallyDead(I)) {
8124 // Make sure we process all operands now that we are reducing their
8125 // use counts.
8126 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
8127 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
8128 WorkList.push_back(OpI);
Misha Brukmanb1c93172005-04-21 23:48:37 +00008129
Chris Lattner63d75af2004-05-01 23:27:23 +00008130 // Instructions may end up in the worklist more than once. Erase all
Robert Bocchinoa8352962006-01-13 22:48:06 +00008131 // occurrences of this instruction.
Chris Lattner99f48c62002-09-02 04:59:56 +00008132 removeFromWorkList(I);
Chris Lattner31f486c2005-01-31 05:36:43 +00008133 I->eraseFromParent();
Chris Lattner396dbfe2004-06-09 05:08:07 +00008134 } else {
8135 WorkList.push_back(Result);
8136 AddUsersToWorkList(*Result);
Chris Lattnerae7a0d32002-08-02 19:29:35 +00008137 }
Chris Lattner053c0932002-05-14 15:24:07 +00008138 }
Chris Lattner260ab202002-04-18 17:39:14 +00008139 Changed = true;
Chris Lattnerca081252001-12-14 16:52:21 +00008140 }
8141 }
8142
Chris Lattner260ab202002-04-18 17:39:14 +00008143 return Changed;
Chris Lattner04805fa2002-02-26 21:46:54 +00008144}
8145
Brian Gaeke38b79e82004-07-27 17:43:21 +00008146FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattner260ab202002-04-18 17:39:14 +00008147 return new InstCombiner();
Chris Lattner04805fa2002-02-26 21:46:54 +00008148}
Brian Gaeke960707c2003-11-11 22:41:34 +00008149