blob: 21f1b2bfe6c5804a3eaeca99bc35f19a8d93b0b3 [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()) {
1014 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1015 KnownZero, KnownOne, Depth+1))
1016 return true;
1017 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1018 break;
1019 }
1020
1021 // Sign or Zero extension. Compute the bits in the result that are not
1022 // present in the input.
1023 uint64_t NotIn = ~SrcTy->getIntegralTypeMask();
1024 uint64_t NewBits = I->getType()->getIntegralTypeMask() & NotIn;
1025
1026 // Handle zero extension.
1027 if (!SrcTy->isSigned()) {
1028 DemandedMask &= SrcTy->getIntegralTypeMask();
1029 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1030 KnownZero, KnownOne, Depth+1))
1031 return true;
1032 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1033 // The top bits are known to be zero.
1034 KnownZero |= NewBits;
1035 } else {
1036 // Sign extension.
Chris Lattner7d852282006-02-13 22:41:07 +00001037 uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
1038 int64_t InputDemandedBits = DemandedMask & SrcTy->getIntegralTypeMask();
1039
1040 // If any of the sign extended bits are demanded, we know that the sign
1041 // bit is demanded.
1042 if (NewBits & DemandedMask)
1043 InputDemandedBits |= InSignBit;
1044
1045 if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
Chris Lattner0157e7f2006-02-11 09:31:47 +00001046 KnownZero, KnownOne, Depth+1))
1047 return true;
1048 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1049
1050 // If the sign bit of the input is known set or clear, then we know the
1051 // top bits of the result.
Chris Lattner2590e512006-02-07 06:56:34 +00001052
Chris Lattner0157e7f2006-02-11 09:31:47 +00001053 // If the input sign bit is known zero, or if the NewBits are not demanded
1054 // convert this into a zero extension.
1055 if ((KnownZero & InSignBit) || (NewBits & ~DemandedMask) == NewBits) {
Chris Lattner2590e512006-02-07 06:56:34 +00001056 // Convert to unsigned first.
Chris Lattner44314822006-02-07 19:07:40 +00001057 Instruction *NewVal;
Chris Lattner2590e512006-02-07 06:56:34 +00001058 NewVal = new CastInst(I->getOperand(0), SrcTy->getUnsignedVersion(),
Chris Lattner44314822006-02-07 19:07:40 +00001059 I->getOperand(0)->getName());
1060 InsertNewInstBefore(NewVal, *I);
Chris Lattner0157e7f2006-02-11 09:31:47 +00001061 // Then cast that to the destination type.
Chris Lattner44314822006-02-07 19:07:40 +00001062 NewVal = new CastInst(NewVal, I->getType(), I->getName());
1063 InsertNewInstBefore(NewVal, *I);
Chris Lattner2590e512006-02-07 06:56:34 +00001064 return UpdateValueUsesWith(I, NewVal);
Chris Lattner0157e7f2006-02-11 09:31:47 +00001065 } else if (KnownOne & InSignBit) { // Input sign bit known set
1066 KnownOne |= NewBits;
1067 KnownZero &= ~NewBits;
1068 } else { // Input sign bit unknown
1069 KnownZero &= ~NewBits;
1070 KnownOne &= ~NewBits;
Chris Lattner2590e512006-02-07 06:56:34 +00001071 }
Chris Lattner2590e512006-02-07 06:56:34 +00001072 }
Chris Lattner0157e7f2006-02-11 09:31:47 +00001073 break;
Chris Lattner2590e512006-02-07 06:56:34 +00001074 }
Chris Lattner2590e512006-02-07 06:56:34 +00001075 case Instruction::Shl:
Chris Lattner0157e7f2006-02-11 09:31:47 +00001076 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1))) {
1077 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask >> SA->getValue(),
1078 KnownZero, KnownOne, Depth+1))
1079 return true;
1080 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1081 KnownZero <<= SA->getValue();
1082 KnownOne <<= SA->getValue();
1083 KnownZero |= (1ULL << SA->getValue())-1; // low bits known zero.
1084 }
Chris Lattner2590e512006-02-07 06:56:34 +00001085 break;
1086 case Instruction::Shr:
Chris Lattner0157e7f2006-02-11 09:31:47 +00001087 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1))) {
1088 unsigned ShAmt = SA->getValue();
1089
1090 // Compute the new bits that are at the top now.
1091 uint64_t HighBits = (1ULL << ShAmt)-1;
1092 HighBits <<= I->getType()->getPrimitiveSizeInBits() - ShAmt;
Chris Lattner68e74752006-02-13 06:09:08 +00001093 uint64_t TypeMask = I->getType()->getIntegralTypeMask();
Chris Lattner0157e7f2006-02-11 09:31:47 +00001094 if (I->getType()->isUnsigned()) { // Unsigned shift right.
Chris Lattner68e74752006-02-13 06:09:08 +00001095 if (SimplifyDemandedBits(I->getOperand(0),
1096 (DemandedMask << ShAmt) & TypeMask,
Chris Lattner0157e7f2006-02-11 09:31:47 +00001097 KnownZero, KnownOne, Depth+1))
1098 return true;
1099 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattner68e74752006-02-13 06:09:08 +00001100 KnownZero &= TypeMask;
1101 KnownOne &= TypeMask;
Chris Lattner0157e7f2006-02-11 09:31:47 +00001102 KnownZero >>= ShAmt;
1103 KnownOne >>= ShAmt;
1104 KnownZero |= HighBits; // high bits known zero.
1105 } else { // Signed shift right.
Chris Lattner68e74752006-02-13 06:09:08 +00001106 if (SimplifyDemandedBits(I->getOperand(0),
1107 (DemandedMask << ShAmt) & TypeMask,
Chris Lattner0157e7f2006-02-11 09:31:47 +00001108 KnownZero, KnownOne, Depth+1))
1109 return true;
1110 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattner68e74752006-02-13 06:09:08 +00001111 KnownZero &= TypeMask;
1112 KnownOne &= TypeMask;
Chris Lattner0157e7f2006-02-11 09:31:47 +00001113 KnownZero >>= SA->getValue();
1114 KnownOne >>= SA->getValue();
1115
1116 // Handle the sign bits.
1117 uint64_t SignBit = 1ULL << (I->getType()->getPrimitiveSizeInBits()-1);
1118 SignBit >>= SA->getValue(); // Adjust to where it is now in the mask.
1119
1120 // If the input sign bit is known to be zero, or if none of the top bits
1121 // are demanded, turn this into an unsigned shift right.
1122 if ((KnownZero & SignBit) || (HighBits & ~DemandedMask) == HighBits) {
1123 // Convert the input to unsigned.
1124 Instruction *NewVal;
1125 NewVal = new CastInst(I->getOperand(0),
1126 I->getType()->getUnsignedVersion(),
1127 I->getOperand(0)->getName());
1128 InsertNewInstBefore(NewVal, *I);
1129 // Perform the unsigned shift right.
1130 NewVal = new ShiftInst(Instruction::Shr, NewVal, SA, I->getName());
1131 InsertNewInstBefore(NewVal, *I);
1132 // Then cast that to the destination type.
1133 NewVal = new CastInst(NewVal, I->getType(), I->getName());
1134 InsertNewInstBefore(NewVal, *I);
1135 return UpdateValueUsesWith(I, NewVal);
1136 } else if (KnownOne & SignBit) { // New bits are known one.
1137 KnownOne |= HighBits;
1138 }
Chris Lattner2590e512006-02-07 06:56:34 +00001139 }
Chris Lattner0157e7f2006-02-11 09:31:47 +00001140 }
Chris Lattner2590e512006-02-07 06:56:34 +00001141 break;
1142 }
Chris Lattner0157e7f2006-02-11 09:31:47 +00001143
1144 // If the client is only demanding bits that we know, return the known
1145 // constant.
1146 if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask)
1147 return UpdateValueUsesWith(I, GetConstantInType(I->getType(), KnownOne));
Chris Lattner2590e512006-02-07 06:56:34 +00001148 return false;
1149}
1150
Chris Lattner623826c2004-09-28 21:48:02 +00001151// isTrueWhenEqual - Return true if the specified setcondinst instruction is
1152// true when both operands are equal...
1153//
1154static bool isTrueWhenEqual(Instruction &I) {
1155 return I.getOpcode() == Instruction::SetEQ ||
1156 I.getOpcode() == Instruction::SetGE ||
1157 I.getOpcode() == Instruction::SetLE;
1158}
Chris Lattnerb8b97502003-08-13 19:01:45 +00001159
1160/// AssociativeOpt - Perform an optimization on an associative operator. This
1161/// function is designed to check a chain of associative operators for a
1162/// potential to apply a certain optimization. Since the optimization may be
1163/// applicable if the expression was reassociated, this checks the chain, then
1164/// reassociates the expression as necessary to expose the optimization
1165/// opportunity. This makes use of a special Functor, which must define
1166/// 'shouldApply' and 'apply' methods.
1167///
1168template<typename Functor>
1169Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1170 unsigned Opcode = Root.getOpcode();
1171 Value *LHS = Root.getOperand(0);
1172
1173 // Quick check, see if the immediate LHS matches...
1174 if (F.shouldApply(LHS))
1175 return F.apply(Root);
1176
1177 // Otherwise, if the LHS is not of the same opcode as the root, return.
1178 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001179 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattnerb8b97502003-08-13 19:01:45 +00001180 // Should we apply this transform to the RHS?
1181 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1182
1183 // If not to the RHS, check to see if we should apply to the LHS...
1184 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1185 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1186 ShouldApply = true;
1187 }
1188
1189 // If the functor wants to apply the optimization to the RHS of LHSI,
1190 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1191 if (ShouldApply) {
1192 BasicBlock *BB = Root.getParent();
Misha Brukmanb1c93172005-04-21 23:48:37 +00001193
Chris Lattnerb8b97502003-08-13 19:01:45 +00001194 // Now all of the instructions are in the current basic block, go ahead
1195 // and perform the reassociation.
1196 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1197
1198 // First move the selected RHS to the LHS of the root...
1199 Root.setOperand(0, LHSI->getOperand(1));
1200
1201 // Make what used to be the LHS of the root be the user of the root...
1202 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner284d3b02004-04-16 18:08:07 +00001203 if (&Root == TmpLHSI) {
Chris Lattner8953b902004-04-05 02:10:19 +00001204 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1205 return 0;
1206 }
Chris Lattner284d3b02004-04-16 18:08:07 +00001207 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattnerb8b97502003-08-13 19:01:45 +00001208 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner284d3b02004-04-16 18:08:07 +00001209 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
1210 BasicBlock::iterator ARI = &Root; ++ARI;
1211 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
1212 ARI = Root;
Chris Lattnerb8b97502003-08-13 19:01:45 +00001213
1214 // Now propagate the ExtraOperand down the chain of instructions until we
1215 // get to LHSI.
1216 while (TmpLHSI != LHSI) {
1217 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner284d3b02004-04-16 18:08:07 +00001218 // Move the instruction to immediately before the chain we are
1219 // constructing to avoid breaking dominance properties.
1220 NextLHSI->getParent()->getInstList().remove(NextLHSI);
1221 BB->getInstList().insert(ARI, NextLHSI);
1222 ARI = NextLHSI;
1223
Chris Lattnerb8b97502003-08-13 19:01:45 +00001224 Value *NextOp = NextLHSI->getOperand(1);
1225 NextLHSI->setOperand(1, ExtraOperand);
1226 TmpLHSI = NextLHSI;
1227 ExtraOperand = NextOp;
1228 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001229
Chris Lattnerb8b97502003-08-13 19:01:45 +00001230 // Now that the instructions are reassociated, have the functor perform
1231 // the transformation...
1232 return F.apply(Root);
1233 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001234
Chris Lattnerb8b97502003-08-13 19:01:45 +00001235 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1236 }
1237 return 0;
1238}
1239
1240
1241// AddRHS - Implements: X + X --> X << 1
1242struct AddRHS {
1243 Value *RHS;
1244 AddRHS(Value *rhs) : RHS(rhs) {}
1245 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1246 Instruction *apply(BinaryOperator &Add) const {
1247 return new ShiftInst(Instruction::Shl, Add.getOperand(0),
1248 ConstantInt::get(Type::UByteTy, 1));
1249 }
1250};
1251
1252// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1253// iff C1&C2 == 0
1254struct AddMaskingAnd {
1255 Constant *C2;
1256 AddMaskingAnd(Constant *c) : C2(c) {}
1257 bool shouldApply(Value *LHS) const {
Chris Lattnerd4252a72004-07-30 07:50:03 +00001258 ConstantInt *C1;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001259 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Chris Lattnerd4252a72004-07-30 07:50:03 +00001260 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattnerb8b97502003-08-13 19:01:45 +00001261 }
1262 Instruction *apply(BinaryOperator &Add) const {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001263 return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattnerb8b97502003-08-13 19:01:45 +00001264 }
1265};
1266
Chris Lattner86102b82005-01-01 16:22:27 +00001267static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner183b3362004-04-09 19:05:30 +00001268 InstCombiner *IC) {
Chris Lattner86102b82005-01-01 16:22:27 +00001269 if (isa<CastInst>(I)) {
1270 if (Constant *SOC = dyn_cast<Constant>(SO))
1271 return ConstantExpr::getCast(SOC, I.getType());
Misha Brukmanb1c93172005-04-21 23:48:37 +00001272
Chris Lattner86102b82005-01-01 16:22:27 +00001273 return IC->InsertNewInstBefore(new CastInst(SO, I.getType(),
1274 SO->getName() + ".cast"), I);
1275 }
1276
Chris Lattner183b3362004-04-09 19:05:30 +00001277 // Figure out if the constant is the left or the right argument.
Chris Lattner86102b82005-01-01 16:22:27 +00001278 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1279 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattnerb8b97502003-08-13 19:01:45 +00001280
Chris Lattner183b3362004-04-09 19:05:30 +00001281 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1282 if (ConstIsRHS)
Chris Lattner86102b82005-01-01 16:22:27 +00001283 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1284 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner183b3362004-04-09 19:05:30 +00001285 }
1286
1287 Value *Op0 = SO, *Op1 = ConstOperand;
1288 if (!ConstIsRHS)
1289 std::swap(Op0, Op1);
1290 Instruction *New;
Chris Lattner86102b82005-01-01 16:22:27 +00001291 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1292 New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
1293 else if (ShiftInst *SI = dyn_cast<ShiftInst>(&I))
1294 New = new ShiftInst(SI->getOpcode(), Op0, Op1, SO->getName()+".sh");
Chris Lattnerf9d96652004-04-10 19:15:56 +00001295 else {
Chris Lattner183b3362004-04-09 19:05:30 +00001296 assert(0 && "Unknown binary instruction type!");
Chris Lattnerf9d96652004-04-10 19:15:56 +00001297 abort();
1298 }
Chris Lattner86102b82005-01-01 16:22:27 +00001299 return IC->InsertNewInstBefore(New, I);
1300}
1301
1302// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1303// constant as the other operand, try to fold the binary operator into the
1304// select arguments. This also works for Cast instructions, which obviously do
1305// not have a second operand.
1306static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1307 InstCombiner *IC) {
1308 // Don't modify shared select instructions
1309 if (!SI->hasOneUse()) return 0;
1310 Value *TV = SI->getOperand(1);
1311 Value *FV = SI->getOperand(2);
1312
1313 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner374e6592005-04-21 05:43:13 +00001314 // Bool selects with constant operands can be folded to logical ops.
1315 if (SI->getType() == Type::BoolTy) return 0;
1316
Chris Lattner86102b82005-01-01 16:22:27 +00001317 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1318 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1319
1320 return new SelectInst(SI->getCondition(), SelectTrueVal,
1321 SelectFalseVal);
1322 }
1323 return 0;
Chris Lattner183b3362004-04-09 19:05:30 +00001324}
1325
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001326
1327/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1328/// node as operand #0, see if we can fold the instruction into the PHI (which
1329/// is only possible if all operands to the PHI are constants).
1330Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1331 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattner7515cab2004-11-14 19:13:23 +00001332 unsigned NumPHIValues = PN->getNumIncomingValues();
1333 if (!PN->hasOneUse() || NumPHIValues == 0 ||
1334 !isa<Constant>(PN->getIncomingValue(0))) return 0;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001335
1336 // Check to see if all of the operands of the PHI are constants. If not, we
1337 // cannot do the transformation.
Chris Lattner7515cab2004-11-14 19:13:23 +00001338 for (unsigned i = 1; i != NumPHIValues; ++i)
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001339 if (!isa<Constant>(PN->getIncomingValue(i)))
1340 return 0;
1341
1342 // Okay, we can do the transformation: create the new PHI node.
1343 PHINode *NewPN = new PHINode(I.getType(), I.getName());
1344 I.setName("");
Chris Lattnerd8e20182005-01-29 00:39:08 +00001345 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001346 InsertNewInstBefore(NewPN, *PN);
1347
1348 // Next, add all of the operands to the PHI.
1349 if (I.getNumOperands() == 2) {
1350 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattner7515cab2004-11-14 19:13:23 +00001351 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001352 Constant *InV = cast<Constant>(PN->getIncomingValue(i));
1353 NewPN->addIncoming(ConstantExpr::get(I.getOpcode(), InV, C),
1354 PN->getIncomingBlock(i));
1355 }
1356 } else {
1357 assert(isa<CastInst>(I) && "Unary op should be a cast!");
1358 const Type *RetTy = I.getType();
Chris Lattner7515cab2004-11-14 19:13:23 +00001359 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001360 Constant *InV = cast<Constant>(PN->getIncomingValue(i));
1361 NewPN->addIncoming(ConstantExpr::getCast(InV, RetTy),
1362 PN->getIncomingBlock(i));
1363 }
1364 }
1365 return ReplaceInstUsesWith(I, NewPN);
1366}
1367
Chris Lattner113f4f42002-06-25 16:13:24 +00001368Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001369 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00001370 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattner9fa53de2002-05-06 16:49:18 +00001371
Chris Lattnercf4a9962004-04-10 22:01:55 +00001372 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattner81a7a232004-10-16 18:11:37 +00001373 // X + undef -> undef
1374 if (isa<UndefValue>(RHS))
1375 return ReplaceInstUsesWith(I, RHS);
1376
Chris Lattnercf4a9962004-04-10 22:01:55 +00001377 // X + 0 --> X
Chris Lattner7fde91e2005-10-17 17:56:38 +00001378 if (!I.getType()->isFloatingPoint()) { // NOTE: -0 + +0 = +0.
1379 if (RHSC->isNullValue())
1380 return ReplaceInstUsesWith(I, LHS);
Chris Lattnerda1b1522005-10-17 20:18:38 +00001381 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
1382 if (CFP->isExactlyValue(-0.0))
1383 return ReplaceInstUsesWith(I, LHS);
Chris Lattner7fde91e2005-10-17 17:56:38 +00001384 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001385
Chris Lattnercf4a9962004-04-10 22:01:55 +00001386 // X + (signbit) --> X ^ signbit
1387 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattner92a68652006-02-07 08:05:22 +00001388 uint64_t Val = CI->getZExtValue();
Chris Lattner77defba2006-02-07 07:00:41 +00001389 if (Val == (1ULL << (CI->getType()->getPrimitiveSizeInBits()-1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001390 return BinaryOperator::createXor(LHS, RHS);
Chris Lattnercf4a9962004-04-10 22:01:55 +00001391 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001392
1393 if (isa<PHINode>(LHS))
1394 if (Instruction *NV = FoldOpIntoPhi(I))
1395 return NV;
Chris Lattner0b3557f2005-09-24 23:43:33 +00001396
Chris Lattner330628a2006-01-06 17:59:59 +00001397 ConstantInt *XorRHS = 0;
1398 Value *XorLHS = 0;
Chris Lattner0b3557f2005-09-24 23:43:33 +00001399 if (match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
1400 unsigned TySizeBits = I.getType()->getPrimitiveSizeInBits();
1401 int64_t RHSSExt = cast<ConstantInt>(RHSC)->getSExtValue();
1402 uint64_t RHSZExt = cast<ConstantInt>(RHSC)->getZExtValue();
1403
1404 uint64_t C0080Val = 1ULL << 31;
1405 int64_t CFF80Val = -C0080Val;
1406 unsigned Size = 32;
1407 do {
1408 if (TySizeBits > Size) {
1409 bool Found = false;
1410 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
1411 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
1412 if (RHSSExt == CFF80Val) {
1413 if (XorRHS->getZExtValue() == C0080Val)
1414 Found = true;
1415 } else if (RHSZExt == C0080Val) {
1416 if (XorRHS->getSExtValue() == CFF80Val)
1417 Found = true;
1418 }
1419 if (Found) {
1420 // This is a sign extend if the top bits are known zero.
Chris Lattner4534dd592006-02-09 07:38:58 +00001421 uint64_t Mask = ~0ULL;
Chris Lattnerc3ebf402006-02-07 07:27:52 +00001422 Mask <<= 64-(TySizeBits-Size);
Chris Lattner4534dd592006-02-09 07:38:58 +00001423 Mask &= XorLHS->getType()->getIntegralTypeMask();
Chris Lattnerc3ebf402006-02-07 07:27:52 +00001424 if (!MaskedValueIsZero(XorLHS, Mask))
Chris Lattner0b3557f2005-09-24 23:43:33 +00001425 Size = 0; // Not a sign ext, but can't be any others either.
1426 goto FoundSExt;
1427 }
1428 }
1429 Size >>= 1;
1430 C0080Val >>= Size;
1431 CFF80Val >>= Size;
1432 } while (Size >= 8);
1433
1434FoundSExt:
1435 const Type *MiddleType = 0;
1436 switch (Size) {
1437 default: break;
1438 case 32: MiddleType = Type::IntTy; break;
1439 case 16: MiddleType = Type::ShortTy; break;
1440 case 8: MiddleType = Type::SByteTy; break;
1441 }
1442 if (MiddleType) {
1443 Instruction *NewTrunc = new CastInst(XorLHS, MiddleType, "sext");
1444 InsertNewInstBefore(NewTrunc, I);
1445 return new CastInst(NewTrunc, I.getType());
1446 }
1447 }
Chris Lattnercf4a9962004-04-10 22:01:55 +00001448 }
Chris Lattner9fa53de2002-05-06 16:49:18 +00001449
Chris Lattnerb8b97502003-08-13 19:01:45 +00001450 // X + X --> X << 1
Robert Bocchino7b5b86c2004-07-27 21:02:21 +00001451 if (I.getType()->isInteger()) {
Chris Lattnerb8b97502003-08-13 19:01:45 +00001452 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Chris Lattner47060462005-04-07 17:14:51 +00001453
1454 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
1455 if (RHSI->getOpcode() == Instruction::Sub)
1456 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
1457 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
1458 }
1459 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
1460 if (LHSI->getOpcode() == Instruction::Sub)
1461 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
1462 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
1463 }
Robert Bocchino7b5b86c2004-07-27 21:02:21 +00001464 }
Chris Lattnerede3fe02003-08-13 04:18:28 +00001465
Chris Lattner147e9752002-05-08 22:46:53 +00001466 // -A + B --> B - A
Chris Lattnerbb74e222003-03-10 23:06:50 +00001467 if (Value *V = dyn_castNegVal(LHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001468 return BinaryOperator::createSub(RHS, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +00001469
1470 // A + -B --> A - B
Chris Lattnerbb74e222003-03-10 23:06:50 +00001471 if (!isa<Constant>(RHS))
1472 if (Value *V = dyn_castNegVal(RHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001473 return BinaryOperator::createSub(LHS, V);
Chris Lattner260ab202002-04-18 17:39:14 +00001474
Misha Brukmanb1c93172005-04-21 23:48:37 +00001475
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001476 ConstantInt *C2;
1477 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
1478 if (X == RHS) // X*C + X --> X * (C+1)
1479 return BinaryOperator::createMul(RHS, AddOne(C2));
1480
1481 // X*C1 + X*C2 --> X * (C1+C2)
1482 ConstantInt *C1;
1483 if (X == dyn_castFoldableMul(RHS, C1))
1484 return BinaryOperator::createMul(X, ConstantExpr::getAdd(C1, C2));
Chris Lattner57c8d992003-02-18 19:57:07 +00001485 }
1486
1487 // X + X*C --> X * (C+1)
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001488 if (dyn_castFoldableMul(RHS, C2) == LHS)
1489 return BinaryOperator::createMul(LHS, AddOne(C2));
1490
Chris Lattner57c8d992003-02-18 19:57:07 +00001491
Chris Lattnerb8b97502003-08-13 19:01:45 +00001492 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattnerd4252a72004-07-30 07:50:03 +00001493 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattnerb8b97502003-08-13 19:01:45 +00001494 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2))) return R;
Chris Lattner7fb29e12003-03-11 00:12:48 +00001495
Chris Lattnerb9cde762003-10-02 15:11:26 +00001496 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner330628a2006-01-06 17:59:59 +00001497 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00001498 if (match(LHS, m_Not(m_Value(X)))) { // ~X + C --> (C-1) - X
1499 Constant *C= ConstantExpr::getSub(CRHS, ConstantInt::get(I.getType(), 1));
1500 return BinaryOperator::createSub(C, X);
Chris Lattnerb9cde762003-10-02 15:11:26 +00001501 }
Chris Lattnerd4252a72004-07-30 07:50:03 +00001502
Chris Lattnerbff91d92004-10-08 05:07:56 +00001503 // (X & FF00) + xx00 -> (X+xx00) & FF00
1504 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
1505 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
1506 if (Anded == CRHS) {
1507 // See if all bits from the first bit set in the Add RHS up are included
1508 // in the mask. First, get the rightmost bit.
1509 uint64_t AddRHSV = CRHS->getRawValue();
1510
1511 // Form a mask of all bits from the lowest bit added through the top.
1512 uint64_t AddRHSHighBits = ~((AddRHSV & -AddRHSV)-1);
Chris Lattner77defba2006-02-07 07:00:41 +00001513 AddRHSHighBits &= C2->getType()->getIntegralTypeMask();
Chris Lattnerbff91d92004-10-08 05:07:56 +00001514
1515 // See if the and mask includes all of these bits.
1516 uint64_t AddRHSHighBitsAnd = AddRHSHighBits & C2->getRawValue();
Misha Brukmanb1c93172005-04-21 23:48:37 +00001517
Chris Lattnerbff91d92004-10-08 05:07:56 +00001518 if (AddRHSHighBits == AddRHSHighBitsAnd) {
1519 // Okay, the xform is safe. Insert the new add pronto.
1520 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
1521 LHS->getName()), I);
1522 return BinaryOperator::createAnd(NewAdd, C2);
1523 }
1524 }
1525 }
1526
Chris Lattnerd4252a72004-07-30 07:50:03 +00001527 // Try to fold constant add into select arguments.
1528 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner86102b82005-01-01 16:22:27 +00001529 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattnerd4252a72004-07-30 07:50:03 +00001530 return R;
Chris Lattnerb9cde762003-10-02 15:11:26 +00001531 }
1532
Chris Lattner113f4f42002-06-25 16:13:24 +00001533 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +00001534}
1535
Chris Lattnerbdb0ce02003-07-22 21:46:59 +00001536// isSignBit - Return true if the value represented by the constant only has the
1537// highest order bit set.
1538static bool isSignBit(ConstantInt *CI) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001539 unsigned NumBits = CI->getType()->getPrimitiveSizeInBits();
Chris Lattner2f1457f2005-04-24 17:46:05 +00001540 return (CI->getRawValue() & (~0ULL >> (64-NumBits))) == (1ULL << (NumBits-1));
Chris Lattnerbdb0ce02003-07-22 21:46:59 +00001541}
1542
Chris Lattner022167f2004-03-13 00:11:49 +00001543/// RemoveNoopCast - Strip off nonconverting casts from the value.
1544///
1545static Value *RemoveNoopCast(Value *V) {
1546 if (CastInst *CI = dyn_cast<CastInst>(V)) {
1547 const Type *CTy = CI->getType();
1548 const Type *OpTy = CI->getOperand(0)->getType();
1549 if (CTy->isInteger() && OpTy->isInteger()) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001550 if (CTy->getPrimitiveSizeInBits() == OpTy->getPrimitiveSizeInBits())
Chris Lattner022167f2004-03-13 00:11:49 +00001551 return RemoveNoopCast(CI->getOperand(0));
1552 } else if (isa<PointerType>(CTy) && isa<PointerType>(OpTy))
1553 return RemoveNoopCast(CI->getOperand(0));
1554 }
1555 return V;
1556}
1557
Chris Lattner113f4f42002-06-25 16:13:24 +00001558Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +00001559 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001560
Chris Lattnere6794492002-08-12 21:17:25 +00001561 if (Op0 == Op1) // sub X, X -> 0
1562 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner260ab202002-04-18 17:39:14 +00001563
Chris Lattnere6794492002-08-12 21:17:25 +00001564 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattnerbb74e222003-03-10 23:06:50 +00001565 if (Value *V = dyn_castNegVal(Op1))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001566 return BinaryOperator::createAdd(Op0, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +00001567
Chris Lattner81a7a232004-10-16 18:11:37 +00001568 if (isa<UndefValue>(Op0))
1569 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
1570 if (isa<UndefValue>(Op1))
1571 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
1572
Chris Lattner8f2f5982003-11-05 01:06:05 +00001573 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
1574 // Replace (-1 - A) with (~A)...
Chris Lattner3082c5a2003-02-18 19:28:33 +00001575 if (C->isAllOnesValue())
1576 return BinaryOperator::createNot(Op1);
Chris Lattnerad3c4952002-05-09 01:29:19 +00001577
Chris Lattner8f2f5982003-11-05 01:06:05 +00001578 // C - ~X == X + (1+C)
Reid Spencer4fdd96c2005-06-18 17:37:34 +00001579 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00001580 if (match(Op1, m_Not(m_Value(X))))
1581 return BinaryOperator::createAdd(X,
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001582 ConstantExpr::getAdd(C, ConstantInt::get(I.getType(), 1)));
Chris Lattner92295c52004-03-12 23:53:13 +00001583 // -((uint)X >> 31) -> ((int)X >> 31)
1584 // -((int)X >> 31) -> ((uint)X >> 31)
Chris Lattner022167f2004-03-13 00:11:49 +00001585 if (C->isNullValue()) {
1586 Value *NoopCastedRHS = RemoveNoopCast(Op1);
1587 if (ShiftInst *SI = dyn_cast<ShiftInst>(NoopCastedRHS))
Chris Lattner92295c52004-03-12 23:53:13 +00001588 if (SI->getOpcode() == Instruction::Shr)
1589 if (ConstantUInt *CU = dyn_cast<ConstantUInt>(SI->getOperand(1))) {
1590 const Type *NewTy;
Chris Lattner022167f2004-03-13 00:11:49 +00001591 if (SI->getType()->isSigned())
Chris Lattner97bfcea2004-06-17 18:16:02 +00001592 NewTy = SI->getType()->getUnsignedVersion();
Chris Lattner92295c52004-03-12 23:53:13 +00001593 else
Chris Lattner97bfcea2004-06-17 18:16:02 +00001594 NewTy = SI->getType()->getSignedVersion();
Chris Lattner92295c52004-03-12 23:53:13 +00001595 // Check to see if we are shifting out everything but the sign bit.
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001596 if (CU->getValue() == SI->getType()->getPrimitiveSizeInBits()-1) {
Chris Lattner92295c52004-03-12 23:53:13 +00001597 // Ok, the transformation is safe. Insert a cast of the incoming
1598 // value, then the new shift, then the new cast.
1599 Instruction *FirstCast = new CastInst(SI->getOperand(0), NewTy,
1600 SI->getOperand(0)->getName());
1601 Value *InV = InsertNewInstBefore(FirstCast, I);
1602 Instruction *NewShift = new ShiftInst(Instruction::Shr, FirstCast,
1603 CU, SI->getName());
Chris Lattner022167f2004-03-13 00:11:49 +00001604 if (NewShift->getType() == I.getType())
1605 return NewShift;
1606 else {
1607 InV = InsertNewInstBefore(NewShift, I);
1608 return new CastInst(NewShift, I.getType());
1609 }
Chris Lattner92295c52004-03-12 23:53:13 +00001610 }
1611 }
Chris Lattner022167f2004-03-13 00:11:49 +00001612 }
Chris Lattner183b3362004-04-09 19:05:30 +00001613
1614 // Try to fold constant sub into select arguments.
1615 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner86102b82005-01-01 16:22:27 +00001616 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00001617 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001618
1619 if (isa<PHINode>(Op0))
1620 if (Instruction *NV = FoldOpIntoPhi(I))
1621 return NV;
Chris Lattner8f2f5982003-11-05 01:06:05 +00001622 }
1623
Chris Lattnera9be4492005-04-07 16:15:25 +00001624 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
1625 if (Op1I->getOpcode() == Instruction::Add &&
1626 !Op0->getType()->isFloatingPoint()) {
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00001627 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Chris Lattnera9be4492005-04-07 16:15:25 +00001628 return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00001629 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Chris Lattnera9be4492005-04-07 16:15:25 +00001630 return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00001631 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
1632 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
1633 // C1-(X+C2) --> (C1-C2)-X
1634 return BinaryOperator::createSub(ConstantExpr::getSub(CI1, CI2),
1635 Op1I->getOperand(0));
1636 }
Chris Lattnera9be4492005-04-07 16:15:25 +00001637 }
1638
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001639 if (Op1I->hasOneUse()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00001640 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
1641 // is not used by anyone else...
1642 //
Chris Lattnerc2f0aa52004-02-02 20:09:56 +00001643 if (Op1I->getOpcode() == Instruction::Sub &&
1644 !Op1I->getType()->isFloatingPoint()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00001645 // Swap the two operands of the subexpr...
1646 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
1647 Op1I->setOperand(0, IIOp1);
1648 Op1I->setOperand(1, IIOp0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001649
Chris Lattner3082c5a2003-02-18 19:28:33 +00001650 // Create the new top level add instruction...
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001651 return BinaryOperator::createAdd(Op0, Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001652 }
1653
1654 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
1655 //
1656 if (Op1I->getOpcode() == Instruction::And &&
1657 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
1658 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
1659
Chris Lattner396dbfe2004-06-09 05:08:07 +00001660 Value *NewNot =
1661 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001662 return BinaryOperator::createAnd(Op0, NewNot);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001663 }
Chris Lattner57c8d992003-02-18 19:57:07 +00001664
Chris Lattner0aee4b72004-10-06 15:08:25 +00001665 // -(X sdiv C) -> (X sdiv -C)
1666 if (Op1I->getOpcode() == Instruction::Div)
1667 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
Chris Lattnera9be4492005-04-07 16:15:25 +00001668 if (CSI->isNullValue())
Chris Lattner0aee4b72004-10-06 15:08:25 +00001669 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Misha Brukmanb1c93172005-04-21 23:48:37 +00001670 return BinaryOperator::createDiv(Op1I->getOperand(0),
Chris Lattner0aee4b72004-10-06 15:08:25 +00001671 ConstantExpr::getNeg(DivRHS));
1672
Chris Lattner57c8d992003-02-18 19:57:07 +00001673 // X - X*C --> X * (1-C)
Reid Spencer4fdd96c2005-06-18 17:37:34 +00001674 ConstantInt *C2 = 0;
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001675 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00001676 Constant *CP1 =
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001677 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1), C2);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001678 return BinaryOperator::createMul(Op0, CP1);
Chris Lattner57c8d992003-02-18 19:57:07 +00001679 }
Chris Lattnerad3c4952002-05-09 01:29:19 +00001680 }
Chris Lattnera9be4492005-04-07 16:15:25 +00001681 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00001682
Chris Lattner47060462005-04-07 17:14:51 +00001683 if (!Op0->getType()->isFloatingPoint())
1684 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
1685 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner411336f2005-01-19 21:50:18 +00001686 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
1687 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
1688 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
1689 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner47060462005-04-07 17:14:51 +00001690 } else if (Op0I->getOpcode() == Instruction::Sub) {
1691 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
1692 return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
Chris Lattner411336f2005-01-19 21:50:18 +00001693 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001694
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001695 ConstantInt *C1;
1696 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
1697 if (X == Op1) { // X*C - X --> X * (C-1)
1698 Constant *CP1 = ConstantExpr::getSub(C1, ConstantInt::get(I.getType(),1));
1699 return BinaryOperator::createMul(Op1, CP1);
1700 }
Chris Lattner57c8d992003-02-18 19:57:07 +00001701
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001702 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
1703 if (X == dyn_castFoldableMul(Op1, C2))
1704 return BinaryOperator::createMul(Op1, ConstantExpr::getSub(C1, C2));
1705 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001706 return 0;
Chris Lattner260ab202002-04-18 17:39:14 +00001707}
1708
Chris Lattnere79e8542004-02-23 06:38:22 +00001709/// isSignBitCheck - Given an exploded setcc instruction, return true if it is
1710/// really just returns true if the most significant (sign) bit is set.
1711static bool isSignBitCheck(unsigned Opcode, Value *LHS, ConstantInt *RHS) {
1712 if (RHS->getType()->isSigned()) {
1713 // True if source is LHS < 0 or LHS <= -1
1714 return Opcode == Instruction::SetLT && RHS->isNullValue() ||
1715 Opcode == Instruction::SetLE && RHS->isAllOnesValue();
1716 } else {
1717 ConstantUInt *RHSC = cast<ConstantUInt>(RHS);
1718 // True if source is LHS > 127 or LHS >= 128, where the constants depend on
1719 // the size of the integer type.
1720 if (Opcode == Instruction::SetGE)
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001721 return RHSC->getValue() ==
1722 1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1);
Chris Lattnere79e8542004-02-23 06:38:22 +00001723 if (Opcode == Instruction::SetGT)
1724 return RHSC->getValue() ==
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001725 (1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1))-1;
Chris Lattnere79e8542004-02-23 06:38:22 +00001726 }
1727 return false;
1728}
1729
Chris Lattner113f4f42002-06-25 16:13:24 +00001730Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001731 bool Changed = SimplifyCommutative(I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001732 Value *Op0 = I.getOperand(0);
Chris Lattner260ab202002-04-18 17:39:14 +00001733
Chris Lattner81a7a232004-10-16 18:11:37 +00001734 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
1735 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1736
Chris Lattnere6794492002-08-12 21:17:25 +00001737 // Simplify mul instructions with a constant RHS...
Chris Lattner3082c5a2003-02-18 19:28:33 +00001738 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
1739 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerede3fe02003-08-13 04:18:28 +00001740
1741 // ((X << C1)*C2) == (X * (C2 << C1))
1742 if (ShiftInst *SI = dyn_cast<ShiftInst>(Op0))
1743 if (SI->getOpcode() == Instruction::Shl)
1744 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001745 return BinaryOperator::createMul(SI->getOperand(0),
1746 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanb1c93172005-04-21 23:48:37 +00001747
Chris Lattnercce81be2003-09-11 22:24:54 +00001748 if (CI->isNullValue())
1749 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
1750 if (CI->equalsInt(1)) // X * 1 == X
1751 return ReplaceInstUsesWith(I, Op0);
1752 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Chris Lattner35236d82003-06-25 17:09:20 +00001753 return BinaryOperator::createNeg(Op0, I.getName());
Chris Lattner31ba1292002-04-29 22:24:47 +00001754
Chris Lattnercce81be2003-09-11 22:24:54 +00001755 int64_t Val = (int64_t)cast<ConstantInt>(CI)->getRawValue();
Chris Lattner22d00a82005-08-02 19:16:58 +00001756 if (isPowerOf2_64(Val)) { // Replace X*(2^C) with X << C
1757 uint64_t C = Log2_64(Val);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001758 return new ShiftInst(Instruction::Shl, Op0,
1759 ConstantUInt::get(Type::UByteTy, C));
Chris Lattner22d00a82005-08-02 19:16:58 +00001760 }
Robert Bocchino7b5b86c2004-07-27 21:02:21 +00001761 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00001762 if (Op1F->isNullValue())
1763 return ReplaceInstUsesWith(I, Op1);
Chris Lattner31ba1292002-04-29 22:24:47 +00001764
Chris Lattner3082c5a2003-02-18 19:28:33 +00001765 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
1766 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
1767 if (Op1F->getValue() == 1.0)
1768 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
1769 }
Chris Lattner32c01df2006-03-04 06:04:02 +00001770
1771 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
1772 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
1773 isa<ConstantInt>(Op0I->getOperand(1))) {
1774 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
1775 Instruction *Add = BinaryOperator::createMul(Op0I->getOperand(0),
1776 Op1, "tmp");
1777 InsertNewInstBefore(Add, I);
1778 Value *C1C2 = ConstantExpr::getMul(Op1,
1779 cast<Constant>(Op0I->getOperand(1)));
1780 return BinaryOperator::createAdd(Add, C1C2);
1781
1782 }
Chris Lattner183b3362004-04-09 19:05:30 +00001783
1784 // Try to fold constant mul into select arguments.
1785 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00001786 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00001787 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001788
1789 if (isa<PHINode>(Op0))
1790 if (Instruction *NV = FoldOpIntoPhi(I))
1791 return NV;
Chris Lattner260ab202002-04-18 17:39:14 +00001792 }
1793
Chris Lattner934a64cf2003-03-10 23:23:04 +00001794 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
1795 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001796 return BinaryOperator::createMul(Op0v, Op1v);
Chris Lattner934a64cf2003-03-10 23:23:04 +00001797
Chris Lattner2635b522004-02-23 05:39:21 +00001798 // If one of the operands of the multiply is a cast from a boolean value, then
1799 // we know the bool is either zero or one, so this is a 'masking' multiply.
1800 // See if we can simplify things based on how the boolean was originally
1801 // formed.
1802 CastInst *BoolCast = 0;
1803 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(0)))
1804 if (CI->getOperand(0)->getType() == Type::BoolTy)
1805 BoolCast = CI;
1806 if (!BoolCast)
1807 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(1)))
1808 if (CI->getOperand(0)->getType() == Type::BoolTy)
1809 BoolCast = CI;
1810 if (BoolCast) {
1811 if (SetCondInst *SCI = dyn_cast<SetCondInst>(BoolCast->getOperand(0))) {
1812 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
1813 const Type *SCOpTy = SCIOp0->getType();
1814
Chris Lattnere79e8542004-02-23 06:38:22 +00001815 // If the setcc is true iff the sign bit of X is set, then convert this
1816 // multiply into a shift/and combination.
1817 if (isa<ConstantInt>(SCIOp1) &&
1818 isSignBitCheck(SCI->getOpcode(), SCIOp0, cast<ConstantInt>(SCIOp1))) {
Chris Lattner2635b522004-02-23 05:39:21 +00001819 // Shift the X value right to turn it into "all signbits".
1820 Constant *Amt = ConstantUInt::get(Type::UByteTy,
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001821 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattnere79e8542004-02-23 06:38:22 +00001822 if (SCIOp0->getType()->isUnsigned()) {
Chris Lattner97bfcea2004-06-17 18:16:02 +00001823 const Type *NewTy = SCIOp0->getType()->getSignedVersion();
Chris Lattnere79e8542004-02-23 06:38:22 +00001824 SCIOp0 = InsertNewInstBefore(new CastInst(SCIOp0, NewTy,
1825 SCIOp0->getName()), I);
1826 }
1827
1828 Value *V =
1829 InsertNewInstBefore(new ShiftInst(Instruction::Shr, SCIOp0, Amt,
1830 BoolCast->getOperand(0)->getName()+
1831 ".mask"), I);
Chris Lattner2635b522004-02-23 05:39:21 +00001832
1833 // If the multiply type is not the same as the source type, sign extend
1834 // or truncate to the multiply type.
1835 if (I.getType() != V->getType())
Chris Lattnere79e8542004-02-23 06:38:22 +00001836 V = InsertNewInstBefore(new CastInst(V, I.getType(), V->getName()),I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001837
Chris Lattner2635b522004-02-23 05:39:21 +00001838 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001839 return BinaryOperator::createAnd(V, OtherOp);
Chris Lattner2635b522004-02-23 05:39:21 +00001840 }
1841 }
1842 }
1843
Chris Lattner113f4f42002-06-25 16:13:24 +00001844 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +00001845}
1846
Chris Lattner113f4f42002-06-25 16:13:24 +00001847Instruction *InstCombiner::visitDiv(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001848 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner81a7a232004-10-16 18:11:37 +00001849
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001850 if (isa<UndefValue>(Op0)) // undef / X -> 0
1851 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1852 if (isa<UndefValue>(Op1))
1853 return ReplaceInstUsesWith(I, Op1); // X / undef -> undef
1854
1855 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnere20c3342004-04-26 14:01:59 +00001856 // div X, 1 == X
Chris Lattnere6794492002-08-12 21:17:25 +00001857 if (RHS->equalsInt(1))
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001858 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001859
Chris Lattnere20c3342004-04-26 14:01:59 +00001860 // div X, -1 == -X
1861 if (RHS->isAllOnesValue())
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001862 return BinaryOperator::createNeg(Op0);
Chris Lattnere20c3342004-04-26 14:01:59 +00001863
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001864 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
Chris Lattner272d5ca2004-09-28 18:22:15 +00001865 if (LHS->getOpcode() == Instruction::Div)
1866 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Chris Lattner272d5ca2004-09-28 18:22:15 +00001867 // (X / C1) / C2 -> X / (C1*C2)
1868 return BinaryOperator::createDiv(LHS->getOperand(0),
1869 ConstantExpr::getMul(RHS, LHSRHS));
1870 }
1871
Chris Lattner3082c5a2003-02-18 19:28:33 +00001872 // Check to see if this is an unsigned division with an exact power of 2,
1873 // if so, convert to a right shift.
1874 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
1875 if (uint64_t Val = C->getValue()) // Don't break X / 0
Chris Lattner22d00a82005-08-02 19:16:58 +00001876 if (isPowerOf2_64(Val)) {
1877 uint64_t C = Log2_64(Val);
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001878 return new ShiftInst(Instruction::Shr, Op0,
Chris Lattner3082c5a2003-02-18 19:28:33 +00001879 ConstantUInt::get(Type::UByteTy, C));
Chris Lattner22d00a82005-08-02 19:16:58 +00001880 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001881
Chris Lattner4ad08352004-10-09 02:50:40 +00001882 // -X/C -> X/-C
1883 if (RHS->getType()->isSigned())
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001884 if (Value *LHSNeg = dyn_castNegVal(Op0))
Chris Lattner4ad08352004-10-09 02:50:40 +00001885 return BinaryOperator::createDiv(LHSNeg, ConstantExpr::getNeg(RHS));
1886
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001887 if (!RHS->isNullValue()) {
1888 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00001889 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001890 return R;
1891 if (isa<PHINode>(Op0))
1892 if (Instruction *NV = FoldOpIntoPhi(I))
1893 return NV;
1894 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00001895 }
1896
Chris Lattnerd79dc792006-09-09 20:26:32 +00001897 // Handle div X, Cond?Y:Z
1898 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
1899 // div X, (Cond ? 0 : Y) -> div X, Y. If the div and the select are in the
1900 // same basic block, then we replace the select with Y, and the condition of
1901 // the select with false (if the cond value is in the same BB). If the
1902 // select has uses other than the div, this allows them to be simplified
1903 // also.
1904 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
1905 if (ST->isNullValue()) {
1906 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
1907 if (CondI && CondI->getParent() == I.getParent())
1908 UpdateValueUsesWith(CondI, ConstantBool::False);
1909 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
1910 I.setOperand(1, SI->getOperand(2));
1911 else
1912 UpdateValueUsesWith(SI, SI->getOperand(2));
1913 return &I;
1914 }
1915 // Likewise for: div X, (Cond ? Y : 0) -> div X, Y
1916 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
1917 if (ST->isNullValue()) {
1918 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
1919 if (CondI && CondI->getParent() == I.getParent())
1920 UpdateValueUsesWith(CondI, ConstantBool::True);
1921 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
1922 I.setOperand(1, SI->getOperand(1));
1923 else
1924 UpdateValueUsesWith(SI, SI->getOperand(1));
1925 return &I;
1926 }
1927
1928 // If this is 'udiv X, (Cond ? C1, C2)' where C1&C2 are powers of two,
1929 // transform this into: '(Cond ? (udiv X, C1) : (udiv X, C2))'.
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001930 if (ConstantUInt *STO = dyn_cast<ConstantUInt>(SI->getOperand(1)))
1931 if (ConstantUInt *SFO = dyn_cast<ConstantUInt>(SI->getOperand(2))) {
Chris Lattnerd79dc792006-09-09 20:26:32 +00001932 // STO == 0 and SFO == 0 handled above.
Chris Lattner42362612005-04-08 04:03:26 +00001933 uint64_t TVA = STO->getValue(), FVA = SFO->getValue();
Chris Lattner22d00a82005-08-02 19:16:58 +00001934 if (isPowerOf2_64(TVA) && isPowerOf2_64(FVA)) {
1935 unsigned TSA = Log2_64(TVA), FSA = Log2_64(FVA);
Chris Lattner42362612005-04-08 04:03:26 +00001936 Constant *TC = ConstantUInt::get(Type::UByteTy, TSA);
1937 Instruction *TSI = new ShiftInst(Instruction::Shr, Op0,
1938 TC, SI->getName()+".t");
1939 TSI = InsertNewInstBefore(TSI, I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001940
Chris Lattner42362612005-04-08 04:03:26 +00001941 Constant *FC = ConstantUInt::get(Type::UByteTy, FSA);
1942 Instruction *FSI = new ShiftInst(Instruction::Shr, Op0,
1943 FC, SI->getName()+".f");
1944 FSI = InsertNewInstBefore(FSI, I);
1945 return new SelectInst(SI->getOperand(0), TSI, FSI);
1946 }
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001947 }
Chris Lattnerd79dc792006-09-09 20:26:32 +00001948 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001949
Chris Lattner3082c5a2003-02-18 19:28:33 +00001950 // 0 / X == 0, we don't need to preserve faults!
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001951 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattner3082c5a2003-02-18 19:28:33 +00001952 if (LHS->equalsInt(0))
1953 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1954
Chris Lattnerdd0c1742005-11-05 07:40:31 +00001955 if (I.getType()->isSigned()) {
Chris Lattnerc3ebf402006-02-07 07:27:52 +00001956 // If the sign bits of both operands are zero (i.e. we can prove they are
Chris Lattnerdd0c1742005-11-05 07:40:31 +00001957 // unsigned inputs), turn this into a udiv.
Chris Lattnerc3ebf402006-02-07 07:27:52 +00001958 uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
1959 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
Chris Lattnerdd0c1742005-11-05 07:40:31 +00001960 const Type *NTy = Op0->getType()->getUnsignedVersion();
1961 Instruction *LHS = new CastInst(Op0, NTy, Op0->getName());
1962 InsertNewInstBefore(LHS, I);
1963 Value *RHS;
1964 if (Constant *R = dyn_cast<Constant>(Op1))
1965 RHS = ConstantExpr::getCast(R, NTy);
1966 else
1967 RHS = InsertNewInstBefore(new CastInst(Op1, NTy, Op1->getName()), I);
1968 Instruction *Div = BinaryOperator::createDiv(LHS, RHS, I.getName());
1969 InsertNewInstBefore(Div, I);
1970 return new CastInst(Div, I.getType());
1971 }
Chris Lattner2e90b732006-02-05 07:54:04 +00001972 } else {
1973 // Known to be an unsigned division.
1974 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
1975 // Turn A / (C1 << N), where C1 is "1<<C2" into A >> (N+C2) [udiv only].
1976 if (RHSI->getOpcode() == Instruction::Shl &&
1977 isa<ConstantUInt>(RHSI->getOperand(0))) {
1978 unsigned C1 = cast<ConstantUInt>(RHSI->getOperand(0))->getRawValue();
1979 if (isPowerOf2_64(C1)) {
1980 unsigned C2 = Log2_64(C1);
1981 Value *Add = RHSI->getOperand(1);
1982 if (C2) {
1983 Constant *C2V = ConstantUInt::get(Add->getType(), C2);
1984 Add = InsertNewInstBefore(BinaryOperator::createAdd(Add, C2V,
1985 "tmp"), I);
1986 }
1987 return new ShiftInst(Instruction::Shr, Op0, Add);
1988 }
1989 }
1990 }
Chris Lattnerdd0c1742005-11-05 07:40:31 +00001991 }
1992
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001993 return 0;
1994}
1995
1996
Chris Lattner85dda9a2006-03-02 06:50:58 +00001997/// GetFactor - If we can prove that the specified value is at least a multiple
1998/// of some factor, return that factor.
1999static Constant *GetFactor(Value *V) {
2000 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
2001 return CI;
2002
2003 // Unless we can be tricky, we know this is a multiple of 1.
2004 Constant *Result = ConstantInt::get(V->getType(), 1);
2005
2006 Instruction *I = dyn_cast<Instruction>(V);
2007 if (!I) return Result;
2008
2009 if (I->getOpcode() == Instruction::Mul) {
2010 // Handle multiplies by a constant, etc.
2011 return ConstantExpr::getMul(GetFactor(I->getOperand(0)),
2012 GetFactor(I->getOperand(1)));
2013 } else if (I->getOpcode() == Instruction::Shl) {
2014 // (X<<C) -> X * (1 << C)
2015 if (Constant *ShRHS = dyn_cast<Constant>(I->getOperand(1))) {
2016 ShRHS = ConstantExpr::getShl(Result, ShRHS);
2017 return ConstantExpr::getMul(GetFactor(I->getOperand(0)), ShRHS);
2018 }
2019 } else if (I->getOpcode() == Instruction::And) {
2020 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
2021 // X & 0xFFF0 is known to be a multiple of 16.
2022 unsigned Zeros = CountTrailingZeros_64(RHS->getZExtValue());
2023 if (Zeros != V->getType()->getPrimitiveSizeInBits())
2024 return ConstantExpr::getShl(Result,
2025 ConstantUInt::get(Type::UByteTy, Zeros));
2026 }
2027 } else if (I->getOpcode() == Instruction::Cast) {
2028 Value *Op = I->getOperand(0);
2029 // Only handle int->int casts.
2030 if (!Op->getType()->isInteger()) return Result;
2031 return ConstantExpr::getCast(GetFactor(Op), V->getType());
2032 }
2033 return Result;
2034}
2035
Chris Lattner113f4f42002-06-25 16:13:24 +00002036Instruction *InstCombiner::visitRem(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002037 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner0de4a8d2006-02-28 05:30:45 +00002038
2039 // 0 % X == 0, we don't need to preserve faults!
2040 if (Constant *LHS = dyn_cast<Constant>(Op0))
2041 if (LHS->isNullValue())
2042 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2043
2044 if (isa<UndefValue>(Op0)) // undef % X -> 0
2045 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2046 if (isa<UndefValue>(Op1))
2047 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
2048
Chris Lattnere9ff0ea2005-11-05 07:28:37 +00002049 if (I.getType()->isSigned()) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002050 if (Value *RHSNeg = dyn_castNegVal(Op1))
Chris Lattner98c6bdf2004-07-06 07:11:42 +00002051 if (!isa<ConstantSInt>(RHSNeg) ||
Chris Lattner8e726062004-08-09 21:05:48 +00002052 cast<ConstantSInt>(RHSNeg)->getValue() > 0) {
Chris Lattner7fd5f072004-07-06 07:01:22 +00002053 // X % -Y -> X % Y
2054 AddUsesToWorkList(I);
2055 I.setOperand(1, RHSNeg);
2056 return &I;
2057 }
Chris Lattnere9ff0ea2005-11-05 07:28:37 +00002058
2059 // If the top bits of both operands are zero (i.e. we can prove they are
2060 // unsigned inputs), turn this into a urem.
Chris Lattnerc3ebf402006-02-07 07:27:52 +00002061 uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
2062 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
Chris Lattnere9ff0ea2005-11-05 07:28:37 +00002063 const Type *NTy = Op0->getType()->getUnsignedVersion();
2064 Instruction *LHS = new CastInst(Op0, NTy, Op0->getName());
2065 InsertNewInstBefore(LHS, I);
2066 Value *RHS;
2067 if (Constant *R = dyn_cast<Constant>(Op1))
2068 RHS = ConstantExpr::getCast(R, NTy);
2069 else
2070 RHS = InsertNewInstBefore(new CastInst(Op1, NTy, Op1->getName()), I);
2071 Instruction *Rem = BinaryOperator::createRem(LHS, RHS, I.getName());
2072 InsertNewInstBefore(Rem, I);
2073 return new CastInst(Rem, I.getType());
2074 }
2075 }
Chris Lattner7fd5f072004-07-06 07:01:22 +00002076
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002077 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner0de4a8d2006-02-28 05:30:45 +00002078 // X % 0 == undef, we don't need to preserve faults!
2079 if (RHS->equalsInt(0))
2080 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2081
Chris Lattner3082c5a2003-02-18 19:28:33 +00002082 if (RHS->equalsInt(1)) // X % 1 == 0
2083 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2084
2085 // Check to see if this is an unsigned remainder with an exact power of 2,
2086 // if so, convert to a bitwise and.
2087 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
Chris Lattner0de4a8d2006-02-28 05:30:45 +00002088 if (isPowerOf2_64(C->getValue()))
2089 return BinaryOperator::createAnd(Op0, SubOne(C));
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002090
Chris Lattnerb70f1412006-02-28 05:49:21 +00002091 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2092 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2093 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2094 return R;
2095 } else if (isa<PHINode>(Op0I)) {
2096 if (Instruction *NV = FoldOpIntoPhi(I))
2097 return NV;
Chris Lattnerb70f1412006-02-28 05:49:21 +00002098 }
Chris Lattner85dda9a2006-03-02 06:50:58 +00002099
2100 // X*C1%C2 --> 0 iff C1%C2 == 0
2101 if (ConstantExpr::getRem(GetFactor(Op0I), RHS)->isNullValue())
2102 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerb70f1412006-02-28 05:49:21 +00002103 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00002104 }
2105
Chris Lattner2e90b732006-02-05 07:54:04 +00002106 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
2107 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1) [urem only].
2108 if (I.getType()->isUnsigned() &&
2109 RHSI->getOpcode() == Instruction::Shl &&
2110 isa<ConstantUInt>(RHSI->getOperand(0))) {
2111 unsigned C1 = cast<ConstantUInt>(RHSI->getOperand(0))->getRawValue();
2112 if (isPowerOf2_64(C1)) {
2113 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
2114 Value *Add = InsertNewInstBefore(BinaryOperator::createAdd(RHSI, N1,
2115 "tmp"), I);
2116 return BinaryOperator::createAnd(Op0, Add);
2117 }
2118 }
Chris Lattner0de4a8d2006-02-28 05:30:45 +00002119
2120 // If this is 'urem X, (Cond ? C1, C2)' where C1&C2 are powers of two,
2121 // transform this into: '(Cond ? (urem X, C1) : (urem X, C2))'.
Chris Lattnerd79dc792006-09-09 20:26:32 +00002122 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2123 // rem X, (Cond ? 0 : Y) -> rem X, Y. If the rem and the select are in
2124 // the same basic block, then we replace the select with Y, and the
2125 // condition of the select with false (if the cond value is in the same
2126 // BB). If the select has uses other than the div, this allows them to be
2127 // simplified also.
2128 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2129 if (ST->isNullValue()) {
2130 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2131 if (CondI && CondI->getParent() == I.getParent())
2132 UpdateValueUsesWith(CondI, ConstantBool::False);
2133 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2134 I.setOperand(1, SI->getOperand(2));
2135 else
2136 UpdateValueUsesWith(SI, SI->getOperand(2));
2137 return &I;
2138 }
2139 // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
2140 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2141 if (ST->isNullValue()) {
2142 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2143 if (CondI && CondI->getParent() == I.getParent())
2144 UpdateValueUsesWith(CondI, ConstantBool::True);
2145 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2146 I.setOperand(1, SI->getOperand(1));
2147 else
2148 UpdateValueUsesWith(SI, SI->getOperand(1));
2149 return &I;
2150 }
2151
2152
Chris Lattner0de4a8d2006-02-28 05:30:45 +00002153 if (ConstantUInt *STO = dyn_cast<ConstantUInt>(SI->getOperand(1)))
2154 if (ConstantUInt *SFO = dyn_cast<ConstantUInt>(SI->getOperand(2))) {
Chris Lattnerd79dc792006-09-09 20:26:32 +00002155 // STO == 0 and SFO == 0 handled above.
Chris Lattner0de4a8d2006-02-28 05:30:45 +00002156
2157 if (isPowerOf2_64(STO->getValue()) && isPowerOf2_64(SFO->getValue())){
2158 Value *TrueAnd = InsertNewInstBefore(BinaryOperator::createAnd(Op0,
2159 SubOne(STO), SI->getName()+".t"), I);
2160 Value *FalseAnd = InsertNewInstBefore(BinaryOperator::createAnd(Op0,
2161 SubOne(SFO), SI->getName()+".f"), I);
2162 return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
2163 }
2164 }
Chris Lattnerd79dc792006-09-09 20:26:32 +00002165 }
Chris Lattner2e90b732006-02-05 07:54:04 +00002166 }
2167
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002168 return 0;
2169}
2170
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002171// isMaxValueMinusOne - return true if this is Max-1
Chris Lattnere6794492002-08-12 21:17:25 +00002172static bool isMaxValueMinusOne(const ConstantInt *C) {
Chris Lattner77defba2006-02-07 07:00:41 +00002173 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
2174 return CU->getValue() == C->getType()->getIntegralTypeMask()-1;
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002175
2176 const ConstantSInt *CS = cast<ConstantSInt>(C);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002177
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002178 // Calculate 0111111111..11111
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002179 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002180 int64_t Val = INT64_MAX; // All ones
2181 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
2182 return CS->getValue() == Val-1;
2183}
2184
2185// isMinValuePlusOne - return true if this is Min+1
Chris Lattnere6794492002-08-12 21:17:25 +00002186static bool isMinValuePlusOne(const ConstantInt *C) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002187 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
2188 return CU->getValue() == 1;
2189
2190 const ConstantSInt *CS = cast<ConstantSInt>(C);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002191
2192 // Calculate 1111111111000000000000
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002193 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002194 int64_t Val = -1; // All ones
2195 Val <<= TypeBits-1; // Shift over to the right spot
2196 return CS->getValue() == Val+1;
2197}
2198
Chris Lattner35167c32004-06-09 07:59:58 +00002199// isOneBitSet - Return true if there is exactly one bit set in the specified
2200// constant.
2201static bool isOneBitSet(const ConstantInt *CI) {
2202 uint64_t V = CI->getRawValue();
2203 return V && (V & (V-1)) == 0;
2204}
2205
Chris Lattner8fc5af42004-09-23 21:46:38 +00002206#if 0 // Currently unused
2207// isLowOnes - Return true if the constant is of the form 0+1+.
2208static bool isLowOnes(const ConstantInt *CI) {
2209 uint64_t V = CI->getRawValue();
2210
2211 // There won't be bits set in parts that the type doesn't contain.
2212 V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
2213
2214 uint64_t U = V+1; // If it is low ones, this should be a power of two.
2215 return U && V && (U & V) == 0;
2216}
2217#endif
2218
2219// isHighOnes - Return true if the constant is of the form 1+0+.
2220// This is the same as lowones(~X).
2221static bool isHighOnes(const ConstantInt *CI) {
2222 uint64_t V = ~CI->getRawValue();
Chris Lattner2c14cf72005-08-07 07:03:10 +00002223 if (~V == 0) return false; // 0's does not match "1+"
Chris Lattner8fc5af42004-09-23 21:46:38 +00002224
2225 // There won't be bits set in parts that the type doesn't contain.
2226 V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
2227
2228 uint64_t U = V+1; // If it is low ones, this should be a power of two.
2229 return U && V && (U & V) == 0;
2230}
2231
2232
Chris Lattner3ac7c262003-08-13 20:16:26 +00002233/// getSetCondCode - Encode a setcc opcode into a three bit mask. These bits
2234/// are carefully arranged to allow folding of expressions such as:
2235///
2236/// (A < B) | (A > B) --> (A != B)
2237///
2238/// Bit value '4' represents that the comparison is true if A > B, bit value '2'
2239/// represents that the comparison is true if A == B, and bit value '1' is true
2240/// if A < B.
2241///
2242static unsigned getSetCondCode(const SetCondInst *SCI) {
2243 switch (SCI->getOpcode()) {
2244 // False -> 0
2245 case Instruction::SetGT: return 1;
2246 case Instruction::SetEQ: return 2;
2247 case Instruction::SetGE: return 3;
2248 case Instruction::SetLT: return 4;
2249 case Instruction::SetNE: return 5;
2250 case Instruction::SetLE: return 6;
2251 // True -> 7
2252 default:
2253 assert(0 && "Invalid SetCC opcode!");
2254 return 0;
2255 }
2256}
2257
2258/// getSetCCValue - This is the complement of getSetCondCode, which turns an
2259/// opcode and two operands into either a constant true or false, or a brand new
2260/// SetCC instruction.
2261static Value *getSetCCValue(unsigned Opcode, Value *LHS, Value *RHS) {
2262 switch (Opcode) {
2263 case 0: return ConstantBool::False;
2264 case 1: return new SetCondInst(Instruction::SetGT, LHS, RHS);
2265 case 2: return new SetCondInst(Instruction::SetEQ, LHS, RHS);
2266 case 3: return new SetCondInst(Instruction::SetGE, LHS, RHS);
2267 case 4: return new SetCondInst(Instruction::SetLT, LHS, RHS);
2268 case 5: return new SetCondInst(Instruction::SetNE, LHS, RHS);
2269 case 6: return new SetCondInst(Instruction::SetLE, LHS, RHS);
2270 case 7: return ConstantBool::True;
2271 default: assert(0 && "Illegal SetCCCode!"); return 0;
2272 }
2273}
2274
2275// FoldSetCCLogical - Implements (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
2276struct FoldSetCCLogical {
2277 InstCombiner &IC;
2278 Value *LHS, *RHS;
2279 FoldSetCCLogical(InstCombiner &ic, SetCondInst *SCI)
2280 : IC(ic), LHS(SCI->getOperand(0)), RHS(SCI->getOperand(1)) {}
2281 bool shouldApply(Value *V) const {
2282 if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
2283 return (SCI->getOperand(0) == LHS && SCI->getOperand(1) == RHS ||
2284 SCI->getOperand(0) == RHS && SCI->getOperand(1) == LHS);
2285 return false;
2286 }
2287 Instruction *apply(BinaryOperator &Log) const {
2288 SetCondInst *SCI = cast<SetCondInst>(Log.getOperand(0));
2289 if (SCI->getOperand(0) != LHS) {
2290 assert(SCI->getOperand(1) == LHS);
2291 SCI->swapOperands(); // Swap the LHS and RHS of the SetCC
2292 }
2293
2294 unsigned LHSCode = getSetCondCode(SCI);
2295 unsigned RHSCode = getSetCondCode(cast<SetCondInst>(Log.getOperand(1)));
2296 unsigned Code;
2297 switch (Log.getOpcode()) {
2298 case Instruction::And: Code = LHSCode & RHSCode; break;
2299 case Instruction::Or: Code = LHSCode | RHSCode; break;
2300 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner2caaaba2003-09-22 20:33:34 +00002301 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattner3ac7c262003-08-13 20:16:26 +00002302 }
2303
2304 Value *RV = getSetCCValue(Code, LHS, RHS);
2305 if (Instruction *I = dyn_cast<Instruction>(RV))
2306 return I;
2307 // Otherwise, it's a constant boolean value...
2308 return IC.ReplaceInstUsesWith(Log, RV);
2309 }
2310};
2311
Chris Lattnerba1cb382003-09-19 17:17:26 +00002312// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
2313// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
2314// guaranteed to be either a shift instruction or a binary operator.
2315Instruction *InstCombiner::OptAndOp(Instruction *Op,
2316 ConstantIntegral *OpRHS,
2317 ConstantIntegral *AndRHS,
2318 BinaryOperator &TheAnd) {
2319 Value *X = Op->getOperand(0);
Chris Lattnerfcf21a72004-01-12 19:47:05 +00002320 Constant *Together = 0;
2321 if (!isa<ShiftInst>(Op))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002322 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002323
Chris Lattnerba1cb382003-09-19 17:17:26 +00002324 switch (Op->getOpcode()) {
2325 case Instruction::Xor:
Chris Lattner86102b82005-01-01 16:22:27 +00002326 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00002327 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
2328 std::string OpName = Op->getName(); Op->setName("");
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002329 Instruction *And = BinaryOperator::createAnd(X, AndRHS, OpName);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002330 InsertNewInstBefore(And, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002331 return BinaryOperator::createXor(And, Together);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002332 }
2333 break;
2334 case Instruction::Or:
Chris Lattner86102b82005-01-01 16:22:27 +00002335 if (Together == AndRHS) // (X | C) & C --> C
2336 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002337
Chris Lattner86102b82005-01-01 16:22:27 +00002338 if (Op->hasOneUse() && Together != OpRHS) {
2339 // (X | C1) & C2 --> (X | (C1&C2)) & C2
2340 std::string Op0Name = Op->getName(); Op->setName("");
2341 Instruction *Or = BinaryOperator::createOr(X, Together, Op0Name);
2342 InsertNewInstBefore(Or, TheAnd);
2343 return BinaryOperator::createAnd(Or, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002344 }
2345 break;
2346 case Instruction::Add:
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002347 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00002348 // Adding a one to a single bit bit-field should be turned into an XOR
2349 // of the bit. First thing to check is to see if this AND is with a
2350 // single bit constant.
Chris Lattner35167c32004-06-09 07:59:58 +00002351 uint64_t AndRHSV = cast<ConstantInt>(AndRHS)->getRawValue();
Chris Lattnerba1cb382003-09-19 17:17:26 +00002352
2353 // Clear bits that are not part of the constant.
Chris Lattner77defba2006-02-07 07:00:41 +00002354 AndRHSV &= AndRHS->getType()->getIntegralTypeMask();
Chris Lattnerba1cb382003-09-19 17:17:26 +00002355
2356 // If there is only one bit set...
Chris Lattner35167c32004-06-09 07:59:58 +00002357 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00002358 // Ok, at this point, we know that we are masking the result of the
2359 // ADD down to exactly one bit. If the constant we are adding has
2360 // no bits set below this bit, then we can eliminate the ADD.
Chris Lattner35167c32004-06-09 07:59:58 +00002361 uint64_t AddRHS = cast<ConstantInt>(OpRHS)->getRawValue();
Misha Brukmanb1c93172005-04-21 23:48:37 +00002362
Chris Lattnerba1cb382003-09-19 17:17:26 +00002363 // Check to see if any bits below the one bit set in AndRHSV are set.
2364 if ((AddRHS & (AndRHSV-1)) == 0) {
2365 // If not, the only thing that can effect the output of the AND is
2366 // the bit specified by AndRHSV. If that bit is set, the effect of
2367 // the XOR is to toggle the bit. If it is clear, then the ADD has
2368 // no effect.
2369 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
2370 TheAnd.setOperand(0, X);
2371 return &TheAnd;
2372 } else {
2373 std::string Name = Op->getName(); Op->setName("");
2374 // Pull the XOR out of the AND.
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002375 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS, Name);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002376 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002377 return BinaryOperator::createXor(NewAnd, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002378 }
2379 }
2380 }
2381 }
2382 break;
Chris Lattner2da29172003-09-19 19:05:02 +00002383
2384 case Instruction::Shl: {
2385 // We know that the AND will not produce any of the bits shifted in, so if
2386 // the anded constant includes them, clear them now!
2387 //
2388 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner7e794272004-09-24 15:21:34 +00002389 Constant *ShlMask = ConstantExpr::getShl(AllOne, OpRHS);
2390 Constant *CI = ConstantExpr::getAnd(AndRHS, ShlMask);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002391
Chris Lattner7e794272004-09-24 15:21:34 +00002392 if (CI == ShlMask) { // Masking out bits that the shift already masks
2393 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
2394 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner2da29172003-09-19 19:05:02 +00002395 TheAnd.setOperand(1, CI);
2396 return &TheAnd;
2397 }
2398 break;
Misha Brukmanb1c93172005-04-21 23:48:37 +00002399 }
Chris Lattner2da29172003-09-19 19:05:02 +00002400 case Instruction::Shr:
2401 // We know that the AND will not produce any of the bits shifted in, so if
2402 // the anded constant includes them, clear them now! This only applies to
2403 // unsigned shifts, because a signed shr may bring in set bits!
2404 //
2405 if (AndRHS->getType()->isUnsigned()) {
2406 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner7e794272004-09-24 15:21:34 +00002407 Constant *ShrMask = ConstantExpr::getShr(AllOne, OpRHS);
2408 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
2409
2410 if (CI == ShrMask) { // Masking out bits that the shift already masks.
2411 return ReplaceInstUsesWith(TheAnd, Op);
2412 } else if (CI != AndRHS) {
2413 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
Chris Lattner2da29172003-09-19 19:05:02 +00002414 return &TheAnd;
2415 }
Chris Lattner7e794272004-09-24 15:21:34 +00002416 } else { // Signed shr.
2417 // See if this is shifting in some sign extension, then masking it out
2418 // with an and.
2419 if (Op->hasOneUse()) {
2420 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
2421 Constant *ShrMask = ConstantExpr::getUShr(AllOne, OpRHS);
2422 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
Chris Lattner5c3c21e2004-10-22 04:53:16 +00002423 if (CI == AndRHS) { // Masking out bits shifted in.
Chris Lattner7e794272004-09-24 15:21:34 +00002424 // Make the argument unsigned.
2425 Value *ShVal = Op->getOperand(0);
2426 ShVal = InsertCastBefore(ShVal,
2427 ShVal->getType()->getUnsignedVersion(),
2428 TheAnd);
2429 ShVal = InsertNewInstBefore(new ShiftInst(Instruction::Shr, ShVal,
2430 OpRHS, Op->getName()),
2431 TheAnd);
Chris Lattner70c20392004-10-27 05:57:15 +00002432 Value *AndRHS2 = ConstantExpr::getCast(AndRHS, ShVal->getType());
2433 ShVal = InsertNewInstBefore(BinaryOperator::createAnd(ShVal, AndRHS2,
2434 TheAnd.getName()),
2435 TheAnd);
Chris Lattner7e794272004-09-24 15:21:34 +00002436 return new CastInst(ShVal, Op->getType());
2437 }
2438 }
Chris Lattner2da29172003-09-19 19:05:02 +00002439 }
2440 break;
Chris Lattnerba1cb382003-09-19 17:17:26 +00002441 }
2442 return 0;
2443}
2444
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002445
Chris Lattner6862fbd2004-09-29 17:40:11 +00002446/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
2447/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
2448/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. IB is the location to
2449/// insert new instructions.
2450Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
2451 bool Inside, Instruction &IB) {
2452 assert(cast<ConstantBool>(ConstantExpr::getSetLE(Lo, Hi))->getValue() &&
2453 "Lo is not <= Hi in range emission code!");
2454 if (Inside) {
2455 if (Lo == Hi) // Trivially false.
2456 return new SetCondInst(Instruction::SetNE, V, V);
2457 if (cast<ConstantIntegral>(Lo)->isMinValue())
2458 return new SetCondInst(Instruction::SetLT, V, Hi);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002459
Chris Lattner6862fbd2004-09-29 17:40:11 +00002460 Constant *AddCST = ConstantExpr::getNeg(Lo);
2461 Instruction *Add = BinaryOperator::createAdd(V, AddCST,V->getName()+".off");
2462 InsertNewInstBefore(Add, IB);
2463 // Convert to unsigned for the comparison.
2464 const Type *UnsType = Add->getType()->getUnsignedVersion();
2465 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
2466 AddCST = ConstantExpr::getAdd(AddCST, Hi);
2467 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2468 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
2469 }
2470
2471 if (Lo == Hi) // Trivially true.
2472 return new SetCondInst(Instruction::SetEQ, V, V);
2473
2474 Hi = SubOne(cast<ConstantInt>(Hi));
2475 if (cast<ConstantIntegral>(Lo)->isMinValue()) // V < 0 || V >= Hi ->'V > Hi-1'
2476 return new SetCondInst(Instruction::SetGT, V, Hi);
2477
2478 // Emit X-Lo > Hi-Lo-1
2479 Constant *AddCST = ConstantExpr::getNeg(Lo);
2480 Instruction *Add = BinaryOperator::createAdd(V, AddCST, V->getName()+".off");
2481 InsertNewInstBefore(Add, IB);
2482 // Convert to unsigned for the comparison.
2483 const Type *UnsType = Add->getType()->getUnsignedVersion();
2484 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
2485 AddCST = ConstantExpr::getAdd(AddCST, Hi);
2486 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2487 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
2488}
2489
Chris Lattnerb4b25302005-09-18 07:22:02 +00002490// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
2491// any number of 0s on either side. The 1s are allowed to wrap from LSB to
2492// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
2493// not, since all 1s are not contiguous.
2494static bool isRunOfOnes(ConstantIntegral *Val, unsigned &MB, unsigned &ME) {
2495 uint64_t V = Val->getRawValue();
2496 if (!isShiftedMask_64(V)) return false;
2497
2498 // look for the first zero bit after the run of ones
2499 MB = 64-CountLeadingZeros_64((V - 1) ^ V);
2500 // look for the first non-zero bit
2501 ME = 64-CountLeadingZeros_64(V);
2502 return true;
2503}
2504
2505
2506
2507/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
2508/// where isSub determines whether the operator is a sub. If we can fold one of
2509/// the following xforms:
Chris Lattneraf517572005-09-18 04:24:45 +00002510///
2511/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
2512/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
2513/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
2514///
2515/// return (A +/- B).
2516///
2517Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
2518 ConstantIntegral *Mask, bool isSub,
2519 Instruction &I) {
2520 Instruction *LHSI = dyn_cast<Instruction>(LHS);
2521 if (!LHSI || LHSI->getNumOperands() != 2 ||
2522 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
2523
2524 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
2525
2526 switch (LHSI->getOpcode()) {
2527 default: return 0;
2528 case Instruction::And:
Chris Lattnerb4b25302005-09-18 07:22:02 +00002529 if (ConstantExpr::getAnd(N, Mask) == Mask) {
2530 // If the AndRHS is a power of two minus one (0+1+), this is simple.
2531 if ((Mask->getRawValue() & Mask->getRawValue()+1) == 0)
2532 break;
2533
2534 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
2535 // part, we don't need any explicit masks to take them out of A. If that
2536 // is all N is, ignore it.
2537 unsigned MB, ME;
2538 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Chris Lattnerc3ebf402006-02-07 07:27:52 +00002539 uint64_t Mask = RHS->getType()->getIntegralTypeMask();
2540 Mask >>= 64-MB+1;
2541 if (MaskedValueIsZero(RHS, Mask))
Chris Lattnerb4b25302005-09-18 07:22:02 +00002542 break;
2543 }
2544 }
Chris Lattneraf517572005-09-18 04:24:45 +00002545 return 0;
2546 case Instruction::Or:
2547 case Instruction::Xor:
Chris Lattnerb4b25302005-09-18 07:22:02 +00002548 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
2549 if ((Mask->getRawValue() & Mask->getRawValue()+1) == 0 &&
2550 ConstantExpr::getAnd(N, Mask)->isNullValue())
Chris Lattneraf517572005-09-18 04:24:45 +00002551 break;
2552 return 0;
2553 }
2554
2555 Instruction *New;
2556 if (isSub)
2557 New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
2558 else
2559 New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
2560 return InsertNewInstBefore(New, I);
2561}
2562
Chris Lattner113f4f42002-06-25 16:13:24 +00002563Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00002564 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00002565 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002566
Chris Lattner81a7a232004-10-16 18:11:37 +00002567 if (isa<UndefValue>(Op1)) // X & undef -> 0
2568 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2569
Chris Lattner86102b82005-01-01 16:22:27 +00002570 // and X, X = X
2571 if (Op0 == Op1)
Chris Lattnere6794492002-08-12 21:17:25 +00002572 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002573
Chris Lattner5b2edb12006-02-12 08:02:11 +00002574 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner5997cf92006-02-08 03:25:32 +00002575 // purpose is to compute bits we don't care about.
Chris Lattner0157e7f2006-02-11 09:31:47 +00002576 uint64_t KnownZero, KnownOne;
Chris Lattnerd70d9f52006-03-25 21:58:26 +00002577 if (!isa<PackedType>(I.getType()) &&
2578 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
Chris Lattner0157e7f2006-02-11 09:31:47 +00002579 KnownZero, KnownOne))
Chris Lattner5997cf92006-02-08 03:25:32 +00002580 return &I;
2581
Chris Lattner86102b82005-01-01 16:22:27 +00002582 if (ConstantIntegral *AndRHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00002583 uint64_t AndRHSMask = AndRHS->getZExtValue();
2584 uint64_t TypeMask = Op0->getType()->getIntegralTypeMask();
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00002585 uint64_t NotAndRHS = AndRHSMask^TypeMask;
Chris Lattner86102b82005-01-01 16:22:27 +00002586
Chris Lattnerba1cb382003-09-19 17:17:26 +00002587 // Optimize a variety of ((val OP C1) & C2) combinations...
2588 if (isa<BinaryOperator>(Op0) || isa<ShiftInst>(Op0)) {
2589 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner86102b82005-01-01 16:22:27 +00002590 Value *Op0LHS = Op0I->getOperand(0);
2591 Value *Op0RHS = Op0I->getOperand(1);
2592 switch (Op0I->getOpcode()) {
2593 case Instruction::Xor:
2594 case Instruction::Or:
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00002595 // If the mask is only needed on one incoming arm, push it up.
2596 if (Op0I->hasOneUse()) {
2597 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
2598 // Not masking anything out for the LHS, move to RHS.
2599 Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
2600 Op0RHS->getName()+".masked");
2601 InsertNewInstBefore(NewRHS, I);
2602 return BinaryOperator::create(
2603 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002604 }
Chris Lattnerc3ebf402006-02-07 07:27:52 +00002605 if (!isa<Constant>(Op0RHS) &&
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00002606 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
2607 // Not masking anything out for the RHS, move to LHS.
2608 Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
2609 Op0LHS->getName()+".masked");
2610 InsertNewInstBefore(NewLHS, I);
2611 return BinaryOperator::create(
2612 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
2613 }
2614 }
2615
Chris Lattner86102b82005-01-01 16:22:27 +00002616 break;
Chris Lattneraf517572005-09-18 04:24:45 +00002617 case Instruction::Add:
Chris Lattnerb4b25302005-09-18 07:22:02 +00002618 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
2619 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
2620 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
2621 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
2622 return BinaryOperator::createAnd(V, AndRHS);
2623 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
2624 return BinaryOperator::createAnd(V, AndRHS); // Add commutes
Chris Lattneraf517572005-09-18 04:24:45 +00002625 break;
2626
2627 case Instruction::Sub:
Chris Lattnerb4b25302005-09-18 07:22:02 +00002628 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
2629 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
2630 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
2631 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
2632 return BinaryOperator::createAnd(V, AndRHS);
Chris Lattneraf517572005-09-18 04:24:45 +00002633 break;
Chris Lattner86102b82005-01-01 16:22:27 +00002634 }
2635
Chris Lattner16464b32003-07-23 19:25:52 +00002636 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner86102b82005-01-01 16:22:27 +00002637 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerba1cb382003-09-19 17:17:26 +00002638 return Res;
Chris Lattner86102b82005-01-01 16:22:27 +00002639 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
2640 const Type *SrcTy = CI->getOperand(0)->getType();
2641
Chris Lattner2c14cf72005-08-07 07:03:10 +00002642 // If this is an integer truncation or change from signed-to-unsigned, and
2643 // if the source is an and/or with immediate, transform it. This
2644 // frequently occurs for bitfield accesses.
2645 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
2646 if (SrcTy->getPrimitiveSizeInBits() >=
2647 I.getType()->getPrimitiveSizeInBits() &&
2648 CastOp->getNumOperands() == 2)
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00002649 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1)))
Chris Lattner2c14cf72005-08-07 07:03:10 +00002650 if (CastOp->getOpcode() == Instruction::And) {
2651 // Change: and (cast (and X, C1) to T), C2
2652 // into : and (cast X to T), trunc(C1)&C2
2653 // This will folds the two ands together, which may allow other
2654 // simplifications.
2655 Instruction *NewCast =
2656 new CastInst(CastOp->getOperand(0), I.getType(),
2657 CastOp->getName()+".shrunk");
2658 NewCast = InsertNewInstBefore(NewCast, I);
2659
2660 Constant *C3=ConstantExpr::getCast(AndCI, I.getType());//trunc(C1)
2661 C3 = ConstantExpr::getAnd(C3, AndRHS); // trunc(C1)&C2
2662 return BinaryOperator::createAnd(NewCast, C3);
2663 } else if (CastOp->getOpcode() == Instruction::Or) {
2664 // Change: and (cast (or X, C1) to T), C2
2665 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
2666 Constant *C3=ConstantExpr::getCast(AndCI, I.getType());//trunc(C1)
2667 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
2668 return ReplaceInstUsesWith(I, AndRHS);
2669 }
2670 }
Chris Lattner33217db2003-07-23 19:36:21 +00002671 }
Chris Lattner183b3362004-04-09 19:05:30 +00002672
2673 // Try to fold constant and into select arguments.
2674 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00002675 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00002676 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002677 if (isa<PHINode>(Op0))
2678 if (Instruction *NV = FoldOpIntoPhi(I))
2679 return NV;
Chris Lattner49b47ae2003-07-23 17:57:01 +00002680 }
2681
Chris Lattnerbb74e222003-03-10 23:06:50 +00002682 Value *Op0NotVal = dyn_castNotVal(Op0);
2683 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002684
Chris Lattner023a4832004-06-18 06:07:51 +00002685 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
2686 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2687
Misha Brukman9c003d82004-07-30 12:50:08 +00002688 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattnerbb74e222003-03-10 23:06:50 +00002689 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002690 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
2691 I.getName()+".demorgan");
Chris Lattner49b47ae2003-07-23 17:57:01 +00002692 InsertNewInstBefore(Or, I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002693 return BinaryOperator::createNot(Or);
2694 }
Chris Lattner8b10ab32006-02-13 23:07:23 +00002695
2696 {
2697 Value *A = 0, *B = 0;
2698 ConstantInt *C1 = 0, *C2 = 0;
2699 if (match(Op0, m_Or(m_Value(A), m_Value(B))))
2700 if (A == Op1 || B == Op1) // (A | ?) & A --> A
2701 return ReplaceInstUsesWith(I, Op1);
2702 if (match(Op1, m_Or(m_Value(A), m_Value(B))))
2703 if (A == Op0 || B == Op0) // A & (A | ?) --> A
2704 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerdcd07922006-04-01 08:03:55 +00002705
2706 if (Op0->hasOneUse() &&
2707 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
2708 if (A == Op1) { // (A^B)&A -> A&(A^B)
2709 I.swapOperands(); // Simplify below
2710 std::swap(Op0, Op1);
2711 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
2712 cast<BinaryOperator>(Op0)->swapOperands();
2713 I.swapOperands(); // Simplify below
2714 std::swap(Op0, Op1);
2715 }
2716 }
2717 if (Op1->hasOneUse() &&
2718 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
2719 if (B == Op0) { // B&(A^B) -> B&(B^A)
2720 cast<BinaryOperator>(Op1)->swapOperands();
2721 std::swap(A, B);
2722 }
2723 if (A == Op0) { // A&(A^B) -> A & ~B
2724 Instruction *NotB = BinaryOperator::createNot(B, "tmp");
2725 InsertNewInstBefore(NotB, I);
2726 return BinaryOperator::createAnd(A, NotB);
2727 }
2728 }
Chris Lattner8b10ab32006-02-13 23:07:23 +00002729 }
2730
Chris Lattner3082c5a2003-02-18 19:28:33 +00002731
Chris Lattner623826c2004-09-28 21:48:02 +00002732 if (SetCondInst *RHS = dyn_cast<SetCondInst>(Op1)) {
2733 // (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
Chris Lattner3ac7c262003-08-13 20:16:26 +00002734 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
2735 return R;
2736
Chris Lattner623826c2004-09-28 21:48:02 +00002737 Value *LHSVal, *RHSVal;
2738 ConstantInt *LHSCst, *RHSCst;
2739 Instruction::BinaryOps LHSCC, RHSCC;
2740 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
2741 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
2742 if (LHSVal == RHSVal && // Found (X setcc C1) & (X setcc C2)
2743 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
Misha Brukmanb1c93172005-04-21 23:48:37 +00002744 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
Chris Lattner623826c2004-09-28 21:48:02 +00002745 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
2746 // Ensure that the larger constant is on the RHS.
2747 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
2748 SetCondInst *LHS = cast<SetCondInst>(Op0);
2749 if (cast<ConstantBool>(Cmp)->getValue()) {
2750 std::swap(LHS, RHS);
2751 std::swap(LHSCst, RHSCst);
2752 std::swap(LHSCC, RHSCC);
2753 }
2754
2755 // At this point, we know we have have two setcc instructions
2756 // comparing a value against two constants and and'ing the result
2757 // together. Because of the above check, we know that we only have
2758 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
2759 // FoldSetCCLogical check above), that the two constants are not
2760 // equal.
2761 assert(LHSCst != RHSCst && "Compares not folded above?");
2762
2763 switch (LHSCC) {
2764 default: assert(0 && "Unknown integer condition code!");
2765 case Instruction::SetEQ:
2766 switch (RHSCC) {
2767 default: assert(0 && "Unknown integer condition code!");
2768 case Instruction::SetEQ: // (X == 13 & X == 15) -> false
2769 case Instruction::SetGT: // (X == 13 & X > 15) -> false
2770 return ReplaceInstUsesWith(I, ConstantBool::False);
2771 case Instruction::SetNE: // (X == 13 & X != 15) -> X == 13
2772 case Instruction::SetLT: // (X == 13 & X < 15) -> X == 13
2773 return ReplaceInstUsesWith(I, LHS);
2774 }
2775 case Instruction::SetNE:
2776 switch (RHSCC) {
2777 default: assert(0 && "Unknown integer condition code!");
2778 case Instruction::SetLT:
2779 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X < 14) -> X < 13
2780 return new SetCondInst(Instruction::SetLT, LHSVal, LHSCst);
2781 break; // (X != 13 & X < 15) -> no change
2782 case Instruction::SetEQ: // (X != 13 & X == 15) -> X == 15
2783 case Instruction::SetGT: // (X != 13 & X > 15) -> X > 15
2784 return ReplaceInstUsesWith(I, RHS);
2785 case Instruction::SetNE:
2786 if (LHSCst == SubOne(RHSCst)) {// (X != 13 & X != 14) -> X-13 >u 1
2787 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
2788 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
2789 LHSVal->getName()+".off");
2790 InsertNewInstBefore(Add, I);
2791 const Type *UnsType = Add->getType()->getUnsignedVersion();
2792 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
2793 AddCST = ConstantExpr::getSub(RHSCst, LHSCst);
2794 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2795 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
2796 }
2797 break; // (X != 13 & X != 15) -> no change
2798 }
2799 break;
2800 case Instruction::SetLT:
2801 switch (RHSCC) {
2802 default: assert(0 && "Unknown integer condition code!");
2803 case Instruction::SetEQ: // (X < 13 & X == 15) -> false
2804 case Instruction::SetGT: // (X < 13 & X > 15) -> false
2805 return ReplaceInstUsesWith(I, ConstantBool::False);
2806 case Instruction::SetNE: // (X < 13 & X != 15) -> X < 13
2807 case Instruction::SetLT: // (X < 13 & X < 15) -> X < 13
2808 return ReplaceInstUsesWith(I, LHS);
2809 }
2810 case Instruction::SetGT:
2811 switch (RHSCC) {
2812 default: assert(0 && "Unknown integer condition code!");
2813 case Instruction::SetEQ: // (X > 13 & X == 15) -> X > 13
2814 return ReplaceInstUsesWith(I, LHS);
2815 case Instruction::SetGT: // (X > 13 & X > 15) -> X > 15
2816 return ReplaceInstUsesWith(I, RHS);
2817 case Instruction::SetNE:
2818 if (RHSCst == AddOne(LHSCst)) // (X > 13 & X != 14) -> X > 14
2819 return new SetCondInst(Instruction::SetGT, LHSVal, RHSCst);
2820 break; // (X > 13 & X != 15) -> no change
Chris Lattner6862fbd2004-09-29 17:40:11 +00002821 case Instruction::SetLT: // (X > 13 & X < 15) -> (X-14) <u 1
2822 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true, I);
Chris Lattner623826c2004-09-28 21:48:02 +00002823 }
2824 }
2825 }
2826 }
2827
Chris Lattner3af10532006-05-05 06:39:07 +00002828 // fold (and (cast A), (cast B)) -> (cast (and A, B))
2829 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattnere745c7d2006-05-05 20:51:30 +00002830 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner3af10532006-05-05 06:39:07 +00002831 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Chris Lattnere745c7d2006-05-05 20:51:30 +00002832 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegral() &&
Chris Lattner1d441ad2006-05-06 09:00:16 +00002833 // Only do this if the casts both really cause code to be generated.
2834 ValueRequiresCast(Op0C->getOperand(0), I.getType(), TD) &&
2835 ValueRequiresCast(Op1C->getOperand(0), I.getType(), TD)) {
Chris Lattner3af10532006-05-05 06:39:07 +00002836 Instruction *NewOp = BinaryOperator::createAnd(Op0C->getOperand(0),
2837 Op1C->getOperand(0),
2838 I.getName());
2839 InsertNewInstBefore(NewOp, I);
2840 return new CastInst(NewOp, I.getType());
2841 }
2842 }
2843
Chris Lattner113f4f42002-06-25 16:13:24 +00002844 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002845}
2846
Chris Lattnerc482a9e2006-06-15 19:07:26 +00002847/// CollectBSwapParts - Look to see if the specified value defines a single byte
2848/// in the result. If it does, and if the specified byte hasn't been filled in
2849/// yet, fill it in and return false.
2850static bool CollectBSwapParts(Value *V, std::vector<Value*> &ByteValues) {
2851 Instruction *I = dyn_cast<Instruction>(V);
2852 if (I == 0) return true;
2853
2854 // If this is an or instruction, it is an inner node of the bswap.
2855 if (I->getOpcode() == Instruction::Or)
2856 return CollectBSwapParts(I->getOperand(0), ByteValues) ||
2857 CollectBSwapParts(I->getOperand(1), ByteValues);
2858
2859 // If this is a shift by a constant int, and it is "24", then its operand
2860 // defines a byte. We only handle unsigned types here.
2861 if (isa<ShiftInst>(I) && isa<ConstantInt>(I->getOperand(1))) {
2862 // Not shifting the entire input by N-1 bytes?
2863 if (cast<ConstantInt>(I->getOperand(1))->getRawValue() !=
2864 8*(ByteValues.size()-1))
2865 return true;
2866
2867 unsigned DestNo;
2868 if (I->getOpcode() == Instruction::Shl) {
2869 // X << 24 defines the top byte with the lowest of the input bytes.
2870 DestNo = ByteValues.size()-1;
2871 } else {
2872 // X >>u 24 defines the low byte with the highest of the input bytes.
2873 DestNo = 0;
2874 }
2875
2876 // If the destination byte value is already defined, the values are or'd
2877 // together, which isn't a bswap (unless it's an or of the same bits).
2878 if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
2879 return true;
2880 ByteValues[DestNo] = I->getOperand(0);
2881 return false;
2882 }
2883
2884 // Otherwise, we can only handle and(shift X, imm), imm). Bail out of if we
2885 // don't have this.
2886 Value *Shift = 0, *ShiftLHS = 0;
2887 ConstantInt *AndAmt = 0, *ShiftAmt = 0;
2888 if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
2889 !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
2890 return true;
2891 Instruction *SI = cast<Instruction>(Shift);
2892
2893 // Make sure that the shift amount is by a multiple of 8 and isn't too big.
2894 if (ShiftAmt->getRawValue() & 7 ||
2895 ShiftAmt->getRawValue() > 8*ByteValues.size())
2896 return true;
2897
2898 // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
2899 unsigned DestByte;
2900 for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
2901 if (AndAmt->getRawValue() == uint64_t(0xFF) << 8*DestByte)
2902 break;
2903 // Unknown mask for bswap.
2904 if (DestByte == ByteValues.size()) return true;
2905
2906 unsigned ShiftBytes = ShiftAmt->getRawValue()/8;
2907 unsigned SrcByte;
2908 if (SI->getOpcode() == Instruction::Shl)
2909 SrcByte = DestByte - ShiftBytes;
2910 else
2911 SrcByte = DestByte + ShiftBytes;
2912
2913 // If the SrcByte isn't a bswapped value from the DestByte, reject it.
2914 if (SrcByte != ByteValues.size()-DestByte-1)
2915 return true;
2916
2917 // If the destination byte value is already defined, the values are or'd
2918 // together, which isn't a bswap (unless it's an or of the same bits).
2919 if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
2920 return true;
2921 ByteValues[DestByte] = SI->getOperand(0);
2922 return false;
2923}
2924
2925/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
2926/// If so, insert the new bswap intrinsic and return it.
2927Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
2928 // We can only handle bswap of unsigned integers, and cannot bswap one byte.
2929 if (!I.getType()->isUnsigned() || I.getType() == Type::UByteTy)
2930 return 0;
2931
2932 /// ByteValues - For each byte of the result, we keep track of which value
2933 /// defines each byte.
2934 std::vector<Value*> ByteValues;
2935 ByteValues.resize(I.getType()->getPrimitiveSize());
2936
2937 // Try to find all the pieces corresponding to the bswap.
2938 if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
2939 CollectBSwapParts(I.getOperand(1), ByteValues))
2940 return 0;
2941
2942 // Check to see if all of the bytes come from the same value.
2943 Value *V = ByteValues[0];
2944 if (V == 0) return 0; // Didn't find a byte? Must be zero.
2945
2946 // Check to make sure that all of the bytes come from the same value.
2947 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
2948 if (ByteValues[i] != V)
2949 return 0;
2950
2951 // If they do then *success* we can turn this into a bswap. Figure out what
2952 // bswap to make it into.
2953 Module *M = I.getParent()->getParent()->getParent();
Chris Lattner091b6ea2006-07-11 18:31:26 +00002954 const char *FnName = 0;
Chris Lattnerc482a9e2006-06-15 19:07:26 +00002955 if (I.getType() == Type::UShortTy)
2956 FnName = "llvm.bswap.i16";
2957 else if (I.getType() == Type::UIntTy)
2958 FnName = "llvm.bswap.i32";
2959 else if (I.getType() == Type::ULongTy)
2960 FnName = "llvm.bswap.i64";
2961 else
2962 assert(0 && "Unknown integer type!");
2963 Function *F = M->getOrInsertFunction(FnName, I.getType(), I.getType(), NULL);
2964
2965 return new CallInst(F, V);
2966}
2967
2968
Chris Lattner113f4f42002-06-25 16:13:24 +00002969Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00002970 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00002971 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002972
Chris Lattner81a7a232004-10-16 18:11:37 +00002973 if (isa<UndefValue>(Op1))
2974 return ReplaceInstUsesWith(I, // X | undef -> -1
2975 ConstantIntegral::getAllOnesValue(I.getType()));
2976
Chris Lattner5b2edb12006-02-12 08:02:11 +00002977 // or X, X = X
2978 if (Op0 == Op1)
Chris Lattnere6794492002-08-12 21:17:25 +00002979 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002980
Chris Lattner5b2edb12006-02-12 08:02:11 +00002981 // See if we can simplify any instructions used by the instruction whose sole
2982 // purpose is to compute bits we don't care about.
2983 uint64_t KnownZero, KnownOne;
Chris Lattnerd70d9f52006-03-25 21:58:26 +00002984 if (!isa<PackedType>(I.getType()) &&
2985 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
Chris Lattner5b2edb12006-02-12 08:02:11 +00002986 KnownZero, KnownOne))
2987 return &I;
2988
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002989 // or X, -1 == -1
Chris Lattner8f0d1562003-07-23 18:29:44 +00002990 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner330628a2006-01-06 17:59:59 +00002991 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00002992 // (X & C1) | C2 --> (X | C2) & (C1|C2)
2993 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Chris Lattnerb62f5082005-05-09 04:58:36 +00002994 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0->getName());
2995 Op0->setName("");
Chris Lattnerd4252a72004-07-30 07:50:03 +00002996 InsertNewInstBefore(Or, I);
2997 return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, C1));
2998 }
Chris Lattner8f0d1562003-07-23 18:29:44 +00002999
Chris Lattnerd4252a72004-07-30 07:50:03 +00003000 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
3001 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
3002 std::string Op0Name = Op0->getName(); Op0->setName("");
3003 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
3004 InsertNewInstBefore(Or, I);
3005 return BinaryOperator::createXor(Or,
3006 ConstantExpr::getAnd(C1, ConstantExpr::getNot(RHS)));
Chris Lattner8f0d1562003-07-23 18:29:44 +00003007 }
Chris Lattner183b3362004-04-09 19:05:30 +00003008
3009 // Try to fold constant and into select arguments.
3010 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00003011 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00003012 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00003013 if (isa<PHINode>(Op0))
3014 if (Instruction *NV = FoldOpIntoPhi(I))
3015 return NV;
Chris Lattner8f0d1562003-07-23 18:29:44 +00003016 }
3017
Chris Lattner330628a2006-01-06 17:59:59 +00003018 Value *A = 0, *B = 0;
3019 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattner4294cec2005-05-07 23:49:08 +00003020
3021 if (match(Op0, m_And(m_Value(A), m_Value(B))))
3022 if (A == Op1 || B == Op1) // (A & ?) | A --> A
3023 return ReplaceInstUsesWith(I, Op1);
3024 if (match(Op1, m_And(m_Value(A), m_Value(B))))
3025 if (A == Op0 || B == Op0) // A | (A & ?) --> A
3026 return ReplaceInstUsesWith(I, Op0);
3027
Chris Lattnerb7845d62006-07-10 20:25:24 +00003028 // (A | B) | C and A | (B | C) -> bswap if possible.
3029 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003030 if (match(Op0, m_Or(m_Value(), m_Value())) ||
Chris Lattnerb7845d62006-07-10 20:25:24 +00003031 match(Op1, m_Or(m_Value(), m_Value())) ||
3032 (match(Op0, m_Shift(m_Value(), m_Value())) &&
3033 match(Op1, m_Shift(m_Value(), m_Value())))) {
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003034 if (Instruction *BSwap = MatchBSwap(I))
3035 return BSwap;
3036 }
3037
Chris Lattnerb62f5082005-05-09 04:58:36 +00003038 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
3039 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003040 MaskedValueIsZero(Op1, C1->getZExtValue())) {
Chris Lattnerb62f5082005-05-09 04:58:36 +00003041 Instruction *NOr = BinaryOperator::createOr(A, Op1, Op0->getName());
3042 Op0->setName("");
3043 return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
3044 }
3045
3046 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
3047 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003048 MaskedValueIsZero(Op0, C1->getZExtValue())) {
Chris Lattnerb62f5082005-05-09 04:58:36 +00003049 Instruction *NOr = BinaryOperator::createOr(A, Op0, Op1->getName());
3050 Op0->setName("");
3051 return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
3052 }
3053
Chris Lattner15212982005-09-18 03:42:07 +00003054 // (A & C1)|(B & C2)
Chris Lattnerd4252a72004-07-30 07:50:03 +00003055 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattner15212982005-09-18 03:42:07 +00003056 match(Op1, m_And(m_Value(B), m_ConstantInt(C2)))) {
3057
3058 if (A == B) // (A & C1)|(A & C2) == A & (C1|C2)
3059 return BinaryOperator::createAnd(A, ConstantExpr::getOr(C1, C2));
3060
3061
Chris Lattner01f56c62005-09-18 06:02:59 +00003062 // If we have: ((V + N) & C1) | (V & C2)
3063 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
3064 // replace with V+N.
3065 if (C1 == ConstantExpr::getNot(C2)) {
Chris Lattner330628a2006-01-06 17:59:59 +00003066 Value *V1 = 0, *V2 = 0;
Chris Lattner01f56c62005-09-18 06:02:59 +00003067 if ((C2->getRawValue() & (C2->getRawValue()+1)) == 0 && // C2 == 0+1+
3068 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
3069 // Add commutes, try both ways.
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003070 if (V1 == B && MaskedValueIsZero(V2, C2->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003071 return ReplaceInstUsesWith(I, A);
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003072 if (V2 == B && MaskedValueIsZero(V1, C2->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003073 return ReplaceInstUsesWith(I, A);
3074 }
3075 // Or commutes, try both ways.
3076 if ((C1->getRawValue() & (C1->getRawValue()+1)) == 0 &&
3077 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
3078 // Add commutes, try both ways.
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003079 if (V1 == A && MaskedValueIsZero(V2, C1->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003080 return ReplaceInstUsesWith(I, B);
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003081 if (V2 == A && MaskedValueIsZero(V1, C1->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003082 return ReplaceInstUsesWith(I, B);
Chris Lattner15212982005-09-18 03:42:07 +00003083 }
3084 }
3085 }
Chris Lattner812aab72003-08-12 19:11:07 +00003086
Chris Lattnerd4252a72004-07-30 07:50:03 +00003087 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
3088 if (A == Op1) // ~A | A == -1
Misha Brukmanb1c93172005-04-21 23:48:37 +00003089 return ReplaceInstUsesWith(I,
Chris Lattnerd4252a72004-07-30 07:50:03 +00003090 ConstantIntegral::getAllOnesValue(I.getType()));
3091 } else {
3092 A = 0;
3093 }
Chris Lattner4294cec2005-05-07 23:49:08 +00003094 // Note, A is still live here!
Chris Lattnerd4252a72004-07-30 07:50:03 +00003095 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
3096 if (Op0 == B)
Misha Brukmanb1c93172005-04-21 23:48:37 +00003097 return ReplaceInstUsesWith(I,
Chris Lattnerd4252a72004-07-30 07:50:03 +00003098 ConstantIntegral::getAllOnesValue(I.getType()));
Chris Lattner3e327a42003-03-10 23:13:59 +00003099
Misha Brukman9c003d82004-07-30 12:50:08 +00003100 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattnerd4252a72004-07-30 07:50:03 +00003101 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3102 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
3103 I.getName()+".demorgan"), I);
3104 return BinaryOperator::createNot(And);
3105 }
Chris Lattner3e327a42003-03-10 23:13:59 +00003106 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00003107
Chris Lattner3ac7c262003-08-13 20:16:26 +00003108 // (setcc1 A, B) | (setcc2 A, B) --> (setcc3 A, B)
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003109 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1))) {
Chris Lattner3ac7c262003-08-13 20:16:26 +00003110 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
3111 return R;
3112
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003113 Value *LHSVal, *RHSVal;
3114 ConstantInt *LHSCst, *RHSCst;
3115 Instruction::BinaryOps LHSCC, RHSCC;
3116 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3117 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3118 if (LHSVal == RHSVal && // Found (X setcc C1) | (X setcc C2)
3119 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
Misha Brukmanb1c93172005-04-21 23:48:37 +00003120 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003121 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
3122 // Ensure that the larger constant is on the RHS.
3123 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
3124 SetCondInst *LHS = cast<SetCondInst>(Op0);
3125 if (cast<ConstantBool>(Cmp)->getValue()) {
3126 std::swap(LHS, RHS);
3127 std::swap(LHSCst, RHSCst);
3128 std::swap(LHSCC, RHSCC);
3129 }
3130
3131 // At this point, we know we have have two setcc instructions
3132 // comparing a value against two constants and or'ing the result
3133 // together. Because of the above check, we know that we only have
3134 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
3135 // FoldSetCCLogical check above), that the two constants are not
3136 // equal.
3137 assert(LHSCst != RHSCst && "Compares not folded above?");
3138
3139 switch (LHSCC) {
3140 default: assert(0 && "Unknown integer condition code!");
3141 case Instruction::SetEQ:
3142 switch (RHSCC) {
3143 default: assert(0 && "Unknown integer condition code!");
3144 case Instruction::SetEQ:
3145 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
3146 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3147 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3148 LHSVal->getName()+".off");
3149 InsertNewInstBefore(Add, I);
3150 const Type *UnsType = Add->getType()->getUnsignedVersion();
3151 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
3152 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
3153 AddCST = ConstantExpr::getCast(AddCST, UnsType);
3154 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
3155 }
3156 break; // (X == 13 | X == 15) -> no change
3157
Chris Lattner5c219462005-04-19 06:04:18 +00003158 case Instruction::SetGT: // (X == 13 | X > 14) -> no change
3159 break;
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003160 case Instruction::SetNE: // (X == 13 | X != 15) -> X != 15
3161 case Instruction::SetLT: // (X == 13 | X < 15) -> X < 15
3162 return ReplaceInstUsesWith(I, RHS);
3163 }
3164 break;
3165 case Instruction::SetNE:
3166 switch (RHSCC) {
3167 default: assert(0 && "Unknown integer condition code!");
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003168 case Instruction::SetEQ: // (X != 13 | X == 15) -> X != 13
3169 case Instruction::SetGT: // (X != 13 | X > 15) -> X != 13
3170 return ReplaceInstUsesWith(I, LHS);
3171 case Instruction::SetNE: // (X != 13 | X != 15) -> true
Chris Lattner2ceb6ee2005-06-17 03:59:17 +00003172 case Instruction::SetLT: // (X != 13 | X < 15) -> true
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003173 return ReplaceInstUsesWith(I, ConstantBool::True);
3174 }
3175 break;
3176 case Instruction::SetLT:
3177 switch (RHSCC) {
3178 default: assert(0 && "Unknown integer condition code!");
3179 case Instruction::SetEQ: // (X < 13 | X == 14) -> no change
3180 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00003181 case Instruction::SetGT: // (X < 13 | X > 15) -> (X-13) > 2
3182 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false, I);
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003183 case Instruction::SetNE: // (X < 13 | X != 15) -> X != 15
3184 case Instruction::SetLT: // (X < 13 | X < 15) -> X < 15
3185 return ReplaceInstUsesWith(I, RHS);
3186 }
3187 break;
3188 case Instruction::SetGT:
3189 switch (RHSCC) {
3190 default: assert(0 && "Unknown integer condition code!");
3191 case Instruction::SetEQ: // (X > 13 | X == 15) -> X > 13
3192 case Instruction::SetGT: // (X > 13 | X > 15) -> X > 13
3193 return ReplaceInstUsesWith(I, LHS);
3194 case Instruction::SetNE: // (X > 13 | X != 15) -> true
3195 case Instruction::SetLT: // (X > 13 | X < 15) -> true
3196 return ReplaceInstUsesWith(I, ConstantBool::True);
3197 }
3198 }
3199 }
3200 }
Chris Lattner3af10532006-05-05 06:39:07 +00003201
3202 // fold (or (cast A), (cast B)) -> (cast (or A, B))
3203 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattnere745c7d2006-05-05 20:51:30 +00003204 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner3af10532006-05-05 06:39:07 +00003205 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Chris Lattnere745c7d2006-05-05 20:51:30 +00003206 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegral() &&
Chris Lattner1d441ad2006-05-06 09:00:16 +00003207 // Only do this if the casts both really cause code to be generated.
3208 ValueRequiresCast(Op0C->getOperand(0), I.getType(), TD) &&
3209 ValueRequiresCast(Op1C->getOperand(0), I.getType(), TD)) {
Chris Lattner3af10532006-05-05 06:39:07 +00003210 Instruction *NewOp = BinaryOperator::createOr(Op0C->getOperand(0),
3211 Op1C->getOperand(0),
3212 I.getName());
3213 InsertNewInstBefore(NewOp, I);
3214 return new CastInst(NewOp, I.getType());
3215 }
3216 }
3217
Chris Lattner15212982005-09-18 03:42:07 +00003218
Chris Lattner113f4f42002-06-25 16:13:24 +00003219 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003220}
3221
Chris Lattnerc2076352004-02-16 01:20:27 +00003222// XorSelf - Implements: X ^ X --> 0
3223struct XorSelf {
3224 Value *RHS;
3225 XorSelf(Value *rhs) : RHS(rhs) {}
3226 bool shouldApply(Value *LHS) const { return LHS == RHS; }
3227 Instruction *apply(BinaryOperator &Xor) const {
3228 return &Xor;
3229 }
3230};
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003231
3232
Chris Lattner113f4f42002-06-25 16:13:24 +00003233Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003234 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00003235 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003236
Chris Lattner81a7a232004-10-16 18:11:37 +00003237 if (isa<UndefValue>(Op1))
3238 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
3239
Chris Lattnerc2076352004-02-16 01:20:27 +00003240 // xor X, X = 0, even if X is nested in a sequence of Xor's.
3241 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
3242 assert(Result == &I && "AssociativeOpt didn't work?");
Chris Lattnere6794492002-08-12 21:17:25 +00003243 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc2076352004-02-16 01:20:27 +00003244 }
Chris Lattner5b2edb12006-02-12 08:02:11 +00003245
3246 // See if we can simplify any instructions used by the instruction whose sole
3247 // purpose is to compute bits we don't care about.
3248 uint64_t KnownZero, KnownOne;
Chris Lattnerd70d9f52006-03-25 21:58:26 +00003249 if (!isa<PackedType>(I.getType()) &&
3250 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
Chris Lattner5b2edb12006-02-12 08:02:11 +00003251 KnownZero, KnownOne))
3252 return &I;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003253
Chris Lattner97638592003-07-23 21:37:07 +00003254 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner97638592003-07-23 21:37:07 +00003255 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerb8d6e402002-08-20 18:24:26 +00003256 // xor (setcc A, B), true = not (setcc A, B) = setncc A, B
Chris Lattner97638592003-07-23 21:37:07 +00003257 if (SetCondInst *SCI = dyn_cast<SetCondInst>(Op0I))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00003258 if (RHS == ConstantBool::True && SCI->hasOneUse())
Chris Lattnerb8d6e402002-08-20 18:24:26 +00003259 return new SetCondInst(SCI->getInverseCondition(),
3260 SCI->getOperand(0), SCI->getOperand(1));
Chris Lattnere5806662003-11-04 23:50:51 +00003261
Chris Lattner8f2f5982003-11-05 01:06:05 +00003262 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003263 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
3264 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003265 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
3266 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003267 ConstantInt::get(I.getType(), 1));
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003268 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003269 }
Chris Lattner023a4832004-06-18 06:07:51 +00003270
3271 // ~(~X & Y) --> (X | ~Y)
3272 if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
3273 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
3274 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
3275 Instruction *NotY =
Misha Brukmanb1c93172005-04-21 23:48:37 +00003276 BinaryOperator::createNot(Op0I->getOperand(1),
Chris Lattner023a4832004-06-18 06:07:51 +00003277 Op0I->getOperand(1)->getName()+".not");
3278 InsertNewInstBefore(NotY, I);
3279 return BinaryOperator::createOr(Op0NotVal, NotY);
3280 }
3281 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003282
Chris Lattner97638592003-07-23 21:37:07 +00003283 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner5b2edb12006-02-12 08:02:11 +00003284 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner0f68fa62003-11-04 23:37:10 +00003285 // ~(X-c) --> (-c-1)-X
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003286 if (RHS->isAllOnesValue()) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003287 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
3288 return BinaryOperator::createSub(
3289 ConstantExpr::getSub(NegOp0CI,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003290 ConstantInt::get(I.getType(), 1)),
Chris Lattner0f68fa62003-11-04 23:37:10 +00003291 Op0I->getOperand(0));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003292 }
Chris Lattnerf78df7c2006-02-26 19:57:54 +00003293 } else if (Op0I->getOpcode() == Instruction::Or) {
3294 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
3295 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getZExtValue())) {
3296 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
3297 // Anything in both C1 and C2 is known to be zero, remove it from
3298 // NewRHS.
3299 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
3300 NewRHS = ConstantExpr::getAnd(NewRHS,
3301 ConstantExpr::getNot(CommonBits));
3302 WorkList.push_back(Op0I);
3303 I.setOperand(0, Op0I->getOperand(0));
3304 I.setOperand(1, NewRHS);
3305 return &I;
3306 }
Chris Lattner97638592003-07-23 21:37:07 +00003307 }
Chris Lattnerb8d6e402002-08-20 18:24:26 +00003308 }
Chris Lattner183b3362004-04-09 19:05:30 +00003309
3310 // Try to fold constant and into select arguments.
3311 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00003312 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00003313 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00003314 if (isa<PHINode>(Op0))
3315 if (Instruction *NV = FoldOpIntoPhi(I))
3316 return NV;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003317 }
3318
Chris Lattnerbb74e222003-03-10 23:06:50 +00003319 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00003320 if (X == Op1)
3321 return ReplaceInstUsesWith(I,
3322 ConstantIntegral::getAllOnesValue(I.getType()));
3323
Chris Lattnerbb74e222003-03-10 23:06:50 +00003324 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00003325 if (X == Op0)
3326 return ReplaceInstUsesWith(I,
3327 ConstantIntegral::getAllOnesValue(I.getType()));
3328
Chris Lattnerdcd07922006-04-01 08:03:55 +00003329 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1))
Chris Lattnerb36d9082004-02-16 03:54:20 +00003330 if (Op1I->getOpcode() == Instruction::Or) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003331 if (Op1I->getOperand(0) == Op0) { // B^(B|A) == (A|B)^B
Chris Lattnerdcd07922006-04-01 08:03:55 +00003332 Op1I->swapOperands();
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003333 I.swapOperands();
3334 std::swap(Op0, Op1);
3335 } else if (Op1I->getOperand(1) == Op0) { // B^(A|B) == (A|B)^B
Chris Lattnerdcd07922006-04-01 08:03:55 +00003336 I.swapOperands(); // Simplified below.
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003337 std::swap(Op0, Op1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003338 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00003339 } else if (Op1I->getOpcode() == Instruction::Xor) {
3340 if (Op0 == Op1I->getOperand(0)) // A^(A^B) == B
3341 return ReplaceInstUsesWith(I, Op1I->getOperand(1));
3342 else if (Op0 == Op1I->getOperand(1)) // A^(B^A) == B
3343 return ReplaceInstUsesWith(I, Op1I->getOperand(0));
Chris Lattnerdcd07922006-04-01 08:03:55 +00003344 } else if (Op1I->getOpcode() == Instruction::And && Op1I->hasOneUse()) {
3345 if (Op1I->getOperand(0) == Op0) // A^(A&B) -> A^(B&A)
3346 Op1I->swapOperands();
3347 if (Op0 == Op1I->getOperand(1)) { // A^(B&A) -> (B&A)^A
3348 I.swapOperands(); // Simplified below.
3349 std::swap(Op0, Op1);
3350 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00003351 }
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003352
Chris Lattnerdcd07922006-04-01 08:03:55 +00003353 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00003354 if (Op0I->getOpcode() == Instruction::Or && Op0I->hasOneUse()) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003355 if (Op0I->getOperand(0) == Op1) // (B|A)^B == (A|B)^B
Chris Lattnerdcd07922006-04-01 08:03:55 +00003356 Op0I->swapOperands();
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003357 if (Op0I->getOperand(1) == Op1) { // (A|B)^B == A & ~B
Chris Lattnerdcd07922006-04-01 08:03:55 +00003358 Instruction *NotB = BinaryOperator::createNot(Op1, "tmp");
3359 InsertNewInstBefore(NotB, I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003360 return BinaryOperator::createAnd(Op0I->getOperand(0), NotB);
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003361 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00003362 } else if (Op0I->getOpcode() == Instruction::Xor) {
3363 if (Op1 == Op0I->getOperand(0)) // (A^B)^A == B
3364 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
3365 else if (Op1 == Op0I->getOperand(1)) // (B^A)^A == B
3366 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattnerdcd07922006-04-01 08:03:55 +00003367 } else if (Op0I->getOpcode() == Instruction::And && Op0I->hasOneUse()) {
3368 if (Op0I->getOperand(0) == Op1) // (A&B)^A -> (B&A)^A
3369 Op0I->swapOperands();
Chris Lattner6cf49142006-04-01 22:05:01 +00003370 if (Op0I->getOperand(1) == Op1 && // (B&A)^A == ~B & A
3371 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattnerdcd07922006-04-01 08:03:55 +00003372 Instruction *N = BinaryOperator::createNot(Op0I->getOperand(0), "tmp");
3373 InsertNewInstBefore(N, I);
3374 return BinaryOperator::createAnd(N, Op1);
3375 }
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003376 }
3377
Chris Lattner3ac7c262003-08-13 20:16:26 +00003378 // (setcc1 A, B) ^ (setcc2 A, B) --> (setcc3 A, B)
3379 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
3380 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
3381 return R;
3382
Chris Lattner3af10532006-05-05 06:39:07 +00003383 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
3384 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattnere745c7d2006-05-05 20:51:30 +00003385 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner3af10532006-05-05 06:39:07 +00003386 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Chris Lattnere745c7d2006-05-05 20:51:30 +00003387 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegral() &&
Chris Lattner1d441ad2006-05-06 09:00:16 +00003388 // Only do this if the casts both really cause code to be generated.
3389 ValueRequiresCast(Op0C->getOperand(0), I.getType(), TD) &&
3390 ValueRequiresCast(Op1C->getOperand(0), I.getType(), TD)) {
Chris Lattner3af10532006-05-05 06:39:07 +00003391 Instruction *NewOp = BinaryOperator::createXor(Op0C->getOperand(0),
3392 Op1C->getOperand(0),
3393 I.getName());
3394 InsertNewInstBefore(NewOp, I);
3395 return new CastInst(NewOp, I.getType());
3396 }
3397 }
3398
Chris Lattner113f4f42002-06-25 16:13:24 +00003399 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003400}
3401
Chris Lattner6862fbd2004-09-29 17:40:11 +00003402/// MulWithOverflow - Compute Result = In1*In2, returning true if the result
3403/// overflowed for this type.
3404static bool MulWithOverflow(ConstantInt *&Result, ConstantInt *In1,
3405 ConstantInt *In2) {
3406 Result = cast<ConstantInt>(ConstantExpr::getMul(In1, In2));
3407 return !In2->isNullValue() && ConstantExpr::getDiv(Result, In2) != In1;
3408}
3409
3410static bool isPositive(ConstantInt *C) {
3411 return cast<ConstantSInt>(C)->getValue() >= 0;
3412}
3413
3414/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
3415/// overflowed for this type.
3416static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
3417 ConstantInt *In2) {
3418 Result = cast<ConstantInt>(ConstantExpr::getAdd(In1, In2));
3419
3420 if (In1->getType()->isUnsigned())
3421 return cast<ConstantUInt>(Result)->getValue() <
3422 cast<ConstantUInt>(In1)->getValue();
3423 if (isPositive(In1) != isPositive(In2))
3424 return false;
3425 if (isPositive(In1))
3426 return cast<ConstantSInt>(Result)->getValue() <
3427 cast<ConstantSInt>(In1)->getValue();
3428 return cast<ConstantSInt>(Result)->getValue() >
3429 cast<ConstantSInt>(In1)->getValue();
3430}
3431
Chris Lattner0798af32005-01-13 20:14:25 +00003432/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
3433/// code necessary to compute the offset from the base pointer (without adding
3434/// in the base pointer). Return the result as a signed integer of intptr size.
3435static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
3436 TargetData &TD = IC.getTargetData();
3437 gep_type_iterator GTI = gep_type_begin(GEP);
3438 const Type *UIntPtrTy = TD.getIntPtrType();
3439 const Type *SIntPtrTy = UIntPtrTy->getSignedVersion();
3440 Value *Result = Constant::getNullValue(SIntPtrTy);
3441
3442 // Build a mask for high order bits.
Chris Lattner77defba2006-02-07 07:00:41 +00003443 uint64_t PtrSizeMask = ~0ULL >> (64-TD.getPointerSize()*8);
Chris Lattner0798af32005-01-13 20:14:25 +00003444
Chris Lattner0798af32005-01-13 20:14:25 +00003445 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
3446 Value *Op = GEP->getOperand(i);
Chris Lattnerd35d2102005-01-13 23:26:48 +00003447 uint64_t Size = TD.getTypeSize(GTI.getIndexedType()) & PtrSizeMask;
Chris Lattner0798af32005-01-13 20:14:25 +00003448 Constant *Scale = ConstantExpr::getCast(ConstantUInt::get(UIntPtrTy, Size),
3449 SIntPtrTy);
3450 if (Constant *OpC = dyn_cast<Constant>(Op)) {
3451 if (!OpC->isNullValue()) {
Chris Lattner4cb9fa32005-01-13 20:40:58 +00003452 OpC = ConstantExpr::getCast(OpC, SIntPtrTy);
Chris Lattner0798af32005-01-13 20:14:25 +00003453 Scale = ConstantExpr::getMul(OpC, Scale);
3454 if (Constant *RC = dyn_cast<Constant>(Result))
3455 Result = ConstantExpr::getAdd(RC, Scale);
3456 else {
3457 // Emit an add instruction.
3458 Result = IC.InsertNewInstBefore(
3459 BinaryOperator::createAdd(Result, Scale,
3460 GEP->getName()+".offs"), I);
3461 }
3462 }
3463 } else {
Chris Lattner7aa41cf2005-01-14 17:17:59 +00003464 // Convert to correct type.
3465 Op = IC.InsertNewInstBefore(new CastInst(Op, SIntPtrTy,
3466 Op->getName()+".c"), I);
3467 if (Size != 1)
Chris Lattner4cb9fa32005-01-13 20:40:58 +00003468 // We'll let instcombine(mul) convert this to a shl if possible.
3469 Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
3470 GEP->getName()+".idx"), I);
Chris Lattner0798af32005-01-13 20:14:25 +00003471
3472 // Emit an add instruction.
Chris Lattner4cb9fa32005-01-13 20:40:58 +00003473 Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
Chris Lattner0798af32005-01-13 20:14:25 +00003474 GEP->getName()+".offs"), I);
3475 }
3476 }
3477 return Result;
3478}
3479
3480/// FoldGEPSetCC - Fold comparisons between a GEP instruction and something
3481/// else. At this point we know that the GEP is on the LHS of the comparison.
3482Instruction *InstCombiner::FoldGEPSetCC(User *GEPLHS, Value *RHS,
3483 Instruction::BinaryOps Cond,
3484 Instruction &I) {
3485 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattner81e84172005-01-13 22:25:21 +00003486
3487 if (CastInst *CI = dyn_cast<CastInst>(RHS))
3488 if (isa<PointerType>(CI->getOperand(0)->getType()))
3489 RHS = CI->getOperand(0);
3490
Chris Lattner0798af32005-01-13 20:14:25 +00003491 Value *PtrBase = GEPLHS->getOperand(0);
3492 if (PtrBase == RHS) {
3493 // As an optimization, we don't actually have to compute the actual value of
3494 // OFFSET if this is a seteq or setne comparison, just return whether each
3495 // index is zero or not.
Chris Lattner81e84172005-01-13 22:25:21 +00003496 if (Cond == Instruction::SetEQ || Cond == Instruction::SetNE) {
3497 Instruction *InVal = 0;
Chris Lattnercd517ff2005-01-28 19:32:01 +00003498 gep_type_iterator GTI = gep_type_begin(GEPLHS);
3499 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i, ++GTI) {
Chris Lattner81e84172005-01-13 22:25:21 +00003500 bool EmitIt = true;
3501 if (Constant *C = dyn_cast<Constant>(GEPLHS->getOperand(i))) {
3502 if (isa<UndefValue>(C)) // undef index -> undef.
3503 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
3504 if (C->isNullValue())
3505 EmitIt = false;
Chris Lattnercd517ff2005-01-28 19:32:01 +00003506 else if (TD->getTypeSize(GTI.getIndexedType()) == 0) {
3507 EmitIt = false; // This is indexing into a zero sized array?
Misha Brukmanb1c93172005-04-21 23:48:37 +00003508 } else if (isa<ConstantInt>(C))
Chris Lattner81e84172005-01-13 22:25:21 +00003509 return ReplaceInstUsesWith(I, // No comparison is needed here.
3510 ConstantBool::get(Cond == Instruction::SetNE));
3511 }
3512
3513 if (EmitIt) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00003514 Instruction *Comp =
Chris Lattner81e84172005-01-13 22:25:21 +00003515 new SetCondInst(Cond, GEPLHS->getOperand(i),
3516 Constant::getNullValue(GEPLHS->getOperand(i)->getType()));
3517 if (InVal == 0)
3518 InVal = Comp;
3519 else {
3520 InVal = InsertNewInstBefore(InVal, I);
3521 InsertNewInstBefore(Comp, I);
3522 if (Cond == Instruction::SetNE) // True if any are unequal
3523 InVal = BinaryOperator::createOr(InVal, Comp);
3524 else // True if all are equal
3525 InVal = BinaryOperator::createAnd(InVal, Comp);
3526 }
3527 }
3528 }
3529
3530 if (InVal)
3531 return InVal;
3532 else
3533 ReplaceInstUsesWith(I, // No comparison is needed here, all indexes = 0
3534 ConstantBool::get(Cond == Instruction::SetEQ));
3535 }
Chris Lattner0798af32005-01-13 20:14:25 +00003536
3537 // Only lower this if the setcc is the only user of the GEP or if we expect
3538 // the result to fold to a constant!
3539 if (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) {
3540 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
3541 Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
3542 return new SetCondInst(Cond, Offset,
3543 Constant::getNullValue(Offset->getType()));
3544 }
3545 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
Chris Lattnera21bf8d2005-04-25 20:17:30 +00003546 // If the base pointers are different, but the indices are the same, just
3547 // compare the base pointer.
3548 if (PtrBase != GEPRHS->getOperand(0)) {
3549 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00003550 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattnerbd43b9d2005-04-26 14:40:41 +00003551 GEPRHS->getOperand(0)->getType();
Chris Lattnera21bf8d2005-04-25 20:17:30 +00003552 if (IndicesTheSame)
3553 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
3554 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
3555 IndicesTheSame = false;
3556 break;
3557 }
3558
3559 // If all indices are the same, just compare the base pointers.
3560 if (IndicesTheSame)
3561 return new SetCondInst(Cond, GEPLHS->getOperand(0),
3562 GEPRHS->getOperand(0));
3563
3564 // Otherwise, the base pointers are different and the indices are
3565 // different, bail out.
Chris Lattner0798af32005-01-13 20:14:25 +00003566 return 0;
Chris Lattnera21bf8d2005-04-25 20:17:30 +00003567 }
Chris Lattner0798af32005-01-13 20:14:25 +00003568
Chris Lattner81e84172005-01-13 22:25:21 +00003569 // If one of the GEPs has all zero indices, recurse.
3570 bool AllZeros = true;
3571 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
3572 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
3573 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
3574 AllZeros = false;
3575 break;
3576 }
3577 if (AllZeros)
3578 return FoldGEPSetCC(GEPRHS, GEPLHS->getOperand(0),
3579 SetCondInst::getSwappedCondition(Cond), I);
Chris Lattner4fa89822005-01-14 00:20:05 +00003580
3581 // If the other GEP has all zero indices, recurse.
Chris Lattner81e84172005-01-13 22:25:21 +00003582 AllZeros = true;
3583 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
3584 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
3585 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
3586 AllZeros = false;
3587 break;
3588 }
3589 if (AllZeros)
3590 return FoldGEPSetCC(GEPLHS, GEPRHS->getOperand(0), Cond, I);
3591
Chris Lattner4fa89822005-01-14 00:20:05 +00003592 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
3593 // If the GEPs only differ by one index, compare it.
3594 unsigned NumDifferences = 0; // Keep track of # differences.
3595 unsigned DiffOperand = 0; // The operand that differs.
3596 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
3597 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003598 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
3599 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattnerfc4429e2005-01-21 23:06:49 +00003600 // Irreconcilable differences.
Chris Lattner4fa89822005-01-14 00:20:05 +00003601 NumDifferences = 2;
3602 break;
3603 } else {
3604 if (NumDifferences++) break;
3605 DiffOperand = i;
3606 }
3607 }
3608
3609 if (NumDifferences == 0) // SAME GEP?
3610 return ReplaceInstUsesWith(I, // No comparison is needed here.
3611 ConstantBool::get(Cond == Instruction::SetEQ));
3612 else if (NumDifferences == 1) {
Chris Lattnerfc4429e2005-01-21 23:06:49 +00003613 Value *LHSV = GEPLHS->getOperand(DiffOperand);
3614 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Chris Lattner247aef82005-07-18 23:07:33 +00003615
3616 // Convert the operands to signed values to make sure to perform a
3617 // signed comparison.
3618 const Type *NewTy = LHSV->getType()->getSignedVersion();
3619 if (LHSV->getType() != NewTy)
3620 LHSV = InsertNewInstBefore(new CastInst(LHSV, NewTy,
3621 LHSV->getName()), I);
3622 if (RHSV->getType() != NewTy)
3623 RHSV = InsertNewInstBefore(new CastInst(RHSV, NewTy,
3624 RHSV->getName()), I);
3625 return new SetCondInst(Cond, LHSV, RHSV);
Chris Lattner4fa89822005-01-14 00:20:05 +00003626 }
3627 }
3628
Chris Lattner0798af32005-01-13 20:14:25 +00003629 // Only lower this if the setcc is the only user of the GEP or if we expect
3630 // the result to fold to a constant!
3631 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
3632 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
3633 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
3634 Value *L = EmitGEPOffset(GEPLHS, I, *this);
3635 Value *R = EmitGEPOffset(GEPRHS, I, *this);
3636 return new SetCondInst(Cond, L, R);
3637 }
3638 }
3639 return 0;
3640}
3641
3642
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003643Instruction *InstCombiner::visitSetCondInst(SetCondInst &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003644 bool Changed = SimplifyCommutative(I);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003645 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3646 const Type *Ty = Op0->getType();
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003647
3648 // setcc X, X
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003649 if (Op0 == Op1)
3650 return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
Chris Lattner1fc23f32002-05-09 20:11:54 +00003651
Chris Lattner81a7a232004-10-16 18:11:37 +00003652 if (isa<UndefValue>(Op1)) // X setcc undef -> undef
3653 return ReplaceInstUsesWith(I, UndefValue::get(Type::BoolTy));
3654
Chris Lattner15ff1e12004-11-14 07:33:16 +00003655 // setcc <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
3656 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanb1c93172005-04-21 23:48:37 +00003657 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
3658 isa<ConstantPointerNull>(Op0)) &&
3659 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner15ff1e12004-11-14 07:33:16 +00003660 isa<ConstantPointerNull>(Op1)))
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003661 return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
3662
3663 // setcc's with boolean values can always be turned into bitwise operations
3664 if (Ty == Type::BoolTy) {
Chris Lattner4456da62004-08-11 00:50:51 +00003665 switch (I.getOpcode()) {
3666 default: assert(0 && "Invalid setcc instruction!");
3667 case Instruction::SetEQ: { // seteq bool %A, %B -> ~(A^B)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003668 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003669 InsertNewInstBefore(Xor, I);
Chris Lattner16930792003-11-03 04:25:02 +00003670 return BinaryOperator::createNot(Xor);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003671 }
Chris Lattner4456da62004-08-11 00:50:51 +00003672 case Instruction::SetNE:
3673 return BinaryOperator::createXor(Op0, Op1);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003674
Chris Lattner4456da62004-08-11 00:50:51 +00003675 case Instruction::SetGT:
3676 std::swap(Op0, Op1); // Change setgt -> setlt
3677 // FALL THROUGH
3678 case Instruction::SetLT: { // setlt bool A, B -> ~X & Y
3679 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
3680 InsertNewInstBefore(Not, I);
3681 return BinaryOperator::createAnd(Not, Op1);
3682 }
3683 case Instruction::SetGE:
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003684 std::swap(Op0, Op1); // Change setge -> setle
Chris Lattner4456da62004-08-11 00:50:51 +00003685 // FALL THROUGH
3686 case Instruction::SetLE: { // setle bool %A, %B -> ~A | B
3687 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
3688 InsertNewInstBefore(Not, I);
3689 return BinaryOperator::createOr(Not, Op1);
3690 }
3691 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003692 }
3693
Chris Lattner2dd01742004-06-09 04:24:29 +00003694 // See if we are doing a comparison between a constant and an instruction that
3695 // can be folded into the comparison.
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003696 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner6862fbd2004-09-29 17:40:11 +00003697 // Check to see if we are comparing against the minimum or maximum value...
3698 if (CI->isMinValue()) {
3699 if (I.getOpcode() == Instruction::SetLT) // A < MIN -> FALSE
3700 return ReplaceInstUsesWith(I, ConstantBool::False);
3701 if (I.getOpcode() == Instruction::SetGE) // A >= MIN -> TRUE
3702 return ReplaceInstUsesWith(I, ConstantBool::True);
3703 if (I.getOpcode() == Instruction::SetLE) // A <= MIN -> A == MIN
3704 return BinaryOperator::createSetEQ(Op0, Op1);
3705 if (I.getOpcode() == Instruction::SetGT) // A > MIN -> A != MIN
3706 return BinaryOperator::createSetNE(Op0, Op1);
3707
3708 } else if (CI->isMaxValue()) {
3709 if (I.getOpcode() == Instruction::SetGT) // A > MAX -> FALSE
3710 return ReplaceInstUsesWith(I, ConstantBool::False);
3711 if (I.getOpcode() == Instruction::SetLE) // A <= MAX -> TRUE
3712 return ReplaceInstUsesWith(I, ConstantBool::True);
3713 if (I.getOpcode() == Instruction::SetGE) // A >= MAX -> A == MAX
3714 return BinaryOperator::createSetEQ(Op0, Op1);
3715 if (I.getOpcode() == Instruction::SetLT) // A < MAX -> A != MAX
3716 return BinaryOperator::createSetNE(Op0, Op1);
3717
3718 // Comparing against a value really close to min or max?
3719 } else if (isMinValuePlusOne(CI)) {
3720 if (I.getOpcode() == Instruction::SetLT) // A < MIN+1 -> A == MIN
3721 return BinaryOperator::createSetEQ(Op0, SubOne(CI));
3722 if (I.getOpcode() == Instruction::SetGE) // A >= MIN-1 -> A != MIN
3723 return BinaryOperator::createSetNE(Op0, SubOne(CI));
3724
3725 } else if (isMaxValueMinusOne(CI)) {
3726 if (I.getOpcode() == Instruction::SetGT) // A > MAX-1 -> A == MAX
3727 return BinaryOperator::createSetEQ(Op0, AddOne(CI));
3728 if (I.getOpcode() == Instruction::SetLE) // A <= MAX-1 -> A != MAX
3729 return BinaryOperator::createSetNE(Op0, AddOne(CI));
3730 }
3731
3732 // If we still have a setle or setge instruction, turn it into the
3733 // appropriate setlt or setgt instruction. Since the border cases have
3734 // already been handled above, this requires little checking.
3735 //
3736 if (I.getOpcode() == Instruction::SetLE)
3737 return BinaryOperator::createSetLT(Op0, AddOne(CI));
3738 if (I.getOpcode() == Instruction::SetGE)
3739 return BinaryOperator::createSetGT(Op0, SubOne(CI));
3740
Chris Lattneree0f2802006-02-12 02:07:56 +00003741
3742 // See if we can fold the comparison based on bits known to be zero or one
3743 // in the input.
3744 uint64_t KnownZero, KnownOne;
3745 if (SimplifyDemandedBits(Op0, Ty->getIntegralTypeMask(),
3746 KnownZero, KnownOne, 0))
3747 return &I;
3748
3749 // Given the known and unknown bits, compute a range that the LHS could be
3750 // in.
3751 if (KnownOne | KnownZero) {
3752 if (Ty->isUnsigned()) { // Unsigned comparison.
3753 uint64_t Min, Max;
3754 uint64_t RHSVal = CI->getZExtValue();
3755 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne,
3756 Min, Max);
3757 switch (I.getOpcode()) { // LE/GE have been folded already.
3758 default: assert(0 && "Unknown setcc opcode!");
3759 case Instruction::SetEQ:
3760 if (Max < RHSVal || Min > RHSVal)
3761 return ReplaceInstUsesWith(I, ConstantBool::False);
3762 break;
3763 case Instruction::SetNE:
3764 if (Max < RHSVal || Min > RHSVal)
3765 return ReplaceInstUsesWith(I, ConstantBool::True);
3766 break;
3767 case Instruction::SetLT:
3768 if (Max < RHSVal) return ReplaceInstUsesWith(I, ConstantBool::True);
3769 if (Min > RHSVal) return ReplaceInstUsesWith(I, ConstantBool::False);
3770 break;
3771 case Instruction::SetGT:
3772 if (Min > RHSVal) return ReplaceInstUsesWith(I, ConstantBool::True);
3773 if (Max < RHSVal) return ReplaceInstUsesWith(I, ConstantBool::False);
3774 break;
3775 }
3776 } else { // Signed comparison.
3777 int64_t Min, Max;
3778 int64_t RHSVal = CI->getSExtValue();
3779 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne,
3780 Min, Max);
3781 switch (I.getOpcode()) { // LE/GE have been folded already.
3782 default: assert(0 && "Unknown setcc opcode!");
3783 case Instruction::SetEQ:
3784 if (Max < RHSVal || Min > RHSVal)
3785 return ReplaceInstUsesWith(I, ConstantBool::False);
3786 break;
3787 case Instruction::SetNE:
3788 if (Max < RHSVal || Min > RHSVal)
3789 return ReplaceInstUsesWith(I, ConstantBool::True);
3790 break;
3791 case Instruction::SetLT:
3792 if (Max < RHSVal) return ReplaceInstUsesWith(I, ConstantBool::True);
3793 if (Min > RHSVal) return ReplaceInstUsesWith(I, ConstantBool::False);
3794 break;
3795 case Instruction::SetGT:
3796 if (Min > RHSVal) return ReplaceInstUsesWith(I, ConstantBool::True);
3797 if (Max < RHSVal) return ReplaceInstUsesWith(I, ConstantBool::False);
3798 break;
3799 }
3800 }
3801 }
3802
3803
Chris Lattnere1e10e12004-05-25 06:32:08 +00003804 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00003805 switch (LHSI->getOpcode()) {
3806 case Instruction::And:
3807 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
3808 LHSI->getOperand(0)->hasOneUse()) {
3809 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
3810 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
3811 // happens a LOT in code produced by the C front-end, for bitfield
3812 // access.
3813 ShiftInst *Shift = dyn_cast<ShiftInst>(LHSI->getOperand(0));
Chris Lattneree0f2802006-02-12 02:07:56 +00003814 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
3815
3816 // Check to see if there is a noop-cast between the shift and the and.
3817 if (!Shift) {
3818 if (CastInst *CI = dyn_cast<CastInst>(LHSI->getOperand(0)))
3819 if (CI->getOperand(0)->getType()->isIntegral() &&
3820 CI->getOperand(0)->getType()->getPrimitiveSizeInBits() ==
3821 CI->getType()->getPrimitiveSizeInBits())
3822 Shift = dyn_cast<ShiftInst>(CI->getOperand(0));
3823 }
3824
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00003825 ConstantUInt *ShAmt;
3826 ShAmt = Shift ? dyn_cast<ConstantUInt>(Shift->getOperand(1)) : 0;
Chris Lattneree0f2802006-02-12 02:07:56 +00003827 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
3828 const Type *AndTy = AndCST->getType(); // Type of the and.
Misha Brukmanb1c93172005-04-21 23:48:37 +00003829
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00003830 // We can fold this as long as we can't shift unknown bits
3831 // into the mask. This can only happen with signed shift
3832 // rights, as they sign-extend.
3833 if (ShAmt) {
3834 bool CanFold = Shift->getOpcode() != Instruction::Shr ||
Chris Lattneree0f2802006-02-12 02:07:56 +00003835 Ty->isUnsigned();
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00003836 if (!CanFold) {
3837 // To test for the bad case of the signed shr, see if any
3838 // of the bits shifted in could be tested after the mask.
Chris Lattnerc53cb9d2005-06-17 01:29:28 +00003839 int ShAmtVal = Ty->getPrimitiveSizeInBits()-ShAmt->getValue();
3840 if (ShAmtVal < 0) ShAmtVal = 0; // Out of range shift.
3841
3842 Constant *OShAmt = ConstantUInt::get(Type::UByteTy, ShAmtVal);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003843 Constant *ShVal =
Chris Lattneree0f2802006-02-12 02:07:56 +00003844 ConstantExpr::getShl(ConstantInt::getAllOnesValue(AndTy),
3845 OShAmt);
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00003846 if (ConstantExpr::getAnd(ShVal, AndCST)->isNullValue())
3847 CanFold = true;
3848 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003849
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00003850 if (CanFold) {
Chris Lattner6afc02f2004-09-28 17:54:07 +00003851 Constant *NewCst;
3852 if (Shift->getOpcode() == Instruction::Shl)
3853 NewCst = ConstantExpr::getUShr(CI, ShAmt);
3854 else
3855 NewCst = ConstantExpr::getShl(CI, ShAmt);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00003856
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00003857 // Check to see if we are shifting out any of the bits being
3858 // compared.
3859 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != CI){
3860 // If we shifted bits out, the fold is not going to work out.
3861 // As a special case, check to see if this means that the
3862 // result is always true or false now.
3863 if (I.getOpcode() == Instruction::SetEQ)
3864 return ReplaceInstUsesWith(I, ConstantBool::False);
3865 if (I.getOpcode() == Instruction::SetNE)
3866 return ReplaceInstUsesWith(I, ConstantBool::True);
3867 } else {
3868 I.setOperand(1, NewCst);
Chris Lattner6afc02f2004-09-28 17:54:07 +00003869 Constant *NewAndCST;
3870 if (Shift->getOpcode() == Instruction::Shl)
3871 NewAndCST = ConstantExpr::getUShr(AndCST, ShAmt);
3872 else
3873 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
3874 LHSI->setOperand(1, NewAndCST);
Chris Lattneree0f2802006-02-12 02:07:56 +00003875 if (AndTy == Ty)
3876 LHSI->setOperand(0, Shift->getOperand(0));
3877 else {
3878 Value *NewCast = InsertCastBefore(Shift->getOperand(0), AndTy,
3879 *Shift);
3880 LHSI->setOperand(0, NewCast);
3881 }
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00003882 WorkList.push_back(Shift); // Shift is dead.
3883 AddUsesToWorkList(I);
3884 return &I;
Chris Lattner1638de42004-07-21 19:50:44 +00003885 }
3886 }
Chris Lattner35167c32004-06-09 07:59:58 +00003887 }
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00003888 }
3889 break;
Chris Lattnerbfff18a2004-09-27 19:29:18 +00003890
Chris Lattner272d5ca2004-09-28 18:22:15 +00003891 case Instruction::Shl: // (setcc (shl X, ShAmt), CI)
3892 if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
3893 switch (I.getOpcode()) {
3894 default: break;
3895 case Instruction::SetEQ:
3896 case Instruction::SetNE: {
Chris Lattner19b57f52005-06-15 20:53:31 +00003897 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
3898
3899 // Check that the shift amount is in range. If not, don't perform
3900 // undefined shifts. When the shift is visited it will be
3901 // simplified.
3902 if (ShAmt->getValue() >= TypeBits)
3903 break;
3904
Chris Lattner272d5ca2004-09-28 18:22:15 +00003905 // If we are comparing against bits always shifted out, the
3906 // comparison cannot succeed.
Misha Brukmanb1c93172005-04-21 23:48:37 +00003907 Constant *Comp =
Chris Lattner272d5ca2004-09-28 18:22:15 +00003908 ConstantExpr::getShl(ConstantExpr::getShr(CI, ShAmt), ShAmt);
3909 if (Comp != CI) {// Comparing against a bit that we know is zero.
3910 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
3911 Constant *Cst = ConstantBool::get(IsSetNE);
3912 return ReplaceInstUsesWith(I, Cst);
3913 }
3914
3915 if (LHSI->hasOneUse()) {
3916 // Otherwise strength reduce the shift into an and.
Chris Lattnerfdfe3e492005-01-08 19:42:22 +00003917 unsigned ShAmtVal = (unsigned)ShAmt->getValue();
Chris Lattner272d5ca2004-09-28 18:22:15 +00003918 uint64_t Val = (1ULL << (TypeBits-ShAmtVal))-1;
3919
3920 Constant *Mask;
3921 if (CI->getType()->isUnsigned()) {
3922 Mask = ConstantUInt::get(CI->getType(), Val);
3923 } else if (ShAmtVal != 0) {
3924 Mask = ConstantSInt::get(CI->getType(), Val);
3925 } else {
3926 Mask = ConstantInt::getAllOnesValue(CI->getType());
3927 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003928
Chris Lattner272d5ca2004-09-28 18:22:15 +00003929 Instruction *AndI =
3930 BinaryOperator::createAnd(LHSI->getOperand(0),
3931 Mask, LHSI->getName()+".mask");
3932 Value *And = InsertNewInstBefore(AndI, I);
3933 return new SetCondInst(I.getOpcode(), And,
3934 ConstantExpr::getUShr(CI, ShAmt));
3935 }
3936 }
3937 }
3938 }
3939 break;
3940
Chris Lattnerbfff18a2004-09-27 19:29:18 +00003941 case Instruction::Shr: // (setcc (shr X, ShAmt), CI)
Chris Lattner1023b872004-09-27 16:18:50 +00003942 if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
Chris Lattner1023b872004-09-27 16:18:50 +00003943 switch (I.getOpcode()) {
3944 default: break;
3945 case Instruction::SetEQ:
3946 case Instruction::SetNE: {
Chris Lattner19b57f52005-06-15 20:53:31 +00003947
3948 // Check that the shift amount is in range. If not, don't perform
3949 // undefined shifts. When the shift is visited it will be
3950 // simplified.
Chris Lattner104002b2005-06-16 01:52:07 +00003951 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
Chris Lattner19b57f52005-06-15 20:53:31 +00003952 if (ShAmt->getValue() >= TypeBits)
3953 break;
3954
Chris Lattner1023b872004-09-27 16:18:50 +00003955 // If we are comparing against bits always shifted out, the
3956 // comparison cannot succeed.
Misha Brukmanb1c93172005-04-21 23:48:37 +00003957 Constant *Comp =
Chris Lattner1023b872004-09-27 16:18:50 +00003958 ConstantExpr::getShr(ConstantExpr::getShl(CI, ShAmt), ShAmt);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003959
Chris Lattner1023b872004-09-27 16:18:50 +00003960 if (Comp != CI) {// Comparing against a bit that we know is zero.
3961 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
3962 Constant *Cst = ConstantBool::get(IsSetNE);
3963 return ReplaceInstUsesWith(I, Cst);
3964 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003965
Chris Lattner1023b872004-09-27 16:18:50 +00003966 if (LHSI->hasOneUse() || CI->isNullValue()) {
Chris Lattnerfdfe3e492005-01-08 19:42:22 +00003967 unsigned ShAmtVal = (unsigned)ShAmt->getValue();
Chris Lattner272d5ca2004-09-28 18:22:15 +00003968
Chris Lattner1023b872004-09-27 16:18:50 +00003969 // Otherwise strength reduce the shift into an and.
3970 uint64_t Val = ~0ULL; // All ones.
3971 Val <<= ShAmtVal; // Shift over to the right spot.
3972
3973 Constant *Mask;
3974 if (CI->getType()->isUnsigned()) {
Chris Lattner2f1457f2005-04-24 17:46:05 +00003975 Val &= ~0ULL >> (64-TypeBits);
Chris Lattner1023b872004-09-27 16:18:50 +00003976 Mask = ConstantUInt::get(CI->getType(), Val);
3977 } else {
3978 Mask = ConstantSInt::get(CI->getType(), Val);
3979 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003980
Chris Lattner1023b872004-09-27 16:18:50 +00003981 Instruction *AndI =
3982 BinaryOperator::createAnd(LHSI->getOperand(0),
3983 Mask, LHSI->getName()+".mask");
3984 Value *And = InsertNewInstBefore(AndI, I);
3985 return new SetCondInst(I.getOpcode(), And,
3986 ConstantExpr::getShl(CI, ShAmt));
3987 }
3988 break;
3989 }
3990 }
3991 }
3992 break;
Chris Lattner7e794272004-09-24 15:21:34 +00003993
Chris Lattner6862fbd2004-09-29 17:40:11 +00003994 case Instruction::Div:
3995 // Fold: (div X, C1) op C2 -> range check
3996 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
3997 // Fold this div into the comparison, producing a range check.
3998 // Determine, based on the divide type, what the range is being
3999 // checked. If there is an overflow on the low or high side, remember
4000 // it, otherwise compute the range [low, hi) bounding the new value.
4001 bool LoOverflow = false, HiOverflow = 0;
4002 ConstantInt *LoBound = 0, *HiBound = 0;
4003
4004 ConstantInt *Prod;
4005 bool ProdOV = MulWithOverflow(Prod, CI, DivRHS);
4006
Chris Lattnera92af962004-10-11 19:40:04 +00004007 Instruction::BinaryOps Opcode = I.getOpcode();
4008
Chris Lattner6862fbd2004-09-29 17:40:11 +00004009 if (DivRHS->isNullValue()) { // Don't hack on divide by zeros.
4010 } else if (LHSI->getType()->isUnsigned()) { // udiv
4011 LoBound = Prod;
4012 LoOverflow = ProdOV;
4013 HiOverflow = ProdOV || AddWithOverflow(HiBound, LoBound, DivRHS);
4014 } else if (isPositive(DivRHS)) { // Divisor is > 0.
4015 if (CI->isNullValue()) { // (X / pos) op 0
4016 // Can't overflow.
4017 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
4018 HiBound = DivRHS;
4019 } else if (isPositive(CI)) { // (X / pos) op pos
4020 LoBound = Prod;
4021 LoOverflow = ProdOV;
4022 HiOverflow = ProdOV || AddWithOverflow(HiBound, Prod, DivRHS);
4023 } else { // (X / pos) op neg
4024 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
4025 LoOverflow = AddWithOverflow(LoBound, Prod,
4026 cast<ConstantInt>(DivRHSH));
4027 HiBound = Prod;
4028 HiOverflow = ProdOV;
4029 }
4030 } else { // Divisor is < 0.
4031 if (CI->isNullValue()) { // (X / neg) op 0
4032 LoBound = AddOne(DivRHS);
4033 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner73bcba52005-06-17 02:05:55 +00004034 if (HiBound == DivRHS)
4035 LoBound = 0; // - INTMIN = INTMIN
Chris Lattner6862fbd2004-09-29 17:40:11 +00004036 } else if (isPositive(CI)) { // (X / neg) op pos
4037 HiOverflow = LoOverflow = ProdOV;
4038 if (!LoOverflow)
4039 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS));
4040 HiBound = AddOne(Prod);
4041 } else { // (X / neg) op neg
4042 LoBound = Prod;
4043 LoOverflow = HiOverflow = ProdOV;
4044 HiBound = cast<ConstantInt>(ConstantExpr::getSub(Prod, DivRHS));
4045 }
Chris Lattner0b41e862004-10-08 19:15:44 +00004046
Chris Lattnera92af962004-10-11 19:40:04 +00004047 // Dividing by a negate swaps the condition.
4048 Opcode = SetCondInst::getSwappedCondition(Opcode);
Chris Lattner6862fbd2004-09-29 17:40:11 +00004049 }
4050
4051 if (LoBound) {
4052 Value *X = LHSI->getOperand(0);
Chris Lattnera92af962004-10-11 19:40:04 +00004053 switch (Opcode) {
Chris Lattner6862fbd2004-09-29 17:40:11 +00004054 default: assert(0 && "Unhandled setcc opcode!");
4055 case Instruction::SetEQ:
4056 if (LoOverflow && HiOverflow)
4057 return ReplaceInstUsesWith(I, ConstantBool::False);
4058 else if (HiOverflow)
4059 return new SetCondInst(Instruction::SetGE, X, LoBound);
4060 else if (LoOverflow)
4061 return new SetCondInst(Instruction::SetLT, X, HiBound);
4062 else
4063 return InsertRangeTest(X, LoBound, HiBound, true, I);
4064 case Instruction::SetNE:
4065 if (LoOverflow && HiOverflow)
4066 return ReplaceInstUsesWith(I, ConstantBool::True);
4067 else if (HiOverflow)
4068 return new SetCondInst(Instruction::SetLT, X, LoBound);
4069 else if (LoOverflow)
4070 return new SetCondInst(Instruction::SetGE, X, HiBound);
4071 else
4072 return InsertRangeTest(X, LoBound, HiBound, false, I);
4073 case Instruction::SetLT:
4074 if (LoOverflow)
4075 return ReplaceInstUsesWith(I, ConstantBool::False);
4076 return new SetCondInst(Instruction::SetLT, X, LoBound);
4077 case Instruction::SetGT:
4078 if (HiOverflow)
4079 return ReplaceInstUsesWith(I, ConstantBool::False);
4080 return new SetCondInst(Instruction::SetGE, X, HiBound);
4081 }
4082 }
4083 }
4084 break;
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004085 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004086
Chris Lattnerd492a0b2003-07-23 17:02:11 +00004087 // Simplify seteq and setne instructions...
4088 if (I.getOpcode() == Instruction::SetEQ ||
4089 I.getOpcode() == Instruction::SetNE) {
4090 bool isSetNE = I.getOpcode() == Instruction::SetNE;
4091
Chris Lattnercfbce7c2003-07-23 17:26:36 +00004092 // If the first operand is (and|or|xor) with a constant, and the second
Chris Lattnerd492a0b2003-07-23 17:02:11 +00004093 // operand is a constant, simplify a bit.
Chris Lattnerc992add2003-08-13 05:33:12 +00004094 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
4095 switch (BO->getOpcode()) {
Chris Lattner23b47b62004-07-06 07:38:18 +00004096 case Instruction::Rem:
4097 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
4098 if (CI->isNullValue() && isa<ConstantSInt>(BO->getOperand(1)) &&
4099 BO->hasOneUse() &&
Chris Lattner22d00a82005-08-02 19:16:58 +00004100 cast<ConstantSInt>(BO->getOperand(1))->getValue() > 1) {
4101 int64_t V = cast<ConstantSInt>(BO->getOperand(1))->getValue();
4102 if (isPowerOf2_64(V)) {
4103 unsigned L2 = Log2_64(V);
Chris Lattner23b47b62004-07-06 07:38:18 +00004104 const Type *UTy = BO->getType()->getUnsignedVersion();
4105 Value *NewX = InsertNewInstBefore(new CastInst(BO->getOperand(0),
4106 UTy, "tmp"), I);
4107 Constant *RHSCst = ConstantUInt::get(UTy, 1ULL << L2);
4108 Value *NewRem =InsertNewInstBefore(BinaryOperator::createRem(NewX,
4109 RHSCst, BO->getName()), I);
4110 return BinaryOperator::create(I.getOpcode(), NewRem,
4111 Constant::getNullValue(UTy));
4112 }
Chris Lattner22d00a82005-08-02 19:16:58 +00004113 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004114 break;
Chris Lattner23b47b62004-07-06 07:38:18 +00004115
Chris Lattnerc992add2003-08-13 05:33:12 +00004116 case Instruction::Add:
Chris Lattner6e079362004-06-27 22:51:36 +00004117 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
4118 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerb121ae12004-09-21 21:35:23 +00004119 if (BO->hasOneUse())
4120 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
4121 ConstantExpr::getSub(CI, BOp1C));
Chris Lattner6e079362004-06-27 22:51:36 +00004122 } else if (CI->isNullValue()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00004123 // Replace ((add A, B) != 0) with (A != -B) if A or B is
4124 // efficiently invertible, or if the add has just this one use.
4125 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004126
Chris Lattnerc992add2003-08-13 05:33:12 +00004127 if (Value *NegVal = dyn_castNegVal(BOp1))
4128 return new SetCondInst(I.getOpcode(), BOp0, NegVal);
4129 else if (Value *NegVal = dyn_castNegVal(BOp0))
4130 return new SetCondInst(I.getOpcode(), NegVal, BOp1);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00004131 else if (BO->hasOneUse()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00004132 Instruction *Neg = BinaryOperator::createNeg(BOp1, BO->getName());
4133 BO->setName("");
4134 InsertNewInstBefore(Neg, I);
4135 return new SetCondInst(I.getOpcode(), BOp0, Neg);
4136 }
4137 }
4138 break;
4139 case Instruction::Xor:
4140 // For the xor case, we can xor two constants together, eliminating
4141 // the explicit xor.
4142 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
4143 return BinaryOperator::create(I.getOpcode(), BO->getOperand(0),
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004144 ConstantExpr::getXor(CI, BOC));
Chris Lattnerc992add2003-08-13 05:33:12 +00004145
4146 // FALLTHROUGH
4147 case Instruction::Sub:
4148 // Replace (([sub|xor] A, B) != 0) with (A != B)
4149 if (CI->isNullValue())
4150 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
4151 BO->getOperand(1));
4152 break;
4153
4154 case Instruction::Or:
4155 // If bits are being or'd in that are not present in the constant we
4156 // are comparing against, then the comparison could never succeed!
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00004157 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Chris Lattnerc8e7e292004-06-10 02:12:35 +00004158 Constant *NotCI = ConstantExpr::getNot(CI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004159 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Chris Lattnerd492a0b2003-07-23 17:02:11 +00004160 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00004161 }
Chris Lattnerc992add2003-08-13 05:33:12 +00004162 break;
4163
4164 case Instruction::And:
4165 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerd492a0b2003-07-23 17:02:11 +00004166 // If bits are being compared against that are and'd out, then the
4167 // comparison can never succeed!
Chris Lattnerc8e7e292004-06-10 02:12:35 +00004168 if (!ConstantExpr::getAnd(CI,
4169 ConstantExpr::getNot(BOC))->isNullValue())
Chris Lattnerd492a0b2003-07-23 17:02:11 +00004170 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattnerc992add2003-08-13 05:33:12 +00004171
Chris Lattner35167c32004-06-09 07:59:58 +00004172 // If we have ((X & C) == C), turn it into ((X & C) != 0).
Chris Lattneree59d4b2004-06-10 02:33:20 +00004173 if (CI == BOC && isOneBitSet(CI))
Chris Lattner35167c32004-06-09 07:59:58 +00004174 return new SetCondInst(isSetNE ? Instruction::SetEQ :
4175 Instruction::SetNE, Op0,
4176 Constant::getNullValue(CI->getType()));
Chris Lattner35167c32004-06-09 07:59:58 +00004177
Chris Lattnerc992add2003-08-13 05:33:12 +00004178 // Replace (and X, (1 << size(X)-1) != 0) with x < 0, converting X
4179 // to be a signed value as appropriate.
4180 if (isSignBit(BOC)) {
4181 Value *X = BO->getOperand(0);
4182 // If 'X' is not signed, insert a cast now...
4183 if (!BOC->getType()->isSigned()) {
Chris Lattner97bfcea2004-06-17 18:16:02 +00004184 const Type *DestTy = BOC->getType()->getSignedVersion();
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004185 X = InsertCastBefore(X, DestTy, I);
Chris Lattnerc992add2003-08-13 05:33:12 +00004186 }
4187 return new SetCondInst(isSetNE ? Instruction::SetLT :
4188 Instruction::SetGE, X,
4189 Constant::getNullValue(X->getType()));
4190 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004191
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004192 // ((X & ~7) == 0) --> X < 8
Chris Lattner8fc5af42004-09-23 21:46:38 +00004193 if (CI->isNullValue() && isHighOnes(BOC)) {
4194 Value *X = BO->getOperand(0);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004195 Constant *NegX = ConstantExpr::getNeg(BOC);
Chris Lattner8fc5af42004-09-23 21:46:38 +00004196
4197 // If 'X' is signed, insert a cast now.
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004198 if (NegX->getType()->isSigned()) {
4199 const Type *DestTy = NegX->getType()->getUnsignedVersion();
4200 X = InsertCastBefore(X, DestTy, I);
4201 NegX = ConstantExpr::getCast(NegX, DestTy);
Chris Lattner8fc5af42004-09-23 21:46:38 +00004202 }
4203
4204 return new SetCondInst(isSetNE ? Instruction::SetGE :
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004205 Instruction::SetLT, X, NegX);
Chris Lattner8fc5af42004-09-23 21:46:38 +00004206 }
4207
Chris Lattnerd492a0b2003-07-23 17:02:11 +00004208 }
Chris Lattnerc992add2003-08-13 05:33:12 +00004209 default: break;
4210 }
4211 }
Chris Lattner2b55ea32004-02-23 07:16:20 +00004212 } else { // Not a SetEQ/SetNE
Misha Brukmanb1c93172005-04-21 23:48:37 +00004213 // If the LHS is a cast from an integral value of the same size,
Chris Lattner2b55ea32004-02-23 07:16:20 +00004214 if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
4215 Value *CastOp = Cast->getOperand(0);
4216 const Type *SrcTy = CastOp->getType();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004217 unsigned SrcTySize = SrcTy->getPrimitiveSizeInBits();
Chris Lattner2b55ea32004-02-23 07:16:20 +00004218 if (SrcTy != Cast->getType() && SrcTy->isInteger() &&
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004219 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00004220 assert((SrcTy->isSigned() ^ Cast->getType()->isSigned()) &&
Chris Lattner2b55ea32004-02-23 07:16:20 +00004221 "Source and destination signednesses should differ!");
4222 if (Cast->getType()->isSigned()) {
4223 // If this is a signed comparison, check for comparisons in the
4224 // vicinity of zero.
4225 if (I.getOpcode() == Instruction::SetLT && CI->isNullValue())
4226 // X < 0 => x > 127
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004227 return BinaryOperator::createSetGT(CastOp,
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004228 ConstantUInt::get(SrcTy, (1ULL << (SrcTySize-1))-1));
Chris Lattner2b55ea32004-02-23 07:16:20 +00004229 else if (I.getOpcode() == Instruction::SetGT &&
4230 cast<ConstantSInt>(CI)->getValue() == -1)
4231 // X > -1 => x < 128
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004232 return BinaryOperator::createSetLT(CastOp,
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004233 ConstantUInt::get(SrcTy, 1ULL << (SrcTySize-1)));
Chris Lattner2b55ea32004-02-23 07:16:20 +00004234 } else {
4235 ConstantUInt *CUI = cast<ConstantUInt>(CI);
4236 if (I.getOpcode() == Instruction::SetLT &&
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004237 CUI->getValue() == 1ULL << (SrcTySize-1))
Chris Lattner2b55ea32004-02-23 07:16:20 +00004238 // X < 128 => X > -1
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004239 return BinaryOperator::createSetGT(CastOp,
4240 ConstantSInt::get(SrcTy, -1));
Chris Lattner2b55ea32004-02-23 07:16:20 +00004241 else if (I.getOpcode() == Instruction::SetGT &&
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004242 CUI->getValue() == (1ULL << (SrcTySize-1))-1)
Chris Lattner2b55ea32004-02-23 07:16:20 +00004243 // X > 127 => X < 0
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004244 return BinaryOperator::createSetLT(CastOp,
4245 Constant::getNullValue(SrcTy));
Chris Lattner2b55ea32004-02-23 07:16:20 +00004246 }
4247 }
4248 }
Chris Lattnere967b342003-06-04 05:10:11 +00004249 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004250 }
4251
Chris Lattner77c32c32005-04-23 15:31:55 +00004252 // Handle setcc with constant RHS's that can be integer, FP or pointer.
4253 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
4254 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4255 switch (LHSI->getOpcode()) {
Chris Lattnera816eee2005-05-01 04:42:15 +00004256 case Instruction::GetElementPtr:
4257 if (RHSC->isNullValue()) {
4258 // Transform setcc GEP P, int 0, int 0, int 0, null -> setcc P, null
4259 bool isAllZeros = true;
4260 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
4261 if (!isa<Constant>(LHSI->getOperand(i)) ||
4262 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
4263 isAllZeros = false;
4264 break;
4265 }
4266 if (isAllZeros)
4267 return new SetCondInst(I.getOpcode(), LHSI->getOperand(0),
4268 Constant::getNullValue(LHSI->getOperand(0)->getType()));
4269 }
4270 break;
4271
Chris Lattner77c32c32005-04-23 15:31:55 +00004272 case Instruction::PHI:
4273 if (Instruction *NV = FoldOpIntoPhi(I))
4274 return NV;
4275 break;
4276 case Instruction::Select:
4277 // If either operand of the select is a constant, we can fold the
4278 // comparison into the select arms, which will cause one to be
4279 // constant folded and the select turned into a bitwise or.
4280 Value *Op1 = 0, *Op2 = 0;
4281 if (LHSI->hasOneUse()) {
4282 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
4283 // Fold the known value into the constant operand.
4284 Op1 = ConstantExpr::get(I.getOpcode(), C, RHSC);
4285 // Insert a new SetCC of the other select operand.
4286 Op2 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
4287 LHSI->getOperand(2), RHSC,
4288 I.getName()), I);
4289 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
4290 // Fold the known value into the constant operand.
4291 Op2 = ConstantExpr::get(I.getOpcode(), C, RHSC);
4292 // Insert a new SetCC of the other select operand.
4293 Op1 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
4294 LHSI->getOperand(1), RHSC,
4295 I.getName()), I);
4296 }
4297 }
Jeff Cohen82639852005-04-23 21:38:35 +00004298
Chris Lattner77c32c32005-04-23 15:31:55 +00004299 if (Op1)
4300 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
4301 break;
4302 }
4303 }
4304
Chris Lattner0798af32005-01-13 20:14:25 +00004305 // If we can optimize a 'setcc GEP, P' or 'setcc P, GEP', do so now.
4306 if (User *GEP = dyn_castGetElementPtr(Op0))
4307 if (Instruction *NI = FoldGEPSetCC(GEP, Op1, I.getOpcode(), I))
4308 return NI;
4309 if (User *GEP = dyn_castGetElementPtr(Op1))
4310 if (Instruction *NI = FoldGEPSetCC(GEP, Op0,
4311 SetCondInst::getSwappedCondition(I.getOpcode()), I))
4312 return NI;
4313
Chris Lattner16930792003-11-03 04:25:02 +00004314 // Test to see if the operands of the setcc are casted versions of other
4315 // values. If the cast can be stripped off both arguments, we do so now.
Chris Lattner6444c372003-11-03 05:17:03 +00004316 if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
4317 Value *CastOp0 = CI->getOperand(0);
4318 if (CastOp0->getType()->isLosslesslyConvertibleTo(CI->getType()) &&
Chris Lattner7d2a5392004-03-13 23:54:27 +00004319 (isa<Constant>(Op1) || isa<CastInst>(Op1)) &&
Chris Lattner16930792003-11-03 04:25:02 +00004320 (I.getOpcode() == Instruction::SetEQ ||
4321 I.getOpcode() == Instruction::SetNE)) {
4322 // We keep moving the cast from the left operand over to the right
4323 // operand, where it can often be eliminated completely.
Chris Lattner6444c372003-11-03 05:17:03 +00004324 Op0 = CastOp0;
Misha Brukmanb1c93172005-04-21 23:48:37 +00004325
Chris Lattner16930792003-11-03 04:25:02 +00004326 // If operand #1 is a cast instruction, see if we can eliminate it as
4327 // well.
Chris Lattner6444c372003-11-03 05:17:03 +00004328 if (CastInst *CI2 = dyn_cast<CastInst>(Op1))
4329 if (CI2->getOperand(0)->getType()->isLosslesslyConvertibleTo(
Chris Lattner16930792003-11-03 04:25:02 +00004330 Op0->getType()))
Chris Lattner6444c372003-11-03 05:17:03 +00004331 Op1 = CI2->getOperand(0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004332
Chris Lattner16930792003-11-03 04:25:02 +00004333 // If Op1 is a constant, we can fold the cast into the constant.
4334 if (Op1->getType() != Op0->getType())
4335 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
4336 Op1 = ConstantExpr::getCast(Op1C, Op0->getType());
4337 } else {
4338 // Otherwise, cast the RHS right before the setcc
4339 Op1 = new CastInst(Op1, Op0->getType(), Op1->getName());
4340 InsertNewInstBefore(cast<Instruction>(Op1), I);
4341 }
4342 return BinaryOperator::create(I.getOpcode(), Op0, Op1);
4343 }
4344
Chris Lattner6444c372003-11-03 05:17:03 +00004345 // Handle the special case of: setcc (cast bool to X), <cst>
4346 // This comes up when you have code like
4347 // int X = A < B;
4348 // if (X) ...
4349 // For generality, we handle any zero-extension of any operand comparison
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004350 // with a constant or another cast from the same type.
4351 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
4352 if (Instruction *R = visitSetCondInstWithCastAndCast(I))
4353 return R;
Chris Lattner6444c372003-11-03 05:17:03 +00004354 }
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00004355
4356 if (I.getOpcode() == Instruction::SetNE ||
4357 I.getOpcode() == Instruction::SetEQ) {
4358 Value *A, *B;
4359 if (match(Op0, m_Xor(m_Value(A), m_Value(B))) &&
4360 (A == Op1 || B == Op1)) {
4361 // (A^B) == A -> B == 0
4362 Value *OtherVal = A == Op1 ? B : A;
4363 return BinaryOperator::create(I.getOpcode(), OtherVal,
4364 Constant::getNullValue(A->getType()));
4365 } else if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
4366 (A == Op0 || B == Op0)) {
4367 // A == (A^B) -> B == 0
4368 Value *OtherVal = A == Op0 ? B : A;
4369 return BinaryOperator::create(I.getOpcode(), OtherVal,
4370 Constant::getNullValue(A->getType()));
4371 } else if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
4372 // (A-B) == A -> B == 0
4373 return BinaryOperator::create(I.getOpcode(), B,
4374 Constant::getNullValue(B->getType()));
4375 } else if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
4376 // A == (A-B) -> B == 0
4377 return BinaryOperator::create(I.getOpcode(), B,
4378 Constant::getNullValue(B->getType()));
4379 }
4380 }
Chris Lattner113f4f42002-06-25 16:13:24 +00004381 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004382}
4383
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004384// visitSetCondInstWithCastAndCast - Handle setcond (cast x to y), (cast/cst).
4385// We only handle extending casts so far.
4386//
4387Instruction *InstCombiner::visitSetCondInstWithCastAndCast(SetCondInst &SCI) {
4388 Value *LHSCIOp = cast<CastInst>(SCI.getOperand(0))->getOperand(0);
4389 const Type *SrcTy = LHSCIOp->getType();
4390 const Type *DestTy = SCI.getOperand(0)->getType();
4391 Value *RHSCIOp;
4392
4393 if (!DestTy->isIntegral() || !SrcTy->isIntegral())
Chris Lattner03f06f12005-01-17 03:20:02 +00004394 return 0;
4395
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004396 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
4397 unsigned DestBits = DestTy->getPrimitiveSizeInBits();
4398 if (SrcBits >= DestBits) return 0; // Only handle extending cast.
4399
4400 // Is this a sign or zero extension?
4401 bool isSignSrc = SrcTy->isSigned();
4402 bool isSignDest = DestTy->isSigned();
4403
4404 if (CastInst *CI = dyn_cast<CastInst>(SCI.getOperand(1))) {
4405 // Not an extension from the same type?
4406 RHSCIOp = CI->getOperand(0);
4407 if (RHSCIOp->getType() != LHSCIOp->getType()) return 0;
4408 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(SCI.getOperand(1))) {
4409 // Compute the constant that would happen if we truncated to SrcTy then
4410 // reextended to DestTy.
4411 Constant *Res = ConstantExpr::getCast(CI, SrcTy);
4412
4413 if (ConstantExpr::getCast(Res, DestTy) == CI) {
4414 RHSCIOp = Res;
4415 } else {
4416 // If the value cannot be represented in the shorter type, we cannot emit
4417 // a simple comparison.
4418 if (SCI.getOpcode() == Instruction::SetEQ)
4419 return ReplaceInstUsesWith(SCI, ConstantBool::False);
4420 if (SCI.getOpcode() == Instruction::SetNE)
4421 return ReplaceInstUsesWith(SCI, ConstantBool::True);
4422
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004423 // Evaluate the comparison for LT.
4424 Value *Result;
4425 if (DestTy->isSigned()) {
4426 // We're performing a signed comparison.
4427 if (isSignSrc) {
4428 // Signed extend and signed comparison.
4429 if (cast<ConstantSInt>(CI)->getValue() < 0) // X < (small) --> false
4430 Result = ConstantBool::False;
4431 else
4432 Result = ConstantBool::True; // X < (large) --> true
4433 } else {
4434 // Unsigned extend and signed comparison.
4435 if (cast<ConstantSInt>(CI)->getValue() < 0)
4436 Result = ConstantBool::False;
4437 else
4438 Result = ConstantBool::True;
4439 }
4440 } else {
4441 // We're performing an unsigned comparison.
4442 if (!isSignSrc) {
4443 // Unsigned extend & compare -> always true.
4444 Result = ConstantBool::True;
4445 } else {
4446 // We're performing an unsigned comp with a sign extended value.
4447 // This is true if the input is >= 0. [aka >s -1]
4448 Constant *NegOne = ConstantIntegral::getAllOnesValue(SrcTy);
4449 Result = InsertNewInstBefore(BinaryOperator::createSetGT(LHSCIOp,
4450 NegOne, SCI.getName()), SCI);
4451 }
Reid Spencer279fa252004-11-28 21:31:15 +00004452 }
Chris Lattner03f06f12005-01-17 03:20:02 +00004453
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00004454 // Finally, return the value computed.
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004455 if (SCI.getOpcode() == Instruction::SetLT) {
4456 return ReplaceInstUsesWith(SCI, Result);
4457 } else {
4458 assert(SCI.getOpcode()==Instruction::SetGT &&"SetCC should be folded!");
4459 if (Constant *CI = dyn_cast<Constant>(Result))
4460 return ReplaceInstUsesWith(SCI, ConstantExpr::getNot(CI));
4461 else
4462 return BinaryOperator::createNot(Result);
4463 }
Chris Lattner03f06f12005-01-17 03:20:02 +00004464 }
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004465 } else {
4466 return 0;
Reid Spencer279fa252004-11-28 21:31:15 +00004467 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004468
Chris Lattner252a8452005-06-16 03:00:08 +00004469 // Okay, just insert a compare of the reduced operands now!
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004470 return BinaryOperator::create(SCI.getOpcode(), LHSCIOp, RHSCIOp);
4471}
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004472
Chris Lattnere8d6c602003-03-10 19:16:08 +00004473Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +00004474 assert(I.getOperand(1)->getType() == Type::UByteTy);
4475 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00004476 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004477
4478 // shl X, 0 == X and shr X, 0 == X
4479 // shl 0, X == 0 and shr 0, X == 0
4480 if (Op1 == Constant::getNullValue(Type::UByteTy) ||
Chris Lattnere6794492002-08-12 21:17:25 +00004481 Op0 == Constant::getNullValue(Op0->getType()))
4482 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf5b4ef72006-02-12 08:07:37 +00004483
Chris Lattner81a7a232004-10-16 18:11:37 +00004484 if (isa<UndefValue>(Op0)) { // undef >>s X -> undef
4485 if (!isLeftShift && I.getType()->isSigned())
Chris Lattner67f05452004-10-16 23:28:04 +00004486 return ReplaceInstUsesWith(I, Op0);
Chris Lattner81a7a232004-10-16 18:11:37 +00004487 else // undef << X -> 0 AND undef >>u X -> 0
4488 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4489 }
4490 if (isa<UndefValue>(Op1)) {
Chris Lattner18aa4d82005-07-20 18:49:28 +00004491 if (isLeftShift || I.getType()->isUnsigned())// X << undef, X >>u undef -> 0
Chris Lattner81a7a232004-10-16 18:11:37 +00004492 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4493 else
4494 return ReplaceInstUsesWith(I, Op0); // X >>s undef -> X
4495 }
4496
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00004497 // shr int -1, X = -1 (for any arithmetic shift rights of ~0)
4498 if (!isLeftShift)
4499 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
4500 if (CSI->isAllOnesValue())
4501 return ReplaceInstUsesWith(I, CSI);
4502
Chris Lattner183b3362004-04-09 19:05:30 +00004503 // Try to fold constant and into select arguments.
4504 if (isa<Constant>(Op0))
4505 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner86102b82005-01-01 16:22:27 +00004506 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00004507 return R;
4508
Chris Lattnerb18dbbf2005-05-08 17:34:56 +00004509 // See if we can turn a signed shr into an unsigned shr.
4510 if (!isLeftShift && I.getType()->isSigned()) {
Chris Lattnerc3ebf402006-02-07 07:27:52 +00004511 if (MaskedValueIsZero(Op0,
4512 1ULL << (I.getType()->getPrimitiveSizeInBits()-1))) {
Chris Lattnerb18dbbf2005-05-08 17:34:56 +00004513 Value *V = InsertCastBefore(Op0, I.getType()->getUnsignedVersion(), I);
4514 V = InsertNewInstBefore(new ShiftInst(Instruction::Shr, V, Op1,
4515 I.getName()), I);
4516 return new CastInst(V, I.getType());
4517 }
4518 }
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00004519
Chris Lattner14553932006-01-06 07:12:35 +00004520 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op1))
4521 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
4522 return Res;
4523 return 0;
4524}
4525
4526Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantUInt *Op1,
4527 ShiftInst &I) {
4528 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattnerb3309392006-01-06 07:22:22 +00004529 bool isSignedShift = Op0->getType()->isSigned();
4530 bool isUnsignedShift = !isSignedShift;
Chris Lattner14553932006-01-06 07:12:35 +00004531
Chris Lattnerf5b4ef72006-02-12 08:07:37 +00004532 // See if we can simplify any instructions used by the instruction whose sole
4533 // purpose is to compute bits we don't care about.
4534 uint64_t KnownZero, KnownOne;
4535 if (SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
4536 KnownZero, KnownOne))
4537 return &I;
4538
Chris Lattner14553932006-01-06 07:12:35 +00004539 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
4540 // of a signed value.
4541 //
4542 unsigned TypeBits = Op0->getType()->getPrimitiveSizeInBits();
4543 if (Op1->getValue() >= TypeBits) {
Chris Lattnerb3309392006-01-06 07:22:22 +00004544 if (isUnsignedShift || isLeftShift)
Chris Lattner14553932006-01-06 07:12:35 +00004545 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
4546 else {
4547 I.setOperand(1, ConstantUInt::get(Type::UByteTy, TypeBits-1));
4548 return &I;
Chris Lattnerf5ce2542004-02-23 20:30:06 +00004549 }
Chris Lattner14553932006-01-06 07:12:35 +00004550 }
4551
4552 // ((X*C1) << C2) == (X * (C1 << C2))
4553 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
4554 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
4555 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
4556 return BinaryOperator::createMul(BO->getOperand(0),
4557 ConstantExpr::getShl(BOOp, Op1));
4558
4559 // Try to fold constant and into select arguments.
4560 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4561 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4562 return R;
4563 if (isa<PHINode>(Op0))
4564 if (Instruction *NV = FoldOpIntoPhi(I))
4565 return NV;
4566
4567 if (Op0->hasOneUse()) {
Chris Lattner14553932006-01-06 07:12:35 +00004568 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
4569 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
4570 Value *V1, *V2;
4571 ConstantInt *CC;
4572 switch (Op0BO->getOpcode()) {
Chris Lattner27cb9db2005-09-18 05:12:10 +00004573 default: break;
4574 case Instruction::Add:
4575 case Instruction::And:
4576 case Instruction::Or:
4577 case Instruction::Xor:
4578 // These operators commute.
4579 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner797dee72005-09-18 06:30:59 +00004580 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
4581 match(Op0BO->getOperand(1),
Chris Lattner14553932006-01-06 07:12:35 +00004582 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Chris Lattner797dee72005-09-18 06:30:59 +00004583 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00004584 Op0BO->getOperand(0), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00004585 Op0BO->getName());
4586 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner24cd2fa2006-02-09 07:41:14 +00004587 Instruction *X =
4588 BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
4589 Op0BO->getOperand(1)->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00004590 InsertNewInstBefore(X, I); // (X + (Y << C))
4591 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
Chris Lattner14553932006-01-06 07:12:35 +00004592 C2 = ConstantExpr::getShl(C2, Op1);
Chris Lattner797dee72005-09-18 06:30:59 +00004593 return BinaryOperator::createAnd(X, C2);
4594 }
Chris Lattner14553932006-01-06 07:12:35 +00004595
Chris Lattner797dee72005-09-18 06:30:59 +00004596 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
4597 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
4598 match(Op0BO->getOperand(1),
4599 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner14553932006-01-06 07:12:35 +00004600 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner24cd2fa2006-02-09 07:41:14 +00004601 cast<BinaryOperator>(Op0BO->getOperand(1))->getOperand(0)->hasOneUse()) {
Chris Lattner797dee72005-09-18 06:30:59 +00004602 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00004603 Op0BO->getOperand(0), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00004604 Op0BO->getName());
4605 InsertNewInstBefore(YS, I); // (Y << C)
4606 Instruction *XM =
Chris Lattner14553932006-01-06 07:12:35 +00004607 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner797dee72005-09-18 06:30:59 +00004608 V1->getName()+".mask");
4609 InsertNewInstBefore(XM, I); // X & (CC << C)
4610
4611 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
4612 }
Chris Lattner14553932006-01-06 07:12:35 +00004613
Chris Lattner797dee72005-09-18 06:30:59 +00004614 // FALL THROUGH.
Chris Lattner27cb9db2005-09-18 05:12:10 +00004615 case Instruction::Sub:
4616 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner797dee72005-09-18 06:30:59 +00004617 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
4618 match(Op0BO->getOperand(0),
Chris Lattner14553932006-01-06 07:12:35 +00004619 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Chris Lattner797dee72005-09-18 06:30:59 +00004620 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00004621 Op0BO->getOperand(1), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00004622 Op0BO->getName());
4623 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner24cd2fa2006-02-09 07:41:14 +00004624 Instruction *X =
Chris Lattner1df0e982006-05-31 21:14:00 +00004625 BinaryOperator::create(Op0BO->getOpcode(), V1, YS,
Chris Lattner24cd2fa2006-02-09 07:41:14 +00004626 Op0BO->getOperand(0)->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00004627 InsertNewInstBefore(X, I); // (X + (Y << C))
4628 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
Chris Lattner14553932006-01-06 07:12:35 +00004629 C2 = ConstantExpr::getShl(C2, Op1);
Chris Lattner797dee72005-09-18 06:30:59 +00004630 return BinaryOperator::createAnd(X, C2);
4631 }
Chris Lattner14553932006-01-06 07:12:35 +00004632
Chris Lattner1df0e982006-05-31 21:14:00 +00004633 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner797dee72005-09-18 06:30:59 +00004634 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
4635 match(Op0BO->getOperand(0),
4636 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner14553932006-01-06 07:12:35 +00004637 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner24cd2fa2006-02-09 07:41:14 +00004638 cast<BinaryOperator>(Op0BO->getOperand(0))
4639 ->getOperand(0)->hasOneUse()) {
Chris Lattner797dee72005-09-18 06:30:59 +00004640 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00004641 Op0BO->getOperand(1), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00004642 Op0BO->getName());
4643 InsertNewInstBefore(YS, I); // (Y << C)
4644 Instruction *XM =
Chris Lattner14553932006-01-06 07:12:35 +00004645 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner797dee72005-09-18 06:30:59 +00004646 V1->getName()+".mask");
4647 InsertNewInstBefore(XM, I); // X & (CC << C)
4648
Chris Lattner1df0e982006-05-31 21:14:00 +00004649 return BinaryOperator::create(Op0BO->getOpcode(), XM, YS);
Chris Lattner797dee72005-09-18 06:30:59 +00004650 }
Chris Lattner14553932006-01-06 07:12:35 +00004651
Chris Lattner27cb9db2005-09-18 05:12:10 +00004652 break;
Chris Lattner14553932006-01-06 07:12:35 +00004653 }
4654
4655
4656 // If the operand is an bitwise operator with a constant RHS, and the
4657 // shift is the only use, we can pull it out of the shift.
4658 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
4659 bool isValid = true; // Valid only for And, Or, Xor
4660 bool highBitSet = false; // Transform if high bit of constant set?
4661
4662 switch (Op0BO->getOpcode()) {
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00004663 default: isValid = false; break; // Do not perform transform!
Chris Lattner44bd3922004-10-08 03:46:20 +00004664 case Instruction::Add:
4665 isValid = isLeftShift;
4666 break;
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00004667 case Instruction::Or:
4668 case Instruction::Xor:
4669 highBitSet = false;
4670 break;
4671 case Instruction::And:
4672 highBitSet = true;
4673 break;
Chris Lattner14553932006-01-06 07:12:35 +00004674 }
4675
4676 // If this is a signed shift right, and the high bit is modified
4677 // by the logical operation, do not perform the transformation.
4678 // The highBitSet boolean indicates the value of the high bit of
4679 // the constant which would cause it to be modified for this
4680 // operation.
4681 //
Chris Lattnerb3309392006-01-06 07:22:22 +00004682 if (isValid && !isLeftShift && isSignedShift) {
Chris Lattner14553932006-01-06 07:12:35 +00004683 uint64_t Val = Op0C->getRawValue();
4684 isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
4685 }
4686
4687 if (isValid) {
4688 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
4689
4690 Instruction *NewShift =
4691 new ShiftInst(I.getOpcode(), Op0BO->getOperand(0), Op1,
4692 Op0BO->getName());
4693 Op0BO->setName("");
4694 InsertNewInstBefore(NewShift, I);
4695
4696 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
4697 NewRHS);
4698 }
4699 }
4700 }
4701 }
4702
Chris Lattnereb372a02006-01-06 07:52:12 +00004703 // Find out if this is a shift of a shift by a constant.
4704 ShiftInst *ShiftOp = 0;
Chris Lattner14553932006-01-06 07:12:35 +00004705 if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0))
Chris Lattnereb372a02006-01-06 07:52:12 +00004706 ShiftOp = Op0SI;
4707 else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
4708 // If this is a noop-integer case of a shift instruction, use the shift.
4709 if (CI->getOperand(0)->getType()->isInteger() &&
4710 CI->getOperand(0)->getType()->getPrimitiveSizeInBits() ==
4711 CI->getType()->getPrimitiveSizeInBits() &&
4712 isa<ShiftInst>(CI->getOperand(0))) {
4713 ShiftOp = cast<ShiftInst>(CI->getOperand(0));
4714 }
4715 }
4716
4717 if (ShiftOp && isa<ConstantUInt>(ShiftOp->getOperand(1))) {
4718 // Find the operands and properties of the input shift. Note that the
4719 // signedness of the input shift may differ from the current shift if there
4720 // is a noop cast between the two.
4721 bool isShiftOfLeftShift = ShiftOp->getOpcode() == Instruction::Shl;
4722 bool isShiftOfSignedShift = ShiftOp->getType()->isSigned();
Chris Lattner9cbfbc22006-01-07 01:32:28 +00004723 bool isShiftOfUnsignedShift = !isShiftOfSignedShift;
Chris Lattnereb372a02006-01-06 07:52:12 +00004724
4725 ConstantUInt *ShiftAmt1C = cast<ConstantUInt>(ShiftOp->getOperand(1));
4726
4727 unsigned ShiftAmt1 = (unsigned)ShiftAmt1C->getValue();
4728 unsigned ShiftAmt2 = (unsigned)Op1->getValue();
4729
4730 // Check for (A << c1) << c2 and (A >> c1) >> c2.
4731 if (isLeftShift == isShiftOfLeftShift) {
4732 // Do not fold these shifts if the first one is signed and the second one
4733 // is unsigned and this is a right shift. Further, don't do any folding
4734 // on them.
4735 if (isShiftOfSignedShift && isUnsignedShift && !isLeftShift)
4736 return 0;
Chris Lattner14553932006-01-06 07:12:35 +00004737
Chris Lattnereb372a02006-01-06 07:52:12 +00004738 unsigned Amt = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
4739 if (Amt > Op0->getType()->getPrimitiveSizeInBits())
4740 Amt = Op0->getType()->getPrimitiveSizeInBits();
Chris Lattner14553932006-01-06 07:12:35 +00004741
Chris Lattnereb372a02006-01-06 07:52:12 +00004742 Value *Op = ShiftOp->getOperand(0);
4743 if (isShiftOfSignedShift != isSignedShift)
4744 Op = InsertNewInstBefore(new CastInst(Op, I.getType(), "tmp"), I);
4745 return new ShiftInst(I.getOpcode(), Op,
4746 ConstantUInt::get(Type::UByteTy, Amt));
4747 }
4748
4749 // Check for (A << c1) >> c2 or (A >> c1) << c2. If we are dealing with
4750 // signed types, we can only support the (A >> c1) << c2 configuration,
4751 // because it can not turn an arbitrary bit of A into a sign bit.
4752 if (isUnsignedShift || isLeftShift) {
4753 // Calculate bitmask for what gets shifted off the edge.
4754 Constant *C = ConstantIntegral::getAllOnesValue(I.getType());
4755 if (isLeftShift)
4756 C = ConstantExpr::getShl(C, ShiftAmt1C);
4757 else
Chris Lattner9cbfbc22006-01-07 01:32:28 +00004758 C = ConstantExpr::getUShr(C, ShiftAmt1C);
Chris Lattnereb372a02006-01-06 07:52:12 +00004759
4760 Value *Op = ShiftOp->getOperand(0);
4761 if (isShiftOfSignedShift != isSignedShift)
4762 Op = InsertNewInstBefore(new CastInst(Op, I.getType(),Op->getName()),I);
4763
4764 Instruction *Mask =
4765 BinaryOperator::createAnd(Op, C, Op->getName()+".mask");
4766 InsertNewInstBefore(Mask, I);
4767
4768 // Figure out what flavor of shift we should use...
Chris Lattner9cbfbc22006-01-07 01:32:28 +00004769 if (ShiftAmt1 == ShiftAmt2) {
Chris Lattnereb372a02006-01-06 07:52:12 +00004770 return ReplaceInstUsesWith(I, Mask); // (A << c) >> c === A & c2
Chris Lattner9cbfbc22006-01-07 01:32:28 +00004771 } else if (ShiftAmt1 < ShiftAmt2) {
Chris Lattnereb372a02006-01-06 07:52:12 +00004772 return new ShiftInst(I.getOpcode(), Mask,
4773 ConstantUInt::get(Type::UByteTy, ShiftAmt2-ShiftAmt1));
Chris Lattner9cbfbc22006-01-07 01:32:28 +00004774 } else if (isShiftOfUnsignedShift || isShiftOfLeftShift) {
4775 if (isShiftOfUnsignedShift && !isShiftOfLeftShift && isSignedShift) {
4776 // Make sure to emit an unsigned shift right, not a signed one.
4777 Mask = InsertNewInstBefore(new CastInst(Mask,
4778 Mask->getType()->getUnsignedVersion(),
4779 Op->getName()), I);
4780 Mask = new ShiftInst(Instruction::Shr, Mask,
Chris Lattnereb372a02006-01-06 07:52:12 +00004781 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
Chris Lattner9cbfbc22006-01-07 01:32:28 +00004782 InsertNewInstBefore(Mask, I);
4783 return new CastInst(Mask, I.getType());
4784 } else {
4785 return new ShiftInst(ShiftOp->getOpcode(), Mask,
4786 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
4787 }
4788 } else {
4789 // (X >>s C1) << C2 where C1 > C2 === (X >>s (C1-C2)) & mask
4790 Op = InsertNewInstBefore(new CastInst(Mask,
4791 I.getType()->getSignedVersion(),
4792 Mask->getName()), I);
4793 Instruction *Shift =
4794 new ShiftInst(ShiftOp->getOpcode(), Op,
4795 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
4796 InsertNewInstBefore(Shift, I);
4797
4798 C = ConstantIntegral::getAllOnesValue(Shift->getType());
4799 C = ConstantExpr::getShl(C, Op1);
4800 Mask = BinaryOperator::createAnd(Shift, C, Op->getName()+".mask");
4801 InsertNewInstBefore(Mask, I);
4802 return new CastInst(Mask, I.getType());
Chris Lattnereb372a02006-01-06 07:52:12 +00004803 }
4804 } else {
Chris Lattner9cbfbc22006-01-07 01:32:28 +00004805 // We can handle signed (X << C1) >>s C2 if it's a sign extend. In
Chris Lattnereb372a02006-01-06 07:52:12 +00004806 // this case, C1 == C2 and C1 is 8, 16, or 32.
4807 if (ShiftAmt1 == ShiftAmt2) {
4808 const Type *SExtType = 0;
Chris Lattner655d08f2006-04-28 22:21:41 +00004809 switch (Op0->getType()->getPrimitiveSizeInBits() - ShiftAmt1) {
Chris Lattnereb372a02006-01-06 07:52:12 +00004810 case 8 : SExtType = Type::SByteTy; break;
4811 case 16: SExtType = Type::ShortTy; break;
4812 case 32: SExtType = Type::IntTy; break;
4813 }
4814
4815 if (SExtType) {
4816 Instruction *NewTrunc = new CastInst(ShiftOp->getOperand(0),
4817 SExtType, "sext");
4818 InsertNewInstBefore(NewTrunc, I);
4819 return new CastInst(NewTrunc, I.getType());
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00004820 }
Chris Lattner27cb9db2005-09-18 05:12:10 +00004821 }
Chris Lattner86102b82005-01-01 16:22:27 +00004822 }
Chris Lattnereb372a02006-01-06 07:52:12 +00004823 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004824 return 0;
4825}
4826
Chris Lattner48a44f72002-05-02 17:06:02 +00004827
Chris Lattner8f663e82005-10-29 04:36:15 +00004828/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
4829/// expression. If so, decompose it, returning some value X, such that Val is
4830/// X*Scale+Offset.
4831///
4832static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
4833 unsigned &Offset) {
4834 assert(Val->getType() == Type::UIntTy && "Unexpected allocation size type!");
4835 if (ConstantUInt *CI = dyn_cast<ConstantUInt>(Val)) {
4836 Offset = CI->getValue();
4837 Scale = 1;
4838 return ConstantUInt::get(Type::UIntTy, 0);
4839 } else if (Instruction *I = dyn_cast<Instruction>(Val)) {
4840 if (I->getNumOperands() == 2) {
4841 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(I->getOperand(1))) {
4842 if (I->getOpcode() == Instruction::Shl) {
4843 // This is a value scaled by '1 << the shift amt'.
4844 Scale = 1U << CUI->getValue();
4845 Offset = 0;
4846 return I->getOperand(0);
4847 } else if (I->getOpcode() == Instruction::Mul) {
4848 // This value is scaled by 'CUI'.
4849 Scale = CUI->getValue();
4850 Offset = 0;
4851 return I->getOperand(0);
4852 } else if (I->getOpcode() == Instruction::Add) {
4853 // We have X+C. Check to see if we really have (X*C2)+C1, where C1 is
4854 // divisible by C2.
4855 unsigned SubScale;
4856 Value *SubVal = DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
4857 Offset);
4858 Offset += CUI->getValue();
4859 if (SubScale > 1 && (Offset % SubScale == 0)) {
4860 Scale = SubScale;
4861 return SubVal;
4862 }
4863 }
4864 }
4865 }
4866 }
4867
4868 // Otherwise, we can't look past this.
4869 Scale = 1;
4870 Offset = 0;
4871 return Val;
4872}
4873
4874
Chris Lattner216be912005-10-24 06:03:58 +00004875/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
4876/// try to eliminate the cast by moving the type information into the alloc.
4877Instruction *InstCombiner::PromoteCastOfAllocation(CastInst &CI,
4878 AllocationInst &AI) {
4879 const PointerType *PTy = dyn_cast<PointerType>(CI.getType());
Chris Lattnerbb171802005-10-27 05:53:56 +00004880 if (!PTy) return 0; // Not casting the allocation to a pointer type.
Chris Lattner216be912005-10-24 06:03:58 +00004881
Chris Lattnerac87beb2005-10-24 06:22:12 +00004882 // Remove any uses of AI that are dead.
4883 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
4884 std::vector<Instruction*> DeadUsers;
4885 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
4886 Instruction *User = cast<Instruction>(*UI++);
4887 if (isInstructionTriviallyDead(User)) {
4888 while (UI != E && *UI == User)
4889 ++UI; // If this instruction uses AI more than once, don't break UI.
4890
4891 // Add operands to the worklist.
4892 AddUsesToWorkList(*User);
4893 ++NumDeadInst;
4894 DEBUG(std::cerr << "IC: DCE: " << *User);
4895
4896 User->eraseFromParent();
4897 removeFromWorkList(User);
4898 }
4899 }
4900
Chris Lattner216be912005-10-24 06:03:58 +00004901 // Get the type really allocated and the type casted to.
4902 const Type *AllocElTy = AI.getAllocatedType();
4903 const Type *CastElTy = PTy->getElementType();
4904 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner355ecc02005-10-24 06:26:18 +00004905
4906 unsigned AllocElTyAlign = TD->getTypeSize(AllocElTy);
4907 unsigned CastElTyAlign = TD->getTypeSize(CastElTy);
4908 if (CastElTyAlign < AllocElTyAlign) return 0;
4909
Chris Lattner46705b22005-10-24 06:35:18 +00004910 // If the allocation has multiple uses, only promote it if we are strictly
4911 // increasing the alignment of the resultant allocation. If we keep it the
4912 // same, we open the door to infinite loops of various kinds.
4913 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
4914
Chris Lattner216be912005-10-24 06:03:58 +00004915 uint64_t AllocElTySize = TD->getTypeSize(AllocElTy);
4916 uint64_t CastElTySize = TD->getTypeSize(CastElTy);
Chris Lattnerbb171802005-10-27 05:53:56 +00004917 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner355ecc02005-10-24 06:26:18 +00004918
Chris Lattner8270c332005-10-29 03:19:53 +00004919 // See if we can satisfy the modulus by pulling a scale out of the array
4920 // size argument.
Chris Lattner8f663e82005-10-29 04:36:15 +00004921 unsigned ArraySizeScale, ArrayOffset;
4922 Value *NumElements = // See if the array size is a decomposable linear expr.
4923 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
4924
Chris Lattner8270c332005-10-29 03:19:53 +00004925 // If we can now satisfy the modulus, by using a non-1 scale, we really can
4926 // do the xform.
Chris Lattner8f663e82005-10-29 04:36:15 +00004927 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
4928 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattnerb3ecf962005-10-27 06:12:00 +00004929
Chris Lattner8270c332005-10-29 03:19:53 +00004930 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
4931 Value *Amt = 0;
4932 if (Scale == 1) {
4933 Amt = NumElements;
4934 } else {
4935 Amt = ConstantUInt::get(Type::UIntTy, Scale);
4936 if (ConstantUInt *CI = dyn_cast<ConstantUInt>(NumElements))
4937 Amt = ConstantExpr::getMul(CI, cast<ConstantUInt>(Amt));
4938 else if (Scale != 1) {
4939 Instruction *Tmp = BinaryOperator::createMul(Amt, NumElements, "tmp");
4940 Amt = InsertNewInstBefore(Tmp, AI);
Chris Lattnerb3ecf962005-10-27 06:12:00 +00004941 }
Chris Lattnerbb171802005-10-27 05:53:56 +00004942 }
4943
Chris Lattner8f663e82005-10-29 04:36:15 +00004944 if (unsigned Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
4945 Value *Off = ConstantUInt::get(Type::UIntTy, Offset);
4946 Instruction *Tmp = BinaryOperator::createAdd(Amt, Off, "tmp");
4947 Amt = InsertNewInstBefore(Tmp, AI);
4948 }
4949
Chris Lattner216be912005-10-24 06:03:58 +00004950 std::string Name = AI.getName(); AI.setName("");
4951 AllocationInst *New;
4952 if (isa<MallocInst>(AI))
Nate Begeman848622f2005-11-05 09:21:28 +00004953 New = new MallocInst(CastElTy, Amt, AI.getAlignment(), Name);
Chris Lattner216be912005-10-24 06:03:58 +00004954 else
Nate Begeman848622f2005-11-05 09:21:28 +00004955 New = new AllocaInst(CastElTy, Amt, AI.getAlignment(), Name);
Chris Lattner216be912005-10-24 06:03:58 +00004956 InsertNewInstBefore(New, AI);
Chris Lattner46705b22005-10-24 06:35:18 +00004957
4958 // If the allocation has multiple uses, insert a cast and change all things
4959 // that used it to use the new cast. This will also hack on CI, but it will
4960 // die soon.
4961 if (!AI.hasOneUse()) {
4962 AddUsesToWorkList(AI);
4963 CastInst *NewCast = new CastInst(New, AI.getType(), "tmpcast");
4964 InsertNewInstBefore(NewCast, AI);
4965 AI.replaceAllUsesWith(NewCast);
4966 }
Chris Lattner216be912005-10-24 06:03:58 +00004967 return ReplaceInstUsesWith(CI, New);
4968}
4969
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00004970/// CanEvaluateInDifferentType - Return true if we can take the specified value
4971/// and return it without inserting any new casts. This is used by code that
4972/// tries to decide whether promoting or shrinking integer operations to wider
4973/// or smaller types will allow us to eliminate a truncate or extend.
4974static bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
4975 int &NumCastsRemoved) {
4976 if (isa<Constant>(V)) return true;
4977
4978 Instruction *I = dyn_cast<Instruction>(V);
4979 if (!I || !I->hasOneUse()) return false;
4980
4981 switch (I->getOpcode()) {
4982 case Instruction::And:
4983 case Instruction::Or:
4984 case Instruction::Xor:
4985 // These operators can all arbitrarily be extended or truncated.
4986 return CanEvaluateInDifferentType(I->getOperand(0), Ty, NumCastsRemoved) &&
4987 CanEvaluateInDifferentType(I->getOperand(1), Ty, NumCastsRemoved);
4988 case Instruction::Cast:
4989 // If this is a cast from the destination type, we can trivially eliminate
4990 // it, and this will remove a cast overall.
4991 if (I->getOperand(0)->getType() == Ty) {
Chris Lattner3fda3862006-06-28 17:34:50 +00004992 // If the first operand is itself a cast, and is eliminable, do not count
4993 // this as an eliminable cast. We would prefer to eliminate those two
4994 // casts first.
4995 if (CastInst *OpCast = dyn_cast<CastInst>(I->getOperand(0)))
4996 return true;
4997
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00004998 ++NumCastsRemoved;
4999 return true;
5000 }
5001 // TODO: Can handle more cases here.
5002 break;
5003 }
5004
5005 return false;
5006}
5007
5008/// EvaluateInDifferentType - Given an expression that
5009/// CanEvaluateInDifferentType returns true for, actually insert the code to
5010/// evaluate the expression.
5011Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty) {
5012 if (Constant *C = dyn_cast<Constant>(V))
5013 return ConstantExpr::getCast(C, Ty);
5014
5015 // Otherwise, it must be an instruction.
5016 Instruction *I = cast<Instruction>(V);
Chris Lattnerd0622b62006-05-20 23:14:03 +00005017 Instruction *Res = 0;
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005018 switch (I->getOpcode()) {
5019 case Instruction::And:
5020 case Instruction::Or:
5021 case Instruction::Xor: {
5022 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty);
5023 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty);
5024 Res = BinaryOperator::create((Instruction::BinaryOps)I->getOpcode(),
5025 LHS, RHS, I->getName());
5026 break;
5027 }
5028 case Instruction::Cast:
5029 // If this is a cast from the destination type, return the input.
5030 if (I->getOperand(0)->getType() == Ty)
5031 return I->getOperand(0);
5032
5033 // TODO: Can handle more cases here.
5034 assert(0 && "Unreachable!");
5035 break;
5036 }
5037
5038 return InsertNewInstBefore(Res, *I);
5039}
5040
Chris Lattner216be912005-10-24 06:03:58 +00005041
Chris Lattner48a44f72002-05-02 17:06:02 +00005042// CastInst simplification
Chris Lattner260ab202002-04-18 17:39:14 +00005043//
Chris Lattner113f4f42002-06-25 16:13:24 +00005044Instruction *InstCombiner::visitCastInst(CastInst &CI) {
Chris Lattner55d4bda2003-06-23 21:59:52 +00005045 Value *Src = CI.getOperand(0);
5046
Chris Lattner48a44f72002-05-02 17:06:02 +00005047 // If the user is casting a value to the same type, eliminate this cast
5048 // instruction...
Chris Lattner55d4bda2003-06-23 21:59:52 +00005049 if (CI.getType() == Src->getType())
5050 return ReplaceInstUsesWith(CI, Src);
Chris Lattner48a44f72002-05-02 17:06:02 +00005051
Chris Lattner81a7a232004-10-16 18:11:37 +00005052 if (isa<UndefValue>(Src)) // cast undef -> undef
5053 return ReplaceInstUsesWith(CI, UndefValue::get(CI.getType()));
5054
Chris Lattner48a44f72002-05-02 17:06:02 +00005055 // If casting the result of another cast instruction, try to eliminate this
5056 // one!
5057 //
Chris Lattner86102b82005-01-01 16:22:27 +00005058 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
5059 Value *A = CSrc->getOperand(0);
5060 if (isEliminableCastOfCast(A->getType(), CSrc->getType(),
5061 CI.getType(), TD)) {
Chris Lattner48a44f72002-05-02 17:06:02 +00005062 // This instruction now refers directly to the cast's src operand. This
5063 // has a good chance of making CSrc dead.
Chris Lattner113f4f42002-06-25 16:13:24 +00005064 CI.setOperand(0, CSrc->getOperand(0));
5065 return &CI;
Chris Lattner48a44f72002-05-02 17:06:02 +00005066 }
5067
Chris Lattner650b6da2002-08-02 20:00:25 +00005068 // If this is an A->B->A cast, and we are dealing with integral types, try
5069 // to convert this into a logical 'and' instruction.
5070 //
Misha Brukmanb1c93172005-04-21 23:48:37 +00005071 if (A->getType()->isInteger() &&
Chris Lattnerb0b412e2002-09-03 01:08:28 +00005072 CI.getType()->isInteger() && CSrc->getType()->isInteger() &&
Chris Lattner86102b82005-01-01 16:22:27 +00005073 CSrc->getType()->isUnsigned() && // B->A cast must zero extend
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005074 CSrc->getType()->getPrimitiveSizeInBits() <
5075 CI.getType()->getPrimitiveSizeInBits()&&
5076 A->getType()->getPrimitiveSizeInBits() ==
5077 CI.getType()->getPrimitiveSizeInBits()) {
Chris Lattner650b6da2002-08-02 20:00:25 +00005078 assert(CSrc->getType() != Type::ULongTy &&
5079 "Cannot have type bigger than ulong!");
Chris Lattner77defba2006-02-07 07:00:41 +00005080 uint64_t AndValue = CSrc->getType()->getIntegralTypeMask();
Chris Lattner86102b82005-01-01 16:22:27 +00005081 Constant *AndOp = ConstantUInt::get(A->getType()->getUnsignedVersion(),
5082 AndValue);
5083 AndOp = ConstantExpr::getCast(AndOp, A->getType());
5084 Instruction *And = BinaryOperator::createAnd(CSrc->getOperand(0), AndOp);
5085 if (And->getType() != CI.getType()) {
5086 And->setName(CSrc->getName()+".mask");
5087 InsertNewInstBefore(And, CI);
5088 And = new CastInst(And, CI.getType());
5089 }
5090 return And;
Chris Lattner650b6da2002-08-02 20:00:25 +00005091 }
5092 }
Chris Lattner2590e512006-02-07 06:56:34 +00005093
Chris Lattner03841652004-05-25 04:29:21 +00005094 // If this is a cast to bool, turn it into the appropriate setne instruction.
5095 if (CI.getType() == Type::BoolTy)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00005096 return BinaryOperator::createSetNE(CI.getOperand(0),
Chris Lattner03841652004-05-25 04:29:21 +00005097 Constant::getNullValue(CI.getOperand(0)->getType()));
5098
Chris Lattner2590e512006-02-07 06:56:34 +00005099 // See if we can simplify any instructions used by the LHS whose sole
5100 // purpose is to compute bits we don't care about.
Chris Lattner0157e7f2006-02-11 09:31:47 +00005101 if (CI.getType()->isInteger() && CI.getOperand(0)->getType()->isIntegral()) {
5102 uint64_t KnownZero, KnownOne;
5103 if (SimplifyDemandedBits(&CI, CI.getType()->getIntegralTypeMask(),
5104 KnownZero, KnownOne))
5105 return &CI;
5106 }
Chris Lattner2590e512006-02-07 06:56:34 +00005107
Chris Lattnerd0d51602003-06-21 23:12:02 +00005108 // If casting the result of a getelementptr instruction with no offset, turn
5109 // this into a cast of the original pointer!
5110 //
Chris Lattner55d4bda2003-06-23 21:59:52 +00005111 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattnerd0d51602003-06-21 23:12:02 +00005112 bool AllZeroOperands = true;
5113 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
5114 if (!isa<Constant>(GEP->getOperand(i)) ||
5115 !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
5116 AllZeroOperands = false;
5117 break;
5118 }
5119 if (AllZeroOperands) {
5120 CI.setOperand(0, GEP->getOperand(0));
5121 return &CI;
5122 }
5123 }
5124
Chris Lattnerf4ad1652003-11-02 05:57:39 +00005125 // If we are casting a malloc or alloca to a pointer to a type of the same
5126 // size, rewrite the allocation instruction to allocate the "right" type.
5127 //
5128 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
Chris Lattner216be912005-10-24 06:03:58 +00005129 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
5130 return V;
Chris Lattnerf4ad1652003-11-02 05:57:39 +00005131
Chris Lattner86102b82005-01-01 16:22:27 +00005132 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
5133 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
5134 return NV;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00005135 if (isa<PHINode>(Src))
5136 if (Instruction *NV = FoldOpIntoPhi(CI))
5137 return NV;
Chris Lattnerb19a5c62006-04-12 18:09:35 +00005138
5139 // If the source and destination are pointers, and this cast is equivalent to
5140 // a getelementptr X, 0, 0, 0... turn it into the appropriate getelementptr.
5141 // This can enhance SROA and other transforms that want type-safe pointers.
5142 if (const PointerType *DstPTy = dyn_cast<PointerType>(CI.getType()))
5143 if (const PointerType *SrcPTy = dyn_cast<PointerType>(Src->getType())) {
5144 const Type *DstTy = DstPTy->getElementType();
5145 const Type *SrcTy = SrcPTy->getElementType();
5146
5147 Constant *ZeroUInt = Constant::getNullValue(Type::UIntTy);
5148 unsigned NumZeros = 0;
5149 while (SrcTy != DstTy &&
5150 isa<CompositeType>(SrcTy) && !isa<PointerType>(SrcTy)) {
5151 SrcTy = cast<CompositeType>(SrcTy)->getTypeAtIndex(ZeroUInt);
5152 ++NumZeros;
5153 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00005154
Chris Lattnerb19a5c62006-04-12 18:09:35 +00005155 // If we found a path from the src to dest, create the getelementptr now.
5156 if (SrcTy == DstTy) {
5157 std::vector<Value*> Idxs(NumZeros+1, ZeroUInt);
5158 return new GetElementPtrInst(Src, Idxs);
5159 }
5160 }
5161
Chris Lattnerdfae8be2003-07-24 17:35:25 +00005162 // If the source value is an instruction with only this use, we can attempt to
5163 // propagate the cast into the instruction. Also, only handle integral types
5164 // for now.
Chris Lattner99155be2006-05-25 23:24:33 +00005165 if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
Chris Lattnerf95d9b92003-10-15 16:48:29 +00005166 if (SrcI->hasOneUse() && Src->getType()->isIntegral() &&
Chris Lattnerdfae8be2003-07-24 17:35:25 +00005167 CI.getType()->isInteger()) { // Don't mess with casts to bool here
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005168
5169 int NumCastsRemoved = 0;
5170 if (CanEvaluateInDifferentType(SrcI, CI.getType(), NumCastsRemoved)) {
5171 // If this cast is a truncate, evaluting in a different type always
5172 // eliminates the cast, so it is always a win. If this is a noop-cast
5173 // this just removes a noop cast which isn't pointful, but simplifies
5174 // the code. If this is a zero-extension, we need to do an AND to
5175 // maintain the clear top-part of the computation, so we require that
5176 // the input have eliminated at least one cast. If this is a sign
5177 // extension, we insert two new casts (to do the extension) so we
5178 // require that two casts have been eliminated.
5179 bool DoXForm;
5180 switch (getCastType(Src->getType(), CI.getType())) {
5181 default: assert(0 && "Unknown cast type!");
5182 case Noop:
5183 case Truncate:
5184 DoXForm = true;
5185 break;
5186 case Zeroext:
5187 DoXForm = NumCastsRemoved >= 1;
5188 break;
5189 case Signext:
5190 DoXForm = NumCastsRemoved >= 2;
5191 break;
5192 }
5193
5194 if (DoXForm) {
5195 Value *Res = EvaluateInDifferentType(SrcI, CI.getType());
5196 assert(Res->getType() == CI.getType());
5197 switch (getCastType(Src->getType(), CI.getType())) {
5198 default: assert(0 && "Unknown cast type!");
5199 case Noop:
5200 case Truncate:
5201 // Just replace this cast with the result.
5202 return ReplaceInstUsesWith(CI, Res);
5203 case Zeroext: {
5204 // We need to emit an AND to clear the high bits.
5205 unsigned SrcBitSize = Src->getType()->getPrimitiveSizeInBits();
5206 unsigned DestBitSize = CI.getType()->getPrimitiveSizeInBits();
5207 assert(SrcBitSize < DestBitSize && "Not a zext?");
5208 Constant *C = ConstantUInt::get(Type::ULongTy, (1 << SrcBitSize)-1);
5209 C = ConstantExpr::getCast(C, CI.getType());
5210 return BinaryOperator::createAnd(Res, C);
5211 }
5212 case Signext:
5213 // We need to emit a cast to truncate, then a cast to sext.
5214 return new CastInst(InsertCastBefore(Res, Src->getType(), CI),
5215 CI.getType());
5216 }
5217 }
5218 }
5219
Chris Lattnerdfae8be2003-07-24 17:35:25 +00005220 const Type *DestTy = CI.getType();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005221 unsigned SrcBitSize = Src->getType()->getPrimitiveSizeInBits();
5222 unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
Chris Lattnerdfae8be2003-07-24 17:35:25 +00005223
5224 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
5225 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
5226
5227 switch (SrcI->getOpcode()) {
5228 case Instruction::Add:
5229 case Instruction::Mul:
5230 case Instruction::And:
5231 case Instruction::Or:
5232 case Instruction::Xor:
5233 // If we are discarding information, or just changing the sign, rewrite.
5234 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
5235 // Don't insert two casts if they cannot be eliminated. We allow two
5236 // casts to be inserted if the sizes are the same. This could only be
5237 // converting signedness, which is a noop.
Chris Lattner11ffd592004-07-20 05:21:00 +00005238 if (DestBitSize == SrcBitSize || !ValueRequiresCast(Op1, DestTy,TD) ||
5239 !ValueRequiresCast(Op0, DestTy, TD)) {
Chris Lattnerdfae8be2003-07-24 17:35:25 +00005240 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
5241 Value *Op1c = InsertOperandCastBefore(Op1, DestTy, SrcI);
5242 return BinaryOperator::create(cast<BinaryOperator>(SrcI)
5243 ->getOpcode(), Op0c, Op1c);
5244 }
5245 }
Chris Lattner72086162005-05-06 02:07:39 +00005246
5247 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
5248 if (SrcBitSize == 1 && SrcI->getOpcode() == Instruction::Xor &&
5249 Op1 == ConstantBool::True &&
5250 (!Op0->hasOneUse() || !isa<SetCondInst>(Op0))) {
5251 Value *New = InsertOperandCastBefore(Op0, DestTy, &CI);
5252 return BinaryOperator::createXor(New,
5253 ConstantInt::get(CI.getType(), 1));
5254 }
Chris Lattnerdfae8be2003-07-24 17:35:25 +00005255 break;
5256 case Instruction::Shl:
5257 // Allow changing the sign of the source operand. Do not allow changing
5258 // the size of the shift, UNLESS the shift amount is a constant. We
5259 // mush not change variable sized shifts to a smaller size, because it
5260 // is undefined to shift more bits out than exist in the value.
5261 if (DestBitSize == SrcBitSize ||
5262 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
5263 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
5264 return new ShiftInst(Instruction::Shl, Op0c, Op1);
5265 }
5266 break;
Chris Lattner87380412005-05-06 04:18:52 +00005267 case Instruction::Shr:
5268 // If this is a signed shr, and if all bits shifted in are about to be
5269 // truncated off, turn it into an unsigned shr to allow greater
5270 // simplifications.
5271 if (DestBitSize < SrcBitSize && Src->getType()->isSigned() &&
5272 isa<ConstantInt>(Op1)) {
5273 unsigned ShiftAmt = cast<ConstantUInt>(Op1)->getValue();
5274 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
5275 // Convert to unsigned.
5276 Value *N1 = InsertOperandCastBefore(Op0,
5277 Op0->getType()->getUnsignedVersion(), &CI);
5278 // Insert the new shift, which is now unsigned.
5279 N1 = InsertNewInstBefore(new ShiftInst(Instruction::Shr, N1,
5280 Op1, Src->getName()), CI);
5281 return new CastInst(N1, CI.getType());
5282 }
5283 }
5284 break;
5285
Chris Lattnerc7bfed02006-02-27 02:38:23 +00005286 case Instruction::SetEQ:
Chris Lattner809dfac2005-05-04 19:10:26 +00005287 case Instruction::SetNE:
Chris Lattnerc7bfed02006-02-27 02:38:23 +00005288 // We if we are just checking for a seteq of a single bit and casting it
5289 // to an integer. If so, shift the bit to the appropriate place then
5290 // cast to integer to avoid the comparison.
Chris Lattner809dfac2005-05-04 19:10:26 +00005291 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerc7bfed02006-02-27 02:38:23 +00005292 uint64_t Op1CV = Op1C->getZExtValue();
5293 // cast (X == 0) to int --> X^1 iff X has only the low bit set.
5294 // cast (X == 0) to int --> (X>>1)^1 iff X has only the 2nd bit set.
5295 // cast (X == 1) to int --> X iff X has only the low bit set.
5296 // cast (X == 2) to int --> X>>1 iff X has only the 2nd bit set.
5297 // cast (X != 0) to int --> X iff X has only the low bit set.
5298 // cast (X != 0) to int --> X>>1 iff X has only the 2nd bit set.
5299 // cast (X != 1) to int --> X^1 iff X has only the low bit set.
5300 // cast (X != 2) to int --> (X>>1)^1 iff X has only the 2nd bit set.
5301 if (Op1CV == 0 || isPowerOf2_64(Op1CV)) {
5302 // If Op1C some other power of two, convert:
5303 uint64_t KnownZero, KnownOne;
5304 uint64_t TypeMask = Op1->getType()->getIntegralTypeMask();
5305 ComputeMaskedBits(Op0, TypeMask, KnownZero, KnownOne);
5306
5307 if (isPowerOf2_64(KnownZero^TypeMask)) { // Exactly one possible 1?
5308 bool isSetNE = SrcI->getOpcode() == Instruction::SetNE;
5309 if (Op1CV && (Op1CV != (KnownZero^TypeMask))) {
5310 // (X&4) == 2 --> false
5311 // (X&4) != 2 --> true
Chris Lattnerc5b6c9a2006-02-28 19:47:20 +00005312 Constant *Res = ConstantBool::get(isSetNE);
5313 Res = ConstantExpr::getCast(Res, CI.getType());
5314 return ReplaceInstUsesWith(CI, Res);
Chris Lattnerc7bfed02006-02-27 02:38:23 +00005315 }
5316
5317 unsigned ShiftAmt = Log2_64(KnownZero^TypeMask);
5318 Value *In = Op0;
5319 if (ShiftAmt) {
Chris Lattner4c2d3782005-05-06 01:53:19 +00005320 // Perform an unsigned shr by shiftamt. Convert input to
5321 // unsigned if it is signed.
Chris Lattner4c2d3782005-05-06 01:53:19 +00005322 if (In->getType()->isSigned())
5323 In = InsertNewInstBefore(new CastInst(In,
5324 In->getType()->getUnsignedVersion(), In->getName()),CI);
5325 // Insert the shift to put the result in the low bit.
5326 In = InsertNewInstBefore(new ShiftInst(Instruction::Shr, In,
Chris Lattnerc7bfed02006-02-27 02:38:23 +00005327 ConstantInt::get(Type::UByteTy, ShiftAmt),
5328 In->getName()+".lobit"), CI);
Chris Lattner4c2d3782005-05-06 01:53:19 +00005329 }
Chris Lattnerc7bfed02006-02-27 02:38:23 +00005330
5331 if ((Op1CV != 0) == isSetNE) { // Toggle the low bit.
5332 Constant *One = ConstantInt::get(In->getType(), 1);
5333 In = BinaryOperator::createXor(In, One, "tmp");
5334 InsertNewInstBefore(cast<Instruction>(In), CI);
Chris Lattner4c2d3782005-05-06 01:53:19 +00005335 }
Chris Lattnerc7bfed02006-02-27 02:38:23 +00005336
5337 if (CI.getType() == In->getType())
5338 return ReplaceInstUsesWith(CI, In);
5339 else
5340 return new CastInst(In, CI.getType());
Chris Lattner4c2d3782005-05-06 01:53:19 +00005341 }
Chris Lattner809dfac2005-05-04 19:10:26 +00005342 }
5343 }
5344 break;
Chris Lattnerdfae8be2003-07-24 17:35:25 +00005345 }
5346 }
Chris Lattner99155be2006-05-25 23:24:33 +00005347
5348 if (SrcI->hasOneUse()) {
5349 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(SrcI)) {
5350 // Okay, we have (cast (shuffle ..)). We know this cast is a bitconvert
5351 // because the inputs are known to be a vector. Check to see if this is
5352 // a cast to a vector with the same # elts.
5353 if (isa<PackedType>(CI.getType()) &&
5354 cast<PackedType>(CI.getType())->getNumElements() ==
5355 SVI->getType()->getNumElements()) {
5356 CastInst *Tmp;
5357 // If either of the operands is a cast from CI.getType(), then
5358 // evaluating the shuffle in the casted destination's type will allow
5359 // us to eliminate at least one cast.
5360 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
5361 Tmp->getOperand(0)->getType() == CI.getType()) ||
5362 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
Chris Lattner95cebb02006-06-06 22:26:02 +00005363 Tmp->getOperand(0)->getType() == CI.getType())) {
Chris Lattner99155be2006-05-25 23:24:33 +00005364 Value *LHS = InsertOperandCastBefore(SVI->getOperand(0),
5365 CI.getType(), &CI);
5366 Value *RHS = InsertOperandCastBefore(SVI->getOperand(1),
5367 CI.getType(), &CI);
5368 // Return a new shuffle vector. Use the same element ID's, as we
5369 // know the vector types match #elts.
5370 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
5371 }
5372 }
5373 }
5374 }
5375 }
Chris Lattnerbb171802005-10-27 05:53:56 +00005376
Chris Lattner260ab202002-04-18 17:39:14 +00005377 return 0;
Chris Lattnerca081252001-12-14 16:52:21 +00005378}
5379
Chris Lattner56e4d3d2004-04-09 23:46:01 +00005380/// GetSelectFoldableOperands - We want to turn code that looks like this:
5381/// %C = or %A, %B
5382/// %D = select %cond, %C, %A
5383/// into:
5384/// %C = select %cond, %B, 0
5385/// %D = or %A, %C
5386///
5387/// Assuming that the specified instruction is an operand to the select, return
5388/// a bitmask indicating which operands of this instruction are foldable if they
5389/// equal the other incoming value of the select.
5390///
5391static unsigned GetSelectFoldableOperands(Instruction *I) {
5392 switch (I->getOpcode()) {
5393 case Instruction::Add:
5394 case Instruction::Mul:
5395 case Instruction::And:
5396 case Instruction::Or:
5397 case Instruction::Xor:
5398 return 3; // Can fold through either operand.
5399 case Instruction::Sub: // Can only fold on the amount subtracted.
5400 case Instruction::Shl: // Can only fold on the shift amount.
5401 case Instruction::Shr:
Misha Brukmanb1c93172005-04-21 23:48:37 +00005402 return 1;
Chris Lattner56e4d3d2004-04-09 23:46:01 +00005403 default:
5404 return 0; // Cannot fold
5405 }
5406}
5407
5408/// GetSelectFoldableConstant - For the same transformation as the previous
5409/// function, return the identity constant that goes into the select.
5410static Constant *GetSelectFoldableConstant(Instruction *I) {
5411 switch (I->getOpcode()) {
5412 default: assert(0 && "This cannot happen!"); abort();
5413 case Instruction::Add:
5414 case Instruction::Sub:
5415 case Instruction::Or:
5416 case Instruction::Xor:
5417 return Constant::getNullValue(I->getType());
5418 case Instruction::Shl:
5419 case Instruction::Shr:
5420 return Constant::getNullValue(Type::UByteTy);
5421 case Instruction::And:
5422 return ConstantInt::getAllOnesValue(I->getType());
5423 case Instruction::Mul:
5424 return ConstantInt::get(I->getType(), 1);
5425 }
5426}
5427
Chris Lattner411336f2005-01-19 21:50:18 +00005428/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
5429/// have the same opcode and only one use each. Try to simplify this.
5430Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
5431 Instruction *FI) {
5432 if (TI->getNumOperands() == 1) {
5433 // If this is a non-volatile load or a cast from the same type,
5434 // merge.
5435 if (TI->getOpcode() == Instruction::Cast) {
5436 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
5437 return 0;
5438 } else {
5439 return 0; // unknown unary op.
5440 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00005441
Chris Lattner411336f2005-01-19 21:50:18 +00005442 // Fold this by inserting a select from the input values.
5443 SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
5444 FI->getOperand(0), SI.getName()+".v");
5445 InsertNewInstBefore(NewSI, SI);
5446 return new CastInst(NewSI, TI->getType());
5447 }
5448
5449 // Only handle binary operators here.
5450 if (!isa<ShiftInst>(TI) && !isa<BinaryOperator>(TI))
5451 return 0;
5452
5453 // Figure out if the operations have any operands in common.
5454 Value *MatchOp, *OtherOpT, *OtherOpF;
5455 bool MatchIsOpZero;
5456 if (TI->getOperand(0) == FI->getOperand(0)) {
5457 MatchOp = TI->getOperand(0);
5458 OtherOpT = TI->getOperand(1);
5459 OtherOpF = FI->getOperand(1);
5460 MatchIsOpZero = true;
5461 } else if (TI->getOperand(1) == FI->getOperand(1)) {
5462 MatchOp = TI->getOperand(1);
5463 OtherOpT = TI->getOperand(0);
5464 OtherOpF = FI->getOperand(0);
5465 MatchIsOpZero = false;
5466 } else if (!TI->isCommutative()) {
5467 return 0;
5468 } else if (TI->getOperand(0) == FI->getOperand(1)) {
5469 MatchOp = TI->getOperand(0);
5470 OtherOpT = TI->getOperand(1);
5471 OtherOpF = FI->getOperand(0);
5472 MatchIsOpZero = true;
5473 } else if (TI->getOperand(1) == FI->getOperand(0)) {
5474 MatchOp = TI->getOperand(1);
5475 OtherOpT = TI->getOperand(0);
5476 OtherOpF = FI->getOperand(1);
5477 MatchIsOpZero = true;
5478 } else {
5479 return 0;
5480 }
5481
5482 // If we reach here, they do have operations in common.
5483 SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
5484 OtherOpF, SI.getName()+".v");
5485 InsertNewInstBefore(NewSI, SI);
5486
5487 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
5488 if (MatchIsOpZero)
5489 return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
5490 else
5491 return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
5492 } else {
5493 if (MatchIsOpZero)
5494 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), MatchOp, NewSI);
5495 else
5496 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), NewSI, MatchOp);
5497 }
5498}
5499
Chris Lattnerb909e8b2004-03-12 05:52:32 +00005500Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattner533bc492004-03-30 19:37:13 +00005501 Value *CondVal = SI.getCondition();
5502 Value *TrueVal = SI.getTrueValue();
5503 Value *FalseVal = SI.getFalseValue();
5504
5505 // select true, X, Y -> X
5506 // select false, X, Y -> Y
5507 if (ConstantBool *C = dyn_cast<ConstantBool>(CondVal))
Chris Lattnerb909e8b2004-03-12 05:52:32 +00005508 if (C == ConstantBool::True)
Chris Lattner533bc492004-03-30 19:37:13 +00005509 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattnerb909e8b2004-03-12 05:52:32 +00005510 else {
5511 assert(C == ConstantBool::False);
Chris Lattner533bc492004-03-30 19:37:13 +00005512 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattnerb909e8b2004-03-12 05:52:32 +00005513 }
Chris Lattner533bc492004-03-30 19:37:13 +00005514
5515 // select C, X, X -> X
5516 if (TrueVal == FalseVal)
5517 return ReplaceInstUsesWith(SI, TrueVal);
5518
Chris Lattner81a7a232004-10-16 18:11:37 +00005519 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
5520 return ReplaceInstUsesWith(SI, FalseVal);
5521 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
5522 return ReplaceInstUsesWith(SI, TrueVal);
5523 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
5524 if (isa<Constant>(TrueVal))
5525 return ReplaceInstUsesWith(SI, TrueVal);
5526 else
5527 return ReplaceInstUsesWith(SI, FalseVal);
5528 }
5529
Chris Lattner1c631e82004-04-08 04:43:23 +00005530 if (SI.getType() == Type::BoolTy)
5531 if (ConstantBool *C = dyn_cast<ConstantBool>(TrueVal)) {
5532 if (C == ConstantBool::True) {
5533 // Change: A = select B, true, C --> A = or B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00005534 return BinaryOperator::createOr(CondVal, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00005535 } else {
5536 // Change: A = select B, false, C --> A = and !B, C
5537 Value *NotCond =
5538 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
5539 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00005540 return BinaryOperator::createAnd(NotCond, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00005541 }
5542 } else if (ConstantBool *C = dyn_cast<ConstantBool>(FalseVal)) {
5543 if (C == ConstantBool::False) {
5544 // Change: A = select B, C, false --> A = and B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00005545 return BinaryOperator::createAnd(CondVal, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00005546 } else {
5547 // Change: A = select B, C, true --> A = or !B, C
5548 Value *NotCond =
5549 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
5550 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00005551 return BinaryOperator::createOr(NotCond, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00005552 }
5553 }
5554
Chris Lattner183b3362004-04-09 19:05:30 +00005555 // Selecting between two integer constants?
5556 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
5557 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
5558 // select C, 1, 0 -> cast C to int
5559 if (FalseValC->isNullValue() && TrueValC->getRawValue() == 1) {
5560 return new CastInst(CondVal, SI.getType());
5561 } else if (TrueValC->isNullValue() && FalseValC->getRawValue() == 1) {
5562 // select C, 0, 1 -> cast !C to int
5563 Value *NotCond =
5564 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
Chris Lattnercf7baf32004-04-09 18:19:44 +00005565 "not."+CondVal->getName()), SI);
Chris Lattner183b3362004-04-09 19:05:30 +00005566 return new CastInst(NotCond, SI.getType());
Chris Lattnercf7baf32004-04-09 18:19:44 +00005567 }
Chris Lattner35167c32004-06-09 07:59:58 +00005568
5569 // If one of the constants is zero (we know they can't both be) and we
5570 // have a setcc instruction with zero, and we have an 'and' with the
5571 // non-constant value, eliminate this whole mess. This corresponds to
5572 // cases like this: ((X & 27) ? 27 : 0)
5573 if (TrueValC->isNullValue() || FalseValC->isNullValue())
5574 if (Instruction *IC = dyn_cast<Instruction>(SI.getCondition()))
5575 if ((IC->getOpcode() == Instruction::SetEQ ||
5576 IC->getOpcode() == Instruction::SetNE) &&
5577 isa<ConstantInt>(IC->getOperand(1)) &&
5578 cast<Constant>(IC->getOperand(1))->isNullValue())
5579 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
5580 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00005581 isa<ConstantInt>(ICA->getOperand(1)) &&
5582 (ICA->getOperand(1) == TrueValC ||
5583 ICA->getOperand(1) == FalseValC) &&
Chris Lattner35167c32004-06-09 07:59:58 +00005584 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
5585 // Okay, now we know that everything is set up, we just don't
5586 // know whether we have a setne or seteq and whether the true or
5587 // false val is the zero.
5588 bool ShouldNotVal = !TrueValC->isNullValue();
5589 ShouldNotVal ^= IC->getOpcode() == Instruction::SetNE;
5590 Value *V = ICA;
5591 if (ShouldNotVal)
5592 V = InsertNewInstBefore(BinaryOperator::create(
5593 Instruction::Xor, V, ICA->getOperand(1)), SI);
5594 return ReplaceInstUsesWith(SI, V);
5595 }
Chris Lattner533bc492004-03-30 19:37:13 +00005596 }
Chris Lattner623fba12004-04-10 22:21:27 +00005597
5598 // See if we are selecting two values based on a comparison of the two values.
5599 if (SetCondInst *SCI = dyn_cast<SetCondInst>(CondVal)) {
5600 if (SCI->getOperand(0) == TrueVal && SCI->getOperand(1) == FalseVal) {
5601 // Transform (X == Y) ? X : Y -> Y
5602 if (SCI->getOpcode() == Instruction::SetEQ)
5603 return ReplaceInstUsesWith(SI, FalseVal);
5604 // Transform (X != Y) ? X : Y -> X
5605 if (SCI->getOpcode() == Instruction::SetNE)
5606 return ReplaceInstUsesWith(SI, TrueVal);
5607 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
5608
5609 } else if (SCI->getOperand(0) == FalseVal && SCI->getOperand(1) == TrueVal){
5610 // Transform (X == Y) ? Y : X -> X
5611 if (SCI->getOpcode() == Instruction::SetEQ)
Chris Lattner24cf0202004-04-11 01:39:19 +00005612 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattner623fba12004-04-10 22:21:27 +00005613 // Transform (X != Y) ? Y : X -> Y
5614 if (SCI->getOpcode() == Instruction::SetNE)
Chris Lattner24cf0202004-04-11 01:39:19 +00005615 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattner623fba12004-04-10 22:21:27 +00005616 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
5617 }
5618 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00005619
Chris Lattnera04c9042005-01-13 22:52:24 +00005620 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
5621 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
5622 if (TI->hasOneUse() && FI->hasOneUse()) {
5623 bool isInverse = false;
5624 Instruction *AddOp = 0, *SubOp = 0;
5625
Chris Lattner411336f2005-01-19 21:50:18 +00005626 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
5627 if (TI->getOpcode() == FI->getOpcode())
5628 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
5629 return IV;
5630
5631 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
5632 // even legal for FP.
Chris Lattnera04c9042005-01-13 22:52:24 +00005633 if (TI->getOpcode() == Instruction::Sub &&
5634 FI->getOpcode() == Instruction::Add) {
5635 AddOp = FI; SubOp = TI;
5636 } else if (FI->getOpcode() == Instruction::Sub &&
5637 TI->getOpcode() == Instruction::Add) {
5638 AddOp = TI; SubOp = FI;
5639 }
5640
5641 if (AddOp) {
5642 Value *OtherAddOp = 0;
5643 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
5644 OtherAddOp = AddOp->getOperand(1);
5645 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
5646 OtherAddOp = AddOp->getOperand(0);
5647 }
5648
5649 if (OtherAddOp) {
Chris Lattnerb580d262006-02-24 18:05:58 +00005650 // So at this point we know we have (Y -> OtherAddOp):
5651 // select C, (add X, Y), (sub X, Z)
5652 Value *NegVal; // Compute -Z
5653 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
5654 NegVal = ConstantExpr::getNeg(C);
5655 } else {
5656 NegVal = InsertNewInstBefore(
5657 BinaryOperator::createNeg(SubOp->getOperand(1), "tmp"), SI);
Chris Lattnera04c9042005-01-13 22:52:24 +00005658 }
Chris Lattnerb580d262006-02-24 18:05:58 +00005659
5660 Value *NewTrueOp = OtherAddOp;
5661 Value *NewFalseOp = NegVal;
5662 if (AddOp != TI)
5663 std::swap(NewTrueOp, NewFalseOp);
5664 Instruction *NewSel =
5665 new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
5666
5667 NewSel = InsertNewInstBefore(NewSel, SI);
5668 return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
Chris Lattnera04c9042005-01-13 22:52:24 +00005669 }
5670 }
5671 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00005672
Chris Lattner56e4d3d2004-04-09 23:46:01 +00005673 // See if we can fold the select into one of our operands.
5674 if (SI.getType()->isInteger()) {
5675 // See the comment above GetSelectFoldableOperands for a description of the
5676 // transformation we are doing here.
5677 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
5678 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
5679 !isa<Constant>(FalseVal))
5680 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
5681 unsigned OpToFold = 0;
5682 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
5683 OpToFold = 1;
5684 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
5685 OpToFold = 2;
5686 }
5687
5688 if (OpToFold) {
5689 Constant *C = GetSelectFoldableConstant(TVI);
5690 std::string Name = TVI->getName(); TVI->setName("");
5691 Instruction *NewSel =
5692 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C,
5693 Name);
5694 InsertNewInstBefore(NewSel, SI);
5695 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
5696 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
5697 else if (ShiftInst *SI = dyn_cast<ShiftInst>(TVI))
5698 return new ShiftInst(SI->getOpcode(), FalseVal, NewSel);
5699 else {
5700 assert(0 && "Unknown instruction!!");
5701 }
5702 }
5703 }
Chris Lattner6862fbd2004-09-29 17:40:11 +00005704
Chris Lattner56e4d3d2004-04-09 23:46:01 +00005705 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
5706 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
5707 !isa<Constant>(TrueVal))
5708 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
5709 unsigned OpToFold = 0;
5710 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
5711 OpToFold = 1;
5712 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
5713 OpToFold = 2;
5714 }
5715
5716 if (OpToFold) {
5717 Constant *C = GetSelectFoldableConstant(FVI);
5718 std::string Name = FVI->getName(); FVI->setName("");
5719 Instruction *NewSel =
5720 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold),
5721 Name);
5722 InsertNewInstBefore(NewSel, SI);
5723 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
5724 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
5725 else if (ShiftInst *SI = dyn_cast<ShiftInst>(FVI))
5726 return new ShiftInst(SI->getOpcode(), TrueVal, NewSel);
5727 else {
5728 assert(0 && "Unknown instruction!!");
5729 }
5730 }
5731 }
5732 }
Chris Lattnerd6f636a2005-04-24 07:30:14 +00005733
5734 if (BinaryOperator::isNot(CondVal)) {
5735 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
5736 SI.setOperand(1, FalseVal);
5737 SI.setOperand(2, TrueVal);
5738 return &SI;
5739 }
5740
Chris Lattnerb909e8b2004-03-12 05:52:32 +00005741 return 0;
5742}
5743
Chris Lattner82f2ef22006-03-06 20:18:44 +00005744/// GetKnownAlignment - If the specified pointer has an alignment that we can
5745/// determine, return it, otherwise return 0.
5746static unsigned GetKnownAlignment(Value *V, TargetData *TD) {
5747 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
5748 unsigned Align = GV->getAlignment();
5749 if (Align == 0 && TD)
5750 Align = TD->getTypeAlignment(GV->getType()->getElementType());
5751 return Align;
5752 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
5753 unsigned Align = AI->getAlignment();
5754 if (Align == 0 && TD) {
5755 if (isa<AllocaInst>(AI))
5756 Align = TD->getTypeAlignment(AI->getType()->getElementType());
5757 else if (isa<MallocInst>(AI)) {
5758 // Malloc returns maximally aligned memory.
5759 Align = TD->getTypeAlignment(AI->getType()->getElementType());
5760 Align = std::max(Align, (unsigned)TD->getTypeAlignment(Type::DoubleTy));
5761 Align = std::max(Align, (unsigned)TD->getTypeAlignment(Type::LongTy));
5762 }
5763 }
5764 return Align;
Chris Lattner53ef5a02006-03-07 01:28:57 +00005765 } else if (isa<CastInst>(V) ||
5766 (isa<ConstantExpr>(V) &&
5767 cast<ConstantExpr>(V)->getOpcode() == Instruction::Cast)) {
5768 User *CI = cast<User>(V);
Chris Lattner82f2ef22006-03-06 20:18:44 +00005769 if (isa<PointerType>(CI->getOperand(0)->getType()))
5770 return GetKnownAlignment(CI->getOperand(0), TD);
5771 return 0;
Chris Lattner53ef5a02006-03-07 01:28:57 +00005772 } else if (isa<GetElementPtrInst>(V) ||
5773 (isa<ConstantExpr>(V) &&
5774 cast<ConstantExpr>(V)->getOpcode()==Instruction::GetElementPtr)) {
5775 User *GEPI = cast<User>(V);
Chris Lattner82f2ef22006-03-06 20:18:44 +00005776 unsigned BaseAlignment = GetKnownAlignment(GEPI->getOperand(0), TD);
5777 if (BaseAlignment == 0) return 0;
5778
5779 // If all indexes are zero, it is just the alignment of the base pointer.
5780 bool AllZeroOperands = true;
5781 for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
5782 if (!isa<Constant>(GEPI->getOperand(i)) ||
5783 !cast<Constant>(GEPI->getOperand(i))->isNullValue()) {
5784 AllZeroOperands = false;
5785 break;
5786 }
5787 if (AllZeroOperands)
5788 return BaseAlignment;
5789
5790 // Otherwise, if the base alignment is >= the alignment we expect for the
5791 // base pointer type, then we know that the resultant pointer is aligned at
5792 // least as much as its type requires.
5793 if (!TD) return 0;
5794
5795 const Type *BasePtrTy = GEPI->getOperand(0)->getType();
5796 if (TD->getTypeAlignment(cast<PointerType>(BasePtrTy)->getElementType())
Chris Lattner53ef5a02006-03-07 01:28:57 +00005797 <= BaseAlignment) {
5798 const Type *GEPTy = GEPI->getType();
5799 return TD->getTypeAlignment(cast<PointerType>(GEPTy)->getElementType());
5800 }
Chris Lattner82f2ef22006-03-06 20:18:44 +00005801 return 0;
5802 }
5803 return 0;
5804}
5805
Chris Lattnerb909e8b2004-03-12 05:52:32 +00005806
Chris Lattnerc66b2232006-01-13 20:11:04 +00005807/// visitCallInst - CallInst simplification. This mostly only handles folding
5808/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
5809/// the heavy lifting.
5810///
Chris Lattner970c33a2003-06-19 17:00:31 +00005811Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattnerc66b2232006-01-13 20:11:04 +00005812 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
5813 if (!II) return visitCallSite(&CI);
5814
Chris Lattner51ea1272004-02-28 05:22:00 +00005815 // Intrinsics cannot occur in an invoke, so handle them here instead of in
5816 // visitCallSite.
Chris Lattnerc66b2232006-01-13 20:11:04 +00005817 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner00648e12004-10-12 04:52:52 +00005818 bool Changed = false;
5819
5820 // memmove/cpy/set of zero bytes is a noop.
5821 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
5822 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
5823
Chris Lattner00648e12004-10-12 04:52:52 +00005824 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
5825 if (CI->getRawValue() == 1) {
5826 // Replace the instruction with just byte operations. We would
5827 // transform other cases to loads/stores, but we don't know if
5828 // alignment is sufficient.
5829 }
Chris Lattner51ea1272004-02-28 05:22:00 +00005830 }
5831
Chris Lattner00648e12004-10-12 04:52:52 +00005832 // If we have a memmove and the source operation is a constant global,
5833 // then the source and dest pointers can't alias, so we can change this
5834 // into a call to memcpy.
Chris Lattner82f2ef22006-03-06 20:18:44 +00005835 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(II)) {
Chris Lattner00648e12004-10-12 04:52:52 +00005836 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
5837 if (GVSrc->isConstant()) {
5838 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner681ef2f2006-03-03 01:34:17 +00005839 const char *Name;
5840 if (CI.getCalledFunction()->getFunctionType()->getParamType(3) ==
5841 Type::UIntTy)
5842 Name = "llvm.memcpy.i32";
5843 else
5844 Name = "llvm.memcpy.i64";
5845 Function *MemCpy = M->getOrInsertFunction(Name,
Chris Lattner00648e12004-10-12 04:52:52 +00005846 CI.getCalledFunction()->getFunctionType());
5847 CI.setOperand(0, MemCpy);
5848 Changed = true;
5849 }
Chris Lattner82f2ef22006-03-06 20:18:44 +00005850 }
Chris Lattner00648e12004-10-12 04:52:52 +00005851
Chris Lattner82f2ef22006-03-06 20:18:44 +00005852 // If we can determine a pointer alignment that is bigger than currently
5853 // set, update the alignment.
5854 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
5855 unsigned Alignment1 = GetKnownAlignment(MI->getOperand(1), TD);
5856 unsigned Alignment2 = GetKnownAlignment(MI->getOperand(2), TD);
5857 unsigned Align = std::min(Alignment1, Alignment2);
5858 if (MI->getAlignment()->getRawValue() < Align) {
5859 MI->setAlignment(ConstantUInt::get(Type::UIntTy, Align));
5860 Changed = true;
5861 }
5862 } else if (isa<MemSetInst>(MI)) {
5863 unsigned Alignment = GetKnownAlignment(MI->getDest(), TD);
5864 if (MI->getAlignment()->getRawValue() < Alignment) {
5865 MI->setAlignment(ConstantUInt::get(Type::UIntTy, Alignment));
5866 Changed = true;
5867 }
5868 }
5869
Chris Lattnerc66b2232006-01-13 20:11:04 +00005870 if (Changed) return II;
Chris Lattner503221f2006-01-13 21:28:09 +00005871 } else {
5872 switch (II->getIntrinsicID()) {
5873 default: break;
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00005874 case Intrinsic::ppc_altivec_lvx:
5875 case Intrinsic::ppc_altivec_lvxl:
Chris Lattner36dd7c92006-04-17 22:26:56 +00005876 case Intrinsic::x86_sse_loadu_ps:
5877 case Intrinsic::x86_sse2_loadu_pd:
5878 case Intrinsic::x86_sse2_loadu_dq:
5879 // Turn PPC lvx -> load if the pointer is known aligned.
5880 // Turn X86 loadups -> load if the pointer is known aligned.
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00005881 if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
Chris Lattnere79d2492006-04-06 19:19:17 +00005882 Value *Ptr = InsertCastBefore(II->getOperand(1),
5883 PointerType::get(II->getType()), CI);
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00005884 return new LoadInst(Ptr);
5885 }
5886 break;
5887 case Intrinsic::ppc_altivec_stvx:
5888 case Intrinsic::ppc_altivec_stvxl:
5889 // Turn stvx -> store if the pointer is known aligned.
5890 if (GetKnownAlignment(II->getOperand(2), TD) >= 16) {
Chris Lattnere79d2492006-04-06 19:19:17 +00005891 const Type *OpPtrTy = PointerType::get(II->getOperand(1)->getType());
5892 Value *Ptr = InsertCastBefore(II->getOperand(2), OpPtrTy, CI);
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00005893 return new StoreInst(II->getOperand(1), Ptr);
5894 }
5895 break;
Chris Lattner36dd7c92006-04-17 22:26:56 +00005896 case Intrinsic::x86_sse_storeu_ps:
5897 case Intrinsic::x86_sse2_storeu_pd:
5898 case Intrinsic::x86_sse2_storeu_dq:
5899 case Intrinsic::x86_sse2_storel_dq:
5900 // Turn X86 storeu -> store if the pointer is known aligned.
5901 if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
5902 const Type *OpPtrTy = PointerType::get(II->getOperand(2)->getType());
5903 Value *Ptr = InsertCastBefore(II->getOperand(1), OpPtrTy, CI);
5904 return new StoreInst(II->getOperand(2), Ptr);
5905 }
5906 break;
Chris Lattnere79d2492006-04-06 19:19:17 +00005907 case Intrinsic::ppc_altivec_vperm:
5908 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
5909 if (ConstantPacked *Mask = dyn_cast<ConstantPacked>(II->getOperand(3))) {
5910 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
5911
5912 // Check that all of the elements are integer constants or undefs.
5913 bool AllEltsOk = true;
5914 for (unsigned i = 0; i != 16; ++i) {
5915 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
5916 !isa<UndefValue>(Mask->getOperand(i))) {
5917 AllEltsOk = false;
5918 break;
5919 }
5920 }
5921
5922 if (AllEltsOk) {
5923 // Cast the input vectors to byte vectors.
5924 Value *Op0 = InsertCastBefore(II->getOperand(1), Mask->getType(), CI);
5925 Value *Op1 = InsertCastBefore(II->getOperand(2), Mask->getType(), CI);
5926 Value *Result = UndefValue::get(Op0->getType());
5927
5928 // Only extract each element once.
5929 Value *ExtractedElts[32];
5930 memset(ExtractedElts, 0, sizeof(ExtractedElts));
5931
5932 for (unsigned i = 0; i != 16; ++i) {
5933 if (isa<UndefValue>(Mask->getOperand(i)))
5934 continue;
5935 unsigned Idx =cast<ConstantInt>(Mask->getOperand(i))->getRawValue();
5936 Idx &= 31; // Match the hardware behavior.
5937
5938 if (ExtractedElts[Idx] == 0) {
5939 Instruction *Elt =
5940 new ExtractElementInst(Idx < 16 ? Op0 : Op1,
5941 ConstantUInt::get(Type::UIntTy, Idx&15),
5942 "tmp");
5943 InsertNewInstBefore(Elt, CI);
5944 ExtractedElts[Idx] = Elt;
5945 }
5946
5947 // Insert this value into the result vector.
5948 Result = new InsertElementInst(Result, ExtractedElts[Idx],
5949 ConstantUInt::get(Type::UIntTy, i),
5950 "tmp");
5951 InsertNewInstBefore(cast<Instruction>(Result), CI);
5952 }
5953 return new CastInst(Result, CI.getType());
5954 }
5955 }
5956 break;
5957
Chris Lattner503221f2006-01-13 21:28:09 +00005958 case Intrinsic::stackrestore: {
5959 // If the save is right next to the restore, remove the restore. This can
5960 // happen when variable allocas are DCE'd.
5961 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
5962 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
5963 BasicBlock::iterator BI = SS;
5964 if (&*++BI == II)
5965 return EraseInstFromFunction(CI);
5966 }
5967 }
5968
5969 // If the stack restore is in a return/unwind block and if there are no
5970 // allocas or calls between the restore and the return, nuke the restore.
5971 TerminatorInst *TI = II->getParent()->getTerminator();
5972 if (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)) {
5973 BasicBlock::iterator BI = II;
5974 bool CannotRemove = false;
5975 for (++BI; &*BI != TI; ++BI) {
5976 if (isa<AllocaInst>(BI) ||
5977 (isa<CallInst>(BI) && !isa<IntrinsicInst>(BI))) {
5978 CannotRemove = true;
5979 break;
5980 }
5981 }
5982 if (!CannotRemove)
5983 return EraseInstFromFunction(CI);
5984 }
5985 break;
5986 }
5987 }
Chris Lattner00648e12004-10-12 04:52:52 +00005988 }
5989
Chris Lattnerc66b2232006-01-13 20:11:04 +00005990 return visitCallSite(II);
Chris Lattner970c33a2003-06-19 17:00:31 +00005991}
5992
5993// InvokeInst simplification
5994//
5995Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattneraec3d942003-10-07 22:32:43 +00005996 return visitCallSite(&II);
Chris Lattner970c33a2003-06-19 17:00:31 +00005997}
5998
Chris Lattneraec3d942003-10-07 22:32:43 +00005999// visitCallSite - Improvements for call and invoke instructions.
6000//
6001Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner75b4d1d2003-10-07 22:54:13 +00006002 bool Changed = false;
6003
6004 // If the callee is a constexpr cast of a function, attempt to move the cast
6005 // to the arguments of the call/invoke.
Chris Lattneraec3d942003-10-07 22:32:43 +00006006 if (transformConstExprCastCall(CS)) return 0;
6007
Chris Lattner75b4d1d2003-10-07 22:54:13 +00006008 Value *Callee = CS.getCalledValue();
Chris Lattner81a7a232004-10-16 18:11:37 +00006009
Chris Lattner61d9d812005-05-13 07:09:09 +00006010 if (Function *CalleeF = dyn_cast<Function>(Callee))
6011 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
6012 Instruction *OldCall = CS.getInstruction();
6013 // If the call and callee calling conventions don't match, this call must
6014 // be unreachable, as the call is undefined.
6015 new StoreInst(ConstantBool::True,
6016 UndefValue::get(PointerType::get(Type::BoolTy)), OldCall);
6017 if (!OldCall->use_empty())
6018 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
6019 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
6020 return EraseInstFromFunction(*OldCall);
6021 return 0;
6022 }
6023
Chris Lattner8ba9ec92004-10-18 02:59:09 +00006024 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
6025 // This instruction is not reachable, just remove it. We insert a store to
6026 // undef so that we know that this code is not reachable, despite the fact
6027 // that we can't modify the CFG here.
6028 new StoreInst(ConstantBool::True,
6029 UndefValue::get(PointerType::get(Type::BoolTy)),
6030 CS.getInstruction());
6031
6032 if (!CS.getInstruction()->use_empty())
6033 CS.getInstruction()->
6034 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
6035
6036 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
6037 // Don't break the CFG, insert a dummy cond branch.
6038 new BranchInst(II->getNormalDest(), II->getUnwindDest(),
6039 ConstantBool::True, II);
Chris Lattner81a7a232004-10-16 18:11:37 +00006040 }
Chris Lattner8ba9ec92004-10-18 02:59:09 +00006041 return EraseInstFromFunction(*CS.getInstruction());
6042 }
Chris Lattner81a7a232004-10-16 18:11:37 +00006043
Chris Lattner75b4d1d2003-10-07 22:54:13 +00006044 const PointerType *PTy = cast<PointerType>(Callee->getType());
6045 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
6046 if (FTy->isVarArg()) {
6047 // See if we can optimize any arguments passed through the varargs area of
6048 // the call.
6049 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
6050 E = CS.arg_end(); I != E; ++I)
6051 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
6052 // If this cast does not effect the value passed through the varargs
6053 // area, we can eliminate the use of the cast.
6054 Value *Op = CI->getOperand(0);
6055 if (CI->getType()->isLosslesslyConvertibleTo(Op->getType())) {
6056 *I = Op;
6057 Changed = true;
6058 }
6059 }
6060 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00006061
Chris Lattner75b4d1d2003-10-07 22:54:13 +00006062 return Changed ? CS.getInstruction() : 0;
Chris Lattneraec3d942003-10-07 22:32:43 +00006063}
6064
Chris Lattner970c33a2003-06-19 17:00:31 +00006065// transformConstExprCastCall - If the callee is a constexpr cast of a function,
6066// attempt to move the cast to the arguments of the call/invoke.
6067//
6068bool InstCombiner::transformConstExprCastCall(CallSite CS) {
6069 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
6070 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Chris Lattnerf3edc492004-07-18 18:59:44 +00006071 if (CE->getOpcode() != Instruction::Cast || !isa<Function>(CE->getOperand(0)))
Chris Lattner970c33a2003-06-19 17:00:31 +00006072 return false;
Reid Spencer87436872004-07-18 00:38:32 +00006073 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner970c33a2003-06-19 17:00:31 +00006074 Instruction *Caller = CS.getInstruction();
6075
6076 // Okay, this is a cast from a function to a different type. Unless doing so
6077 // would cause a type conversion of one of our arguments, change this call to
6078 // be a direct call with arguments casted to the appropriate types.
6079 //
6080 const FunctionType *FT = Callee->getFunctionType();
6081 const Type *OldRetTy = Caller->getType();
6082
Chris Lattner1f7942f2004-01-14 06:06:08 +00006083 // Check to see if we are changing the return type...
6084 if (OldRetTy != FT->getReturnType()) {
6085 if (Callee->isExternal() &&
Andrew Lenharth61eae292006-04-20 14:56:47 +00006086 !(OldRetTy->isLosslesslyConvertibleTo(FT->getReturnType()) ||
6087 (isa<PointerType>(FT->getReturnType()) &&
Andrew Lenharthf89e6302006-04-20 15:41:37 +00006088 TD->getIntPtrType()->isLosslesslyConvertibleTo(OldRetTy)))
Andrew Lenharth61eae292006-04-20 14:56:47 +00006089 && !Caller->use_empty())
Chris Lattner1f7942f2004-01-14 06:06:08 +00006090 return false; // Cannot transform this return value...
6091
6092 // If the callsite is an invoke instruction, and the return value is used by
6093 // a PHI node in a successor, we cannot change the return type of the call
6094 // because there is no place to put the cast instruction (without breaking
6095 // the critical edge). Bail out in this case.
6096 if (!Caller->use_empty())
6097 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
6098 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
6099 UI != E; ++UI)
6100 if (PHINode *PN = dyn_cast<PHINode>(*UI))
6101 if (PN->getParent() == II->getNormalDest() ||
Chris Lattnerfae8ab32004-02-08 21:44:31 +00006102 PN->getParent() == II->getUnwindDest())
Chris Lattner1f7942f2004-01-14 06:06:08 +00006103 return false;
6104 }
Chris Lattner970c33a2003-06-19 17:00:31 +00006105
6106 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
6107 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanb1c93172005-04-21 23:48:37 +00006108
Chris Lattner970c33a2003-06-19 17:00:31 +00006109 CallSite::arg_iterator AI = CS.arg_begin();
6110 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
6111 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthebfa24e2006-06-28 01:01:52 +00006112 const Type *ActTy = (*AI)->getType();
6113 ConstantSInt* c = dyn_cast<ConstantSInt>(*AI);
6114 //Either we can cast directly, or we can upconvert the argument
6115 bool isConvertible = ActTy->isLosslesslyConvertibleTo(ParamTy) ||
6116 (ParamTy->isIntegral() && ActTy->isIntegral() &&
6117 ParamTy->isSigned() == ActTy->isSigned() &&
6118 ParamTy->getPrimitiveSize() >= ActTy->getPrimitiveSize()) ||
6119 (c && ParamTy->getPrimitiveSize() >= ActTy->getPrimitiveSize() &&
6120 c->getValue() > 0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00006121 if (Callee->isExternal() && !isConvertible) return false;
Chris Lattner970c33a2003-06-19 17:00:31 +00006122 }
6123
6124 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
6125 Callee->isExternal())
6126 return false; // Do not delete arguments unless we have a function body...
6127
6128 // Okay, we decided that this is a safe thing to do: go ahead and start
6129 // inserting cast instructions as necessary...
6130 std::vector<Value*> Args;
6131 Args.reserve(NumActualArgs);
6132
6133 AI = CS.arg_begin();
6134 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
6135 const Type *ParamTy = FT->getParamType(i);
6136 if ((*AI)->getType() == ParamTy) {
6137 Args.push_back(*AI);
6138 } else {
Chris Lattner1c631e82004-04-08 04:43:23 +00006139 Args.push_back(InsertNewInstBefore(new CastInst(*AI, ParamTy, "tmp"),
6140 *Caller));
Chris Lattner970c33a2003-06-19 17:00:31 +00006141 }
6142 }
6143
6144 // If the function takes more arguments than the call was taking, add them
6145 // now...
6146 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
6147 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
6148
6149 // If we are removing arguments to the function, emit an obnoxious warning...
6150 if (FT->getNumParams() < NumActualArgs)
6151 if (!FT->isVarArg()) {
6152 std::cerr << "WARNING: While resolving call to function '"
6153 << Callee->getName() << "' arguments were dropped!\n";
6154 } else {
6155 // Add all of the arguments in their promoted form to the arg list...
6156 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
6157 const Type *PTy = getPromotedType((*AI)->getType());
6158 if (PTy != (*AI)->getType()) {
6159 // Must promote to pass through va_arg area!
6160 Instruction *Cast = new CastInst(*AI, PTy, "tmp");
6161 InsertNewInstBefore(Cast, *Caller);
6162 Args.push_back(Cast);
6163 } else {
6164 Args.push_back(*AI);
6165 }
6166 }
6167 }
6168
6169 if (FT->getReturnType() == Type::VoidTy)
6170 Caller->setName(""); // Void type should not have a name...
6171
6172 Instruction *NC;
6173 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Chris Lattnerfae8ab32004-02-08 21:44:31 +00006174 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
Chris Lattner970c33a2003-06-19 17:00:31 +00006175 Args, Caller->getName(), Caller);
Chris Lattner05c703e2005-05-14 12:25:32 +00006176 cast<InvokeInst>(II)->setCallingConv(II->getCallingConv());
Chris Lattner970c33a2003-06-19 17:00:31 +00006177 } else {
6178 NC = new CallInst(Callee, Args, Caller->getName(), Caller);
Chris Lattner6aacb0f2005-05-06 06:48:21 +00006179 if (cast<CallInst>(Caller)->isTailCall())
6180 cast<CallInst>(NC)->setTailCall();
Chris Lattner05c703e2005-05-14 12:25:32 +00006181 cast<CallInst>(NC)->setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Chris Lattner970c33a2003-06-19 17:00:31 +00006182 }
6183
6184 // Insert a cast of the return type as necessary...
6185 Value *NV = NC;
6186 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
6187 if (NV->getType() != Type::VoidTy) {
6188 NV = NC = new CastInst(NC, Caller->getType(), "tmp");
Chris Lattner686767f2003-10-30 00:46:41 +00006189
6190 // If this is an invoke instruction, we should insert it after the first
6191 // non-phi, instruction in the normal successor block.
6192 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
6193 BasicBlock::iterator I = II->getNormalDest()->begin();
6194 while (isa<PHINode>(I)) ++I;
6195 InsertNewInstBefore(NC, *I);
6196 } else {
6197 // Otherwise, it's a call, just insert cast right after the call instr
6198 InsertNewInstBefore(NC, *Caller);
6199 }
Chris Lattner51ea1272004-02-28 05:22:00 +00006200 AddUsersToWorkList(*Caller);
Chris Lattner970c33a2003-06-19 17:00:31 +00006201 } else {
Chris Lattnere29d6342004-10-17 21:22:38 +00006202 NV = UndefValue::get(Caller->getType());
Chris Lattner970c33a2003-06-19 17:00:31 +00006203 }
6204 }
6205
6206 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
6207 Caller->replaceAllUsesWith(NV);
6208 Caller->getParent()->getInstList().erase(Caller);
6209 removeFromWorkList(Caller);
6210 return true;
6211}
6212
6213
Chris Lattner7515cab2004-11-14 19:13:23 +00006214// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
6215// operator and they all are only used by the PHI, PHI together their
6216// inputs, and do the operation once, to the result of the PHI.
6217Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
6218 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
6219
6220 // Scan the instruction, looking for input operations that can be folded away.
6221 // If all input operands to the phi are the same instruction (e.g. a cast from
6222 // the same type or "+42") we can pull the operation through the PHI, reducing
6223 // code size and simplifying code.
6224 Constant *ConstantOp = 0;
6225 const Type *CastSrcTy = 0;
6226 if (isa<CastInst>(FirstInst)) {
6227 CastSrcTy = FirstInst->getOperand(0)->getType();
6228 } else if (isa<BinaryOperator>(FirstInst) || isa<ShiftInst>(FirstInst)) {
6229 // Can fold binop or shift if the RHS is a constant.
6230 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
6231 if (ConstantOp == 0) return 0;
6232 } else {
6233 return 0; // Cannot fold this operation.
6234 }
6235
6236 // Check to see if all arguments are the same operation.
6237 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
6238 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
6239 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
6240 if (!I->hasOneUse() || I->getOpcode() != FirstInst->getOpcode())
6241 return 0;
6242 if (CastSrcTy) {
6243 if (I->getOperand(0)->getType() != CastSrcTy)
6244 return 0; // Cast operation must match.
6245 } else if (I->getOperand(1) != ConstantOp) {
6246 return 0;
6247 }
6248 }
6249
6250 // Okay, they are all the same operation. Create a new PHI node of the
6251 // correct type, and PHI together all of the LHS's of the instructions.
6252 PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
6253 PN.getName()+".in");
Chris Lattnerd8e20182005-01-29 00:39:08 +00006254 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattner46dd5a62004-11-14 19:29:34 +00006255
6256 Value *InVal = FirstInst->getOperand(0);
6257 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattner7515cab2004-11-14 19:13:23 +00006258
6259 // Add all operands to the new PHI.
Chris Lattner46dd5a62004-11-14 19:29:34 +00006260 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
6261 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
6262 if (NewInVal != InVal)
6263 InVal = 0;
6264 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
6265 }
6266
6267 Value *PhiVal;
6268 if (InVal) {
6269 // The new PHI unions all of the same values together. This is really
6270 // common, so we handle it intelligently here for compile-time speed.
6271 PhiVal = InVal;
6272 delete NewPN;
6273 } else {
6274 InsertNewInstBefore(NewPN, PN);
6275 PhiVal = NewPN;
6276 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00006277
Chris Lattner7515cab2004-11-14 19:13:23 +00006278 // Insert and return the new operation.
6279 if (isa<CastInst>(FirstInst))
Chris Lattner46dd5a62004-11-14 19:29:34 +00006280 return new CastInst(PhiVal, PN.getType());
Chris Lattner7515cab2004-11-14 19:13:23 +00006281 else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattner46dd5a62004-11-14 19:29:34 +00006282 return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattner7515cab2004-11-14 19:13:23 +00006283 else
6284 return new ShiftInst(cast<ShiftInst>(FirstInst)->getOpcode(),
Chris Lattner46dd5a62004-11-14 19:29:34 +00006285 PhiVal, ConstantOp);
Chris Lattner7515cab2004-11-14 19:13:23 +00006286}
Chris Lattner48a44f72002-05-02 17:06:02 +00006287
Chris Lattner71536432005-01-17 05:10:15 +00006288/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
6289/// that is dead.
6290static bool DeadPHICycle(PHINode *PN, std::set<PHINode*> &PotentiallyDeadPHIs) {
6291 if (PN->use_empty()) return true;
6292 if (!PN->hasOneUse()) return false;
6293
6294 // Remember this node, and if we find the cycle, return.
6295 if (!PotentiallyDeadPHIs.insert(PN).second)
6296 return true;
6297
6298 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
6299 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanb1c93172005-04-21 23:48:37 +00006300
Chris Lattner71536432005-01-17 05:10:15 +00006301 return false;
6302}
6303
Chris Lattnerbbbdd852002-05-06 18:06:38 +00006304// PHINode simplification
6305//
Chris Lattner113f4f42002-06-25 16:13:24 +00006306Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonbbf89902006-07-10 22:15:25 +00006307 // If LCSSA is around, don't mess with Phi nodes
6308 if (mustPreserveAnalysisID(LCSSAID)) return 0;
Owen Andersona6968f82006-07-10 19:03:49 +00006309
Owen Andersonae8aa642006-07-10 22:03:18 +00006310 if (Value *V = PN.hasConstantValue())
6311 return ReplaceInstUsesWith(PN, V);
6312
6313 // If the only user of this instruction is a cast instruction, and all of the
6314 // incoming values are constants, change this PHI to merge together the casted
6315 // constants.
6316 if (PN.hasOneUse())
6317 if (CastInst *CI = dyn_cast<CastInst>(PN.use_back()))
6318 if (CI->getType() != PN.getType()) { // noop casts will be folded
6319 bool AllConstant = true;
6320 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
6321 if (!isa<Constant>(PN.getIncomingValue(i))) {
6322 AllConstant = false;
6323 break;
6324 }
6325 if (AllConstant) {
6326 // Make a new PHI with all casted values.
6327 PHINode *New = new PHINode(CI->getType(), PN.getName(), &PN);
6328 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
6329 Constant *OldArg = cast<Constant>(PN.getIncomingValue(i));
6330 New->addIncoming(ConstantExpr::getCast(OldArg, New->getType()),
6331 PN.getIncomingBlock(i));
6332 }
6333
6334 // Update the cast instruction.
6335 CI->setOperand(0, New);
6336 WorkList.push_back(CI); // revisit the cast instruction to fold.
6337 WorkList.push_back(New); // Make sure to revisit the new Phi
6338 return &PN; // PN is now dead!
6339 }
6340 }
6341
6342 // If all PHI operands are the same operation, pull them through the PHI,
6343 // reducing code size.
6344 if (isa<Instruction>(PN.getIncomingValue(0)) &&
6345 PN.getIncomingValue(0)->hasOneUse())
6346 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
6347 return Result;
6348
6349 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
6350 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
6351 // PHI)... break the cycle.
6352 if (PN.hasOneUse())
6353 if (PHINode *PU = dyn_cast<PHINode>(PN.use_back())) {
6354 std::set<PHINode*> PotentiallyDeadPHIs;
6355 PotentiallyDeadPHIs.insert(&PN);
6356 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
6357 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
6358 }
6359
Chris Lattner91daeb52003-12-19 05:58:40 +00006360 return 0;
Chris Lattnerbbbdd852002-05-06 18:06:38 +00006361}
6362
Chris Lattner69193f92004-04-05 01:30:19 +00006363static Value *InsertSignExtendToPtrTy(Value *V, const Type *DTy,
6364 Instruction *InsertPoint,
6365 InstCombiner *IC) {
6366 unsigned PS = IC->getTargetData().getPointerSize();
6367 const Type *VTy = V->getType();
Chris Lattner69193f92004-04-05 01:30:19 +00006368 if (!VTy->isSigned() && VTy->getPrimitiveSize() < PS)
6369 // We must insert a cast to ensure we sign-extend.
6370 V = IC->InsertNewInstBefore(new CastInst(V, VTy->getSignedVersion(),
6371 V->getName()), *InsertPoint);
6372 return IC->InsertNewInstBefore(new CastInst(V, DTy, V->getName()),
6373 *InsertPoint);
6374}
6375
Chris Lattner48a44f72002-05-02 17:06:02 +00006376
Chris Lattner113f4f42002-06-25 16:13:24 +00006377Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner5f667a62004-05-07 22:09:22 +00006378 Value *PtrOp = GEP.getOperand(0);
Chris Lattner471bd762003-05-22 19:07:21 +00006379 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
Chris Lattner113f4f42002-06-25 16:13:24 +00006380 // If so, eliminate the noop.
Chris Lattner8d0bacb2004-02-22 05:25:17 +00006381 if (GEP.getNumOperands() == 1)
Chris Lattner5f667a62004-05-07 22:09:22 +00006382 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner8d0bacb2004-02-22 05:25:17 +00006383
Chris Lattner81a7a232004-10-16 18:11:37 +00006384 if (isa<UndefValue>(GEP.getOperand(0)))
6385 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
6386
Chris Lattner8d0bacb2004-02-22 05:25:17 +00006387 bool HasZeroPointerIndex = false;
6388 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
6389 HasZeroPointerIndex = C->isNullValue();
6390
6391 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner5f667a62004-05-07 22:09:22 +00006392 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner48a44f72002-05-02 17:06:02 +00006393
Chris Lattner69193f92004-04-05 01:30:19 +00006394 // Eliminate unneeded casts for indices.
6395 bool MadeChange = false;
Chris Lattner2b2412d2004-04-07 18:38:20 +00006396 gep_type_iterator GTI = gep_type_begin(GEP);
6397 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI)
6398 if (isa<SequentialType>(*GTI)) {
6399 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
6400 Value *Src = CI->getOperand(0);
6401 const Type *SrcTy = Src->getType();
6402 const Type *DestTy = CI->getType();
6403 if (Src->getType()->isInteger()) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00006404 if (SrcTy->getPrimitiveSizeInBits() ==
6405 DestTy->getPrimitiveSizeInBits()) {
Chris Lattner2b2412d2004-04-07 18:38:20 +00006406 // We can always eliminate a cast from ulong or long to the other.
6407 // We can always eliminate a cast from uint to int or the other on
6408 // 32-bit pointer platforms.
Chris Lattnerd1f46d32005-04-24 06:59:08 +00006409 if (DestTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()){
Chris Lattner2b2412d2004-04-07 18:38:20 +00006410 MadeChange = true;
6411 GEP.setOperand(i, Src);
6412 }
6413 } else if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
6414 SrcTy->getPrimitiveSize() == 4) {
6415 // We can always eliminate a cast from int to [u]long. We can
6416 // eliminate a cast from uint to [u]long iff the target is a 32-bit
6417 // pointer target.
Misha Brukmanb1c93172005-04-21 23:48:37 +00006418 if (SrcTy->isSigned() ||
Chris Lattnerd1f46d32005-04-24 06:59:08 +00006419 SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
Chris Lattner2b2412d2004-04-07 18:38:20 +00006420 MadeChange = true;
6421 GEP.setOperand(i, Src);
6422 }
Chris Lattner69193f92004-04-05 01:30:19 +00006423 }
6424 }
6425 }
Chris Lattner2b2412d2004-04-07 18:38:20 +00006426 // If we are using a wider index than needed for this platform, shrink it
6427 // to what we need. If the incoming value needs a cast instruction,
6428 // insert it. This explicit cast can make subsequent optimizations more
6429 // obvious.
6430 Value *Op = GEP.getOperand(i);
6431 if (Op->getType()->getPrimitiveSize() > TD->getPointerSize())
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00006432 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner44d0b952004-07-20 01:48:15 +00006433 GEP.setOperand(i, ConstantExpr::getCast(C,
6434 TD->getIntPtrType()->getSignedVersion()));
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00006435 MadeChange = true;
6436 } else {
Chris Lattner2b2412d2004-04-07 18:38:20 +00006437 Op = InsertNewInstBefore(new CastInst(Op, TD->getIntPtrType(),
6438 Op->getName()), GEP);
6439 GEP.setOperand(i, Op);
6440 MadeChange = true;
6441 }
Chris Lattner44d0b952004-07-20 01:48:15 +00006442
6443 // If this is a constant idx, make sure to canonicalize it to be a signed
6444 // operand, otherwise CSE and other optimizations are pessimized.
6445 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op)) {
6446 GEP.setOperand(i, ConstantExpr::getCast(CUI,
6447 CUI->getType()->getSignedVersion()));
6448 MadeChange = true;
6449 }
Chris Lattner69193f92004-04-05 01:30:19 +00006450 }
6451 if (MadeChange) return &GEP;
6452
Chris Lattnerae7a0d32002-08-02 19:29:35 +00006453 // Combine Indices - If the source pointer to this getelementptr instruction
6454 // is a getelementptr instruction, combine the indices of the two
6455 // getelementptr instructions into a single instruction.
6456 //
Chris Lattner57c67b02004-03-25 22:59:29 +00006457 std::vector<Value*> SrcGEPOperands;
Chris Lattner0798af32005-01-13 20:14:25 +00006458 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattner57c67b02004-03-25 22:59:29 +00006459 SrcGEPOperands.assign(Src->op_begin(), Src->op_end());
Chris Lattner57c67b02004-03-25 22:59:29 +00006460
6461 if (!SrcGEPOperands.empty()) {
Chris Lattner5f667a62004-05-07 22:09:22 +00006462 // Note that if our source is a gep chain itself that we wait for that
6463 // chain to be resolved before we perform this transformation. This
6464 // avoids us creating a TON of code in some cases.
6465 //
6466 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
6467 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
6468 return 0; // Wait until our source is folded to completion.
6469
Chris Lattnerae7a0d32002-08-02 19:29:35 +00006470 std::vector<Value *> Indices;
Chris Lattner5f667a62004-05-07 22:09:22 +00006471
6472 // Find out whether the last index in the source GEP is a sequential idx.
6473 bool EndsWithSequential = false;
6474 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
6475 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattner8ec5f882004-05-08 22:41:42 +00006476 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00006477
Chris Lattnerae7a0d32002-08-02 19:29:35 +00006478 // Can we combine the two pointer arithmetics offsets?
Chris Lattner5f667a62004-05-07 22:09:22 +00006479 if (EndsWithSequential) {
Chris Lattner235af562003-03-05 22:33:14 +00006480 // Replace: gep (gep %P, long B), long A, ...
6481 // With: T = long A+B; gep %P, T, ...
6482 //
Chris Lattner5f667a62004-05-07 22:09:22 +00006483 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner69193f92004-04-05 01:30:19 +00006484 if (SO1 == Constant::getNullValue(SO1->getType())) {
6485 Sum = GO1;
6486 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
6487 Sum = SO1;
6488 } else {
6489 // If they aren't the same type, convert both to an integer of the
6490 // target's pointer size.
6491 if (SO1->getType() != GO1->getType()) {
6492 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
6493 SO1 = ConstantExpr::getCast(SO1C, GO1->getType());
6494 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
6495 GO1 = ConstantExpr::getCast(GO1C, SO1->getType());
6496 } else {
6497 unsigned PS = TD->getPointerSize();
Chris Lattner69193f92004-04-05 01:30:19 +00006498 if (SO1->getType()->getPrimitiveSize() == PS) {
6499 // Convert GO1 to SO1's type.
6500 GO1 = InsertSignExtendToPtrTy(GO1, SO1->getType(), &GEP, this);
6501
6502 } else if (GO1->getType()->getPrimitiveSize() == PS) {
6503 // Convert SO1 to GO1's type.
6504 SO1 = InsertSignExtendToPtrTy(SO1, GO1->getType(), &GEP, this);
6505 } else {
6506 const Type *PT = TD->getIntPtrType();
6507 SO1 = InsertSignExtendToPtrTy(SO1, PT, &GEP, this);
6508 GO1 = InsertSignExtendToPtrTy(GO1, PT, &GEP, this);
6509 }
6510 }
6511 }
Chris Lattner5f667a62004-05-07 22:09:22 +00006512 if (isa<Constant>(SO1) && isa<Constant>(GO1))
6513 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
6514 else {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00006515 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
6516 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner5f667a62004-05-07 22:09:22 +00006517 }
Chris Lattner69193f92004-04-05 01:30:19 +00006518 }
Chris Lattner5f667a62004-05-07 22:09:22 +00006519
6520 // Recycle the GEP we already have if possible.
6521 if (SrcGEPOperands.size() == 2) {
6522 GEP.setOperand(0, SrcGEPOperands[0]);
6523 GEP.setOperand(1, Sum);
6524 return &GEP;
6525 } else {
6526 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
6527 SrcGEPOperands.end()-1);
6528 Indices.push_back(Sum);
6529 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
6530 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00006531 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner69193f92004-04-05 01:30:19 +00006532 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00006533 SrcGEPOperands.size() != 1) {
Chris Lattnerae7a0d32002-08-02 19:29:35 +00006534 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattner57c67b02004-03-25 22:59:29 +00006535 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
6536 SrcGEPOperands.end());
Chris Lattnerae7a0d32002-08-02 19:29:35 +00006537 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
6538 }
6539
6540 if (!Indices.empty())
Chris Lattner57c67b02004-03-25 22:59:29 +00006541 return new GetElementPtrInst(SrcGEPOperands[0], Indices, GEP.getName());
Chris Lattnerc59af1d2002-08-17 22:21:59 +00006542
Chris Lattner5f667a62004-05-07 22:09:22 +00006543 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattnerc59af1d2002-08-17 22:21:59 +00006544 // GEP of global variable. If all of the indices for this GEP are
6545 // constants, we can promote this to a constexpr instead of an instruction.
6546
6547 // Scan for nonconstants...
6548 std::vector<Constant*> Indices;
6549 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
6550 for (; I != E && isa<Constant>(*I); ++I)
6551 Indices.push_back(cast<Constant>(*I));
6552
6553 if (I == E) { // If they are all constants...
Chris Lattnerf3edc492004-07-18 18:59:44 +00006554 Constant *CE = ConstantExpr::getGetElementPtr(GV, Indices);
Chris Lattnerc59af1d2002-08-17 22:21:59 +00006555
6556 // Replace all uses of the GEP with the new constexpr...
6557 return ReplaceInstUsesWith(GEP, CE);
6558 }
Chris Lattner567b81f2005-09-13 00:40:14 +00006559 } else if (Value *X = isCast(PtrOp)) { // Is the operand a cast?
6560 if (!isa<PointerType>(X->getType())) {
6561 // Not interesting. Source pointer must be a cast from pointer.
6562 } else if (HasZeroPointerIndex) {
6563 // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
6564 // into : GEP [10 x ubyte]* X, long 0, ...
6565 //
6566 // This occurs when the program declares an array extern like "int X[];"
6567 //
6568 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
6569 const PointerType *XTy = cast<PointerType>(X->getType());
6570 if (const ArrayType *XATy =
6571 dyn_cast<ArrayType>(XTy->getElementType()))
6572 if (const ArrayType *CATy =
6573 dyn_cast<ArrayType>(CPTy->getElementType()))
6574 if (CATy->getElementType() == XATy->getElementType()) {
6575 // At this point, we know that the cast source type is a pointer
6576 // to an array of the same type as the destination pointer
6577 // array. Because the array type is never stepped over (there
6578 // is a leading zero) we can fold the cast into this GEP.
6579 GEP.setOperand(0, X);
6580 return &GEP;
6581 }
6582 } else if (GEP.getNumOperands() == 2) {
6583 // Transform things like:
Chris Lattner2a893292005-09-13 18:36:04 +00006584 // %t = getelementptr ubyte* cast ([2 x int]* %str to uint*), uint %V
6585 // into: %t1 = getelementptr [2 x int*]* %str, int 0, uint %V; cast
Chris Lattner567b81f2005-09-13 00:40:14 +00006586 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
6587 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
6588 if (isa<ArrayType>(SrcElTy) &&
6589 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
6590 TD->getTypeSize(ResElTy)) {
6591 Value *V = InsertNewInstBefore(
6592 new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
6593 GEP.getOperand(1), GEP.getName()), GEP);
6594 return new CastInst(V, GEP.getType());
Chris Lattner8d0bacb2004-02-22 05:25:17 +00006595 }
Chris Lattner2a893292005-09-13 18:36:04 +00006596
6597 // Transform things like:
6598 // getelementptr sbyte* cast ([100 x double]* X to sbyte*), int %tmp
6599 // (where tmp = 8*tmp2) into:
6600 // getelementptr [100 x double]* %arr, int 0, int %tmp.2
6601
6602 if (isa<ArrayType>(SrcElTy) &&
6603 (ResElTy == Type::SByteTy || ResElTy == Type::UByteTy)) {
6604 uint64_t ArrayEltSize =
6605 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType());
6606
6607 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
6608 // allow either a mul, shift, or constant here.
6609 Value *NewIdx = 0;
6610 ConstantInt *Scale = 0;
6611 if (ArrayEltSize == 1) {
6612 NewIdx = GEP.getOperand(1);
6613 Scale = ConstantInt::get(NewIdx->getType(), 1);
6614 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Chris Lattnera393e4d2005-09-14 17:32:56 +00006615 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner2a893292005-09-13 18:36:04 +00006616 Scale = CI;
6617 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
6618 if (Inst->getOpcode() == Instruction::Shl &&
6619 isa<ConstantInt>(Inst->getOperand(1))) {
6620 unsigned ShAmt =cast<ConstantUInt>(Inst->getOperand(1))->getValue();
6621 if (Inst->getType()->isSigned())
6622 Scale = ConstantSInt::get(Inst->getType(), 1ULL << ShAmt);
6623 else
6624 Scale = ConstantUInt::get(Inst->getType(), 1ULL << ShAmt);
6625 NewIdx = Inst->getOperand(0);
6626 } else if (Inst->getOpcode() == Instruction::Mul &&
6627 isa<ConstantInt>(Inst->getOperand(1))) {
6628 Scale = cast<ConstantInt>(Inst->getOperand(1));
6629 NewIdx = Inst->getOperand(0);
6630 }
6631 }
6632
6633 // If the index will be to exactly the right offset with the scale taken
6634 // out, perform the transformation.
6635 if (Scale && Scale->getRawValue() % ArrayEltSize == 0) {
6636 if (ConstantSInt *C = dyn_cast<ConstantSInt>(Scale))
6637 Scale = ConstantSInt::get(C->getType(),
Chris Lattnera393e4d2005-09-14 17:32:56 +00006638 (int64_t)C->getRawValue() /
6639 (int64_t)ArrayEltSize);
Chris Lattner2a893292005-09-13 18:36:04 +00006640 else
6641 Scale = ConstantUInt::get(Scale->getType(),
6642 Scale->getRawValue() / ArrayEltSize);
6643 if (Scale->getRawValue() != 1) {
6644 Constant *C = ConstantExpr::getCast(Scale, NewIdx->getType());
6645 Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
6646 NewIdx = InsertNewInstBefore(Sc, GEP);
6647 }
6648
6649 // Insert the new GEP instruction.
6650 Instruction *Idx =
6651 new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
6652 NewIdx, GEP.getName());
6653 Idx = InsertNewInstBefore(Idx, GEP);
6654 return new CastInst(Idx, GEP.getType());
6655 }
6656 }
Chris Lattner8d0bacb2004-02-22 05:25:17 +00006657 }
Chris Lattnerca081252001-12-14 16:52:21 +00006658 }
6659
Chris Lattnerca081252001-12-14 16:52:21 +00006660 return 0;
6661}
6662
Chris Lattner1085bdf2002-11-04 16:18:53 +00006663Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
6664 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
6665 if (AI.isArrayAllocation()) // Check C != 1
6666 if (const ConstantUInt *C = dyn_cast<ConstantUInt>(AI.getArraySize())) {
6667 const Type *NewTy = ArrayType::get(AI.getAllocatedType(), C->getValue());
Chris Lattnera2620ac2002-11-09 00:49:43 +00006668 AllocationInst *New = 0;
Chris Lattner1085bdf2002-11-04 16:18:53 +00006669
6670 // Create and insert the replacement instruction...
6671 if (isa<MallocInst>(AI))
Nate Begeman848622f2005-11-05 09:21:28 +00006672 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00006673 else {
6674 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Nate Begeman848622f2005-11-05 09:21:28 +00006675 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00006676 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00006677
6678 InsertNewInstBefore(New, AI);
Misha Brukmanb1c93172005-04-21 23:48:37 +00006679
Chris Lattner1085bdf2002-11-04 16:18:53 +00006680 // Scan to the end of the allocation instructions, to skip over a block of
6681 // allocas if possible...
6682 //
6683 BasicBlock::iterator It = New;
6684 while (isa<AllocationInst>(*It)) ++It;
6685
6686 // Now that I is pointing to the first non-allocation-inst in the block,
6687 // insert our getelementptr instruction...
6688 //
Chris Lattner809dfac2005-05-04 19:10:26 +00006689 Value *NullIdx = Constant::getNullValue(Type::IntTy);
6690 Value *V = new GetElementPtrInst(New, NullIdx, NullIdx,
6691 New->getName()+".sub", It);
Chris Lattner1085bdf2002-11-04 16:18:53 +00006692
6693 // Now make everything use the getelementptr instead of the original
6694 // allocation.
Chris Lattnerabb77c92004-03-19 06:08:10 +00006695 return ReplaceInstUsesWith(AI, V);
Chris Lattner81a7a232004-10-16 18:11:37 +00006696 } else if (isa<UndefValue>(AI.getArraySize())) {
6697 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner1085bdf2002-11-04 16:18:53 +00006698 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00006699
6700 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
6701 // Note that we only do this for alloca's, because malloc should allocate and
6702 // return a unique pointer, even for a zero byte allocation.
Misha Brukmanb1c93172005-04-21 23:48:37 +00006703 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
Chris Lattner49df6ce2004-07-02 22:55:47 +00006704 TD->getTypeSize(AI.getAllocatedType()) == 0)
Chris Lattnerabb77c92004-03-19 06:08:10 +00006705 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
6706
Chris Lattner1085bdf2002-11-04 16:18:53 +00006707 return 0;
6708}
6709
Chris Lattner8427bff2003-12-07 01:24:23 +00006710Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
6711 Value *Op = FI.getOperand(0);
6712
6713 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
6714 if (CastInst *CI = dyn_cast<CastInst>(Op))
6715 if (isa<PointerType>(CI->getOperand(0)->getType())) {
6716 FI.setOperand(0, CI->getOperand(0));
6717 return &FI;
6718 }
6719
Chris Lattner8ba9ec92004-10-18 02:59:09 +00006720 // free undef -> unreachable.
6721 if (isa<UndefValue>(Op)) {
6722 // Insert a new store to null because we cannot modify the CFG here.
6723 new StoreInst(ConstantBool::True,
6724 UndefValue::get(PointerType::get(Type::BoolTy)), &FI);
6725 return EraseInstFromFunction(FI);
6726 }
6727
Chris Lattnerf3a36602004-02-28 04:57:37 +00006728 // If we have 'free null' delete the instruction. This can happen in stl code
6729 // when lots of inlining happens.
Chris Lattner8ba9ec92004-10-18 02:59:09 +00006730 if (isa<ConstantPointerNull>(Op))
Chris Lattner51ea1272004-02-28 05:22:00 +00006731 return EraseInstFromFunction(FI);
Chris Lattnerf3a36602004-02-28 04:57:37 +00006732
Chris Lattner8427bff2003-12-07 01:24:23 +00006733 return 0;
6734}
6735
6736
Chris Lattner72684fe2005-01-31 05:51:45 +00006737/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Chris Lattner35e24772004-07-13 01:49:43 +00006738static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
6739 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00006740 Value *CastOp = CI->getOperand(0);
Chris Lattner35e24772004-07-13 01:49:43 +00006741
6742 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00006743 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Chris Lattner35e24772004-07-13 01:49:43 +00006744 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00006745
Chris Lattnerebca4762006-04-02 05:37:12 +00006746 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
6747 isa<PackedType>(DestPTy)) {
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00006748 // If the source is an array, the code below will not succeed. Check to
6749 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
6750 // constants.
6751 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
6752 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
6753 if (ASrcTy->getNumElements() != 0) {
6754 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
6755 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
6756 SrcTy = cast<PointerType>(CastOp->getType());
6757 SrcPTy = SrcTy->getElementType();
6758 }
6759
Chris Lattnerebca4762006-04-02 05:37:12 +00006760 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
6761 isa<PackedType>(SrcPTy)) &&
Chris Lattnerecfa9b52005-03-29 06:37:47 +00006762 // Do not allow turning this into a load of an integer, which is then
6763 // casted to a pointer, this pessimizes pointer analysis a lot.
6764 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00006765 IC.getTargetData().getTypeSize(SrcPTy) ==
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00006766 IC.getTargetData().getTypeSize(DestPTy)) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00006767
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00006768 // Okay, we are casting from one integer or pointer type to another of
6769 // the same size. Instead of casting the pointer before the load, cast
6770 // the result of the loaded value.
6771 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
6772 CI->getName(),
6773 LI.isVolatile()),LI);
6774 // Now cast the result of the load.
6775 return new CastInst(NewLoad, LI.getType());
6776 }
Chris Lattner35e24772004-07-13 01:49:43 +00006777 }
6778 }
6779 return 0;
6780}
6781
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00006782/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattnere6f13092004-09-19 19:18:10 +00006783/// from this value cannot trap. If it is not obviously safe to load from the
6784/// specified pointer, we do a quick local scan of the basic block containing
6785/// ScanFrom, to determine if the address is already accessed.
6786static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
6787 // If it is an alloca or global variable, it is always safe to load from.
6788 if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
6789
6790 // Otherwise, be a little bit agressive by scanning the local block where we
6791 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00006792 // from/to. If so, the previous load or store would have already trapped,
6793 // so there is no harm doing an extra load (also, CSE will later eliminate
6794 // the load entirely).
Chris Lattnere6f13092004-09-19 19:18:10 +00006795 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
6796
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00006797 while (BBI != E) {
Chris Lattnere6f13092004-09-19 19:18:10 +00006798 --BBI;
6799
6800 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
6801 if (LI->getOperand(0) == V) return true;
6802 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
6803 if (SI->getOperand(1) == V) return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +00006804
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00006805 }
Chris Lattnere6f13092004-09-19 19:18:10 +00006806 return false;
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00006807}
6808
Chris Lattner0f1d8a32003-06-26 05:06:25 +00006809Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
6810 Value *Op = LI.getOperand(0);
Chris Lattner7e8af382004-01-12 04:13:56 +00006811
Chris Lattnera9d84e32005-05-01 04:24:53 +00006812 // load (cast X) --> cast (load X) iff safe
6813 if (CastInst *CI = dyn_cast<CastInst>(Op))
6814 if (Instruction *Res = InstCombineLoadCast(*this, LI))
6815 return Res;
6816
6817 // None of the following transforms are legal for volatile loads.
6818 if (LI.isVolatile()) return 0;
Chris Lattnerb990f7d2005-09-12 22:00:15 +00006819
Chris Lattnerb990f7d2005-09-12 22:00:15 +00006820 if (&LI.getParent()->front() != &LI) {
6821 BasicBlock::iterator BBI = &LI; --BBI;
Chris Lattnere0bfdf12005-09-12 22:21:03 +00006822 // If the instruction immediately before this is a store to the same
6823 // address, do a simple form of store->load forwarding.
Chris Lattnerb990f7d2005-09-12 22:00:15 +00006824 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
6825 if (SI->getOperand(1) == LI.getOperand(0))
6826 return ReplaceInstUsesWith(LI, SI->getOperand(0));
Chris Lattnere0bfdf12005-09-12 22:21:03 +00006827 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
6828 if (LIB->getOperand(0) == LI.getOperand(0))
6829 return ReplaceInstUsesWith(LI, LIB);
Chris Lattnerb990f7d2005-09-12 22:00:15 +00006830 }
Chris Lattnera9d84e32005-05-01 04:24:53 +00006831
6832 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op))
6833 if (isa<ConstantPointerNull>(GEPI->getOperand(0)) ||
6834 isa<UndefValue>(GEPI->getOperand(0))) {
6835 // Insert a new store to null instruction before the load to indicate
6836 // that this code is not reachable. We do this instead of inserting
6837 // an unreachable instruction directly because we cannot modify the
6838 // CFG.
6839 new StoreInst(UndefValue::get(LI.getType()),
6840 Constant::getNullValue(Op->getType()), &LI);
6841 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
6842 }
6843
Chris Lattner81a7a232004-10-16 18:11:37 +00006844 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattnera9d84e32005-05-01 04:24:53 +00006845 // load null/undef -> undef
6846 if ((C->isNullValue() || isa<UndefValue>(C))) {
Chris Lattner8ba9ec92004-10-18 02:59:09 +00006847 // Insert a new store to null instruction before the load to indicate that
6848 // this code is not reachable. We do this instead of inserting an
6849 // unreachable instruction directly because we cannot modify the CFG.
Chris Lattnera9d84e32005-05-01 04:24:53 +00006850 new StoreInst(UndefValue::get(LI.getType()),
6851 Constant::getNullValue(Op->getType()), &LI);
Chris Lattner81a7a232004-10-16 18:11:37 +00006852 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner8ba9ec92004-10-18 02:59:09 +00006853 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00006854
Chris Lattner81a7a232004-10-16 18:11:37 +00006855 // Instcombine load (constant global) into the value loaded.
6856 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
6857 if (GV->isConstant() && !GV->isExternal())
6858 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanb1c93172005-04-21 23:48:37 +00006859
Chris Lattner81a7a232004-10-16 18:11:37 +00006860 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
6861 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
6862 if (CE->getOpcode() == Instruction::GetElementPtr) {
6863 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
6864 if (GV->isConstant() && !GV->isExternal())
Chris Lattner0b011ec2005-09-26 05:28:06 +00006865 if (Constant *V =
6866 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
Chris Lattner81a7a232004-10-16 18:11:37 +00006867 return ReplaceInstUsesWith(LI, V);
Chris Lattnera9d84e32005-05-01 04:24:53 +00006868 if (CE->getOperand(0)->isNullValue()) {
6869 // Insert a new store to null instruction before the load to indicate
6870 // that this code is not reachable. We do this instead of inserting
6871 // an unreachable instruction directly because we cannot modify the
6872 // CFG.
6873 new StoreInst(UndefValue::get(LI.getType()),
6874 Constant::getNullValue(Op->getType()), &LI);
6875 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
6876 }
6877
Chris Lattner81a7a232004-10-16 18:11:37 +00006878 } else if (CE->getOpcode() == Instruction::Cast) {
6879 if (Instruction *Res = InstCombineLoadCast(*this, LI))
6880 return Res;
6881 }
6882 }
Chris Lattnere228ee52004-04-08 20:39:49 +00006883
Chris Lattnera9d84e32005-05-01 04:24:53 +00006884 if (Op->hasOneUse()) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00006885 // Change select and PHI nodes to select values instead of addresses: this
6886 // helps alias analysis out a lot, allows many others simplifications, and
6887 // exposes redundancy in the code.
6888 //
6889 // Note that we cannot do the transformation unless we know that the
6890 // introduced loads cannot trap! Something like this is valid as long as
6891 // the condition is always false: load (select bool %C, int* null, int* %G),
6892 // but it would not be valid if we transformed it to load from null
6893 // unconditionally.
6894 //
6895 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
6896 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattnere6f13092004-09-19 19:18:10 +00006897 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
6898 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00006899 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner42618552004-09-20 10:15:10 +00006900 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00006901 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner42618552004-09-20 10:15:10 +00006902 SI->getOperand(2)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00006903 return new SelectInst(SI->getCondition(), V1, V2);
6904 }
6905
Chris Lattnerbdcf41a2004-09-23 15:46:00 +00006906 // load (select (cond, null, P)) -> load P
6907 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
6908 if (C->isNullValue()) {
6909 LI.setOperand(0, SI->getOperand(2));
6910 return &LI;
6911 }
6912
6913 // load (select (cond, P, null)) -> load P
6914 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
6915 if (C->isNullValue()) {
6916 LI.setOperand(0, SI->getOperand(1));
6917 return &LI;
6918 }
6919
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00006920 } else if (PHINode *PN = dyn_cast<PHINode>(Op)) {
6921 // load (phi (&V1, &V2, &V3)) --> phi(load &V1, load &V2, load &V3)
Chris Lattner42618552004-09-20 10:15:10 +00006922 bool Safe = PN->getParent() == LI.getParent();
6923
6924 // Scan all of the instructions between the PHI and the load to make
6925 // sure there are no instructions that might possibly alter the value
6926 // loaded from the PHI.
6927 if (Safe) {
6928 BasicBlock::iterator I = &LI;
6929 for (--I; !isa<PHINode>(I); --I)
6930 if (isa<StoreInst>(I) || isa<CallInst>(I)) {
6931 Safe = false;
6932 break;
6933 }
6934 }
6935
6936 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e && Safe; ++i)
Chris Lattnere6f13092004-09-19 19:18:10 +00006937 if (!isSafeToLoadUnconditionally(PN->getIncomingValue(i),
Chris Lattner42618552004-09-20 10:15:10 +00006938 PN->getIncomingBlock(i)->getTerminator()))
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00006939 Safe = false;
Chris Lattner42618552004-09-20 10:15:10 +00006940
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00006941 if (Safe) {
6942 // Create the PHI.
6943 PHINode *NewPN = new PHINode(LI.getType(), PN->getName());
6944 InsertNewInstBefore(NewPN, *PN);
6945 std::map<BasicBlock*,Value*> LoadMap; // Don't insert duplicate loads
6946
6947 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
6948 BasicBlock *BB = PN->getIncomingBlock(i);
6949 Value *&TheLoad = LoadMap[BB];
6950 if (TheLoad == 0) {
6951 Value *InVal = PN->getIncomingValue(i);
6952 TheLoad = InsertNewInstBefore(new LoadInst(InVal,
6953 InVal->getName()+".val"),
6954 *BB->getTerminator());
6955 }
6956 NewPN->addIncoming(TheLoad, BB);
6957 }
6958 return ReplaceInstUsesWith(LI, NewPN);
6959 }
6960 }
6961 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00006962 return 0;
6963}
6964
Chris Lattner72684fe2005-01-31 05:51:45 +00006965/// InstCombineStoreToCast - Fold 'store V, (cast P)' -> store (cast V), P'
6966/// when possible.
6967static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
6968 User *CI = cast<User>(SI.getOperand(1));
6969 Value *CastOp = CI->getOperand(0);
6970
6971 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
6972 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
6973 const Type *SrcPTy = SrcTy->getElementType();
6974
6975 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
6976 // If the source is an array, the code below will not succeed. Check to
6977 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
6978 // constants.
6979 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
6980 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
6981 if (ASrcTy->getNumElements() != 0) {
6982 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
6983 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
6984 SrcTy = cast<PointerType>(CastOp->getType());
6985 SrcPTy = SrcTy->getElementType();
6986 }
6987
6988 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00006989 IC.getTargetData().getTypeSize(SrcPTy) ==
Chris Lattner72684fe2005-01-31 05:51:45 +00006990 IC.getTargetData().getTypeSize(DestPTy)) {
6991
6992 // Okay, we are casting from one integer or pointer type to another of
6993 // the same size. Instead of casting the pointer before the store, cast
6994 // the value to be stored.
6995 Value *NewCast;
6996 if (Constant *C = dyn_cast<Constant>(SI.getOperand(0)))
6997 NewCast = ConstantExpr::getCast(C, SrcPTy);
6998 else
6999 NewCast = IC.InsertNewInstBefore(new CastInst(SI.getOperand(0),
7000 SrcPTy,
7001 SI.getOperand(0)->getName()+".c"), SI);
7002
7003 return new StoreInst(NewCast, CastOp);
7004 }
7005 }
7006 }
7007 return 0;
7008}
7009
Chris Lattner31f486c2005-01-31 05:36:43 +00007010Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
7011 Value *Val = SI.getOperand(0);
7012 Value *Ptr = SI.getOperand(1);
7013
7014 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner5997cf92006-02-08 03:25:32 +00007015 EraseInstFromFunction(SI);
Chris Lattner31f486c2005-01-31 05:36:43 +00007016 ++NumCombined;
7017 return 0;
7018 }
7019
Chris Lattner5997cf92006-02-08 03:25:32 +00007020 // Do really simple DSE, to catch cases where there are several consequtive
7021 // stores to the same location, separated by a few arithmetic operations. This
7022 // situation often occurs with bitfield accesses.
7023 BasicBlock::iterator BBI = &SI;
7024 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
7025 --ScanInsts) {
7026 --BBI;
7027
7028 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
7029 // Prev store isn't volatile, and stores to the same location?
7030 if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
7031 ++NumDeadStore;
7032 ++BBI;
7033 EraseInstFromFunction(*PrevSI);
7034 continue;
7035 }
7036 break;
7037 }
7038
Chris Lattnerdab43b22006-05-26 19:19:20 +00007039 // If this is a load, we have to stop. However, if the loaded value is from
7040 // the pointer we're loading and is producing the pointer we're storing,
7041 // then *this* store is dead (X = load P; store X -> P).
7042 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
7043 if (LI == Val && LI->getOperand(0) == Ptr) {
7044 EraseInstFromFunction(SI);
7045 ++NumCombined;
7046 return 0;
7047 }
7048 // Otherwise, this is a load from some other location. Stores before it
7049 // may not be dead.
7050 break;
7051 }
7052
Chris Lattner5997cf92006-02-08 03:25:32 +00007053 // Don't skip over loads or things that can modify memory.
Chris Lattnerdab43b22006-05-26 19:19:20 +00007054 if (BBI->mayWriteToMemory())
Chris Lattner5997cf92006-02-08 03:25:32 +00007055 break;
7056 }
7057
7058
7059 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner31f486c2005-01-31 05:36:43 +00007060
7061 // store X, null -> turns into 'unreachable' in SimplifyCFG
7062 if (isa<ConstantPointerNull>(Ptr)) {
7063 if (!isa<UndefValue>(Val)) {
7064 SI.setOperand(0, UndefValue::get(Val->getType()));
7065 if (Instruction *U = dyn_cast<Instruction>(Val))
7066 WorkList.push_back(U); // Dropped a use.
7067 ++NumCombined;
7068 }
7069 return 0; // Do not modify these!
7070 }
7071
7072 // store undef, Ptr -> noop
7073 if (isa<UndefValue>(Val)) {
Chris Lattner5997cf92006-02-08 03:25:32 +00007074 EraseInstFromFunction(SI);
Chris Lattner31f486c2005-01-31 05:36:43 +00007075 ++NumCombined;
7076 return 0;
7077 }
7078
Chris Lattner72684fe2005-01-31 05:51:45 +00007079 // If the pointer destination is a cast, see if we can fold the cast into the
7080 // source instead.
7081 if (CastInst *CI = dyn_cast<CastInst>(Ptr))
7082 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
7083 return Res;
7084 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
7085 if (CE->getOpcode() == Instruction::Cast)
7086 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
7087 return Res;
7088
Chris Lattner219175c2005-09-12 23:23:25 +00007089
7090 // If this store is the last instruction in the basic block, and if the block
7091 // ends with an unconditional branch, try to move it to the successor block.
Chris Lattner5997cf92006-02-08 03:25:32 +00007092 BBI = &SI; ++BBI;
Chris Lattner219175c2005-09-12 23:23:25 +00007093 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
7094 if (BI->isUnconditional()) {
7095 // Check to see if the successor block has exactly two incoming edges. If
7096 // so, see if the other predecessor contains a store to the same location.
7097 // if so, insert a PHI node (if needed) and move the stores down.
7098 BasicBlock *Dest = BI->getSuccessor(0);
7099
7100 pred_iterator PI = pred_begin(Dest);
7101 BasicBlock *Other = 0;
7102 if (*PI != BI->getParent())
7103 Other = *PI;
7104 ++PI;
7105 if (PI != pred_end(Dest)) {
7106 if (*PI != BI->getParent())
7107 if (Other)
7108 Other = 0;
7109 else
7110 Other = *PI;
7111 if (++PI != pred_end(Dest))
7112 Other = 0;
7113 }
7114 if (Other) { // If only one other pred...
7115 BBI = Other->getTerminator();
7116 // Make sure this other block ends in an unconditional branch and that
7117 // there is an instruction before the branch.
7118 if (isa<BranchInst>(BBI) && cast<BranchInst>(BBI)->isUnconditional() &&
7119 BBI != Other->begin()) {
7120 --BBI;
7121 StoreInst *OtherStore = dyn_cast<StoreInst>(BBI);
7122
7123 // If this instruction is a store to the same location.
7124 if (OtherStore && OtherStore->getOperand(1) == SI.getOperand(1)) {
7125 // Okay, we know we can perform this transformation. Insert a PHI
7126 // node now if we need it.
7127 Value *MergedVal = OtherStore->getOperand(0);
7128 if (MergedVal != SI.getOperand(0)) {
7129 PHINode *PN = new PHINode(MergedVal->getType(), "storemerge");
7130 PN->reserveOperandSpace(2);
7131 PN->addIncoming(SI.getOperand(0), SI.getParent());
7132 PN->addIncoming(OtherStore->getOperand(0), Other);
7133 MergedVal = InsertNewInstBefore(PN, Dest->front());
7134 }
7135
7136 // Advance to a place where it is safe to insert the new store and
7137 // insert it.
7138 BBI = Dest->begin();
7139 while (isa<PHINode>(BBI)) ++BBI;
7140 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
7141 OtherStore->isVolatile()), *BBI);
7142
7143 // Nuke the old stores.
Chris Lattner5997cf92006-02-08 03:25:32 +00007144 EraseInstFromFunction(SI);
7145 EraseInstFromFunction(*OtherStore);
Chris Lattner219175c2005-09-12 23:23:25 +00007146 ++NumCombined;
7147 return 0;
7148 }
7149 }
7150 }
7151 }
7152
Chris Lattner31f486c2005-01-31 05:36:43 +00007153 return 0;
7154}
7155
7156
Chris Lattner9eef8a72003-06-04 04:46:00 +00007157Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
7158 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4fdd96c2005-06-18 17:37:34 +00007159 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00007160 BasicBlock *TrueDest;
7161 BasicBlock *FalseDest;
7162 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
7163 !isa<Constant>(X)) {
7164 // Swap Destinations and condition...
7165 BI.setCondition(X);
7166 BI.setSuccessor(0, FalseDest);
7167 BI.setSuccessor(1, TrueDest);
7168 return &BI;
7169 }
7170
7171 // Cannonicalize setne -> seteq
7172 Instruction::BinaryOps Op; Value *Y;
7173 if (match(&BI, m_Br(m_SetCond(Op, m_Value(X), m_Value(Y)),
7174 TrueDest, FalseDest)))
7175 if ((Op == Instruction::SetNE || Op == Instruction::SetLE ||
7176 Op == Instruction::SetGE) && BI.getCondition()->hasOneUse()) {
7177 SetCondInst *I = cast<SetCondInst>(BI.getCondition());
7178 std::string Name = I->getName(); I->setName("");
7179 Instruction::BinaryOps NewOpcode = SetCondInst::getInverseCondition(Op);
7180 Value *NewSCC = BinaryOperator::create(NewOpcode, X, Y, Name, I);
Chris Lattnere967b342003-06-04 05:10:11 +00007181 // Swap Destinations and condition...
Chris Lattnerd4252a72004-07-30 07:50:03 +00007182 BI.setCondition(NewSCC);
Chris Lattnere967b342003-06-04 05:10:11 +00007183 BI.setSuccessor(0, FalseDest);
7184 BI.setSuccessor(1, TrueDest);
Chris Lattnerd4252a72004-07-30 07:50:03 +00007185 removeFromWorkList(I);
7186 I->getParent()->getInstList().erase(I);
7187 WorkList.push_back(cast<Instruction>(NewSCC));
Chris Lattnere967b342003-06-04 05:10:11 +00007188 return &BI;
7189 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00007190
Chris Lattner9eef8a72003-06-04 04:46:00 +00007191 return 0;
7192}
Chris Lattner1085bdf2002-11-04 16:18:53 +00007193
Chris Lattner4c9c20a2004-07-03 00:26:11 +00007194Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
7195 Value *Cond = SI.getCondition();
7196 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
7197 if (I->getOpcode() == Instruction::Add)
7198 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7199 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
7200 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattner81a7a232004-10-16 18:11:37 +00007201 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner4c9c20a2004-07-03 00:26:11 +00007202 AddRHS));
7203 SI.setOperand(0, I->getOperand(0));
7204 WorkList.push_back(I);
7205 return &SI;
7206 }
7207 }
7208 return 0;
7209}
7210
Chris Lattner6bc98652006-03-05 00:22:33 +00007211/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
7212/// is to leave as a vector operation.
7213static bool CheapToScalarize(Value *V, bool isConstant) {
7214 if (isa<ConstantAggregateZero>(V))
7215 return true;
7216 if (ConstantPacked *C = dyn_cast<ConstantPacked>(V)) {
7217 if (isConstant) return true;
7218 // If all elts are the same, we can extract.
7219 Constant *Op0 = C->getOperand(0);
7220 for (unsigned i = 1; i < C->getNumOperands(); ++i)
7221 if (C->getOperand(i) != Op0)
7222 return false;
7223 return true;
7224 }
7225 Instruction *I = dyn_cast<Instruction>(V);
7226 if (!I) return false;
7227
7228 // Insert element gets simplified to the inserted element or is deleted if
7229 // this is constant idx extract element and its a constant idx insertelt.
7230 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
7231 isa<ConstantInt>(I->getOperand(2)))
7232 return true;
7233 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
7234 return true;
7235 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
7236 if (BO->hasOneUse() &&
7237 (CheapToScalarize(BO->getOperand(0), isConstant) ||
7238 CheapToScalarize(BO->getOperand(1), isConstant)))
7239 return true;
7240
7241 return false;
7242}
7243
Chris Lattner12249be2006-05-25 23:48:38 +00007244/// getShuffleMask - Read and decode a shufflevector mask. It turns undef
7245/// elements into values that are larger than the #elts in the input.
7246static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
7247 unsigned NElts = SVI->getType()->getNumElements();
7248 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
7249 return std::vector<unsigned>(NElts, 0);
7250 if (isa<UndefValue>(SVI->getOperand(2)))
7251 return std::vector<unsigned>(NElts, 2*NElts);
7252
7253 std::vector<unsigned> Result;
7254 const ConstantPacked *CP = cast<ConstantPacked>(SVI->getOperand(2));
7255 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
7256 if (isa<UndefValue>(CP->getOperand(i)))
7257 Result.push_back(NElts*2); // undef -> 8
7258 else
7259 Result.push_back(cast<ConstantUInt>(CP->getOperand(i))->getValue());
7260 return Result;
7261}
7262
Chris Lattner8d1d8d32006-03-31 23:01:56 +00007263/// FindScalarElement - Given a vector and an element number, see if the scalar
7264/// value is already around as a register, for example if it were inserted then
7265/// extracted from the vector.
7266static Value *FindScalarElement(Value *V, unsigned EltNo) {
7267 assert(isa<PackedType>(V->getType()) && "Not looking at a vector?");
7268 const PackedType *PTy = cast<PackedType>(V->getType());
Chris Lattner2d37f922006-04-10 23:06:36 +00007269 unsigned Width = PTy->getNumElements();
7270 if (EltNo >= Width) // Out of range access.
Chris Lattner8d1d8d32006-03-31 23:01:56 +00007271 return UndefValue::get(PTy->getElementType());
7272
7273 if (isa<UndefValue>(V))
7274 return UndefValue::get(PTy->getElementType());
7275 else if (isa<ConstantAggregateZero>(V))
7276 return Constant::getNullValue(PTy->getElementType());
7277 else if (ConstantPacked *CP = dyn_cast<ConstantPacked>(V))
7278 return CP->getOperand(EltNo);
7279 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
7280 // If this is an insert to a variable element, we don't know what it is.
7281 if (!isa<ConstantUInt>(III->getOperand(2))) return 0;
7282 unsigned IIElt = cast<ConstantUInt>(III->getOperand(2))->getValue();
7283
7284 // If this is an insert to the element we are looking for, return the
7285 // inserted value.
7286 if (EltNo == IIElt) return III->getOperand(1);
7287
7288 // Otherwise, the insertelement doesn't modify the value, recurse on its
7289 // vector input.
7290 return FindScalarElement(III->getOperand(0), EltNo);
Chris Lattner2d37f922006-04-10 23:06:36 +00007291 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Chris Lattner12249be2006-05-25 23:48:38 +00007292 unsigned InEl = getShuffleMask(SVI)[EltNo];
7293 if (InEl < Width)
7294 return FindScalarElement(SVI->getOperand(0), InEl);
7295 else if (InEl < Width*2)
7296 return FindScalarElement(SVI->getOperand(1), InEl - Width);
7297 else
7298 return UndefValue::get(PTy->getElementType());
Chris Lattner8d1d8d32006-03-31 23:01:56 +00007299 }
7300
7301 // Otherwise, we don't know.
7302 return 0;
7303}
7304
Robert Bocchinoa8352962006-01-13 22:48:06 +00007305Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Chris Lattner8d1d8d32006-03-31 23:01:56 +00007306
Chris Lattner92346c32006-03-31 18:25:14 +00007307 // If packed val is undef, replace extract with scalar undef.
7308 if (isa<UndefValue>(EI.getOperand(0)))
7309 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
7310
7311 // If packed val is constant 0, replace extract with scalar 0.
7312 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
7313 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
7314
Robert Bocchinoa8352962006-01-13 22:48:06 +00007315 if (ConstantPacked *C = dyn_cast<ConstantPacked>(EI.getOperand(0))) {
7316 // If packed val is constant with uniform operands, replace EI
7317 // with that operand
Chris Lattner6bc98652006-03-05 00:22:33 +00007318 Constant *op0 = C->getOperand(0);
Robert Bocchinoa8352962006-01-13 22:48:06 +00007319 for (unsigned i = 1; i < C->getNumOperands(); ++i)
Chris Lattner6bc98652006-03-05 00:22:33 +00007320 if (C->getOperand(i) != op0) {
7321 op0 = 0;
7322 break;
7323 }
7324 if (op0)
7325 return ReplaceInstUsesWith(EI, op0);
Robert Bocchinoa8352962006-01-13 22:48:06 +00007326 }
Chris Lattner6bc98652006-03-05 00:22:33 +00007327
Chris Lattner8d1d8d32006-03-31 23:01:56 +00007328 // If extracting a specified index from the vector, see if we can recursively
7329 // find a previously computed scalar that was inserted into the vector.
Chris Lattner2d37f922006-04-10 23:06:36 +00007330 if (ConstantUInt *IdxC = dyn_cast<ConstantUInt>(EI.getOperand(1))) {
Chris Lattner8d1d8d32006-03-31 23:01:56 +00007331 if (Value *Elt = FindScalarElement(EI.getOperand(0), IdxC->getValue()))
7332 return ReplaceInstUsesWith(EI, Elt);
Chris Lattner2d37f922006-04-10 23:06:36 +00007333 }
Chris Lattner8d1d8d32006-03-31 23:01:56 +00007334
Chris Lattner83f65782006-05-25 22:53:38 +00007335 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Robert Bocchinoa8352962006-01-13 22:48:06 +00007336 if (I->hasOneUse()) {
7337 // Push extractelement into predecessor operation if legal and
7338 // profitable to do so
7339 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Chris Lattner6bc98652006-03-05 00:22:33 +00007340 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
7341 if (CheapToScalarize(BO, isConstantElt)) {
7342 ExtractElementInst *newEI0 =
7343 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
7344 EI.getName()+".lhs");
7345 ExtractElementInst *newEI1 =
7346 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
7347 EI.getName()+".rhs");
7348 InsertNewInstBefore(newEI0, EI);
7349 InsertNewInstBefore(newEI1, EI);
7350 return BinaryOperator::create(BO->getOpcode(), newEI0, newEI1);
7351 }
7352 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Robert Bocchinoa8352962006-01-13 22:48:06 +00007353 Value *Ptr = InsertCastBefore(I->getOperand(0),
7354 PointerType::get(EI.getType()), EI);
7355 GetElementPtrInst *GEP =
7356 new GetElementPtrInst(Ptr, EI.getOperand(1),
7357 I->getName() + ".gep");
7358 InsertNewInstBefore(GEP, EI);
7359 return new LoadInst(GEP);
Chris Lattner83f65782006-05-25 22:53:38 +00007360 }
7361 }
7362 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
7363 // Extracting the inserted element?
7364 if (IE->getOperand(2) == EI.getOperand(1))
7365 return ReplaceInstUsesWith(EI, IE->getOperand(1));
7366 // If the inserted and extracted elements are constants, they must not
7367 // be the same value, extract from the pre-inserted value instead.
7368 if (isa<Constant>(IE->getOperand(2)) &&
7369 isa<Constant>(EI.getOperand(1))) {
7370 AddUsesToWorkList(EI);
7371 EI.setOperand(0, IE->getOperand(0));
7372 return &EI;
7373 }
7374 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
7375 // If this is extracting an element from a shufflevector, figure out where
7376 // it came from and extract from the appropriate input element instead.
7377 if (ConstantUInt *Elt = dyn_cast<ConstantUInt>(EI.getOperand(1))) {
Chris Lattner12249be2006-05-25 23:48:38 +00007378 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getValue()];
7379 Value *Src;
7380 if (SrcIdx < SVI->getType()->getNumElements())
7381 Src = SVI->getOperand(0);
7382 else if (SrcIdx < SVI->getType()->getNumElements()*2) {
7383 SrcIdx -= SVI->getType()->getNumElements();
7384 Src = SVI->getOperand(1);
7385 } else {
7386 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattner612fa8e2006-03-30 22:02:40 +00007387 }
Chris Lattner12249be2006-05-25 23:48:38 +00007388 return new ExtractElementInst(Src,
7389 ConstantUInt::get(Type::UIntTy, SrcIdx));
Robert Bocchinoa8352962006-01-13 22:48:06 +00007390 }
7391 }
Chris Lattner83f65782006-05-25 22:53:38 +00007392 }
Robert Bocchinoa8352962006-01-13 22:48:06 +00007393 return 0;
7394}
7395
Chris Lattner90951862006-04-16 00:51:47 +00007396/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
7397/// elements from either LHS or RHS, return the shuffle mask and true.
7398/// Otherwise, return false.
7399static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
7400 std::vector<Constant*> &Mask) {
7401 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
7402 "Invalid CollectSingleShuffleElements");
7403 unsigned NumElts = cast<PackedType>(V->getType())->getNumElements();
7404
7405 if (isa<UndefValue>(V)) {
7406 Mask.assign(NumElts, UndefValue::get(Type::UIntTy));
7407 return true;
7408 } else if (V == LHS) {
7409 for (unsigned i = 0; i != NumElts; ++i)
7410 Mask.push_back(ConstantUInt::get(Type::UIntTy, i));
7411 return true;
7412 } else if (V == RHS) {
7413 for (unsigned i = 0; i != NumElts; ++i)
7414 Mask.push_back(ConstantUInt::get(Type::UIntTy, i+NumElts));
7415 return true;
7416 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
7417 // If this is an insert of an extract from some other vector, include it.
7418 Value *VecOp = IEI->getOperand(0);
7419 Value *ScalarOp = IEI->getOperand(1);
7420 Value *IdxOp = IEI->getOperand(2);
7421
Chris Lattnerb6cb64b2006-04-27 21:14:21 +00007422 if (!isa<ConstantInt>(IdxOp))
7423 return false;
7424 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getRawValue();
7425
7426 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
7427 // Okay, we can handle this if the vector we are insertinting into is
7428 // transitively ok.
7429 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
7430 // If so, update the mask to reflect the inserted undef.
7431 Mask[InsertedIdx] = UndefValue::get(Type::UIntTy);
7432 return true;
7433 }
7434 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
7435 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner90951862006-04-16 00:51:47 +00007436 EI->getOperand(0)->getType() == V->getType()) {
7437 unsigned ExtractedIdx =
7438 cast<ConstantInt>(EI->getOperand(1))->getRawValue();
Chris Lattner90951862006-04-16 00:51:47 +00007439
7440 // This must be extracting from either LHS or RHS.
7441 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
7442 // Okay, we can handle this if the vector we are insertinting into is
7443 // transitively ok.
7444 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
7445 // If so, update the mask to reflect the inserted value.
7446 if (EI->getOperand(0) == LHS) {
7447 Mask[InsertedIdx & (NumElts-1)] =
7448 ConstantUInt::get(Type::UIntTy, ExtractedIdx);
7449 } else {
7450 assert(EI->getOperand(0) == RHS);
7451 Mask[InsertedIdx & (NumElts-1)] =
7452 ConstantUInt::get(Type::UIntTy, ExtractedIdx+NumElts);
7453
7454 }
7455 return true;
7456 }
7457 }
7458 }
7459 }
7460 }
7461 // TODO: Handle shufflevector here!
7462
7463 return false;
7464}
7465
7466/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
7467/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
7468/// that computes V and the LHS value of the shuffle.
Chris Lattner39fac442006-04-15 01:39:45 +00007469static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Chris Lattner90951862006-04-16 00:51:47 +00007470 Value *&RHS) {
7471 assert(isa<PackedType>(V->getType()) &&
7472 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattner39fac442006-04-15 01:39:45 +00007473 "Invalid shuffle!");
7474 unsigned NumElts = cast<PackedType>(V->getType())->getNumElements();
7475
7476 if (isa<UndefValue>(V)) {
7477 Mask.assign(NumElts, UndefValue::get(Type::UIntTy));
7478 return V;
7479 } else if (isa<ConstantAggregateZero>(V)) {
7480 Mask.assign(NumElts, ConstantUInt::get(Type::UIntTy, 0));
7481 return V;
7482 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
7483 // If this is an insert of an extract from some other vector, include it.
7484 Value *VecOp = IEI->getOperand(0);
7485 Value *ScalarOp = IEI->getOperand(1);
7486 Value *IdxOp = IEI->getOperand(2);
7487
7488 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
7489 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
7490 EI->getOperand(0)->getType() == V->getType()) {
7491 unsigned ExtractedIdx =
7492 cast<ConstantInt>(EI->getOperand(1))->getRawValue();
7493 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getRawValue();
7494
7495 // Either the extracted from or inserted into vector must be RHSVec,
7496 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner90951862006-04-16 00:51:47 +00007497 if (EI->getOperand(0) == RHS || RHS == 0) {
7498 RHS = EI->getOperand(0);
7499 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
Chris Lattner39fac442006-04-15 01:39:45 +00007500 Mask[InsertedIdx & (NumElts-1)] =
7501 ConstantUInt::get(Type::UIntTy, NumElts+ExtractedIdx);
7502 return V;
7503 }
7504
Chris Lattner90951862006-04-16 00:51:47 +00007505 if (VecOp == RHS) {
7506 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
Chris Lattner39fac442006-04-15 01:39:45 +00007507 // Everything but the extracted element is replaced with the RHS.
7508 for (unsigned i = 0; i != NumElts; ++i) {
7509 if (i != InsertedIdx)
7510 Mask[i] = ConstantUInt::get(Type::UIntTy, NumElts+i);
7511 }
7512 return V;
7513 }
Chris Lattner90951862006-04-16 00:51:47 +00007514
7515 // If this insertelement is a chain that comes from exactly these two
7516 // vectors, return the vector and the effective shuffle.
7517 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
7518 return EI->getOperand(0);
7519
Chris Lattner39fac442006-04-15 01:39:45 +00007520 }
7521 }
7522 }
Chris Lattner90951862006-04-16 00:51:47 +00007523 // TODO: Handle shufflevector here!
Chris Lattner39fac442006-04-15 01:39:45 +00007524
7525 // Otherwise, can't do anything fancy. Return an identity vector.
7526 for (unsigned i = 0; i != NumElts; ++i)
7527 Mask.push_back(ConstantUInt::get(Type::UIntTy, i));
7528 return V;
7529}
7530
7531Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
7532 Value *VecOp = IE.getOperand(0);
7533 Value *ScalarOp = IE.getOperand(1);
7534 Value *IdxOp = IE.getOperand(2);
7535
7536 // If the inserted element was extracted from some other vector, and if the
7537 // indexes are constant, try to turn this into a shufflevector operation.
7538 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
7539 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
7540 EI->getOperand(0)->getType() == IE.getType()) {
7541 unsigned NumVectorElts = IE.getType()->getNumElements();
7542 unsigned ExtractedIdx=cast<ConstantInt>(EI->getOperand(1))->getRawValue();
7543 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getRawValue();
7544
7545 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
7546 return ReplaceInstUsesWith(IE, VecOp);
7547
7548 if (InsertedIdx >= NumVectorElts) // Out of range insert.
7549 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
7550
7551 // If we are extracting a value from a vector, then inserting it right
7552 // back into the same place, just use the input vector.
7553 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
7554 return ReplaceInstUsesWith(IE, VecOp);
7555
7556 // We could theoretically do this for ANY input. However, doing so could
7557 // turn chains of insertelement instructions into a chain of shufflevector
7558 // instructions, and right now we do not merge shufflevectors. As such,
7559 // only do this in a situation where it is clear that there is benefit.
7560 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
7561 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
7562 // the values of VecOp, except then one read from EIOp0.
7563 // Build a new shuffle mask.
7564 std::vector<Constant*> Mask;
7565 if (isa<UndefValue>(VecOp))
7566 Mask.assign(NumVectorElts, UndefValue::get(Type::UIntTy));
7567 else {
7568 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
7569 Mask.assign(NumVectorElts, ConstantUInt::get(Type::UIntTy,
7570 NumVectorElts));
7571 }
7572 Mask[InsertedIdx] = ConstantUInt::get(Type::UIntTy, ExtractedIdx);
7573 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
7574 ConstantPacked::get(Mask));
7575 }
7576
7577 // If this insertelement isn't used by some other insertelement, turn it
7578 // (and any insertelements it points to), into one big shuffle.
7579 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
7580 std::vector<Constant*> Mask;
Chris Lattner90951862006-04-16 00:51:47 +00007581 Value *RHS = 0;
7582 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
7583 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
7584 // We now have a shuffle of LHS, RHS, Mask.
7585 return new ShuffleVectorInst(LHS, RHS, ConstantPacked::get(Mask));
Chris Lattner39fac442006-04-15 01:39:45 +00007586 }
7587 }
7588 }
7589
7590 return 0;
7591}
7592
7593
Chris Lattnerfbb77a42006-04-10 22:45:52 +00007594Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
7595 Value *LHS = SVI.getOperand(0);
7596 Value *RHS = SVI.getOperand(1);
Chris Lattner12249be2006-05-25 23:48:38 +00007597 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnerfbb77a42006-04-10 22:45:52 +00007598
7599 bool MadeChange = false;
7600
Chris Lattner12249be2006-05-25 23:48:38 +00007601 if (isa<UndefValue>(SVI.getOperand(2)))
Chris Lattnerfbb77a42006-04-10 22:45:52 +00007602 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
7603
Chris Lattner39fac442006-04-15 01:39:45 +00007604 // TODO: If we have shuffle(x, undef, mask) and any elements of mask refer to
7605 // the undef, change them to undefs.
7606
Chris Lattner12249be2006-05-25 23:48:38 +00007607 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
7608 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
7609 if (LHS == RHS || isa<UndefValue>(LHS)) {
7610 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnerfbb77a42006-04-10 22:45:52 +00007611 // shuffle(undef,undef,mask) -> undef.
7612 return ReplaceInstUsesWith(SVI, LHS);
7613 }
7614
Chris Lattner12249be2006-05-25 23:48:38 +00007615 // Remap any references to RHS to use LHS.
7616 std::vector<Constant*> Elts;
7617 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner0e477162006-05-26 00:29:06 +00007618 if (Mask[i] >= 2*e)
Chris Lattner12249be2006-05-25 23:48:38 +00007619 Elts.push_back(UndefValue::get(Type::UIntTy));
Chris Lattner0e477162006-05-26 00:29:06 +00007620 else {
7621 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
7622 (Mask[i] < e && isa<UndefValue>(LHS)))
7623 Mask[i] = 2*e; // Turn into undef.
7624 else
7625 Mask[i] &= (e-1); // Force to LHS.
7626 Elts.push_back(ConstantUInt::get(Type::UIntTy, Mask[i]));
7627 }
Chris Lattnerfbb77a42006-04-10 22:45:52 +00007628 }
Chris Lattner12249be2006-05-25 23:48:38 +00007629 SVI.setOperand(0, SVI.getOperand(1));
Chris Lattnerfbb77a42006-04-10 22:45:52 +00007630 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Chris Lattner12249be2006-05-25 23:48:38 +00007631 SVI.setOperand(2, ConstantPacked::get(Elts));
Chris Lattner0e477162006-05-26 00:29:06 +00007632 LHS = SVI.getOperand(0);
7633 RHS = SVI.getOperand(1);
Chris Lattnerfbb77a42006-04-10 22:45:52 +00007634 MadeChange = true;
7635 }
7636
Chris Lattner0e477162006-05-26 00:29:06 +00007637 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner12249be2006-05-25 23:48:38 +00007638 bool isLHSID = true, isRHSID = true;
Chris Lattner34cebe72006-04-16 00:03:56 +00007639
Chris Lattner12249be2006-05-25 23:48:38 +00007640 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
7641 if (Mask[i] >= e*2) continue; // Ignore undef values.
7642 // Is this an identity shuffle of the LHS value?
7643 isLHSID &= (Mask[i] == i);
7644
7645 // Is this an identity shuffle of the RHS value?
7646 isRHSID &= (Mask[i]-e == i);
Chris Lattner34cebe72006-04-16 00:03:56 +00007647 }
Chris Lattnerfbb77a42006-04-10 22:45:52 +00007648
Chris Lattner12249be2006-05-25 23:48:38 +00007649 // Eliminate identity shuffles.
7650 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
7651 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnerfbb77a42006-04-10 22:45:52 +00007652
Chris Lattner0e477162006-05-26 00:29:06 +00007653 // If the LHS is a shufflevector itself, see if we can combine it with this
7654 // one without producing an unusual shuffle. Here we are really conservative:
7655 // we are absolutely afraid of producing a shuffle mask not in the input
7656 // program, because the code gen may not be smart enough to turn a merged
7657 // shuffle into two specific shuffles: it may produce worse code. As such,
7658 // we only merge two shuffles if the result is one of the two input shuffle
7659 // masks. In this case, merging the shuffles just removes one instruction,
7660 // which we know is safe. This is good for things like turning:
7661 // (splat(splat)) -> splat.
7662 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
7663 if (isa<UndefValue>(RHS)) {
7664 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
7665
7666 std::vector<unsigned> NewMask;
7667 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
7668 if (Mask[i] >= 2*e)
7669 NewMask.push_back(2*e);
7670 else
7671 NewMask.push_back(LHSMask[Mask[i]]);
7672
7673 // If the result mask is equal to the src shuffle or this shuffle mask, do
7674 // the replacement.
7675 if (NewMask == LHSMask || NewMask == Mask) {
7676 std::vector<Constant*> Elts;
7677 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
7678 if (NewMask[i] >= e*2) {
7679 Elts.push_back(UndefValue::get(Type::UIntTy));
7680 } else {
7681 Elts.push_back(ConstantUInt::get(Type::UIntTy, NewMask[i]));
7682 }
7683 }
7684 return new ShuffleVectorInst(LHSSVI->getOperand(0),
7685 LHSSVI->getOperand(1),
7686 ConstantPacked::get(Elts));
7687 }
7688 }
7689 }
7690
Chris Lattnerfbb77a42006-04-10 22:45:52 +00007691 return MadeChange ? &SVI : 0;
7692}
7693
7694
Robert Bocchinoa8352962006-01-13 22:48:06 +00007695
Chris Lattner99f48c62002-09-02 04:59:56 +00007696void InstCombiner::removeFromWorkList(Instruction *I) {
7697 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
7698 WorkList.end());
7699}
7700
Chris Lattner39c98bb2004-12-08 23:43:58 +00007701
7702/// TryToSinkInstruction - Try to move the specified instruction from its
7703/// current block into the beginning of DestBlock, which can only happen if it's
7704/// safe to move the instruction past all of the instructions between it and the
7705/// end of its block.
7706static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
7707 assert(I->hasOneUse() && "Invariants didn't hold!");
7708
Chris Lattnerc4f67e62005-10-27 17:13:11 +00007709 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
7710 if (isa<PHINode>(I) || I->mayWriteToMemory()) return false;
Misha Brukmanb1c93172005-04-21 23:48:37 +00007711
Chris Lattner39c98bb2004-12-08 23:43:58 +00007712 // Do not sink alloca instructions out of the entry block.
7713 if (isa<AllocaInst>(I) && I->getParent() == &DestBlock->getParent()->front())
7714 return false;
7715
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00007716 // We can only sink load instructions if there is nothing between the load and
7717 // the end of block that could change the value.
7718 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00007719 for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
7720 Scan != E; ++Scan)
7721 if (Scan->mayWriteToMemory())
7722 return false;
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00007723 }
Chris Lattner39c98bb2004-12-08 23:43:58 +00007724
7725 BasicBlock::iterator InsertPos = DestBlock->begin();
7726 while (isa<PHINode>(InsertPos)) ++InsertPos;
7727
Chris Lattner9f269e42005-08-08 19:11:57 +00007728 I->moveBefore(InsertPos);
Chris Lattner39c98bb2004-12-08 23:43:58 +00007729 ++NumSunkInst;
7730 return true;
7731}
7732
Chris Lattner1443bc52006-05-11 17:11:52 +00007733/// OptimizeConstantExpr - Given a constant expression and target data layout
7734/// information, symbolically evaluation the constant expr to something simpler
7735/// if possible.
7736static Constant *OptimizeConstantExpr(ConstantExpr *CE, const TargetData *TD) {
7737 if (!TD) return CE;
7738
7739 Constant *Ptr = CE->getOperand(0);
7740 if (CE->getOpcode() == Instruction::GetElementPtr && Ptr->isNullValue() &&
7741 cast<PointerType>(Ptr->getType())->getElementType()->isSized()) {
7742 // If this is a constant expr gep that is effectively computing an
7743 // "offsetof", fold it into 'cast int Size to T*' instead of 'gep 0, 0, 12'
7744 bool isFoldableGEP = true;
7745 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
7746 if (!isa<ConstantInt>(CE->getOperand(i)))
7747 isFoldableGEP = false;
7748 if (isFoldableGEP) {
7749 std::vector<Value*> Ops(CE->op_begin()+1, CE->op_end());
7750 uint64_t Offset = TD->getIndexedOffset(Ptr->getType(), Ops);
7751 Constant *C = ConstantUInt::get(Type::ULongTy, Offset);
7752 C = ConstantExpr::getCast(C, TD->getIntPtrType());
7753 return ConstantExpr::getCast(C, CE->getType());
7754 }
7755 }
7756
7757 return CE;
7758}
7759
Chris Lattnera36ee4e2006-05-10 19:00:36 +00007760
7761/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
7762/// all reachable code to the worklist.
7763///
7764/// This has a couple of tricks to make the code faster and more powerful. In
7765/// particular, we constant fold and DCE instructions as we go, to avoid adding
7766/// them to the worklist (this significantly speeds up instcombine on code where
7767/// many instructions are dead or constant). Additionally, if we find a branch
7768/// whose condition is a known constant, we only visit the reachable successors.
7769///
7770static void AddReachableCodeToWorklist(BasicBlock *BB,
7771 std::set<BasicBlock*> &Visited,
Chris Lattner1443bc52006-05-11 17:11:52 +00007772 std::vector<Instruction*> &WorkList,
7773 const TargetData *TD) {
Chris Lattnera36ee4e2006-05-10 19:00:36 +00007774 // We have now visited this block! If we've already been here, bail out.
7775 if (!Visited.insert(BB).second) return;
7776
7777 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
7778 Instruction *Inst = BBI++;
7779
7780 // DCE instruction if trivially dead.
7781 if (isInstructionTriviallyDead(Inst)) {
7782 ++NumDeadInst;
7783 DEBUG(std::cerr << "IC: DCE: " << *Inst);
7784 Inst->eraseFromParent();
7785 continue;
7786 }
7787
7788 // ConstantProp instruction if trivially constant.
7789 if (Constant *C = ConstantFoldInstruction(Inst)) {
Chris Lattner1443bc52006-05-11 17:11:52 +00007790 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
7791 C = OptimizeConstantExpr(CE, TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00007792 DEBUG(std::cerr << "IC: ConstFold to: " << *C << " from: " << *Inst);
7793 Inst->replaceAllUsesWith(C);
7794 ++NumConstProp;
7795 Inst->eraseFromParent();
7796 continue;
7797 }
7798
7799 WorkList.push_back(Inst);
7800 }
7801
7802 // Recursively visit successors. If this is a branch or switch on a constant,
7803 // only visit the reachable successor.
7804 TerminatorInst *TI = BB->getTerminator();
7805 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
7806 if (BI->isConditional() && isa<ConstantBool>(BI->getCondition())) {
7807 bool CondVal = cast<ConstantBool>(BI->getCondition())->getValue();
Chris Lattner1443bc52006-05-11 17:11:52 +00007808 AddReachableCodeToWorklist(BI->getSuccessor(!CondVal), Visited, WorkList,
7809 TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00007810 return;
7811 }
7812 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
7813 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
7814 // See if this is an explicit destination.
7815 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
7816 if (SI->getCaseValue(i) == Cond) {
Chris Lattner1443bc52006-05-11 17:11:52 +00007817 AddReachableCodeToWorklist(SI->getSuccessor(i), Visited, WorkList,TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00007818 return;
7819 }
7820
7821 // Otherwise it is the default destination.
Chris Lattner1443bc52006-05-11 17:11:52 +00007822 AddReachableCodeToWorklist(SI->getSuccessor(0), Visited, WorkList, TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00007823 return;
7824 }
7825 }
7826
7827 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
Chris Lattner1443bc52006-05-11 17:11:52 +00007828 AddReachableCodeToWorklist(TI->getSuccessor(i), Visited, WorkList, TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00007829}
7830
Chris Lattner113f4f42002-06-25 16:13:24 +00007831bool InstCombiner::runOnFunction(Function &F) {
Chris Lattner260ab202002-04-18 17:39:14 +00007832 bool Changed = false;
Chris Lattnerf4ad1652003-11-02 05:57:39 +00007833 TD = &getAnalysis<TargetData>();
Chris Lattnerca081252001-12-14 16:52:21 +00007834
Chris Lattner4ed40f72005-07-07 20:40:38 +00007835 {
Chris Lattnera36ee4e2006-05-10 19:00:36 +00007836 // Do a depth-first traversal of the function, populate the worklist with
7837 // the reachable instructions. Ignore blocks that are not reachable. Keep
7838 // track of which blocks we visit.
Chris Lattner4ed40f72005-07-07 20:40:38 +00007839 std::set<BasicBlock*> Visited;
Chris Lattner1443bc52006-05-11 17:11:52 +00007840 AddReachableCodeToWorklist(F.begin(), Visited, WorkList, TD);
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00007841
Chris Lattner4ed40f72005-07-07 20:40:38 +00007842 // Do a quick scan over the function. If we find any blocks that are
7843 // unreachable, remove any instructions inside of them. This prevents
7844 // the instcombine code from having to deal with some bad special cases.
7845 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
7846 if (!Visited.count(BB)) {
7847 Instruction *Term = BB->getTerminator();
7848 while (Term != BB->begin()) { // Remove instrs bottom-up
7849 BasicBlock::iterator I = Term; --I;
Chris Lattner2d3a7a62004-04-27 15:13:33 +00007850
Chris Lattner4ed40f72005-07-07 20:40:38 +00007851 DEBUG(std::cerr << "IC: DCE: " << *I);
7852 ++NumDeadInst;
7853
7854 if (!I->use_empty())
7855 I->replaceAllUsesWith(UndefValue::get(I->getType()));
7856 I->eraseFromParent();
7857 }
7858 }
7859 }
Chris Lattnerca081252001-12-14 16:52:21 +00007860
7861 while (!WorkList.empty()) {
7862 Instruction *I = WorkList.back(); // Get an instruction from the worklist
7863 WorkList.pop_back();
7864
Chris Lattner1443bc52006-05-11 17:11:52 +00007865 // Check to see if we can DCE the instruction.
Chris Lattner99f48c62002-09-02 04:59:56 +00007866 if (isInstructionTriviallyDead(I)) {
Chris Lattner1443bc52006-05-11 17:11:52 +00007867 // Add operands to the worklist.
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00007868 if (I->getNumOperands() < 4)
Chris Lattner51ea1272004-02-28 05:22:00 +00007869 AddUsesToWorkList(*I);
Chris Lattner99f48c62002-09-02 04:59:56 +00007870 ++NumDeadInst;
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00007871
Chris Lattnercd517ff2005-01-28 19:32:01 +00007872 DEBUG(std::cerr << "IC: DCE: " << *I);
7873
7874 I->eraseFromParent();
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00007875 removeFromWorkList(I);
7876 continue;
7877 }
Chris Lattner99f48c62002-09-02 04:59:56 +00007878
Chris Lattner1443bc52006-05-11 17:11:52 +00007879 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattner99f48c62002-09-02 04:59:56 +00007880 if (Constant *C = ConstantFoldInstruction(I)) {
Chris Lattner1443bc52006-05-11 17:11:52 +00007881 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
7882 C = OptimizeConstantExpr(CE, TD);
Chris Lattnercd517ff2005-01-28 19:32:01 +00007883 DEBUG(std::cerr << "IC: ConstFold to: " << *C << " from: " << *I);
7884
Chris Lattner1443bc52006-05-11 17:11:52 +00007885 // Add operands to the worklist.
Chris Lattner51ea1272004-02-28 05:22:00 +00007886 AddUsesToWorkList(*I);
Chris Lattnerc6509f42002-12-05 22:41:53 +00007887 ReplaceInstUsesWith(*I, C);
7888
Chris Lattner99f48c62002-09-02 04:59:56 +00007889 ++NumConstProp;
Chris Lattnera36ee4e2006-05-10 19:00:36 +00007890 I->eraseFromParent();
Chris Lattner800aaaf2003-10-07 15:17:02 +00007891 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00007892 continue;
Chris Lattner99f48c62002-09-02 04:59:56 +00007893 }
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00007894
Chris Lattner39c98bb2004-12-08 23:43:58 +00007895 // See if we can trivially sink this instruction to a successor basic block.
7896 if (I->hasOneUse()) {
7897 BasicBlock *BB = I->getParent();
7898 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
7899 if (UserParent != BB) {
7900 bool UserIsSuccessor = false;
7901 // See if the user is one of our successors.
7902 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
7903 if (*SI == UserParent) {
7904 UserIsSuccessor = true;
7905 break;
7906 }
7907
7908 // If the user is one of our immediate successors, and if that successor
7909 // only has us as a predecessors (we'd have to split the critical edge
7910 // otherwise), we can keep going.
7911 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
7912 next(pred_begin(UserParent)) == pred_end(UserParent))
7913 // Okay, the CFG is simple enough, try to sink this instruction.
7914 Changed |= TryToSinkInstruction(I, UserParent);
7915 }
7916 }
7917
Chris Lattnerca081252001-12-14 16:52:21 +00007918 // Now that we have an instruction, try combining it to simplify it...
Chris Lattnerae7a0d32002-08-02 19:29:35 +00007919 if (Instruction *Result = visit(*I)) {
Chris Lattner0b18c1d2002-05-10 15:38:35 +00007920 ++NumCombined;
Chris Lattner260ab202002-04-18 17:39:14 +00007921 // Should we replace the old instruction with a new one?
Chris Lattner053c0932002-05-14 15:24:07 +00007922 if (Result != I) {
Chris Lattner7d2a5392004-03-13 23:54:27 +00007923 DEBUG(std::cerr << "IC: Old = " << *I
7924 << " New = " << *Result);
7925
Chris Lattner396dbfe2004-06-09 05:08:07 +00007926 // Everything uses the new instruction now.
7927 I->replaceAllUsesWith(Result);
7928
7929 // Push the new instruction and any users onto the worklist.
7930 WorkList.push_back(Result);
7931 AddUsersToWorkList(*Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00007932
7933 // Move the name to the new instruction first...
7934 std::string OldName = I->getName(); I->setName("");
Chris Lattner950fc782003-10-07 22:58:41 +00007935 Result->setName(OldName);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00007936
7937 // Insert the new instruction into the basic block...
7938 BasicBlock *InstParent = I->getParent();
Chris Lattner7515cab2004-11-14 19:13:23 +00007939 BasicBlock::iterator InsertPos = I;
7940
7941 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
7942 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
7943 ++InsertPos;
7944
7945 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00007946
Chris Lattner63d75af2004-05-01 23:27:23 +00007947 // Make sure that we reprocess all operands now that we reduced their
7948 // use counts.
Chris Lattnerb643a9e2004-05-01 23:19:52 +00007949 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
7950 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
7951 WorkList.push_back(OpI);
7952
Chris Lattner396dbfe2004-06-09 05:08:07 +00007953 // Instructions can end up on the worklist more than once. Make sure
7954 // we do not process an instruction that has been deleted.
7955 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00007956
7957 // Erase the old instruction.
7958 InstParent->getInstList().erase(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00007959 } else {
Chris Lattner7d2a5392004-03-13 23:54:27 +00007960 DEBUG(std::cerr << "IC: MOD = " << *I);
7961
Chris Lattnerae7a0d32002-08-02 19:29:35 +00007962 // If the instruction was modified, it's possible that it is now dead.
7963 // if so, remove it.
Chris Lattner63d75af2004-05-01 23:27:23 +00007964 if (isInstructionTriviallyDead(I)) {
7965 // Make sure we process all operands now that we are reducing their
7966 // use counts.
7967 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
7968 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
7969 WorkList.push_back(OpI);
Misha Brukmanb1c93172005-04-21 23:48:37 +00007970
Chris Lattner63d75af2004-05-01 23:27:23 +00007971 // Instructions may end up in the worklist more than once. Erase all
Robert Bocchinoa8352962006-01-13 22:48:06 +00007972 // occurrences of this instruction.
Chris Lattner99f48c62002-09-02 04:59:56 +00007973 removeFromWorkList(I);
Chris Lattner31f486c2005-01-31 05:36:43 +00007974 I->eraseFromParent();
Chris Lattner396dbfe2004-06-09 05:08:07 +00007975 } else {
7976 WorkList.push_back(Result);
7977 AddUsersToWorkList(*Result);
Chris Lattnerae7a0d32002-08-02 19:29:35 +00007978 }
Chris Lattner053c0932002-05-14 15:24:07 +00007979 }
Chris Lattner260ab202002-04-18 17:39:14 +00007980 Changed = true;
Chris Lattnerca081252001-12-14 16:52:21 +00007981 }
7982 }
7983
Chris Lattner260ab202002-04-18 17:39:14 +00007984 return Changed;
Chris Lattner04805fa2002-02-26 21:46:54 +00007985}
7986
Brian Gaeke38b79e82004-07-27 17:43:21 +00007987FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattner260ab202002-04-18 17:39:14 +00007988 return new InstCombiner();
Chris Lattner04805fa2002-02-26 21:46:54 +00007989}
Brian Gaeke960707c2003-11-11 22:41:34 +00007990