blob: 9bfd66afb2905a94966003b27c3e6848fd7f608b [file] [log] [blame]
Chris Lattnere6794492002-08-12 21:17:25 +00001//===- InstructionCombining.cpp - Combine multiple instructions -----------===//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
John Criswell482202a2003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
Misha Brukmanb1c93172005-04-21 23:48:37 +00007//
John Criswell482202a2003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattnerca081252001-12-14 16:52:21 +00009//
10// InstructionCombining - Combine instructions to form fewer, simple
Chris Lattner99f48c62002-09-02 04:59:56 +000011// instructions. This pass does not modify the CFG This pass is where algebraic
12// simplification happens.
Chris Lattnerca081252001-12-14 16:52:21 +000013//
14// This pass combines things like:
Chris Lattnerdd1a86d2004-05-04 15:19:33 +000015// %Y = add int %X, 1
16// %Z = add int %Y, 1
Chris Lattnerca081252001-12-14 16:52:21 +000017// into:
Chris Lattnerdd1a86d2004-05-04 15:19:33 +000018// %Z = add int %X, 2
Chris Lattnerca081252001-12-14 16:52:21 +000019//
20// This is a simple worklist driven algorithm.
21//
Chris Lattner216c7b82003-09-10 05:29:43 +000022// This pass guarantees that the following canonicalizations are performed on
Chris Lattnerbfb1d032003-07-23 21:41:57 +000023// the program:
24// 1. If a binary operator has a constant operand, it is moved to the RHS
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +000025// 2. Bitwise operators with constant operands are always grouped so that
26// shifts are performed first, then or's, then and's, then xor's.
Chris Lattnerbfb1d032003-07-23 21:41:57 +000027// 3. SetCC instructions are converted from <,>,<=,>= to ==,!= if possible
28// 4. All SetCC instructions on boolean values are replaced with logical ops
Chris Lattnerede3fe02003-08-13 04:18:28 +000029// 5. add X, X is represented as (X*2) => (X << 1)
30// 6. Multiplies with a power-of-two constant argument are transformed into
31// shifts.
Chris Lattner7515cab2004-11-14 19:13:23 +000032// ... etc.
Chris Lattnerbfb1d032003-07-23 21:41:57 +000033//
Chris Lattnerca081252001-12-14 16:52:21 +000034//===----------------------------------------------------------------------===//
35
Chris Lattner7d2a5392004-03-13 23:54:27 +000036#define DEBUG_TYPE "instcombine"
Chris Lattnerb4cfa7f2002-05-07 20:03:00 +000037#include "llvm/Transforms/Scalar.h"
Chris Lattner00648e12004-10-12 04:52:52 +000038#include "llvm/IntrinsicInst.h"
Chris Lattner04805fa2002-02-26 21:46:54 +000039#include "llvm/Pass.h"
Chris Lattner1085bdf2002-11-04 16:18:53 +000040#include "llvm/DerivedTypes.h"
Chris Lattner0f1d8a32003-06-26 05:06:25 +000041#include "llvm/GlobalVariable.h"
Chris Lattnerf4ad1652003-11-02 05:57:39 +000042#include "llvm/Target/TargetData.h"
43#include "llvm/Transforms/Utils/BasicBlockUtils.h"
44#include "llvm/Transforms/Utils/Local.h"
Chris Lattner69193f92004-04-05 01:30:19 +000045#include "llvm/Support/CallSite.h"
Chris Lattner39c98bb2004-12-08 23:43:58 +000046#include "llvm/Support/Debug.h"
Chris Lattner69193f92004-04-05 01:30:19 +000047#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner260ab202002-04-18 17:39:14 +000048#include "llvm/Support/InstVisitor.h"
Chris Lattner22d00a82005-08-02 19:16:58 +000049#include "llvm/Support/MathExtras.h"
Chris Lattnerd4252a72004-07-30 07:50:03 +000050#include "llvm/Support/PatternMatch.h"
Chris Lattner3d27be12006-08-27 12:54:02 +000051#include "llvm/Support/Compiler.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000052#include "llvm/ADT/Statistic.h"
Chris Lattner39c98bb2004-12-08 23:43:58 +000053#include "llvm/ADT/STLExtras.h"
Chris Lattner053c0932002-05-14 15:24:07 +000054#include <algorithm>
Chris Lattnerc597b8a2006-01-22 23:32:06 +000055#include <iostream>
Chris Lattner8427bff2003-12-07 01:24:23 +000056using namespace llvm;
Chris Lattnerd4252a72004-07-30 07:50:03 +000057using namespace llvm::PatternMatch;
Brian Gaeke960707c2003-11-11 22:41:34 +000058
Chris Lattner260ab202002-04-18 17:39:14 +000059namespace {
Chris Lattnerbf3a0992002-10-01 22:38:41 +000060 Statistic<> NumCombined ("instcombine", "Number of insts combined");
61 Statistic<> NumConstProp("instcombine", "Number of constant folds");
62 Statistic<> NumDeadInst ("instcombine", "Number of dead inst eliminated");
Chris Lattner5997cf92006-02-08 03:25:32 +000063 Statistic<> NumDeadStore("instcombine", "Number of dead stores eliminated");
Chris Lattner39c98bb2004-12-08 23:43:58 +000064 Statistic<> NumSunkInst ("instcombine", "Number of instructions sunk");
Chris Lattnerbf3a0992002-10-01 22:38:41 +000065
Chris Lattner4a4c7fe2006-06-28 22:08:15 +000066 class VISIBILITY_HIDDEN InstCombiner
67 : public FunctionPass,
68 public InstVisitor<InstCombiner, Instruction*> {
Chris Lattner260ab202002-04-18 17:39:14 +000069 // Worklist of all of the instructions that need to be simplified.
70 std::vector<Instruction*> WorkList;
Chris Lattnerf4ad1652003-11-02 05:57:39 +000071 TargetData *TD;
Chris Lattner260ab202002-04-18 17:39:14 +000072
Chris Lattner51ea1272004-02-28 05:22:00 +000073 /// AddUsersToWorkList - When an instruction is simplified, add all users of
74 /// the instruction to the work lists because they might get more simplified
75 /// now.
76 ///
Chris Lattner2590e512006-02-07 06:56:34 +000077 void AddUsersToWorkList(Value &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +000078 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
Chris Lattner260ab202002-04-18 17:39:14 +000079 UI != UE; ++UI)
80 WorkList.push_back(cast<Instruction>(*UI));
81 }
82
Chris Lattner51ea1272004-02-28 05:22:00 +000083 /// AddUsesToWorkList - When an instruction is simplified, add operands to
84 /// the work lists because they might get more simplified now.
85 ///
86 void AddUsesToWorkList(Instruction &I) {
87 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
88 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i)))
89 WorkList.push_back(Op);
90 }
91
Chris Lattner99f48c62002-09-02 04:59:56 +000092 // removeFromWorkList - remove all instances of I from the worklist.
93 void removeFromWorkList(Instruction *I);
Chris Lattner260ab202002-04-18 17:39:14 +000094 public:
Chris Lattner113f4f42002-06-25 16:13:24 +000095 virtual bool runOnFunction(Function &F);
Chris Lattner260ab202002-04-18 17:39:14 +000096
Chris Lattnerf12cc842002-04-28 21:27:06 +000097 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnerf4ad1652003-11-02 05:57:39 +000098 AU.addRequired<TargetData>();
Owen Andersona6968f82006-07-10 19:03:49 +000099 AU.addPreservedID(LCSSAID);
Chris Lattner820d9712002-10-21 20:00:28 +0000100 AU.setPreservesCFG();
Chris Lattnerf12cc842002-04-28 21:27:06 +0000101 }
102
Chris Lattner69193f92004-04-05 01:30:19 +0000103 TargetData &getTargetData() const { return *TD; }
104
Chris Lattner260ab202002-04-18 17:39:14 +0000105 // Visitation implementation - Implement instruction combining for different
106 // instruction types. The semantics are as follows:
107 // Return Value:
108 // null - No change was made
Chris Lattnere6794492002-08-12 21:17:25 +0000109 // I - Change was made, I is still valid, I may be dead though
Chris Lattner260ab202002-04-18 17:39:14 +0000110 // otherwise - Change was made, replace I with returned instruction
Misha Brukmanb1c93172005-04-21 23:48:37 +0000111 //
Chris Lattner113f4f42002-06-25 16:13:24 +0000112 Instruction *visitAdd(BinaryOperator &I);
113 Instruction *visitSub(BinaryOperator &I);
114 Instruction *visitMul(BinaryOperator &I);
115 Instruction *visitDiv(BinaryOperator &I);
116 Instruction *visitRem(BinaryOperator &I);
117 Instruction *visitAnd(BinaryOperator &I);
118 Instruction *visitOr (BinaryOperator &I);
119 Instruction *visitXor(BinaryOperator &I);
Chris Lattnerd1f46d32005-04-24 06:59:08 +0000120 Instruction *visitSetCondInst(SetCondInst &I);
121 Instruction *visitSetCondInstWithCastAndCast(SetCondInst &SCI);
122
Chris Lattner0798af32005-01-13 20:14:25 +0000123 Instruction *FoldGEPSetCC(User *GEPLHS, Value *RHS,
124 Instruction::BinaryOps Cond, Instruction &I);
Chris Lattnere8d6c602003-03-10 19:16:08 +0000125 Instruction *visitShiftInst(ShiftInst &I);
Chris Lattner14553932006-01-06 07:12:35 +0000126 Instruction *FoldShiftByConstant(Value *Op0, ConstantUInt *Op1,
127 ShiftInst &I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000128 Instruction *visitCastInst(CastInst &CI);
Chris Lattner411336f2005-01-19 21:50:18 +0000129 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
130 Instruction *FI);
Chris Lattnerb909e8b2004-03-12 05:52:32 +0000131 Instruction *visitSelectInst(SelectInst &CI);
Chris Lattner970c33a2003-06-19 17:00:31 +0000132 Instruction *visitCallInst(CallInst &CI);
133 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner113f4f42002-06-25 16:13:24 +0000134 Instruction *visitPHINode(PHINode &PN);
135 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Chris Lattner1085bdf2002-11-04 16:18:53 +0000136 Instruction *visitAllocationInst(AllocationInst &AI);
Chris Lattner8427bff2003-12-07 01:24:23 +0000137 Instruction *visitFreeInst(FreeInst &FI);
Chris Lattner0f1d8a32003-06-26 05:06:25 +0000138 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattner31f486c2005-01-31 05:36:43 +0000139 Instruction *visitStoreInst(StoreInst &SI);
Chris Lattner9eef8a72003-06-04 04:46:00 +0000140 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner4c9c20a2004-07-03 00:26:11 +0000141 Instruction *visitSwitchInst(SwitchInst &SI);
Chris Lattner39fac442006-04-15 01:39:45 +0000142 Instruction *visitInsertElementInst(InsertElementInst &IE);
Robert Bocchinoa8352962006-01-13 22:48:06 +0000143 Instruction *visitExtractElementInst(ExtractElementInst &EI);
Chris Lattnerfbb77a42006-04-10 22:45:52 +0000144 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
Chris Lattner260ab202002-04-18 17:39:14 +0000145
146 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner113f4f42002-06-25 16:13:24 +0000147 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000148
Chris Lattner970c33a2003-06-19 17:00:31 +0000149 private:
Chris Lattneraec3d942003-10-07 22:32:43 +0000150 Instruction *visitCallSite(CallSite CS);
Chris Lattner970c33a2003-06-19 17:00:31 +0000151 bool transformConstExprCastCall(CallSite CS);
152
Chris Lattner69193f92004-04-05 01:30:19 +0000153 public:
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000154 // InsertNewInstBefore - insert an instruction New before instruction Old
155 // in the program. Add the new instruction to the worklist.
156 //
Chris Lattner623826c2004-09-28 21:48:02 +0000157 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattner65217ff2002-08-23 18:32:43 +0000158 assert(New && New->getParent() == 0 &&
159 "New instruction already inserted into a basic block!");
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000160 BasicBlock *BB = Old.getParent();
161 BB->getInstList().insert(&Old, New); // Insert inst
162 WorkList.push_back(New); // Add to worklist
Chris Lattnere79e8542004-02-23 06:38:22 +0000163 return New;
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000164 }
165
Chris Lattner7e794272004-09-24 15:21:34 +0000166 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
167 /// This also adds the cast to the worklist. Finally, this returns the
168 /// cast.
169 Value *InsertCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
170 if (V->getType() == Ty) return V;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000171
Chris Lattnere79d2492006-04-06 19:19:17 +0000172 if (Constant *CV = dyn_cast<Constant>(V))
173 return ConstantExpr::getCast(CV, Ty);
174
Chris Lattner7e794272004-09-24 15:21:34 +0000175 Instruction *C = new CastInst(V, Ty, V->getName(), &Pos);
176 WorkList.push_back(C);
177 return C;
178 }
179
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000180 // ReplaceInstUsesWith - This method is to be used when an instruction is
181 // found to be dead, replacable with another preexisting expression. Here
182 // we add all uses of I to the worklist, replace all uses of I with the new
183 // value, then return I, so that the inst combiner will know that I was
184 // modified.
185 //
186 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattner51ea1272004-02-28 05:22:00 +0000187 AddUsersToWorkList(I); // Add all modified instrs to worklist
Chris Lattner8953b902004-04-05 02:10:19 +0000188 if (&I != V) {
189 I.replaceAllUsesWith(V);
190 return &I;
191 } else {
192 // If we are replacing the instruction with itself, this must be in a
193 // segment of unreachable code, so just clobber the instruction.
Chris Lattner8ba9ec92004-10-18 02:59:09 +0000194 I.replaceAllUsesWith(UndefValue::get(I.getType()));
Chris Lattner8953b902004-04-05 02:10:19 +0000195 return &I;
196 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000197 }
Chris Lattner51ea1272004-02-28 05:22:00 +0000198
Chris Lattner2590e512006-02-07 06:56:34 +0000199 // UpdateValueUsesWith - This method is to be used when an value is
200 // found to be replacable with another preexisting expression or was
201 // updated. Here we add all uses of I to the worklist, replace all uses of
202 // I with the new value (unless the instruction was just updated), then
203 // return true, so that the inst combiner will know that I was modified.
204 //
205 bool UpdateValueUsesWith(Value *Old, Value *New) {
206 AddUsersToWorkList(*Old); // Add all modified instrs to worklist
207 if (Old != New)
208 Old->replaceAllUsesWith(New);
209 if (Instruction *I = dyn_cast<Instruction>(Old))
210 WorkList.push_back(I);
Chris Lattner5b2edb12006-02-12 08:02:11 +0000211 if (Instruction *I = dyn_cast<Instruction>(New))
212 WorkList.push_back(I);
Chris Lattner2590e512006-02-07 06:56:34 +0000213 return true;
214 }
215
Chris Lattner51ea1272004-02-28 05:22:00 +0000216 // EraseInstFromFunction - When dealing with an instruction that has side
217 // effects or produces a void value, we can't rely on DCE to delete the
218 // instruction. Instead, visit methods should return the value returned by
219 // this function.
220 Instruction *EraseInstFromFunction(Instruction &I) {
221 assert(I.use_empty() && "Cannot erase instruction that is used!");
222 AddUsesToWorkList(I);
223 removeFromWorkList(&I);
Chris Lattner95307542004-11-18 21:41:39 +0000224 I.eraseFromParent();
Chris Lattner51ea1272004-02-28 05:22:00 +0000225 return 0; // Don't do anything with FI
226 }
227
Chris Lattner3ac7c262003-08-13 20:16:26 +0000228 private:
Chris Lattnerdfae8be2003-07-24 17:35:25 +0000229 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
230 /// InsertBefore instruction. This is specialized a bit to avoid inserting
231 /// casts that are known to not do anything...
232 ///
233 Value *InsertOperandCastBefore(Value *V, const Type *DestTy,
234 Instruction *InsertBefore);
235
Chris Lattner7fb29e12003-03-11 00:12:48 +0000236 // SimplifyCommutative - This performs a few simplifications for commutative
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000237 // operators.
Chris Lattner7fb29e12003-03-11 00:12:48 +0000238 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerba1cb382003-09-19 17:17:26 +0000239
Chris Lattner0157e7f2006-02-11 09:31:47 +0000240 bool SimplifyDemandedBits(Value *V, uint64_t Mask,
241 uint64_t &KnownZero, uint64_t &KnownOne,
242 unsigned Depth = 0);
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000243
244 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
245 // PHI node as operand #0, see if we can fold the instruction into the PHI
246 // (which is only possible if all operands to the PHI are constants).
247 Instruction *FoldOpIntoPhi(Instruction &I);
248
Chris Lattner7515cab2004-11-14 19:13:23 +0000249 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
250 // operator and they all are only used by the PHI, PHI together their
251 // inputs, and do the operation once, to the result of the PHI.
252 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
253
Chris Lattnerba1cb382003-09-19 17:17:26 +0000254 Instruction *OptAndOp(Instruction *Op, ConstantIntegral *OpRHS,
255 ConstantIntegral *AndRHS, BinaryOperator &TheAnd);
Chris Lattneraf517572005-09-18 04:24:45 +0000256
257 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantIntegral *Mask,
258 bool isSub, Instruction &I);
Chris Lattner6862fbd2004-09-29 17:40:11 +0000259 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
260 bool Inside, Instruction &IB);
Chris Lattner216be912005-10-24 06:03:58 +0000261 Instruction *PromoteCastOfAllocation(CastInst &CI, AllocationInst &AI);
Chris Lattnerc482a9e2006-06-15 19:07:26 +0000262 Instruction *MatchBSwap(BinaryOperator &I);
263
Chris Lattner1ebbe6a2006-05-13 02:06:03 +0000264 Value *EvaluateInDifferentType(Value *V, const Type *Ty);
Chris Lattner260ab202002-04-18 17:39:14 +0000265 };
Chris Lattnerb28b6802002-07-23 18:06:35 +0000266
Chris Lattnerc2d3d312006-08-27 22:42:52 +0000267 RegisterPass<InstCombiner> X("instcombine", "Combine redundant instructions");
Chris Lattner260ab202002-04-18 17:39:14 +0000268}
269
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000270// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattner81a7a232004-10-16 18:11:37 +0000271// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000272static unsigned getComplexity(Value *V) {
273 if (isa<Instruction>(V)) {
274 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
Chris Lattner81a7a232004-10-16 18:11:37 +0000275 return 3;
276 return 4;
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000277 }
Chris Lattner81a7a232004-10-16 18:11:37 +0000278 if (isa<Argument>(V)) return 3;
279 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000280}
Chris Lattner260ab202002-04-18 17:39:14 +0000281
Chris Lattner7fb29e12003-03-11 00:12:48 +0000282// isOnlyUse - Return true if this instruction will be deleted if we stop using
283// it.
284static bool isOnlyUse(Value *V) {
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000285 return V->hasOneUse() || isa<Constant>(V);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000286}
287
Chris Lattnere79e8542004-02-23 06:38:22 +0000288// getPromotedType - Return the specified type promoted as it would be to pass
289// though a va_arg area...
290static const Type *getPromotedType(const Type *Ty) {
Chris Lattner97bfcea2004-06-17 18:16:02 +0000291 switch (Ty->getTypeID()) {
Chris Lattnere79e8542004-02-23 06:38:22 +0000292 case Type::SByteTyID:
293 case Type::ShortTyID: return Type::IntTy;
294 case Type::UByteTyID:
295 case Type::UShortTyID: return Type::UIntTy;
296 case Type::FloatTyID: return Type::DoubleTy;
297 default: return Ty;
298 }
299}
300
Chris Lattner567b81f2005-09-13 00:40:14 +0000301/// isCast - If the specified operand is a CastInst or a constant expr cast,
302/// return the operand value, otherwise return null.
303static Value *isCast(Value *V) {
304 if (CastInst *I = dyn_cast<CastInst>(V))
305 return I->getOperand(0);
306 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
307 if (CE->getOpcode() == Instruction::Cast)
308 return CE->getOperand(0);
309 return 0;
310}
311
Chris Lattner1d441ad2006-05-06 09:00:16 +0000312enum CastType {
313 Noop = 0,
314 Truncate = 1,
315 Signext = 2,
316 Zeroext = 3
317};
318
319/// getCastType - In the future, we will split the cast instruction into these
320/// various types. Until then, we have to do the analysis here.
321static CastType getCastType(const Type *Src, const Type *Dest) {
322 assert(Src->isIntegral() && Dest->isIntegral() &&
323 "Only works on integral types!");
324 unsigned SrcSize = Src->getPrimitiveSizeInBits();
325 unsigned DestSize = Dest->getPrimitiveSizeInBits();
326
327 if (SrcSize == DestSize) return Noop;
328 if (SrcSize > DestSize) return Truncate;
329 if (Src->isSigned()) return Signext;
330 return Zeroext;
331}
332
333
334// isEliminableCastOfCast - Return true if it is valid to eliminate the CI
335// instruction.
336//
337static bool isEliminableCastOfCast(const Type *SrcTy, const Type *MidTy,
338 const Type *DstTy, TargetData *TD) {
339
340 // It is legal to eliminate the instruction if casting A->B->A if the sizes
341 // are identical and the bits don't get reinterpreted (for example
342 // int->float->int would not be allowed).
343 if (SrcTy == DstTy && SrcTy->isLosslesslyConvertibleTo(MidTy))
344 return true;
345
346 // If we are casting between pointer and integer types, treat pointers as
347 // integers of the appropriate size for the code below.
348 if (isa<PointerType>(SrcTy)) SrcTy = TD->getIntPtrType();
349 if (isa<PointerType>(MidTy)) MidTy = TD->getIntPtrType();
350 if (isa<PointerType>(DstTy)) DstTy = TD->getIntPtrType();
351
352 // Allow free casting and conversion of sizes as long as the sign doesn't
353 // change...
354 if (SrcTy->isIntegral() && MidTy->isIntegral() && DstTy->isIntegral()) {
355 CastType FirstCast = getCastType(SrcTy, MidTy);
356 CastType SecondCast = getCastType(MidTy, DstTy);
357
358 // Capture the effect of these two casts. If the result is a legal cast,
359 // the CastType is stored here, otherwise a special code is used.
360 static const unsigned CastResult[] = {
361 // First cast is noop
362 0, 1, 2, 3,
363 // First cast is a truncate
364 1, 1, 4, 4, // trunc->extend is not safe to eliminate
365 // First cast is a sign ext
366 2, 5, 2, 4, // signext->zeroext never ok
367 // First cast is a zero ext
368 3, 5, 3, 3,
369 };
370
371 unsigned Result = CastResult[FirstCast*4+SecondCast];
372 switch (Result) {
373 default: assert(0 && "Illegal table value!");
374 case 0:
375 case 1:
376 case 2:
377 case 3:
378 // FIXME: in the future, when LLVM has explicit sign/zeroextends and
379 // truncates, we could eliminate more casts.
380 return (unsigned)getCastType(SrcTy, DstTy) == Result;
381 case 4:
382 return false; // Not possible to eliminate this here.
383 case 5:
384 // Sign or zero extend followed by truncate is always ok if the result
385 // is a truncate or noop.
386 CastType ResultCast = getCastType(SrcTy, DstTy);
387 if (ResultCast == Noop || ResultCast == Truncate)
388 return true;
389 // Otherwise we are still growing the value, we are only safe if the
390 // result will match the sign/zeroextendness of the result.
391 return ResultCast == FirstCast;
392 }
393 }
394
395 // If this is a cast from 'float -> double -> integer', cast from
396 // 'float -> integer' directly, as the value isn't changed by the
397 // float->double conversion.
398 if (SrcTy->isFloatingPoint() && MidTy->isFloatingPoint() &&
399 DstTy->isIntegral() &&
400 SrcTy->getPrimitiveSize() < MidTy->getPrimitiveSize())
401 return true;
402
403 // Packed type conversions don't modify bits.
404 if (isa<PackedType>(SrcTy) && isa<PackedType>(MidTy) &&isa<PackedType>(DstTy))
405 return true;
406
407 return false;
408}
409
410/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
411/// in any code being generated. It does not require codegen if V is simple
412/// enough or if the cast can be folded into other casts.
413static bool ValueRequiresCast(const Value *V, const Type *Ty, TargetData *TD) {
414 if (V->getType() == Ty || isa<Constant>(V)) return false;
415
416 // If this is a noop cast, it isn't real codegen.
417 if (V->getType()->isLosslesslyConvertibleTo(Ty))
418 return false;
419
Chris Lattner99155be2006-05-25 23:24:33 +0000420 // If this is another cast that can be eliminated, it isn't codegen either.
Chris Lattner1d441ad2006-05-06 09:00:16 +0000421 if (const CastInst *CI = dyn_cast<CastInst>(V))
422 if (isEliminableCastOfCast(CI->getOperand(0)->getType(), CI->getType(), Ty,
423 TD))
424 return false;
425 return true;
426}
427
428/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
429/// InsertBefore instruction. This is specialized a bit to avoid inserting
430/// casts that are known to not do anything...
431///
432Value *InstCombiner::InsertOperandCastBefore(Value *V, const Type *DestTy,
433 Instruction *InsertBefore) {
434 if (V->getType() == DestTy) return V;
435 if (Constant *C = dyn_cast<Constant>(V))
436 return ConstantExpr::getCast(C, DestTy);
437
438 CastInst *CI = new CastInst(V, DestTy, V->getName());
439 InsertNewInstBefore(CI, *InsertBefore);
440 return CI;
441}
442
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000443// SimplifyCommutative - This performs a few simplifications for commutative
444// operators:
Chris Lattner260ab202002-04-18 17:39:14 +0000445//
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000446// 1. Order operands such that they are listed from right (least complex) to
447// left (most complex). This puts constants before unary operators before
448// binary operators.
449//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000450// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
451// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000452//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000453bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000454 bool Changed = false;
455 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
456 Changed = !I.swapOperands();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000457
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000458 if (!I.isAssociative()) return Changed;
459 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattner7fb29e12003-03-11 00:12:48 +0000460 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
461 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
462 if (isa<Constant>(I.getOperand(1))) {
Chris Lattner34428442003-05-27 16:40:51 +0000463 Constant *Folded = ConstantExpr::get(I.getOpcode(),
464 cast<Constant>(I.getOperand(1)),
465 cast<Constant>(Op->getOperand(1)));
Chris Lattner7fb29e12003-03-11 00:12:48 +0000466 I.setOperand(0, Op->getOperand(0));
467 I.setOperand(1, Folded);
468 return true;
469 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
470 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
471 isOnlyUse(Op) && isOnlyUse(Op1)) {
472 Constant *C1 = cast<Constant>(Op->getOperand(1));
473 Constant *C2 = cast<Constant>(Op1->getOperand(1));
474
475 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner34428442003-05-27 16:40:51 +0000476 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000477 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
478 Op1->getOperand(0),
479 Op1->getName(), &I);
480 WorkList.push_back(New);
481 I.setOperand(0, New);
482 I.setOperand(1, Folded);
483 return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000484 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000485 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000486 return Changed;
Chris Lattner260ab202002-04-18 17:39:14 +0000487}
Chris Lattnerca081252001-12-14 16:52:21 +0000488
Chris Lattnerbb74e222003-03-10 23:06:50 +0000489// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
490// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattner9fa53de2002-05-06 16:49:18 +0000491//
Chris Lattnerbb74e222003-03-10 23:06:50 +0000492static inline Value *dyn_castNegVal(Value *V) {
493 if (BinaryOperator::isNeg(V))
Chris Lattnerd6f636a2005-04-24 07:30:14 +0000494 return BinaryOperator::getNegArgument(V);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000495
Chris Lattner9ad0d552004-12-14 20:08:06 +0000496 // Constants can be considered to be negated values if they can be folded.
497 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
498 return ConstantExpr::getNeg(C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000499 return 0;
Chris Lattner9fa53de2002-05-06 16:49:18 +0000500}
501
Chris Lattnerbb74e222003-03-10 23:06:50 +0000502static inline Value *dyn_castNotVal(Value *V) {
503 if (BinaryOperator::isNot(V))
Chris Lattnerd6f636a2005-04-24 07:30:14 +0000504 return BinaryOperator::getNotArgument(V);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000505
506 // Constants can be considered to be not'ed values...
Chris Lattnerdd65d862003-04-30 22:34:06 +0000507 if (ConstantIntegral *C = dyn_cast<ConstantIntegral>(V))
Chris Lattnerc8e7e292004-06-10 02:12:35 +0000508 return ConstantExpr::getNot(C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000509 return 0;
510}
511
Chris Lattner7fb29e12003-03-11 00:12:48 +0000512// dyn_castFoldableMul - If this value is a multiply that can be folded into
513// other computations (because it has a constant operand), return the
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000514// non-constant operand of the multiply, and set CST to point to the multiplier.
515// Otherwise, return null.
Chris Lattner7fb29e12003-03-11 00:12:48 +0000516//
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000517static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000518 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000519 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattner7fb29e12003-03-11 00:12:48 +0000520 if (I->getOpcode() == Instruction::Mul)
Chris Lattner970136362004-11-15 05:54:07 +0000521 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattner7fb29e12003-03-11 00:12:48 +0000522 return I->getOperand(0);
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000523 if (I->getOpcode() == Instruction::Shl)
Chris Lattner970136362004-11-15 05:54:07 +0000524 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000525 // The multiplier is really 1 << CST.
526 Constant *One = ConstantInt::get(V->getType(), 1);
527 CST = cast<ConstantInt>(ConstantExpr::getShl(One, CST));
528 return I->getOperand(0);
529 }
530 }
Chris Lattner7fb29e12003-03-11 00:12:48 +0000531 return 0;
Chris Lattner3082c5a2003-02-18 19:28:33 +0000532}
Chris Lattner31ae8632002-08-14 17:51:49 +0000533
Chris Lattner0798af32005-01-13 20:14:25 +0000534/// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
535/// expression, return it.
536static User *dyn_castGetElementPtr(Value *V) {
537 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
538 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
539 if (CE->getOpcode() == Instruction::GetElementPtr)
540 return cast<User>(V);
541 return false;
542}
543
Chris Lattner623826c2004-09-28 21:48:02 +0000544// AddOne, SubOne - Add or subtract a constant one from an integer constant...
Chris Lattner6862fbd2004-09-29 17:40:11 +0000545static ConstantInt *AddOne(ConstantInt *C) {
546 return cast<ConstantInt>(ConstantExpr::getAdd(C,
547 ConstantInt::get(C->getType(), 1)));
Chris Lattner623826c2004-09-28 21:48:02 +0000548}
Chris Lattner6862fbd2004-09-29 17:40:11 +0000549static ConstantInt *SubOne(ConstantInt *C) {
550 return cast<ConstantInt>(ConstantExpr::getSub(C,
551 ConstantInt::get(C->getType(), 1)));
Chris Lattner623826c2004-09-28 21:48:02 +0000552}
553
Chris Lattner0157e7f2006-02-11 09:31:47 +0000554/// GetConstantInType - Return a ConstantInt with the specified type and value.
555///
Chris Lattneree0f2802006-02-12 02:07:56 +0000556static ConstantIntegral *GetConstantInType(const Type *Ty, uint64_t Val) {
Chris Lattner0157e7f2006-02-11 09:31:47 +0000557 if (Ty->isUnsigned())
558 return ConstantUInt::get(Ty, Val);
Chris Lattneree0f2802006-02-12 02:07:56 +0000559 else if (Ty->getTypeID() == Type::BoolTyID)
560 return ConstantBool::get(Val);
Chris Lattner0157e7f2006-02-11 09:31:47 +0000561 int64_t SVal = Val;
562 SVal <<= 64-Ty->getPrimitiveSizeInBits();
563 SVal >>= 64-Ty->getPrimitiveSizeInBits();
564 return ConstantSInt::get(Ty, SVal);
565}
566
567
Chris Lattner4534dd592006-02-09 07:38:58 +0000568/// ComputeMaskedBits - Determine which of the bits specified in Mask are
569/// known to be either zero or one and return them in the KnownZero/KnownOne
570/// bitsets. This code only analyzes bits in Mask, in order to short-circuit
571/// processing.
572static void ComputeMaskedBits(Value *V, uint64_t Mask, uint64_t &KnownZero,
573 uint64_t &KnownOne, unsigned Depth = 0) {
Chris Lattner0b3557f2005-09-24 23:43:33 +0000574 // Note, we cannot consider 'undef' to be "IsZero" here. The problem is that
575 // we cannot optimize based on the assumption that it is zero without changing
Chris Lattnerc3ebf402006-02-07 07:27:52 +0000576 // it to be an explicit zero. If we don't change it to zero, other code could
Chris Lattner0b3557f2005-09-24 23:43:33 +0000577 // optimized based on the contradictory assumption that it is non-zero.
578 // Because instcombine aggressively folds operations with undef args anyway,
579 // this won't lose us code quality.
Chris Lattner4534dd592006-02-09 07:38:58 +0000580 if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(V)) {
581 // We know all of the bits for a constant!
Chris Lattner0157e7f2006-02-11 09:31:47 +0000582 KnownOne = CI->getZExtValue() & Mask;
Chris Lattner4534dd592006-02-09 07:38:58 +0000583 KnownZero = ~KnownOne & Mask;
584 return;
585 }
586
587 KnownZero = KnownOne = 0; // Don't know anything.
Chris Lattner92a68652006-02-07 08:05:22 +0000588 if (Depth == 6 || Mask == 0)
Chris Lattner4534dd592006-02-09 07:38:58 +0000589 return; // Limit search depth.
590
591 uint64_t KnownZero2, KnownOne2;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000592 Instruction *I = dyn_cast<Instruction>(V);
593 if (!I) return;
594
Chris Lattnerfb296922006-05-04 17:33:35 +0000595 Mask &= V->getType()->getIntegralTypeMask();
596
Chris Lattner0157e7f2006-02-11 09:31:47 +0000597 switch (I->getOpcode()) {
598 case Instruction::And:
599 // If either the LHS or the RHS are Zero, the result is zero.
600 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
601 Mask &= ~KnownZero;
602 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
603 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
604 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
605
606 // Output known-1 bits are only known if set in both the LHS & RHS.
607 KnownOne &= KnownOne2;
608 // Output known-0 are known to be clear if zero in either the LHS | RHS.
609 KnownZero |= KnownZero2;
610 return;
611 case Instruction::Or:
612 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
613 Mask &= ~KnownOne;
614 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
615 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
616 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
617
618 // Output known-0 bits are only known if clear in both the LHS & RHS.
619 KnownZero &= KnownZero2;
620 // Output known-1 are known to be set if set in either the LHS | RHS.
621 KnownOne |= KnownOne2;
622 return;
623 case Instruction::Xor: {
624 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
625 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
626 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
627 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
628
629 // Output known-0 bits are known if clear or set in both the LHS & RHS.
630 uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
631 // Output known-1 are known to be set if set in only one of the LHS, RHS.
632 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
633 KnownZero = KnownZeroOut;
634 return;
635 }
636 case Instruction::Select:
637 ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
638 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
639 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
640 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
641
642 // Only known if known in both the LHS and RHS.
643 KnownOne &= KnownOne2;
644 KnownZero &= KnownZero2;
645 return;
646 case Instruction::Cast: {
647 const Type *SrcTy = I->getOperand(0)->getType();
648 if (!SrcTy->isIntegral()) return;
649
650 // If this is an integer truncate or noop, just look in the input.
651 if (SrcTy->getPrimitiveSizeInBits() >=
652 I->getType()->getPrimitiveSizeInBits()) {
653 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
Chris Lattner4534dd592006-02-09 07:38:58 +0000654 return;
655 }
Chris Lattner4534dd592006-02-09 07:38:58 +0000656
Chris Lattner0157e7f2006-02-11 09:31:47 +0000657 // Sign or Zero extension. Compute the bits in the result that are not
658 // present in the input.
659 uint64_t NotIn = ~SrcTy->getIntegralTypeMask();
660 uint64_t NewBits = I->getType()->getIntegralTypeMask() & NotIn;
Chris Lattner62010c42005-10-09 06:36:35 +0000661
Chris Lattner0157e7f2006-02-11 09:31:47 +0000662 // Handle zero extension.
663 if (!SrcTy->isSigned()) {
664 Mask &= SrcTy->getIntegralTypeMask();
665 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
666 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
667 // The top bits are known to be zero.
668 KnownZero |= NewBits;
669 } else {
670 // Sign extension.
671 Mask &= SrcTy->getIntegralTypeMask();
672 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
673 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattner92a68652006-02-07 08:05:22 +0000674
Chris Lattner0157e7f2006-02-11 09:31:47 +0000675 // If the sign bit of the input is known set or clear, then we know the
676 // top bits of the result.
677 uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
678 if (KnownZero & InSignBit) { // Input sign bit known zero
Chris Lattner4534dd592006-02-09 07:38:58 +0000679 KnownZero |= NewBits;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000680 KnownOne &= ~NewBits;
681 } else if (KnownOne & InSignBit) { // Input sign bit known set
682 KnownOne |= NewBits;
683 KnownZero &= ~NewBits;
684 } else { // Input sign bit unknown
685 KnownZero &= ~NewBits;
686 KnownOne &= ~NewBits;
687 }
688 }
689 return;
690 }
691 case Instruction::Shl:
692 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
693 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1))) {
694 Mask >>= SA->getValue();
695 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
696 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
697 KnownZero <<= SA->getValue();
698 KnownOne <<= SA->getValue();
699 KnownZero |= (1ULL << SA->getValue())-1; // low bits known zero.
700 return;
701 }
702 break;
703 case Instruction::Shr:
704 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
705 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1))) {
706 // Compute the new bits that are at the top now.
707 uint64_t HighBits = (1ULL << SA->getValue())-1;
708 HighBits <<= I->getType()->getPrimitiveSizeInBits()-SA->getValue();
709
710 if (I->getType()->isUnsigned()) { // Unsigned shift right.
711 Mask <<= SA->getValue();
712 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
713 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
714 KnownZero >>= SA->getValue();
715 KnownOne >>= SA->getValue();
716 KnownZero |= HighBits; // high bits known zero.
Chris Lattner4534dd592006-02-09 07:38:58 +0000717 } else {
Chris Lattner0157e7f2006-02-11 09:31:47 +0000718 Mask <<= SA->getValue();
719 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
720 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
721 KnownZero >>= SA->getValue();
722 KnownOne >>= SA->getValue();
723
724 // Handle the sign bits.
725 uint64_t SignBit = 1ULL << (I->getType()->getPrimitiveSizeInBits()-1);
726 SignBit >>= SA->getValue(); // Adjust to where it is now in the mask.
727
728 if (KnownZero & SignBit) { // New bits are known zero.
729 KnownZero |= HighBits;
730 } else if (KnownOne & SignBit) { // New bits are known one.
731 KnownOne |= HighBits;
Chris Lattner4534dd592006-02-09 07:38:58 +0000732 }
733 }
734 return;
Chris Lattner62010c42005-10-09 06:36:35 +0000735 }
Chris Lattner0157e7f2006-02-11 09:31:47 +0000736 break;
Chris Lattner0b3557f2005-09-24 23:43:33 +0000737 }
Chris Lattner92a68652006-02-07 08:05:22 +0000738}
739
740/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
741/// this predicate to simplify operations downstream. Mask is known to be zero
742/// for bits that V cannot have.
743static bool MaskedValueIsZero(Value *V, uint64_t Mask, unsigned Depth = 0) {
Chris Lattner4534dd592006-02-09 07:38:58 +0000744 uint64_t KnownZero, KnownOne;
745 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
746 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
747 return (KnownZero & Mask) == Mask;
Chris Lattner0b3557f2005-09-24 23:43:33 +0000748}
749
Chris Lattner0157e7f2006-02-11 09:31:47 +0000750/// ShrinkDemandedConstant - Check to see if the specified operand of the
751/// specified instruction is a constant integer. If so, check to see if there
752/// are any bits set in the constant that are not demanded. If so, shrink the
753/// constant and return true.
754static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
755 uint64_t Demanded) {
756 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
757 if (!OpC) return false;
758
759 // If there are no bits set that aren't demanded, nothing to do.
760 if ((~Demanded & OpC->getZExtValue()) == 0)
761 return false;
762
763 // This is producing any bits that are not needed, shrink the RHS.
764 uint64_t Val = Demanded & OpC->getZExtValue();
765 I->setOperand(OpNo, GetConstantInType(OpC->getType(), Val));
766 return true;
767}
768
Chris Lattneree0f2802006-02-12 02:07:56 +0000769// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
770// set of known zero and one bits, compute the maximum and minimum values that
771// could have the specified known zero and known one bits, returning them in
772// min/max.
773static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
774 uint64_t KnownZero,
775 uint64_t KnownOne,
776 int64_t &Min, int64_t &Max) {
777 uint64_t TypeBits = Ty->getIntegralTypeMask();
778 uint64_t UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
779
780 uint64_t SignBit = 1ULL << (Ty->getPrimitiveSizeInBits()-1);
781
782 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
783 // bit if it is unknown.
784 Min = KnownOne;
785 Max = KnownOne|UnknownBits;
786
787 if (SignBit & UnknownBits) { // Sign bit is unknown
788 Min |= SignBit;
789 Max &= ~SignBit;
790 }
791
792 // Sign extend the min/max values.
793 int ShAmt = 64-Ty->getPrimitiveSizeInBits();
794 Min = (Min << ShAmt) >> ShAmt;
795 Max = (Max << ShAmt) >> ShAmt;
796}
797
798// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
799// a set of known zero and one bits, compute the maximum and minimum values that
800// could have the specified known zero and known one bits, returning them in
801// min/max.
802static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
803 uint64_t KnownZero,
804 uint64_t KnownOne,
805 uint64_t &Min,
806 uint64_t &Max) {
807 uint64_t TypeBits = Ty->getIntegralTypeMask();
808 uint64_t UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
809
810 // The minimum value is when the unknown bits are all zeros.
811 Min = KnownOne;
812 // The maximum value is when the unknown bits are all ones.
813 Max = KnownOne|UnknownBits;
814}
Chris Lattner0157e7f2006-02-11 09:31:47 +0000815
816
817/// SimplifyDemandedBits - Look at V. At this point, we know that only the
818/// DemandedMask bits of the result of V are ever used downstream. If we can
819/// use this information to simplify V, do so and return true. Otherwise,
820/// analyze the expression and return a mask of KnownOne and KnownZero bits for
821/// the expression (used to simplify the caller). The KnownZero/One bits may
822/// only be accurate for those bits in the DemandedMask.
823bool InstCombiner::SimplifyDemandedBits(Value *V, uint64_t DemandedMask,
824 uint64_t &KnownZero, uint64_t &KnownOne,
Chris Lattner2590e512006-02-07 06:56:34 +0000825 unsigned Depth) {
Chris Lattner0157e7f2006-02-11 09:31:47 +0000826 if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(V)) {
827 // We know all of the bits for a constant!
828 KnownOne = CI->getZExtValue() & DemandedMask;
829 KnownZero = ~KnownOne & DemandedMask;
830 return false;
831 }
832
833 KnownZero = KnownOne = 0;
Chris Lattner2590e512006-02-07 06:56:34 +0000834 if (!V->hasOneUse()) { // Other users may use these bits.
Chris Lattner0157e7f2006-02-11 09:31:47 +0000835 if (Depth != 0) { // Not at the root.
836 // Just compute the KnownZero/KnownOne bits to simplify things downstream.
837 ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
Chris Lattner2590e512006-02-07 06:56:34 +0000838 return false;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000839 }
Chris Lattner2590e512006-02-07 06:56:34 +0000840 // If this is the root being simplified, allow it to have multiple uses,
Chris Lattner0157e7f2006-02-11 09:31:47 +0000841 // just set the DemandedMask to all bits.
842 DemandedMask = V->getType()->getIntegralTypeMask();
843 } else if (DemandedMask == 0) { // Not demanding any bits from V.
Chris Lattner92a68652006-02-07 08:05:22 +0000844 if (V != UndefValue::get(V->getType()))
845 return UpdateValueUsesWith(V, UndefValue::get(V->getType()));
846 return false;
Chris Lattner2590e512006-02-07 06:56:34 +0000847 } else if (Depth == 6) { // Limit search depth.
848 return false;
849 }
850
851 Instruction *I = dyn_cast<Instruction>(V);
852 if (!I) return false; // Only analyze instructions.
853
Chris Lattnerfb296922006-05-04 17:33:35 +0000854 DemandedMask &= V->getType()->getIntegralTypeMask();
855
Chris Lattner0157e7f2006-02-11 09:31:47 +0000856 uint64_t KnownZero2, KnownOne2;
Chris Lattner2590e512006-02-07 06:56:34 +0000857 switch (I->getOpcode()) {
858 default: break;
859 case Instruction::And:
Chris Lattner0157e7f2006-02-11 09:31:47 +0000860 // If either the LHS or the RHS are Zero, the result is zero.
861 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
862 KnownZero, KnownOne, Depth+1))
863 return true;
864 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
865
866 // If something is known zero on the RHS, the bits aren't demanded on the
867 // LHS.
868 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownZero,
869 KnownZero2, KnownOne2, Depth+1))
870 return true;
871 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
872
873 // If all of the demanded bits are known one on one side, return the other.
874 // These bits cannot contribute to the result of the 'and'.
875 if ((DemandedMask & ~KnownZero2 & KnownOne) == (DemandedMask & ~KnownZero2))
876 return UpdateValueUsesWith(I, I->getOperand(0));
877 if ((DemandedMask & ~KnownZero & KnownOne2) == (DemandedMask & ~KnownZero))
878 return UpdateValueUsesWith(I, I->getOperand(1));
Chris Lattner5b2edb12006-02-12 08:02:11 +0000879
880 // If all of the demanded bits in the inputs are known zeros, return zero.
881 if ((DemandedMask & (KnownZero|KnownZero2)) == DemandedMask)
882 return UpdateValueUsesWith(I, Constant::getNullValue(I->getType()));
883
Chris Lattner0157e7f2006-02-11 09:31:47 +0000884 // If the RHS is a constant, see if we can simplify it.
Chris Lattner5b2edb12006-02-12 08:02:11 +0000885 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~KnownZero2))
Chris Lattner0157e7f2006-02-11 09:31:47 +0000886 return UpdateValueUsesWith(I, I);
887
888 // Output known-1 bits are only known if set in both the LHS & RHS.
889 KnownOne &= KnownOne2;
890 // Output known-0 are known to be clear if zero in either the LHS | RHS.
891 KnownZero |= KnownZero2;
892 break;
893 case Instruction::Or:
894 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
895 KnownZero, KnownOne, Depth+1))
896 return true;
897 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
898 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownOne,
899 KnownZero2, KnownOne2, Depth+1))
900 return true;
901 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
902
903 // If all of the demanded bits are known zero on one side, return the other.
904 // These bits cannot contribute to the result of the 'or'.
Jeff Cohen0add83e2006-02-18 03:20:33 +0000905 if ((DemandedMask & ~KnownOne2 & KnownZero) == (DemandedMask & ~KnownOne2))
Chris Lattner0157e7f2006-02-11 09:31:47 +0000906 return UpdateValueUsesWith(I, I->getOperand(0));
Jeff Cohen0add83e2006-02-18 03:20:33 +0000907 if ((DemandedMask & ~KnownOne & KnownZero2) == (DemandedMask & ~KnownOne))
Chris Lattner0157e7f2006-02-11 09:31:47 +0000908 return UpdateValueUsesWith(I, I->getOperand(1));
Chris Lattner5b2edb12006-02-12 08:02:11 +0000909
910 // If all of the potentially set bits on one side are known to be set on
911 // the other side, just use the 'other' side.
912 if ((DemandedMask & (~KnownZero) & KnownOne2) ==
913 (DemandedMask & (~KnownZero)))
914 return UpdateValueUsesWith(I, I->getOperand(0));
Nate Begeman8a77efe2006-02-16 21:11:51 +0000915 if ((DemandedMask & (~KnownZero2) & KnownOne) ==
916 (DemandedMask & (~KnownZero2)))
917 return UpdateValueUsesWith(I, I->getOperand(1));
Chris Lattner0157e7f2006-02-11 09:31:47 +0000918
919 // If the RHS is a constant, see if we can simplify it.
920 if (ShrinkDemandedConstant(I, 1, DemandedMask))
921 return UpdateValueUsesWith(I, I);
922
923 // Output known-0 bits are only known if clear in both the LHS & RHS.
924 KnownZero &= KnownZero2;
925 // Output known-1 are known to be set if set in either the LHS | RHS.
926 KnownOne |= KnownOne2;
927 break;
928 case Instruction::Xor: {
929 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
930 KnownZero, KnownOne, Depth+1))
931 return true;
932 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
933 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
934 KnownZero2, KnownOne2, Depth+1))
935 return true;
936 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
937
938 // If all of the demanded bits are known zero on one side, return the other.
939 // These bits cannot contribute to the result of the 'xor'.
940 if ((DemandedMask & KnownZero) == DemandedMask)
941 return UpdateValueUsesWith(I, I->getOperand(0));
942 if ((DemandedMask & KnownZero2) == DemandedMask)
943 return UpdateValueUsesWith(I, I->getOperand(1));
944
945 // Output known-0 bits are known if clear or set in both the LHS & RHS.
946 uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
947 // Output known-1 are known to be set if set in only one of the LHS, RHS.
948 uint64_t KnownOneOut = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
949
950 // If all of the unknown bits are known to be zero on one side or the other
951 // (but not both) turn this into an *inclusive* or.
Chris Lattner5b2edb12006-02-12 08:02:11 +0000952 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattner0157e7f2006-02-11 09:31:47 +0000953 if (uint64_t UnknownBits = DemandedMask & ~(KnownZeroOut|KnownOneOut)) {
954 if ((UnknownBits & (KnownZero|KnownZero2)) == UnknownBits) {
955 Instruction *Or =
956 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
957 I->getName());
958 InsertNewInstBefore(Or, *I);
959 return UpdateValueUsesWith(I, Or);
Chris Lattner2590e512006-02-07 06:56:34 +0000960 }
961 }
Chris Lattner0157e7f2006-02-11 09:31:47 +0000962
Chris Lattner5b2edb12006-02-12 08:02:11 +0000963 // If all of the demanded bits on one side are known, and all of the set
964 // bits on that side are also known to be set on the other side, turn this
965 // into an AND, as we know the bits will be cleared.
966 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
967 if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask) { // all known
968 if ((KnownOne & KnownOne2) == KnownOne) {
969 Constant *AndC = GetConstantInType(I->getType(),
970 ~KnownOne & DemandedMask);
971 Instruction *And =
972 BinaryOperator::createAnd(I->getOperand(0), AndC, "tmp");
973 InsertNewInstBefore(And, *I);
974 return UpdateValueUsesWith(I, And);
975 }
976 }
977
Chris Lattner0157e7f2006-02-11 09:31:47 +0000978 // If the RHS is a constant, see if we can simplify it.
979 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
980 if (ShrinkDemandedConstant(I, 1, DemandedMask))
981 return UpdateValueUsesWith(I, I);
982
983 KnownZero = KnownZeroOut;
984 KnownOne = KnownOneOut;
985 break;
986 }
987 case Instruction::Select:
988 if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
989 KnownZero, KnownOne, Depth+1))
990 return true;
991 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
992 KnownZero2, KnownOne2, Depth+1))
993 return true;
994 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
995 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
996
997 // If the operands are constants, see if we can simplify them.
998 if (ShrinkDemandedConstant(I, 1, DemandedMask))
999 return UpdateValueUsesWith(I, I);
1000 if (ShrinkDemandedConstant(I, 2, DemandedMask))
1001 return UpdateValueUsesWith(I, I);
1002
1003 // Only known if known in both the LHS and RHS.
1004 KnownOne &= KnownOne2;
1005 KnownZero &= KnownZero2;
1006 break;
Chris Lattner2590e512006-02-07 06:56:34 +00001007 case Instruction::Cast: {
1008 const Type *SrcTy = I->getOperand(0)->getType();
Chris Lattner0157e7f2006-02-11 09:31:47 +00001009 if (!SrcTy->isIntegral()) return false;
Chris Lattner2590e512006-02-07 06:56:34 +00001010
Chris Lattner0157e7f2006-02-11 09:31:47 +00001011 // If this is an integer truncate or noop, just look in the input.
1012 if (SrcTy->getPrimitiveSizeInBits() >=
1013 I->getType()->getPrimitiveSizeInBits()) {
Chris Lattner850465d2006-09-16 03:14:10 +00001014 // Cast to bool is a comparison against 0, which demands all bits. We
1015 // can't propagate anything useful up.
1016 if (I->getType() == Type::BoolTy)
1017 break;
1018
Chris Lattner0157e7f2006-02-11 09:31:47 +00001019 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1020 KnownZero, KnownOne, Depth+1))
1021 return true;
1022 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1023 break;
1024 }
1025
1026 // Sign or Zero extension. Compute the bits in the result that are not
1027 // present in the input.
1028 uint64_t NotIn = ~SrcTy->getIntegralTypeMask();
1029 uint64_t NewBits = I->getType()->getIntegralTypeMask() & NotIn;
1030
1031 // Handle zero extension.
1032 if (!SrcTy->isSigned()) {
1033 DemandedMask &= SrcTy->getIntegralTypeMask();
1034 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1035 KnownZero, KnownOne, Depth+1))
1036 return true;
1037 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1038 // The top bits are known to be zero.
1039 KnownZero |= NewBits;
1040 } else {
1041 // Sign extension.
Chris Lattner7d852282006-02-13 22:41:07 +00001042 uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
1043 int64_t InputDemandedBits = DemandedMask & SrcTy->getIntegralTypeMask();
1044
1045 // If any of the sign extended bits are demanded, we know that the sign
1046 // bit is demanded.
1047 if (NewBits & DemandedMask)
1048 InputDemandedBits |= InSignBit;
1049
1050 if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
Chris Lattner0157e7f2006-02-11 09:31:47 +00001051 KnownZero, KnownOne, Depth+1))
1052 return true;
1053 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1054
1055 // If the sign bit of the input is known set or clear, then we know the
1056 // top bits of the result.
Chris Lattner2590e512006-02-07 06:56:34 +00001057
Chris Lattner0157e7f2006-02-11 09:31:47 +00001058 // If the input sign bit is known zero, or if the NewBits are not demanded
1059 // convert this into a zero extension.
1060 if ((KnownZero & InSignBit) || (NewBits & ~DemandedMask) == NewBits) {
Chris Lattner2590e512006-02-07 06:56:34 +00001061 // Convert to unsigned first.
Chris Lattner44314822006-02-07 19:07:40 +00001062 Instruction *NewVal;
Chris Lattner2590e512006-02-07 06:56:34 +00001063 NewVal = new CastInst(I->getOperand(0), SrcTy->getUnsignedVersion(),
Chris Lattner44314822006-02-07 19:07:40 +00001064 I->getOperand(0)->getName());
1065 InsertNewInstBefore(NewVal, *I);
Chris Lattner0157e7f2006-02-11 09:31:47 +00001066 // Then cast that to the destination type.
Chris Lattner44314822006-02-07 19:07:40 +00001067 NewVal = new CastInst(NewVal, I->getType(), I->getName());
1068 InsertNewInstBefore(NewVal, *I);
Chris Lattner2590e512006-02-07 06:56:34 +00001069 return UpdateValueUsesWith(I, NewVal);
Chris Lattner0157e7f2006-02-11 09:31:47 +00001070 } else if (KnownOne & InSignBit) { // Input sign bit known set
1071 KnownOne |= NewBits;
1072 KnownZero &= ~NewBits;
1073 } else { // Input sign bit unknown
1074 KnownZero &= ~NewBits;
1075 KnownOne &= ~NewBits;
Chris Lattner2590e512006-02-07 06:56:34 +00001076 }
Chris Lattner2590e512006-02-07 06:56:34 +00001077 }
Chris Lattner0157e7f2006-02-11 09:31:47 +00001078 break;
Chris Lattner2590e512006-02-07 06:56:34 +00001079 }
Chris Lattner2590e512006-02-07 06:56:34 +00001080 case Instruction::Shl:
Chris Lattner0157e7f2006-02-11 09:31:47 +00001081 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1))) {
1082 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask >> SA->getValue(),
1083 KnownZero, KnownOne, Depth+1))
1084 return true;
1085 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1086 KnownZero <<= SA->getValue();
1087 KnownOne <<= SA->getValue();
1088 KnownZero |= (1ULL << SA->getValue())-1; // low bits known zero.
1089 }
Chris Lattner2590e512006-02-07 06:56:34 +00001090 break;
1091 case Instruction::Shr:
Chris Lattner420c4bc2006-09-18 04:31:40 +00001092 // If this is an arithmetic shift right and only the low-bit is set, we can
1093 // always convert this into a logical shr, even if the shift amount is
1094 // variable. The low bit of the shift cannot be an input sign bit unless
1095 // the shift amount is >= the size of the datatype, which is undefined.
1096 if (DemandedMask == 1 && I->getType()->isSigned()) {
1097 // Convert the input to unsigned.
1098 Instruction *NewVal = new CastInst(I->getOperand(0),
1099 I->getType()->getUnsignedVersion(),
1100 I->getOperand(0)->getName());
1101 InsertNewInstBefore(NewVal, *I);
1102 // Perform the unsigned shift right.
1103 NewVal = new ShiftInst(Instruction::Shr, NewVal, I->getOperand(1),
1104 I->getName());
1105 InsertNewInstBefore(NewVal, *I);
1106 // Then cast that to the destination type.
1107 NewVal = new CastInst(NewVal, I->getType(), I->getName());
1108 InsertNewInstBefore(NewVal, *I);
1109 return UpdateValueUsesWith(I, NewVal);
1110 }
1111
Chris Lattner0157e7f2006-02-11 09:31:47 +00001112 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1))) {
1113 unsigned ShAmt = SA->getValue();
1114
1115 // Compute the new bits that are at the top now.
1116 uint64_t HighBits = (1ULL << ShAmt)-1;
1117 HighBits <<= I->getType()->getPrimitiveSizeInBits() - ShAmt;
Chris Lattner68e74752006-02-13 06:09:08 +00001118 uint64_t TypeMask = I->getType()->getIntegralTypeMask();
Chris Lattner0157e7f2006-02-11 09:31:47 +00001119 if (I->getType()->isUnsigned()) { // Unsigned shift right.
Chris Lattner68e74752006-02-13 06:09:08 +00001120 if (SimplifyDemandedBits(I->getOperand(0),
1121 (DemandedMask << ShAmt) & TypeMask,
Chris Lattner0157e7f2006-02-11 09:31:47 +00001122 KnownZero, KnownOne, Depth+1))
1123 return true;
1124 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattner68e74752006-02-13 06:09:08 +00001125 KnownZero &= TypeMask;
1126 KnownOne &= TypeMask;
Chris Lattner0157e7f2006-02-11 09:31:47 +00001127 KnownZero >>= ShAmt;
1128 KnownOne >>= ShAmt;
1129 KnownZero |= HighBits; // high bits known zero.
1130 } else { // Signed shift right.
Chris Lattner68e74752006-02-13 06:09:08 +00001131 if (SimplifyDemandedBits(I->getOperand(0),
1132 (DemandedMask << ShAmt) & TypeMask,
Chris Lattner0157e7f2006-02-11 09:31:47 +00001133 KnownZero, KnownOne, Depth+1))
1134 return true;
1135 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattner68e74752006-02-13 06:09:08 +00001136 KnownZero &= TypeMask;
1137 KnownOne &= TypeMask;
Chris Lattner0157e7f2006-02-11 09:31:47 +00001138 KnownZero >>= SA->getValue();
1139 KnownOne >>= SA->getValue();
1140
1141 // Handle the sign bits.
1142 uint64_t SignBit = 1ULL << (I->getType()->getPrimitiveSizeInBits()-1);
1143 SignBit >>= SA->getValue(); // Adjust to where it is now in the mask.
1144
1145 // If the input sign bit is known to be zero, or if none of the top bits
1146 // are demanded, turn this into an unsigned shift right.
1147 if ((KnownZero & SignBit) || (HighBits & ~DemandedMask) == HighBits) {
1148 // Convert the input to unsigned.
1149 Instruction *NewVal;
1150 NewVal = new CastInst(I->getOperand(0),
1151 I->getType()->getUnsignedVersion(),
1152 I->getOperand(0)->getName());
1153 InsertNewInstBefore(NewVal, *I);
1154 // Perform the unsigned shift right.
1155 NewVal = new ShiftInst(Instruction::Shr, NewVal, SA, I->getName());
1156 InsertNewInstBefore(NewVal, *I);
1157 // Then cast that to the destination type.
1158 NewVal = new CastInst(NewVal, I->getType(), I->getName());
1159 InsertNewInstBefore(NewVal, *I);
1160 return UpdateValueUsesWith(I, NewVal);
1161 } else if (KnownOne & SignBit) { // New bits are known one.
1162 KnownOne |= HighBits;
1163 }
Chris Lattner2590e512006-02-07 06:56:34 +00001164 }
Chris Lattner0157e7f2006-02-11 09:31:47 +00001165 }
Chris Lattner2590e512006-02-07 06:56:34 +00001166 break;
1167 }
Chris Lattner0157e7f2006-02-11 09:31:47 +00001168
1169 // If the client is only demanding bits that we know, return the known
1170 // constant.
1171 if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask)
1172 return UpdateValueUsesWith(I, GetConstantInType(I->getType(), KnownOne));
Chris Lattner2590e512006-02-07 06:56:34 +00001173 return false;
1174}
1175
Chris Lattner623826c2004-09-28 21:48:02 +00001176// isTrueWhenEqual - Return true if the specified setcondinst instruction is
1177// true when both operands are equal...
1178//
1179static bool isTrueWhenEqual(Instruction &I) {
1180 return I.getOpcode() == Instruction::SetEQ ||
1181 I.getOpcode() == Instruction::SetGE ||
1182 I.getOpcode() == Instruction::SetLE;
1183}
Chris Lattnerb8b97502003-08-13 19:01:45 +00001184
1185/// AssociativeOpt - Perform an optimization on an associative operator. This
1186/// function is designed to check a chain of associative operators for a
1187/// potential to apply a certain optimization. Since the optimization may be
1188/// applicable if the expression was reassociated, this checks the chain, then
1189/// reassociates the expression as necessary to expose the optimization
1190/// opportunity. This makes use of a special Functor, which must define
1191/// 'shouldApply' and 'apply' methods.
1192///
1193template<typename Functor>
1194Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1195 unsigned Opcode = Root.getOpcode();
1196 Value *LHS = Root.getOperand(0);
1197
1198 // Quick check, see if the immediate LHS matches...
1199 if (F.shouldApply(LHS))
1200 return F.apply(Root);
1201
1202 // Otherwise, if the LHS is not of the same opcode as the root, return.
1203 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001204 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattnerb8b97502003-08-13 19:01:45 +00001205 // Should we apply this transform to the RHS?
1206 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1207
1208 // If not to the RHS, check to see if we should apply to the LHS...
1209 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1210 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1211 ShouldApply = true;
1212 }
1213
1214 // If the functor wants to apply the optimization to the RHS of LHSI,
1215 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1216 if (ShouldApply) {
1217 BasicBlock *BB = Root.getParent();
Misha Brukmanb1c93172005-04-21 23:48:37 +00001218
Chris Lattnerb8b97502003-08-13 19:01:45 +00001219 // Now all of the instructions are in the current basic block, go ahead
1220 // and perform the reassociation.
1221 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1222
1223 // First move the selected RHS to the LHS of the root...
1224 Root.setOperand(0, LHSI->getOperand(1));
1225
1226 // Make what used to be the LHS of the root be the user of the root...
1227 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner284d3b02004-04-16 18:08:07 +00001228 if (&Root == TmpLHSI) {
Chris Lattner8953b902004-04-05 02:10:19 +00001229 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1230 return 0;
1231 }
Chris Lattner284d3b02004-04-16 18:08:07 +00001232 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattnerb8b97502003-08-13 19:01:45 +00001233 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner284d3b02004-04-16 18:08:07 +00001234 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
1235 BasicBlock::iterator ARI = &Root; ++ARI;
1236 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
1237 ARI = Root;
Chris Lattnerb8b97502003-08-13 19:01:45 +00001238
1239 // Now propagate the ExtraOperand down the chain of instructions until we
1240 // get to LHSI.
1241 while (TmpLHSI != LHSI) {
1242 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner284d3b02004-04-16 18:08:07 +00001243 // Move the instruction to immediately before the chain we are
1244 // constructing to avoid breaking dominance properties.
1245 NextLHSI->getParent()->getInstList().remove(NextLHSI);
1246 BB->getInstList().insert(ARI, NextLHSI);
1247 ARI = NextLHSI;
1248
Chris Lattnerb8b97502003-08-13 19:01:45 +00001249 Value *NextOp = NextLHSI->getOperand(1);
1250 NextLHSI->setOperand(1, ExtraOperand);
1251 TmpLHSI = NextLHSI;
1252 ExtraOperand = NextOp;
1253 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001254
Chris Lattnerb8b97502003-08-13 19:01:45 +00001255 // Now that the instructions are reassociated, have the functor perform
1256 // the transformation...
1257 return F.apply(Root);
1258 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001259
Chris Lattnerb8b97502003-08-13 19:01:45 +00001260 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1261 }
1262 return 0;
1263}
1264
1265
1266// AddRHS - Implements: X + X --> X << 1
1267struct AddRHS {
1268 Value *RHS;
1269 AddRHS(Value *rhs) : RHS(rhs) {}
1270 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1271 Instruction *apply(BinaryOperator &Add) const {
1272 return new ShiftInst(Instruction::Shl, Add.getOperand(0),
1273 ConstantInt::get(Type::UByteTy, 1));
1274 }
1275};
1276
1277// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1278// iff C1&C2 == 0
1279struct AddMaskingAnd {
1280 Constant *C2;
1281 AddMaskingAnd(Constant *c) : C2(c) {}
1282 bool shouldApply(Value *LHS) const {
Chris Lattnerd4252a72004-07-30 07:50:03 +00001283 ConstantInt *C1;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001284 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Chris Lattnerd4252a72004-07-30 07:50:03 +00001285 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattnerb8b97502003-08-13 19:01:45 +00001286 }
1287 Instruction *apply(BinaryOperator &Add) const {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001288 return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattnerb8b97502003-08-13 19:01:45 +00001289 }
1290};
1291
Chris Lattner86102b82005-01-01 16:22:27 +00001292static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner183b3362004-04-09 19:05:30 +00001293 InstCombiner *IC) {
Chris Lattner86102b82005-01-01 16:22:27 +00001294 if (isa<CastInst>(I)) {
1295 if (Constant *SOC = dyn_cast<Constant>(SO))
1296 return ConstantExpr::getCast(SOC, I.getType());
Misha Brukmanb1c93172005-04-21 23:48:37 +00001297
Chris Lattner86102b82005-01-01 16:22:27 +00001298 return IC->InsertNewInstBefore(new CastInst(SO, I.getType(),
1299 SO->getName() + ".cast"), I);
1300 }
1301
Chris Lattner183b3362004-04-09 19:05:30 +00001302 // Figure out if the constant is the left or the right argument.
Chris Lattner86102b82005-01-01 16:22:27 +00001303 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1304 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattnerb8b97502003-08-13 19:01:45 +00001305
Chris Lattner183b3362004-04-09 19:05:30 +00001306 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1307 if (ConstIsRHS)
Chris Lattner86102b82005-01-01 16:22:27 +00001308 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1309 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner183b3362004-04-09 19:05:30 +00001310 }
1311
1312 Value *Op0 = SO, *Op1 = ConstOperand;
1313 if (!ConstIsRHS)
1314 std::swap(Op0, Op1);
1315 Instruction *New;
Chris Lattner86102b82005-01-01 16:22:27 +00001316 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1317 New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
1318 else if (ShiftInst *SI = dyn_cast<ShiftInst>(&I))
1319 New = new ShiftInst(SI->getOpcode(), Op0, Op1, SO->getName()+".sh");
Chris Lattnerf9d96652004-04-10 19:15:56 +00001320 else {
Chris Lattner183b3362004-04-09 19:05:30 +00001321 assert(0 && "Unknown binary instruction type!");
Chris Lattnerf9d96652004-04-10 19:15:56 +00001322 abort();
1323 }
Chris Lattner86102b82005-01-01 16:22:27 +00001324 return IC->InsertNewInstBefore(New, I);
1325}
1326
1327// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1328// constant as the other operand, try to fold the binary operator into the
1329// select arguments. This also works for Cast instructions, which obviously do
1330// not have a second operand.
1331static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1332 InstCombiner *IC) {
1333 // Don't modify shared select instructions
1334 if (!SI->hasOneUse()) return 0;
1335 Value *TV = SI->getOperand(1);
1336 Value *FV = SI->getOperand(2);
1337
1338 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner374e6592005-04-21 05:43:13 +00001339 // Bool selects with constant operands can be folded to logical ops.
1340 if (SI->getType() == Type::BoolTy) return 0;
1341
Chris Lattner86102b82005-01-01 16:22:27 +00001342 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1343 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1344
1345 return new SelectInst(SI->getCondition(), SelectTrueVal,
1346 SelectFalseVal);
1347 }
1348 return 0;
Chris Lattner183b3362004-04-09 19:05:30 +00001349}
1350
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001351
1352/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1353/// node as operand #0, see if we can fold the instruction into the PHI (which
1354/// is only possible if all operands to the PHI are constants).
1355Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1356 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattner7515cab2004-11-14 19:13:23 +00001357 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner04689872006-09-09 22:02:56 +00001358 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001359
Chris Lattner04689872006-09-09 22:02:56 +00001360 // Check to see if all of the operands of the PHI are constants. If there is
1361 // one non-constant value, remember the BB it is. If there is more than one
1362 // bail out.
1363 BasicBlock *NonConstBB = 0;
1364 for (unsigned i = 0; i != NumPHIValues; ++i)
1365 if (!isa<Constant>(PN->getIncomingValue(i))) {
1366 if (NonConstBB) return 0; // More than one non-const value.
1367 NonConstBB = PN->getIncomingBlock(i);
1368
1369 // If the incoming non-constant value is in I's block, we have an infinite
1370 // loop.
1371 if (NonConstBB == I.getParent())
1372 return 0;
1373 }
1374
1375 // If there is exactly one non-constant value, we can insert a copy of the
1376 // operation in that block. However, if this is a critical edge, we would be
1377 // inserting the computation one some other paths (e.g. inside a loop). Only
1378 // do this if the pred block is unconditionally branching into the phi block.
1379 if (NonConstBB) {
1380 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1381 if (!BI || !BI->isUnconditional()) return 0;
1382 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001383
1384 // Okay, we can do the transformation: create the new PHI node.
1385 PHINode *NewPN = new PHINode(I.getType(), I.getName());
1386 I.setName("");
Chris Lattnerd8e20182005-01-29 00:39:08 +00001387 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001388 InsertNewInstBefore(NewPN, *PN);
1389
1390 // Next, add all of the operands to the PHI.
1391 if (I.getNumOperands() == 2) {
1392 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattner7515cab2004-11-14 19:13:23 +00001393 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner04689872006-09-09 22:02:56 +00001394 Value *InV;
1395 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1396 InV = ConstantExpr::get(I.getOpcode(), InC, C);
1397 } else {
1398 assert(PN->getIncomingBlock(i) == NonConstBB);
1399 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1400 InV = BinaryOperator::create(BO->getOpcode(),
1401 PN->getIncomingValue(i), C, "phitmp",
1402 NonConstBB->getTerminator());
1403 else if (ShiftInst *SI = dyn_cast<ShiftInst>(&I))
1404 InV = new ShiftInst(SI->getOpcode(),
1405 PN->getIncomingValue(i), C, "phitmp",
1406 NonConstBB->getTerminator());
1407 else
1408 assert(0 && "Unknown binop!");
1409
1410 WorkList.push_back(cast<Instruction>(InV));
1411 }
1412 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001413 }
1414 } else {
1415 assert(isa<CastInst>(I) && "Unary op should be a cast!");
1416 const Type *RetTy = I.getType();
Chris Lattner7515cab2004-11-14 19:13:23 +00001417 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner04689872006-09-09 22:02:56 +00001418 Value *InV;
1419 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1420 InV = ConstantExpr::getCast(InC, RetTy);
1421 } else {
1422 assert(PN->getIncomingBlock(i) == NonConstBB);
1423 InV = new CastInst(PN->getIncomingValue(i), I.getType(), "phitmp",
1424 NonConstBB->getTerminator());
1425 WorkList.push_back(cast<Instruction>(InV));
1426 }
1427 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001428 }
1429 }
1430 return ReplaceInstUsesWith(I, NewPN);
1431}
1432
Chris Lattner113f4f42002-06-25 16:13:24 +00001433Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001434 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00001435 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattner9fa53de2002-05-06 16:49:18 +00001436
Chris Lattnercf4a9962004-04-10 22:01:55 +00001437 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattner81a7a232004-10-16 18:11:37 +00001438 // X + undef -> undef
1439 if (isa<UndefValue>(RHS))
1440 return ReplaceInstUsesWith(I, RHS);
1441
Chris Lattnercf4a9962004-04-10 22:01:55 +00001442 // X + 0 --> X
Chris Lattner7fde91e2005-10-17 17:56:38 +00001443 if (!I.getType()->isFloatingPoint()) { // NOTE: -0 + +0 = +0.
1444 if (RHSC->isNullValue())
1445 return ReplaceInstUsesWith(I, LHS);
Chris Lattnerda1b1522005-10-17 20:18:38 +00001446 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
1447 if (CFP->isExactlyValue(-0.0))
1448 return ReplaceInstUsesWith(I, LHS);
Chris Lattner7fde91e2005-10-17 17:56:38 +00001449 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001450
Chris Lattnercf4a9962004-04-10 22:01:55 +00001451 // X + (signbit) --> X ^ signbit
1452 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattner92a68652006-02-07 08:05:22 +00001453 uint64_t Val = CI->getZExtValue();
Chris Lattner77defba2006-02-07 07:00:41 +00001454 if (Val == (1ULL << (CI->getType()->getPrimitiveSizeInBits()-1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001455 return BinaryOperator::createXor(LHS, RHS);
Chris Lattnercf4a9962004-04-10 22:01:55 +00001456 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001457
1458 if (isa<PHINode>(LHS))
1459 if (Instruction *NV = FoldOpIntoPhi(I))
1460 return NV;
Chris Lattner0b3557f2005-09-24 23:43:33 +00001461
Chris Lattner330628a2006-01-06 17:59:59 +00001462 ConstantInt *XorRHS = 0;
1463 Value *XorLHS = 0;
Chris Lattner0b3557f2005-09-24 23:43:33 +00001464 if (match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
1465 unsigned TySizeBits = I.getType()->getPrimitiveSizeInBits();
1466 int64_t RHSSExt = cast<ConstantInt>(RHSC)->getSExtValue();
1467 uint64_t RHSZExt = cast<ConstantInt>(RHSC)->getZExtValue();
1468
1469 uint64_t C0080Val = 1ULL << 31;
1470 int64_t CFF80Val = -C0080Val;
1471 unsigned Size = 32;
1472 do {
1473 if (TySizeBits > Size) {
1474 bool Found = false;
1475 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
1476 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
1477 if (RHSSExt == CFF80Val) {
1478 if (XorRHS->getZExtValue() == C0080Val)
1479 Found = true;
1480 } else if (RHSZExt == C0080Val) {
1481 if (XorRHS->getSExtValue() == CFF80Val)
1482 Found = true;
1483 }
1484 if (Found) {
1485 // This is a sign extend if the top bits are known zero.
Chris Lattner4534dd592006-02-09 07:38:58 +00001486 uint64_t Mask = ~0ULL;
Chris Lattnerc3ebf402006-02-07 07:27:52 +00001487 Mask <<= 64-(TySizeBits-Size);
Chris Lattner4534dd592006-02-09 07:38:58 +00001488 Mask &= XorLHS->getType()->getIntegralTypeMask();
Chris Lattnerc3ebf402006-02-07 07:27:52 +00001489 if (!MaskedValueIsZero(XorLHS, Mask))
Chris Lattner0b3557f2005-09-24 23:43:33 +00001490 Size = 0; // Not a sign ext, but can't be any others either.
1491 goto FoundSExt;
1492 }
1493 }
1494 Size >>= 1;
1495 C0080Val >>= Size;
1496 CFF80Val >>= Size;
1497 } while (Size >= 8);
1498
1499FoundSExt:
1500 const Type *MiddleType = 0;
1501 switch (Size) {
1502 default: break;
1503 case 32: MiddleType = Type::IntTy; break;
1504 case 16: MiddleType = Type::ShortTy; break;
1505 case 8: MiddleType = Type::SByteTy; break;
1506 }
1507 if (MiddleType) {
1508 Instruction *NewTrunc = new CastInst(XorLHS, MiddleType, "sext");
1509 InsertNewInstBefore(NewTrunc, I);
1510 return new CastInst(NewTrunc, I.getType());
1511 }
1512 }
Chris Lattnercf4a9962004-04-10 22:01:55 +00001513 }
Chris Lattner9fa53de2002-05-06 16:49:18 +00001514
Chris Lattnerb8b97502003-08-13 19:01:45 +00001515 // X + X --> X << 1
Robert Bocchino7b5b86c2004-07-27 21:02:21 +00001516 if (I.getType()->isInteger()) {
Chris Lattnerb8b97502003-08-13 19:01:45 +00001517 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Chris Lattner47060462005-04-07 17:14:51 +00001518
1519 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
1520 if (RHSI->getOpcode() == Instruction::Sub)
1521 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
1522 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
1523 }
1524 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
1525 if (LHSI->getOpcode() == Instruction::Sub)
1526 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
1527 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
1528 }
Robert Bocchino7b5b86c2004-07-27 21:02:21 +00001529 }
Chris Lattnerede3fe02003-08-13 04:18:28 +00001530
Chris Lattner147e9752002-05-08 22:46:53 +00001531 // -A + B --> B - A
Chris Lattnerbb74e222003-03-10 23:06:50 +00001532 if (Value *V = dyn_castNegVal(LHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001533 return BinaryOperator::createSub(RHS, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +00001534
1535 // A + -B --> A - B
Chris Lattnerbb74e222003-03-10 23:06:50 +00001536 if (!isa<Constant>(RHS))
1537 if (Value *V = dyn_castNegVal(RHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001538 return BinaryOperator::createSub(LHS, V);
Chris Lattner260ab202002-04-18 17:39:14 +00001539
Misha Brukmanb1c93172005-04-21 23:48:37 +00001540
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001541 ConstantInt *C2;
1542 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
1543 if (X == RHS) // X*C + X --> X * (C+1)
1544 return BinaryOperator::createMul(RHS, AddOne(C2));
1545
1546 // X*C1 + X*C2 --> X * (C1+C2)
1547 ConstantInt *C1;
1548 if (X == dyn_castFoldableMul(RHS, C1))
1549 return BinaryOperator::createMul(X, ConstantExpr::getAdd(C1, C2));
Chris Lattner57c8d992003-02-18 19:57:07 +00001550 }
1551
1552 // X + X*C --> X * (C+1)
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001553 if (dyn_castFoldableMul(RHS, C2) == LHS)
1554 return BinaryOperator::createMul(LHS, AddOne(C2));
1555
Chris Lattner57c8d992003-02-18 19:57:07 +00001556
Chris Lattnerb8b97502003-08-13 19:01:45 +00001557 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattnerd4252a72004-07-30 07:50:03 +00001558 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattnerb8b97502003-08-13 19:01:45 +00001559 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2))) return R;
Chris Lattner7fb29e12003-03-11 00:12:48 +00001560
Chris Lattnerb9cde762003-10-02 15:11:26 +00001561 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner330628a2006-01-06 17:59:59 +00001562 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00001563 if (match(LHS, m_Not(m_Value(X)))) { // ~X + C --> (C-1) - X
1564 Constant *C= ConstantExpr::getSub(CRHS, ConstantInt::get(I.getType(), 1));
1565 return BinaryOperator::createSub(C, X);
Chris Lattnerb9cde762003-10-02 15:11:26 +00001566 }
Chris Lattnerd4252a72004-07-30 07:50:03 +00001567
Chris Lattnerbff91d92004-10-08 05:07:56 +00001568 // (X & FF00) + xx00 -> (X+xx00) & FF00
1569 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
1570 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
1571 if (Anded == CRHS) {
1572 // See if all bits from the first bit set in the Add RHS up are included
1573 // in the mask. First, get the rightmost bit.
1574 uint64_t AddRHSV = CRHS->getRawValue();
1575
1576 // Form a mask of all bits from the lowest bit added through the top.
1577 uint64_t AddRHSHighBits = ~((AddRHSV & -AddRHSV)-1);
Chris Lattner77defba2006-02-07 07:00:41 +00001578 AddRHSHighBits &= C2->getType()->getIntegralTypeMask();
Chris Lattnerbff91d92004-10-08 05:07:56 +00001579
1580 // See if the and mask includes all of these bits.
1581 uint64_t AddRHSHighBitsAnd = AddRHSHighBits & C2->getRawValue();
Misha Brukmanb1c93172005-04-21 23:48:37 +00001582
Chris Lattnerbff91d92004-10-08 05:07:56 +00001583 if (AddRHSHighBits == AddRHSHighBitsAnd) {
1584 // Okay, the xform is safe. Insert the new add pronto.
1585 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
1586 LHS->getName()), I);
1587 return BinaryOperator::createAnd(NewAdd, C2);
1588 }
1589 }
1590 }
1591
Chris Lattnerd4252a72004-07-30 07:50:03 +00001592 // Try to fold constant add into select arguments.
1593 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner86102b82005-01-01 16:22:27 +00001594 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattnerd4252a72004-07-30 07:50:03 +00001595 return R;
Chris Lattnerb9cde762003-10-02 15:11:26 +00001596 }
1597
Andrew Lenharth4f339be2006-09-19 18:24:51 +00001598 // add (cast *A to intptrtype) B -> cast (GEP (cast *A to sbyte*) B) -> intptrtype
1599 {
1600 CastInst* CI = dyn_cast<CastInst>(LHS);
1601 Value* Other = RHS;
1602 if (!CI) {
1603 CI = dyn_cast<CastInst>(RHS);
1604 Other = LHS;
1605 }
Andrew Lenharth44cb67a2006-09-20 15:37:57 +00001606 if (CI && CI->getType()->isSized() &&
1607 (CI->getType()->getPrimitiveSize() ==
1608 TD->getIntPtrType()->getPrimitiveSize())
1609 && isa<PointerType>(CI->getOperand(0)->getType())) {
1610 Value* I2 = InsertCastBefore(CI->getOperand(0),
1611 PointerType::get(Type::SByteTy), I);
1612 I2 = InsertNewInstBefore(new GetElementPtrInst(I2, Other, "ctg2"), I);
1613 return new CastInst(I2, CI->getType());
Andrew Lenharth4f339be2006-09-19 18:24:51 +00001614 }
1615 }
1616
Chris Lattner113f4f42002-06-25 16:13:24 +00001617 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +00001618}
1619
Chris Lattnerbdb0ce02003-07-22 21:46:59 +00001620// isSignBit - Return true if the value represented by the constant only has the
1621// highest order bit set.
1622static bool isSignBit(ConstantInt *CI) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001623 unsigned NumBits = CI->getType()->getPrimitiveSizeInBits();
Chris Lattner2f1457f2005-04-24 17:46:05 +00001624 return (CI->getRawValue() & (~0ULL >> (64-NumBits))) == (1ULL << (NumBits-1));
Chris Lattnerbdb0ce02003-07-22 21:46:59 +00001625}
1626
Chris Lattner022167f2004-03-13 00:11:49 +00001627/// RemoveNoopCast - Strip off nonconverting casts from the value.
1628///
1629static Value *RemoveNoopCast(Value *V) {
1630 if (CastInst *CI = dyn_cast<CastInst>(V)) {
1631 const Type *CTy = CI->getType();
1632 const Type *OpTy = CI->getOperand(0)->getType();
1633 if (CTy->isInteger() && OpTy->isInteger()) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001634 if (CTy->getPrimitiveSizeInBits() == OpTy->getPrimitiveSizeInBits())
Chris Lattner022167f2004-03-13 00:11:49 +00001635 return RemoveNoopCast(CI->getOperand(0));
1636 } else if (isa<PointerType>(CTy) && isa<PointerType>(OpTy))
1637 return RemoveNoopCast(CI->getOperand(0));
1638 }
1639 return V;
1640}
1641
Chris Lattner113f4f42002-06-25 16:13:24 +00001642Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +00001643 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001644
Chris Lattnere6794492002-08-12 21:17:25 +00001645 if (Op0 == Op1) // sub X, X -> 0
1646 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner260ab202002-04-18 17:39:14 +00001647
Chris Lattnere6794492002-08-12 21:17:25 +00001648 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattnerbb74e222003-03-10 23:06:50 +00001649 if (Value *V = dyn_castNegVal(Op1))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001650 return BinaryOperator::createAdd(Op0, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +00001651
Chris Lattner81a7a232004-10-16 18:11:37 +00001652 if (isa<UndefValue>(Op0))
1653 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
1654 if (isa<UndefValue>(Op1))
1655 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
1656
Chris Lattner8f2f5982003-11-05 01:06:05 +00001657 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
1658 // Replace (-1 - A) with (~A)...
Chris Lattner3082c5a2003-02-18 19:28:33 +00001659 if (C->isAllOnesValue())
1660 return BinaryOperator::createNot(Op1);
Chris Lattnerad3c4952002-05-09 01:29:19 +00001661
Chris Lattner8f2f5982003-11-05 01:06:05 +00001662 // C - ~X == X + (1+C)
Reid Spencer4fdd96c2005-06-18 17:37:34 +00001663 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00001664 if (match(Op1, m_Not(m_Value(X))))
1665 return BinaryOperator::createAdd(X,
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001666 ConstantExpr::getAdd(C, ConstantInt::get(I.getType(), 1)));
Chris Lattner92295c52004-03-12 23:53:13 +00001667 // -((uint)X >> 31) -> ((int)X >> 31)
1668 // -((int)X >> 31) -> ((uint)X >> 31)
Chris Lattner022167f2004-03-13 00:11:49 +00001669 if (C->isNullValue()) {
1670 Value *NoopCastedRHS = RemoveNoopCast(Op1);
1671 if (ShiftInst *SI = dyn_cast<ShiftInst>(NoopCastedRHS))
Chris Lattner92295c52004-03-12 23:53:13 +00001672 if (SI->getOpcode() == Instruction::Shr)
1673 if (ConstantUInt *CU = dyn_cast<ConstantUInt>(SI->getOperand(1))) {
1674 const Type *NewTy;
Chris Lattner022167f2004-03-13 00:11:49 +00001675 if (SI->getType()->isSigned())
Chris Lattner97bfcea2004-06-17 18:16:02 +00001676 NewTy = SI->getType()->getUnsignedVersion();
Chris Lattner92295c52004-03-12 23:53:13 +00001677 else
Chris Lattner97bfcea2004-06-17 18:16:02 +00001678 NewTy = SI->getType()->getSignedVersion();
Chris Lattner92295c52004-03-12 23:53:13 +00001679 // Check to see if we are shifting out everything but the sign bit.
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001680 if (CU->getValue() == SI->getType()->getPrimitiveSizeInBits()-1) {
Chris Lattner92295c52004-03-12 23:53:13 +00001681 // Ok, the transformation is safe. Insert a cast of the incoming
1682 // value, then the new shift, then the new cast.
1683 Instruction *FirstCast = new CastInst(SI->getOperand(0), NewTy,
1684 SI->getOperand(0)->getName());
1685 Value *InV = InsertNewInstBefore(FirstCast, I);
1686 Instruction *NewShift = new ShiftInst(Instruction::Shr, FirstCast,
1687 CU, SI->getName());
Chris Lattner022167f2004-03-13 00:11:49 +00001688 if (NewShift->getType() == I.getType())
1689 return NewShift;
1690 else {
1691 InV = InsertNewInstBefore(NewShift, I);
1692 return new CastInst(NewShift, I.getType());
1693 }
Chris Lattner92295c52004-03-12 23:53:13 +00001694 }
1695 }
Chris Lattner022167f2004-03-13 00:11:49 +00001696 }
Chris Lattner183b3362004-04-09 19:05:30 +00001697
1698 // Try to fold constant sub into select arguments.
1699 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner86102b82005-01-01 16:22:27 +00001700 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00001701 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001702
1703 if (isa<PHINode>(Op0))
1704 if (Instruction *NV = FoldOpIntoPhi(I))
1705 return NV;
Chris Lattner8f2f5982003-11-05 01:06:05 +00001706 }
1707
Chris Lattnera9be4492005-04-07 16:15:25 +00001708 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
1709 if (Op1I->getOpcode() == Instruction::Add &&
1710 !Op0->getType()->isFloatingPoint()) {
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00001711 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Chris Lattnera9be4492005-04-07 16:15:25 +00001712 return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00001713 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Chris Lattnera9be4492005-04-07 16:15:25 +00001714 return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00001715 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
1716 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
1717 // C1-(X+C2) --> (C1-C2)-X
1718 return BinaryOperator::createSub(ConstantExpr::getSub(CI1, CI2),
1719 Op1I->getOperand(0));
1720 }
Chris Lattnera9be4492005-04-07 16:15:25 +00001721 }
1722
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001723 if (Op1I->hasOneUse()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00001724 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
1725 // is not used by anyone else...
1726 //
Chris Lattnerc2f0aa52004-02-02 20:09:56 +00001727 if (Op1I->getOpcode() == Instruction::Sub &&
1728 !Op1I->getType()->isFloatingPoint()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00001729 // Swap the two operands of the subexpr...
1730 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
1731 Op1I->setOperand(0, IIOp1);
1732 Op1I->setOperand(1, IIOp0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001733
Chris Lattner3082c5a2003-02-18 19:28:33 +00001734 // Create the new top level add instruction...
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001735 return BinaryOperator::createAdd(Op0, Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001736 }
1737
1738 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
1739 //
1740 if (Op1I->getOpcode() == Instruction::And &&
1741 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
1742 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
1743
Chris Lattner396dbfe2004-06-09 05:08:07 +00001744 Value *NewNot =
1745 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001746 return BinaryOperator::createAnd(Op0, NewNot);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001747 }
Chris Lattner57c8d992003-02-18 19:57:07 +00001748
Chris Lattner0aee4b72004-10-06 15:08:25 +00001749 // -(X sdiv C) -> (X sdiv -C)
1750 if (Op1I->getOpcode() == Instruction::Div)
1751 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
Chris Lattnera9be4492005-04-07 16:15:25 +00001752 if (CSI->isNullValue())
Chris Lattner0aee4b72004-10-06 15:08:25 +00001753 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Misha Brukmanb1c93172005-04-21 23:48:37 +00001754 return BinaryOperator::createDiv(Op1I->getOperand(0),
Chris Lattner0aee4b72004-10-06 15:08:25 +00001755 ConstantExpr::getNeg(DivRHS));
1756
Chris Lattner57c8d992003-02-18 19:57:07 +00001757 // X - X*C --> X * (1-C)
Reid Spencer4fdd96c2005-06-18 17:37:34 +00001758 ConstantInt *C2 = 0;
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001759 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00001760 Constant *CP1 =
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001761 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1), C2);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001762 return BinaryOperator::createMul(Op0, CP1);
Chris Lattner57c8d992003-02-18 19:57:07 +00001763 }
Chris Lattnerad3c4952002-05-09 01:29:19 +00001764 }
Chris Lattnera9be4492005-04-07 16:15:25 +00001765 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00001766
Chris Lattner47060462005-04-07 17:14:51 +00001767 if (!Op0->getType()->isFloatingPoint())
1768 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
1769 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner411336f2005-01-19 21:50:18 +00001770 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
1771 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
1772 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
1773 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner47060462005-04-07 17:14:51 +00001774 } else if (Op0I->getOpcode() == Instruction::Sub) {
1775 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
1776 return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
Chris Lattner411336f2005-01-19 21:50:18 +00001777 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001778
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001779 ConstantInt *C1;
1780 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
1781 if (X == Op1) { // X*C - X --> X * (C-1)
1782 Constant *CP1 = ConstantExpr::getSub(C1, ConstantInt::get(I.getType(),1));
1783 return BinaryOperator::createMul(Op1, CP1);
1784 }
Chris Lattner57c8d992003-02-18 19:57:07 +00001785
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001786 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
1787 if (X == dyn_castFoldableMul(Op1, C2))
1788 return BinaryOperator::createMul(Op1, ConstantExpr::getSub(C1, C2));
1789 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001790 return 0;
Chris Lattner260ab202002-04-18 17:39:14 +00001791}
1792
Chris Lattnere79e8542004-02-23 06:38:22 +00001793/// isSignBitCheck - Given an exploded setcc instruction, return true if it is
1794/// really just returns true if the most significant (sign) bit is set.
1795static bool isSignBitCheck(unsigned Opcode, Value *LHS, ConstantInt *RHS) {
1796 if (RHS->getType()->isSigned()) {
1797 // True if source is LHS < 0 or LHS <= -1
1798 return Opcode == Instruction::SetLT && RHS->isNullValue() ||
1799 Opcode == Instruction::SetLE && RHS->isAllOnesValue();
1800 } else {
1801 ConstantUInt *RHSC = cast<ConstantUInt>(RHS);
1802 // True if source is LHS > 127 or LHS >= 128, where the constants depend on
1803 // the size of the integer type.
1804 if (Opcode == Instruction::SetGE)
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001805 return RHSC->getValue() ==
1806 1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1);
Chris Lattnere79e8542004-02-23 06:38:22 +00001807 if (Opcode == Instruction::SetGT)
1808 return RHSC->getValue() ==
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001809 (1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1))-1;
Chris Lattnere79e8542004-02-23 06:38:22 +00001810 }
1811 return false;
1812}
1813
Chris Lattner113f4f42002-06-25 16:13:24 +00001814Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001815 bool Changed = SimplifyCommutative(I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001816 Value *Op0 = I.getOperand(0);
Chris Lattner260ab202002-04-18 17:39:14 +00001817
Chris Lattner81a7a232004-10-16 18:11:37 +00001818 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
1819 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1820
Chris Lattnere6794492002-08-12 21:17:25 +00001821 // Simplify mul instructions with a constant RHS...
Chris Lattner3082c5a2003-02-18 19:28:33 +00001822 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
1823 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerede3fe02003-08-13 04:18:28 +00001824
1825 // ((X << C1)*C2) == (X * (C2 << C1))
1826 if (ShiftInst *SI = dyn_cast<ShiftInst>(Op0))
1827 if (SI->getOpcode() == Instruction::Shl)
1828 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001829 return BinaryOperator::createMul(SI->getOperand(0),
1830 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanb1c93172005-04-21 23:48:37 +00001831
Chris Lattnercce81be2003-09-11 22:24:54 +00001832 if (CI->isNullValue())
1833 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
1834 if (CI->equalsInt(1)) // X * 1 == X
1835 return ReplaceInstUsesWith(I, Op0);
1836 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Chris Lattner35236d82003-06-25 17:09:20 +00001837 return BinaryOperator::createNeg(Op0, I.getName());
Chris Lattner31ba1292002-04-29 22:24:47 +00001838
Chris Lattnercce81be2003-09-11 22:24:54 +00001839 int64_t Val = (int64_t)cast<ConstantInt>(CI)->getRawValue();
Chris Lattner22d00a82005-08-02 19:16:58 +00001840 if (isPowerOf2_64(Val)) { // Replace X*(2^C) with X << C
1841 uint64_t C = Log2_64(Val);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001842 return new ShiftInst(Instruction::Shl, Op0,
1843 ConstantUInt::get(Type::UByteTy, C));
Chris Lattner22d00a82005-08-02 19:16:58 +00001844 }
Robert Bocchino7b5b86c2004-07-27 21:02:21 +00001845 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00001846 if (Op1F->isNullValue())
1847 return ReplaceInstUsesWith(I, Op1);
Chris Lattner31ba1292002-04-29 22:24:47 +00001848
Chris Lattner3082c5a2003-02-18 19:28:33 +00001849 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
1850 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
1851 if (Op1F->getValue() == 1.0)
1852 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
1853 }
Chris Lattner32c01df2006-03-04 06:04:02 +00001854
1855 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
1856 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
1857 isa<ConstantInt>(Op0I->getOperand(1))) {
1858 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
1859 Instruction *Add = BinaryOperator::createMul(Op0I->getOperand(0),
1860 Op1, "tmp");
1861 InsertNewInstBefore(Add, I);
1862 Value *C1C2 = ConstantExpr::getMul(Op1,
1863 cast<Constant>(Op0I->getOperand(1)));
1864 return BinaryOperator::createAdd(Add, C1C2);
1865
1866 }
Chris Lattner183b3362004-04-09 19:05:30 +00001867
1868 // Try to fold constant mul into select arguments.
1869 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00001870 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00001871 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001872
1873 if (isa<PHINode>(Op0))
1874 if (Instruction *NV = FoldOpIntoPhi(I))
1875 return NV;
Chris Lattner260ab202002-04-18 17:39:14 +00001876 }
1877
Chris Lattner934a64cf2003-03-10 23:23:04 +00001878 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
1879 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001880 return BinaryOperator::createMul(Op0v, Op1v);
Chris Lattner934a64cf2003-03-10 23:23:04 +00001881
Chris Lattner2635b522004-02-23 05:39:21 +00001882 // If one of the operands of the multiply is a cast from a boolean value, then
1883 // we know the bool is either zero or one, so this is a 'masking' multiply.
1884 // See if we can simplify things based on how the boolean was originally
1885 // formed.
1886 CastInst *BoolCast = 0;
1887 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(0)))
1888 if (CI->getOperand(0)->getType() == Type::BoolTy)
1889 BoolCast = CI;
1890 if (!BoolCast)
1891 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(1)))
1892 if (CI->getOperand(0)->getType() == Type::BoolTy)
1893 BoolCast = CI;
1894 if (BoolCast) {
1895 if (SetCondInst *SCI = dyn_cast<SetCondInst>(BoolCast->getOperand(0))) {
1896 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
1897 const Type *SCOpTy = SCIOp0->getType();
1898
Chris Lattnere79e8542004-02-23 06:38:22 +00001899 // If the setcc is true iff the sign bit of X is set, then convert this
1900 // multiply into a shift/and combination.
1901 if (isa<ConstantInt>(SCIOp1) &&
1902 isSignBitCheck(SCI->getOpcode(), SCIOp0, cast<ConstantInt>(SCIOp1))) {
Chris Lattner2635b522004-02-23 05:39:21 +00001903 // Shift the X value right to turn it into "all signbits".
1904 Constant *Amt = ConstantUInt::get(Type::UByteTy,
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001905 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattnere79e8542004-02-23 06:38:22 +00001906 if (SCIOp0->getType()->isUnsigned()) {
Chris Lattner97bfcea2004-06-17 18:16:02 +00001907 const Type *NewTy = SCIOp0->getType()->getSignedVersion();
Chris Lattnere79e8542004-02-23 06:38:22 +00001908 SCIOp0 = InsertNewInstBefore(new CastInst(SCIOp0, NewTy,
1909 SCIOp0->getName()), I);
1910 }
1911
1912 Value *V =
1913 InsertNewInstBefore(new ShiftInst(Instruction::Shr, SCIOp0, Amt,
1914 BoolCast->getOperand(0)->getName()+
1915 ".mask"), I);
Chris Lattner2635b522004-02-23 05:39:21 +00001916
1917 // If the multiply type is not the same as the source type, sign extend
1918 // or truncate to the multiply type.
1919 if (I.getType() != V->getType())
Chris Lattnere79e8542004-02-23 06:38:22 +00001920 V = InsertNewInstBefore(new CastInst(V, I.getType(), V->getName()),I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001921
Chris Lattner2635b522004-02-23 05:39:21 +00001922 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001923 return BinaryOperator::createAnd(V, OtherOp);
Chris Lattner2635b522004-02-23 05:39:21 +00001924 }
1925 }
1926 }
1927
Chris Lattner113f4f42002-06-25 16:13:24 +00001928 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +00001929}
1930
Chris Lattner113f4f42002-06-25 16:13:24 +00001931Instruction *InstCombiner::visitDiv(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001932 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner81a7a232004-10-16 18:11:37 +00001933
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001934 if (isa<UndefValue>(Op0)) // undef / X -> 0
1935 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1936 if (isa<UndefValue>(Op1))
1937 return ReplaceInstUsesWith(I, Op1); // X / undef -> undef
1938
1939 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnere20c3342004-04-26 14:01:59 +00001940 // div X, 1 == X
Chris Lattnere6794492002-08-12 21:17:25 +00001941 if (RHS->equalsInt(1))
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001942 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001943
Chris Lattnere20c3342004-04-26 14:01:59 +00001944 // div X, -1 == -X
1945 if (RHS->isAllOnesValue())
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001946 return BinaryOperator::createNeg(Op0);
Chris Lattnere20c3342004-04-26 14:01:59 +00001947
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001948 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
Chris Lattner272d5ca2004-09-28 18:22:15 +00001949 if (LHS->getOpcode() == Instruction::Div)
1950 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Chris Lattner272d5ca2004-09-28 18:22:15 +00001951 // (X / C1) / C2 -> X / (C1*C2)
1952 return BinaryOperator::createDiv(LHS->getOperand(0),
1953 ConstantExpr::getMul(RHS, LHSRHS));
1954 }
1955
Chris Lattner3082c5a2003-02-18 19:28:33 +00001956 // Check to see if this is an unsigned division with an exact power of 2,
1957 // if so, convert to a right shift.
1958 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
1959 if (uint64_t Val = C->getValue()) // Don't break X / 0
Chris Lattner22d00a82005-08-02 19:16:58 +00001960 if (isPowerOf2_64(Val)) {
1961 uint64_t C = Log2_64(Val);
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001962 return new ShiftInst(Instruction::Shr, Op0,
Chris Lattner3082c5a2003-02-18 19:28:33 +00001963 ConstantUInt::get(Type::UByteTy, C));
Chris Lattner22d00a82005-08-02 19:16:58 +00001964 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001965
Chris Lattner4ad08352004-10-09 02:50:40 +00001966 // -X/C -> X/-C
1967 if (RHS->getType()->isSigned())
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001968 if (Value *LHSNeg = dyn_castNegVal(Op0))
Chris Lattner4ad08352004-10-09 02:50:40 +00001969 return BinaryOperator::createDiv(LHSNeg, ConstantExpr::getNeg(RHS));
1970
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001971 if (!RHS->isNullValue()) {
1972 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00001973 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001974 return R;
1975 if (isa<PHINode>(Op0))
1976 if (Instruction *NV = FoldOpIntoPhi(I))
1977 return NV;
1978 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00001979 }
1980
Chris Lattnerd79dc792006-09-09 20:26:32 +00001981 // Handle div X, Cond?Y:Z
1982 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
1983 // div X, (Cond ? 0 : Y) -> div X, Y. If the div and the select are in the
1984 // same basic block, then we replace the select with Y, and the condition of
1985 // the select with false (if the cond value is in the same BB). If the
1986 // select has uses other than the div, this allows them to be simplified
1987 // also.
1988 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
1989 if (ST->isNullValue()) {
1990 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
1991 if (CondI && CondI->getParent() == I.getParent())
Chris Lattner6ab03f62006-09-28 23:35:22 +00001992 UpdateValueUsesWith(CondI, ConstantBool::getFalse());
Chris Lattnerd79dc792006-09-09 20:26:32 +00001993 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
1994 I.setOperand(1, SI->getOperand(2));
1995 else
1996 UpdateValueUsesWith(SI, SI->getOperand(2));
1997 return &I;
1998 }
1999 // Likewise for: div X, (Cond ? Y : 0) -> div X, Y
2000 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2001 if (ST->isNullValue()) {
2002 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2003 if (CondI && CondI->getParent() == I.getParent())
Chris Lattner6ab03f62006-09-28 23:35:22 +00002004 UpdateValueUsesWith(CondI, ConstantBool::getTrue());
Chris Lattnerd79dc792006-09-09 20:26:32 +00002005 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2006 I.setOperand(1, SI->getOperand(1));
2007 else
2008 UpdateValueUsesWith(SI, SI->getOperand(1));
2009 return &I;
2010 }
2011
2012 // If this is 'udiv X, (Cond ? C1, C2)' where C1&C2 are powers of two,
2013 // transform this into: '(Cond ? (udiv X, C1) : (udiv X, C2))'.
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002014 if (ConstantUInt *STO = dyn_cast<ConstantUInt>(SI->getOperand(1)))
2015 if (ConstantUInt *SFO = dyn_cast<ConstantUInt>(SI->getOperand(2))) {
Chris Lattnerd79dc792006-09-09 20:26:32 +00002016 // STO == 0 and SFO == 0 handled above.
Chris Lattner42362612005-04-08 04:03:26 +00002017 uint64_t TVA = STO->getValue(), FVA = SFO->getValue();
Chris Lattner22d00a82005-08-02 19:16:58 +00002018 if (isPowerOf2_64(TVA) && isPowerOf2_64(FVA)) {
2019 unsigned TSA = Log2_64(TVA), FSA = Log2_64(FVA);
Chris Lattner42362612005-04-08 04:03:26 +00002020 Constant *TC = ConstantUInt::get(Type::UByteTy, TSA);
2021 Instruction *TSI = new ShiftInst(Instruction::Shr, Op0,
2022 TC, SI->getName()+".t");
2023 TSI = InsertNewInstBefore(TSI, I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002024
Chris Lattner42362612005-04-08 04:03:26 +00002025 Constant *FC = ConstantUInt::get(Type::UByteTy, FSA);
2026 Instruction *FSI = new ShiftInst(Instruction::Shr, Op0,
2027 FC, SI->getName()+".f");
2028 FSI = InsertNewInstBefore(FSI, I);
2029 return new SelectInst(SI->getOperand(0), TSI, FSI);
2030 }
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002031 }
Chris Lattnerd79dc792006-09-09 20:26:32 +00002032 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002033
Chris Lattner3082c5a2003-02-18 19:28:33 +00002034 // 0 / X == 0, we don't need to preserve faults!
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002035 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattner3082c5a2003-02-18 19:28:33 +00002036 if (LHS->equalsInt(0))
2037 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2038
Chris Lattnerdd0c1742005-11-05 07:40:31 +00002039 if (I.getType()->isSigned()) {
Chris Lattnerc3ebf402006-02-07 07:27:52 +00002040 // If the sign bits of both operands are zero (i.e. we can prove they are
Chris Lattnerdd0c1742005-11-05 07:40:31 +00002041 // unsigned inputs), turn this into a udiv.
Chris Lattnerc3ebf402006-02-07 07:27:52 +00002042 uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
2043 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
Chris Lattnerdd0c1742005-11-05 07:40:31 +00002044 const Type *NTy = Op0->getType()->getUnsignedVersion();
2045 Instruction *LHS = new CastInst(Op0, NTy, Op0->getName());
2046 InsertNewInstBefore(LHS, I);
2047 Value *RHS;
2048 if (Constant *R = dyn_cast<Constant>(Op1))
2049 RHS = ConstantExpr::getCast(R, NTy);
2050 else
2051 RHS = InsertNewInstBefore(new CastInst(Op1, NTy, Op1->getName()), I);
2052 Instruction *Div = BinaryOperator::createDiv(LHS, RHS, I.getName());
2053 InsertNewInstBefore(Div, I);
2054 return new CastInst(Div, I.getType());
2055 }
Chris Lattner2e90b732006-02-05 07:54:04 +00002056 } else {
2057 // Known to be an unsigned division.
2058 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
2059 // Turn A / (C1 << N), where C1 is "1<<C2" into A >> (N+C2) [udiv only].
2060 if (RHSI->getOpcode() == Instruction::Shl &&
2061 isa<ConstantUInt>(RHSI->getOperand(0))) {
2062 unsigned C1 = cast<ConstantUInt>(RHSI->getOperand(0))->getRawValue();
2063 if (isPowerOf2_64(C1)) {
2064 unsigned C2 = Log2_64(C1);
2065 Value *Add = RHSI->getOperand(1);
2066 if (C2) {
2067 Constant *C2V = ConstantUInt::get(Add->getType(), C2);
2068 Add = InsertNewInstBefore(BinaryOperator::createAdd(Add, C2V,
2069 "tmp"), I);
2070 }
2071 return new ShiftInst(Instruction::Shr, Op0, Add);
2072 }
2073 }
2074 }
Chris Lattnerdd0c1742005-11-05 07:40:31 +00002075 }
2076
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002077 return 0;
2078}
2079
2080
Chris Lattner85dda9a2006-03-02 06:50:58 +00002081/// GetFactor - If we can prove that the specified value is at least a multiple
2082/// of some factor, return that factor.
2083static Constant *GetFactor(Value *V) {
2084 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
2085 return CI;
2086
2087 // Unless we can be tricky, we know this is a multiple of 1.
2088 Constant *Result = ConstantInt::get(V->getType(), 1);
2089
2090 Instruction *I = dyn_cast<Instruction>(V);
2091 if (!I) return Result;
2092
2093 if (I->getOpcode() == Instruction::Mul) {
2094 // Handle multiplies by a constant, etc.
2095 return ConstantExpr::getMul(GetFactor(I->getOperand(0)),
2096 GetFactor(I->getOperand(1)));
2097 } else if (I->getOpcode() == Instruction::Shl) {
2098 // (X<<C) -> X * (1 << C)
2099 if (Constant *ShRHS = dyn_cast<Constant>(I->getOperand(1))) {
2100 ShRHS = ConstantExpr::getShl(Result, ShRHS);
2101 return ConstantExpr::getMul(GetFactor(I->getOperand(0)), ShRHS);
2102 }
2103 } else if (I->getOpcode() == Instruction::And) {
2104 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
2105 // X & 0xFFF0 is known to be a multiple of 16.
2106 unsigned Zeros = CountTrailingZeros_64(RHS->getZExtValue());
2107 if (Zeros != V->getType()->getPrimitiveSizeInBits())
2108 return ConstantExpr::getShl(Result,
2109 ConstantUInt::get(Type::UByteTy, Zeros));
2110 }
2111 } else if (I->getOpcode() == Instruction::Cast) {
2112 Value *Op = I->getOperand(0);
2113 // Only handle int->int casts.
2114 if (!Op->getType()->isInteger()) return Result;
2115 return ConstantExpr::getCast(GetFactor(Op), V->getType());
2116 }
2117 return Result;
2118}
2119
Chris Lattner113f4f42002-06-25 16:13:24 +00002120Instruction *InstCombiner::visitRem(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002121 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner0de4a8d2006-02-28 05:30:45 +00002122
2123 // 0 % X == 0, we don't need to preserve faults!
2124 if (Constant *LHS = dyn_cast<Constant>(Op0))
2125 if (LHS->isNullValue())
2126 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2127
2128 if (isa<UndefValue>(Op0)) // undef % X -> 0
2129 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2130 if (isa<UndefValue>(Op1))
2131 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
2132
Chris Lattnere9ff0ea2005-11-05 07:28:37 +00002133 if (I.getType()->isSigned()) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002134 if (Value *RHSNeg = dyn_castNegVal(Op1))
Chris Lattner98c6bdf2004-07-06 07:11:42 +00002135 if (!isa<ConstantSInt>(RHSNeg) ||
Chris Lattner8e726062004-08-09 21:05:48 +00002136 cast<ConstantSInt>(RHSNeg)->getValue() > 0) {
Chris Lattner7fd5f072004-07-06 07:01:22 +00002137 // X % -Y -> X % Y
2138 AddUsesToWorkList(I);
2139 I.setOperand(1, RHSNeg);
2140 return &I;
2141 }
Chris Lattnere9ff0ea2005-11-05 07:28:37 +00002142
2143 // If the top bits of both operands are zero (i.e. we can prove they are
2144 // unsigned inputs), turn this into a urem.
Chris Lattnerc3ebf402006-02-07 07:27:52 +00002145 uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
2146 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
Chris Lattnere9ff0ea2005-11-05 07:28:37 +00002147 const Type *NTy = Op0->getType()->getUnsignedVersion();
2148 Instruction *LHS = new CastInst(Op0, NTy, Op0->getName());
2149 InsertNewInstBefore(LHS, I);
2150 Value *RHS;
2151 if (Constant *R = dyn_cast<Constant>(Op1))
2152 RHS = ConstantExpr::getCast(R, NTy);
2153 else
2154 RHS = InsertNewInstBefore(new CastInst(Op1, NTy, Op1->getName()), I);
2155 Instruction *Rem = BinaryOperator::createRem(LHS, RHS, I.getName());
2156 InsertNewInstBefore(Rem, I);
2157 return new CastInst(Rem, I.getType());
2158 }
2159 }
Chris Lattner7fd5f072004-07-06 07:01:22 +00002160
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002161 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner0de4a8d2006-02-28 05:30:45 +00002162 // X % 0 == undef, we don't need to preserve faults!
2163 if (RHS->equalsInt(0))
2164 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2165
Chris Lattner3082c5a2003-02-18 19:28:33 +00002166 if (RHS->equalsInt(1)) // X % 1 == 0
2167 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2168
2169 // Check to see if this is an unsigned remainder with an exact power of 2,
2170 // if so, convert to a bitwise and.
2171 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
Chris Lattner0de4a8d2006-02-28 05:30:45 +00002172 if (isPowerOf2_64(C->getValue()))
2173 return BinaryOperator::createAnd(Op0, SubOne(C));
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002174
Chris Lattnerb70f1412006-02-28 05:49:21 +00002175 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2176 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2177 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2178 return R;
2179 } else if (isa<PHINode>(Op0I)) {
2180 if (Instruction *NV = FoldOpIntoPhi(I))
2181 return NV;
Chris Lattnerb70f1412006-02-28 05:49:21 +00002182 }
Chris Lattner85dda9a2006-03-02 06:50:58 +00002183
2184 // X*C1%C2 --> 0 iff C1%C2 == 0
2185 if (ConstantExpr::getRem(GetFactor(Op0I), RHS)->isNullValue())
2186 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerb70f1412006-02-28 05:49:21 +00002187 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00002188 }
2189
Chris Lattner2e90b732006-02-05 07:54:04 +00002190 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
2191 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1) [urem only].
2192 if (I.getType()->isUnsigned() &&
2193 RHSI->getOpcode() == Instruction::Shl &&
2194 isa<ConstantUInt>(RHSI->getOperand(0))) {
2195 unsigned C1 = cast<ConstantUInt>(RHSI->getOperand(0))->getRawValue();
2196 if (isPowerOf2_64(C1)) {
2197 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
2198 Value *Add = InsertNewInstBefore(BinaryOperator::createAdd(RHSI, N1,
2199 "tmp"), I);
2200 return BinaryOperator::createAnd(Op0, Add);
2201 }
2202 }
Chris Lattner0de4a8d2006-02-28 05:30:45 +00002203
2204 // If this is 'urem X, (Cond ? C1, C2)' where C1&C2 are powers of two,
2205 // transform this into: '(Cond ? (urem X, C1) : (urem X, C2))'.
Chris Lattnerd79dc792006-09-09 20:26:32 +00002206 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2207 // rem X, (Cond ? 0 : Y) -> rem X, Y. If the rem and the select are in
2208 // the same basic block, then we replace the select with Y, and the
2209 // condition of the select with false (if the cond value is in the same
2210 // BB). If the select has uses other than the div, this allows them to be
2211 // simplified also.
2212 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2213 if (ST->isNullValue()) {
2214 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2215 if (CondI && CondI->getParent() == I.getParent())
Chris Lattner6ab03f62006-09-28 23:35:22 +00002216 UpdateValueUsesWith(CondI, ConstantBool::getFalse());
Chris Lattnerd79dc792006-09-09 20:26:32 +00002217 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2218 I.setOperand(1, SI->getOperand(2));
2219 else
2220 UpdateValueUsesWith(SI, SI->getOperand(2));
2221 return &I;
2222 }
2223 // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
2224 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2225 if (ST->isNullValue()) {
2226 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2227 if (CondI && CondI->getParent() == I.getParent())
Chris Lattner6ab03f62006-09-28 23:35:22 +00002228 UpdateValueUsesWith(CondI, ConstantBool::getTrue());
Chris Lattnerd79dc792006-09-09 20:26:32 +00002229 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2230 I.setOperand(1, SI->getOperand(1));
2231 else
2232 UpdateValueUsesWith(SI, SI->getOperand(1));
2233 return &I;
2234 }
2235
2236
Chris Lattner0de4a8d2006-02-28 05:30:45 +00002237 if (ConstantUInt *STO = dyn_cast<ConstantUInt>(SI->getOperand(1)))
2238 if (ConstantUInt *SFO = dyn_cast<ConstantUInt>(SI->getOperand(2))) {
Chris Lattnerd79dc792006-09-09 20:26:32 +00002239 // STO == 0 and SFO == 0 handled above.
Chris Lattner0de4a8d2006-02-28 05:30:45 +00002240
2241 if (isPowerOf2_64(STO->getValue()) && isPowerOf2_64(SFO->getValue())){
2242 Value *TrueAnd = InsertNewInstBefore(BinaryOperator::createAnd(Op0,
2243 SubOne(STO), SI->getName()+".t"), I);
2244 Value *FalseAnd = InsertNewInstBefore(BinaryOperator::createAnd(Op0,
2245 SubOne(SFO), SI->getName()+".f"), I);
2246 return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
2247 }
2248 }
Chris Lattnerd79dc792006-09-09 20:26:32 +00002249 }
Chris Lattner2e90b732006-02-05 07:54:04 +00002250 }
2251
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002252 return 0;
2253}
2254
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002255// isMaxValueMinusOne - return true if this is Max-1
Chris Lattnere6794492002-08-12 21:17:25 +00002256static bool isMaxValueMinusOne(const ConstantInt *C) {
Chris Lattner77defba2006-02-07 07:00:41 +00002257 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
2258 return CU->getValue() == C->getType()->getIntegralTypeMask()-1;
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002259
2260 const ConstantSInt *CS = cast<ConstantSInt>(C);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002261
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002262 // Calculate 0111111111..11111
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002263 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002264 int64_t Val = INT64_MAX; // All ones
2265 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
2266 return CS->getValue() == Val-1;
2267}
2268
2269// isMinValuePlusOne - return true if this is Min+1
Chris Lattnere6794492002-08-12 21:17:25 +00002270static bool isMinValuePlusOne(const ConstantInt *C) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002271 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
2272 return CU->getValue() == 1;
2273
2274 const ConstantSInt *CS = cast<ConstantSInt>(C);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002275
2276 // Calculate 1111111111000000000000
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002277 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002278 int64_t Val = -1; // All ones
2279 Val <<= TypeBits-1; // Shift over to the right spot
2280 return CS->getValue() == Val+1;
2281}
2282
Chris Lattner35167c32004-06-09 07:59:58 +00002283// isOneBitSet - Return true if there is exactly one bit set in the specified
2284// constant.
2285static bool isOneBitSet(const ConstantInt *CI) {
2286 uint64_t V = CI->getRawValue();
2287 return V && (V & (V-1)) == 0;
2288}
2289
Chris Lattner8fc5af42004-09-23 21:46:38 +00002290#if 0 // Currently unused
2291// isLowOnes - Return true if the constant is of the form 0+1+.
2292static bool isLowOnes(const ConstantInt *CI) {
2293 uint64_t V = CI->getRawValue();
2294
2295 // There won't be bits set in parts that the type doesn't contain.
2296 V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
2297
2298 uint64_t U = V+1; // If it is low ones, this should be a power of two.
2299 return U && V && (U & V) == 0;
2300}
2301#endif
2302
2303// isHighOnes - Return true if the constant is of the form 1+0+.
2304// This is the same as lowones(~X).
2305static bool isHighOnes(const ConstantInt *CI) {
2306 uint64_t V = ~CI->getRawValue();
Chris Lattner2c14cf72005-08-07 07:03:10 +00002307 if (~V == 0) return false; // 0's does not match "1+"
Chris Lattner8fc5af42004-09-23 21:46:38 +00002308
2309 // There won't be bits set in parts that the type doesn't contain.
2310 V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
2311
2312 uint64_t U = V+1; // If it is low ones, this should be a power of two.
2313 return U && V && (U & V) == 0;
2314}
2315
2316
Chris Lattner3ac7c262003-08-13 20:16:26 +00002317/// getSetCondCode - Encode a setcc opcode into a three bit mask. These bits
2318/// are carefully arranged to allow folding of expressions such as:
2319///
2320/// (A < B) | (A > B) --> (A != B)
2321///
2322/// Bit value '4' represents that the comparison is true if A > B, bit value '2'
2323/// represents that the comparison is true if A == B, and bit value '1' is true
2324/// if A < B.
2325///
2326static unsigned getSetCondCode(const SetCondInst *SCI) {
2327 switch (SCI->getOpcode()) {
2328 // False -> 0
2329 case Instruction::SetGT: return 1;
2330 case Instruction::SetEQ: return 2;
2331 case Instruction::SetGE: return 3;
2332 case Instruction::SetLT: return 4;
2333 case Instruction::SetNE: return 5;
2334 case Instruction::SetLE: return 6;
2335 // True -> 7
2336 default:
2337 assert(0 && "Invalid SetCC opcode!");
2338 return 0;
2339 }
2340}
2341
2342/// getSetCCValue - This is the complement of getSetCondCode, which turns an
2343/// opcode and two operands into either a constant true or false, or a brand new
2344/// SetCC instruction.
2345static Value *getSetCCValue(unsigned Opcode, Value *LHS, Value *RHS) {
2346 switch (Opcode) {
Chris Lattner6ab03f62006-09-28 23:35:22 +00002347 case 0: return ConstantBool::getFalse();
Chris Lattner3ac7c262003-08-13 20:16:26 +00002348 case 1: return new SetCondInst(Instruction::SetGT, LHS, RHS);
2349 case 2: return new SetCondInst(Instruction::SetEQ, LHS, RHS);
2350 case 3: return new SetCondInst(Instruction::SetGE, LHS, RHS);
2351 case 4: return new SetCondInst(Instruction::SetLT, LHS, RHS);
2352 case 5: return new SetCondInst(Instruction::SetNE, LHS, RHS);
2353 case 6: return new SetCondInst(Instruction::SetLE, LHS, RHS);
Chris Lattner6ab03f62006-09-28 23:35:22 +00002354 case 7: return ConstantBool::getTrue();
Chris Lattner3ac7c262003-08-13 20:16:26 +00002355 default: assert(0 && "Illegal SetCCCode!"); return 0;
2356 }
2357}
2358
2359// FoldSetCCLogical - Implements (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
2360struct FoldSetCCLogical {
2361 InstCombiner &IC;
2362 Value *LHS, *RHS;
2363 FoldSetCCLogical(InstCombiner &ic, SetCondInst *SCI)
2364 : IC(ic), LHS(SCI->getOperand(0)), RHS(SCI->getOperand(1)) {}
2365 bool shouldApply(Value *V) const {
2366 if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
2367 return (SCI->getOperand(0) == LHS && SCI->getOperand(1) == RHS ||
2368 SCI->getOperand(0) == RHS && SCI->getOperand(1) == LHS);
2369 return false;
2370 }
2371 Instruction *apply(BinaryOperator &Log) const {
2372 SetCondInst *SCI = cast<SetCondInst>(Log.getOperand(0));
2373 if (SCI->getOperand(0) != LHS) {
2374 assert(SCI->getOperand(1) == LHS);
2375 SCI->swapOperands(); // Swap the LHS and RHS of the SetCC
2376 }
2377
2378 unsigned LHSCode = getSetCondCode(SCI);
2379 unsigned RHSCode = getSetCondCode(cast<SetCondInst>(Log.getOperand(1)));
2380 unsigned Code;
2381 switch (Log.getOpcode()) {
2382 case Instruction::And: Code = LHSCode & RHSCode; break;
2383 case Instruction::Or: Code = LHSCode | RHSCode; break;
2384 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner2caaaba2003-09-22 20:33:34 +00002385 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattner3ac7c262003-08-13 20:16:26 +00002386 }
2387
2388 Value *RV = getSetCCValue(Code, LHS, RHS);
2389 if (Instruction *I = dyn_cast<Instruction>(RV))
2390 return I;
2391 // Otherwise, it's a constant boolean value...
2392 return IC.ReplaceInstUsesWith(Log, RV);
2393 }
2394};
2395
Chris Lattnerba1cb382003-09-19 17:17:26 +00002396// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
2397// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
2398// guaranteed to be either a shift instruction or a binary operator.
2399Instruction *InstCombiner::OptAndOp(Instruction *Op,
2400 ConstantIntegral *OpRHS,
2401 ConstantIntegral *AndRHS,
2402 BinaryOperator &TheAnd) {
2403 Value *X = Op->getOperand(0);
Chris Lattnerfcf21a72004-01-12 19:47:05 +00002404 Constant *Together = 0;
2405 if (!isa<ShiftInst>(Op))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002406 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002407
Chris Lattnerba1cb382003-09-19 17:17:26 +00002408 switch (Op->getOpcode()) {
2409 case Instruction::Xor:
Chris Lattner86102b82005-01-01 16:22:27 +00002410 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00002411 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
2412 std::string OpName = Op->getName(); Op->setName("");
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002413 Instruction *And = BinaryOperator::createAnd(X, AndRHS, OpName);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002414 InsertNewInstBefore(And, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002415 return BinaryOperator::createXor(And, Together);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002416 }
2417 break;
2418 case Instruction::Or:
Chris Lattner86102b82005-01-01 16:22:27 +00002419 if (Together == AndRHS) // (X | C) & C --> C
2420 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002421
Chris Lattner86102b82005-01-01 16:22:27 +00002422 if (Op->hasOneUse() && Together != OpRHS) {
2423 // (X | C1) & C2 --> (X | (C1&C2)) & C2
2424 std::string Op0Name = Op->getName(); Op->setName("");
2425 Instruction *Or = BinaryOperator::createOr(X, Together, Op0Name);
2426 InsertNewInstBefore(Or, TheAnd);
2427 return BinaryOperator::createAnd(Or, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002428 }
2429 break;
2430 case Instruction::Add:
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002431 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00002432 // Adding a one to a single bit bit-field should be turned into an XOR
2433 // of the bit. First thing to check is to see if this AND is with a
2434 // single bit constant.
Chris Lattner35167c32004-06-09 07:59:58 +00002435 uint64_t AndRHSV = cast<ConstantInt>(AndRHS)->getRawValue();
Chris Lattnerba1cb382003-09-19 17:17:26 +00002436
2437 // Clear bits that are not part of the constant.
Chris Lattner77defba2006-02-07 07:00:41 +00002438 AndRHSV &= AndRHS->getType()->getIntegralTypeMask();
Chris Lattnerba1cb382003-09-19 17:17:26 +00002439
2440 // If there is only one bit set...
Chris Lattner35167c32004-06-09 07:59:58 +00002441 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00002442 // Ok, at this point, we know that we are masking the result of the
2443 // ADD down to exactly one bit. If the constant we are adding has
2444 // no bits set below this bit, then we can eliminate the ADD.
Chris Lattner35167c32004-06-09 07:59:58 +00002445 uint64_t AddRHS = cast<ConstantInt>(OpRHS)->getRawValue();
Misha Brukmanb1c93172005-04-21 23:48:37 +00002446
Chris Lattnerba1cb382003-09-19 17:17:26 +00002447 // Check to see if any bits below the one bit set in AndRHSV are set.
2448 if ((AddRHS & (AndRHSV-1)) == 0) {
2449 // If not, the only thing that can effect the output of the AND is
2450 // the bit specified by AndRHSV. If that bit is set, the effect of
2451 // the XOR is to toggle the bit. If it is clear, then the ADD has
2452 // no effect.
2453 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
2454 TheAnd.setOperand(0, X);
2455 return &TheAnd;
2456 } else {
2457 std::string Name = Op->getName(); Op->setName("");
2458 // Pull the XOR out of the AND.
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002459 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS, Name);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002460 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002461 return BinaryOperator::createXor(NewAnd, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002462 }
2463 }
2464 }
2465 }
2466 break;
Chris Lattner2da29172003-09-19 19:05:02 +00002467
2468 case Instruction::Shl: {
2469 // We know that the AND will not produce any of the bits shifted in, so if
2470 // the anded constant includes them, clear them now!
2471 //
2472 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner7e794272004-09-24 15:21:34 +00002473 Constant *ShlMask = ConstantExpr::getShl(AllOne, OpRHS);
2474 Constant *CI = ConstantExpr::getAnd(AndRHS, ShlMask);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002475
Chris Lattner7e794272004-09-24 15:21:34 +00002476 if (CI == ShlMask) { // Masking out bits that the shift already masks
2477 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
2478 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner2da29172003-09-19 19:05:02 +00002479 TheAnd.setOperand(1, CI);
2480 return &TheAnd;
2481 }
2482 break;
Misha Brukmanb1c93172005-04-21 23:48:37 +00002483 }
Chris Lattner2da29172003-09-19 19:05:02 +00002484 case Instruction::Shr:
2485 // We know that the AND will not produce any of the bits shifted in, so if
2486 // the anded constant includes them, clear them now! This only applies to
2487 // unsigned shifts, because a signed shr may bring in set bits!
2488 //
2489 if (AndRHS->getType()->isUnsigned()) {
2490 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner7e794272004-09-24 15:21:34 +00002491 Constant *ShrMask = ConstantExpr::getShr(AllOne, OpRHS);
2492 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
2493
2494 if (CI == ShrMask) { // Masking out bits that the shift already masks.
2495 return ReplaceInstUsesWith(TheAnd, Op);
2496 } else if (CI != AndRHS) {
2497 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
Chris Lattner2da29172003-09-19 19:05:02 +00002498 return &TheAnd;
2499 }
Chris Lattner7e794272004-09-24 15:21:34 +00002500 } else { // Signed shr.
2501 // See if this is shifting in some sign extension, then masking it out
2502 // with an and.
2503 if (Op->hasOneUse()) {
2504 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
2505 Constant *ShrMask = ConstantExpr::getUShr(AllOne, OpRHS);
2506 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
Chris Lattner5c3c21e2004-10-22 04:53:16 +00002507 if (CI == AndRHS) { // Masking out bits shifted in.
Chris Lattner7e794272004-09-24 15:21:34 +00002508 // Make the argument unsigned.
2509 Value *ShVal = Op->getOperand(0);
2510 ShVal = InsertCastBefore(ShVal,
2511 ShVal->getType()->getUnsignedVersion(),
2512 TheAnd);
2513 ShVal = InsertNewInstBefore(new ShiftInst(Instruction::Shr, ShVal,
2514 OpRHS, Op->getName()),
2515 TheAnd);
Chris Lattner70c20392004-10-27 05:57:15 +00002516 Value *AndRHS2 = ConstantExpr::getCast(AndRHS, ShVal->getType());
2517 ShVal = InsertNewInstBefore(BinaryOperator::createAnd(ShVal, AndRHS2,
2518 TheAnd.getName()),
2519 TheAnd);
Chris Lattner7e794272004-09-24 15:21:34 +00002520 return new CastInst(ShVal, Op->getType());
2521 }
2522 }
Chris Lattner2da29172003-09-19 19:05:02 +00002523 }
2524 break;
Chris Lattnerba1cb382003-09-19 17:17:26 +00002525 }
2526 return 0;
2527}
2528
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002529
Chris Lattner6862fbd2004-09-29 17:40:11 +00002530/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
2531/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
2532/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. IB is the location to
2533/// insert new instructions.
2534Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
2535 bool Inside, Instruction &IB) {
2536 assert(cast<ConstantBool>(ConstantExpr::getSetLE(Lo, Hi))->getValue() &&
2537 "Lo is not <= Hi in range emission code!");
2538 if (Inside) {
2539 if (Lo == Hi) // Trivially false.
2540 return new SetCondInst(Instruction::SetNE, V, V);
2541 if (cast<ConstantIntegral>(Lo)->isMinValue())
2542 return new SetCondInst(Instruction::SetLT, V, Hi);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002543
Chris Lattner6862fbd2004-09-29 17:40:11 +00002544 Constant *AddCST = ConstantExpr::getNeg(Lo);
2545 Instruction *Add = BinaryOperator::createAdd(V, AddCST,V->getName()+".off");
2546 InsertNewInstBefore(Add, IB);
2547 // Convert to unsigned for the comparison.
2548 const Type *UnsType = Add->getType()->getUnsignedVersion();
2549 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
2550 AddCST = ConstantExpr::getAdd(AddCST, Hi);
2551 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2552 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
2553 }
2554
2555 if (Lo == Hi) // Trivially true.
2556 return new SetCondInst(Instruction::SetEQ, V, V);
2557
2558 Hi = SubOne(cast<ConstantInt>(Hi));
2559 if (cast<ConstantIntegral>(Lo)->isMinValue()) // V < 0 || V >= Hi ->'V > Hi-1'
2560 return new SetCondInst(Instruction::SetGT, V, Hi);
2561
2562 // Emit X-Lo > Hi-Lo-1
2563 Constant *AddCST = ConstantExpr::getNeg(Lo);
2564 Instruction *Add = BinaryOperator::createAdd(V, AddCST, V->getName()+".off");
2565 InsertNewInstBefore(Add, IB);
2566 // Convert to unsigned for the comparison.
2567 const Type *UnsType = Add->getType()->getUnsignedVersion();
2568 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
2569 AddCST = ConstantExpr::getAdd(AddCST, Hi);
2570 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2571 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
2572}
2573
Chris Lattnerb4b25302005-09-18 07:22:02 +00002574// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
2575// any number of 0s on either side. The 1s are allowed to wrap from LSB to
2576// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
2577// not, since all 1s are not contiguous.
2578static bool isRunOfOnes(ConstantIntegral *Val, unsigned &MB, unsigned &ME) {
2579 uint64_t V = Val->getRawValue();
2580 if (!isShiftedMask_64(V)) return false;
2581
2582 // look for the first zero bit after the run of ones
2583 MB = 64-CountLeadingZeros_64((V - 1) ^ V);
2584 // look for the first non-zero bit
2585 ME = 64-CountLeadingZeros_64(V);
2586 return true;
2587}
2588
2589
2590
2591/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
2592/// where isSub determines whether the operator is a sub. If we can fold one of
2593/// the following xforms:
Chris Lattneraf517572005-09-18 04:24:45 +00002594///
2595/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
2596/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
2597/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
2598///
2599/// return (A +/- B).
2600///
2601Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
2602 ConstantIntegral *Mask, bool isSub,
2603 Instruction &I) {
2604 Instruction *LHSI = dyn_cast<Instruction>(LHS);
2605 if (!LHSI || LHSI->getNumOperands() != 2 ||
2606 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
2607
2608 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
2609
2610 switch (LHSI->getOpcode()) {
2611 default: return 0;
2612 case Instruction::And:
Chris Lattnerb4b25302005-09-18 07:22:02 +00002613 if (ConstantExpr::getAnd(N, Mask) == Mask) {
2614 // If the AndRHS is a power of two minus one (0+1+), this is simple.
2615 if ((Mask->getRawValue() & Mask->getRawValue()+1) == 0)
2616 break;
2617
2618 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
2619 // part, we don't need any explicit masks to take them out of A. If that
2620 // is all N is, ignore it.
2621 unsigned MB, ME;
2622 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Chris Lattnerc3ebf402006-02-07 07:27:52 +00002623 uint64_t Mask = RHS->getType()->getIntegralTypeMask();
2624 Mask >>= 64-MB+1;
2625 if (MaskedValueIsZero(RHS, Mask))
Chris Lattnerb4b25302005-09-18 07:22:02 +00002626 break;
2627 }
2628 }
Chris Lattneraf517572005-09-18 04:24:45 +00002629 return 0;
2630 case Instruction::Or:
2631 case Instruction::Xor:
Chris Lattnerb4b25302005-09-18 07:22:02 +00002632 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
2633 if ((Mask->getRawValue() & Mask->getRawValue()+1) == 0 &&
2634 ConstantExpr::getAnd(N, Mask)->isNullValue())
Chris Lattneraf517572005-09-18 04:24:45 +00002635 break;
2636 return 0;
2637 }
2638
2639 Instruction *New;
2640 if (isSub)
2641 New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
2642 else
2643 New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
2644 return InsertNewInstBefore(New, I);
2645}
2646
Chris Lattner113f4f42002-06-25 16:13:24 +00002647Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00002648 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00002649 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002650
Chris Lattner81a7a232004-10-16 18:11:37 +00002651 if (isa<UndefValue>(Op1)) // X & undef -> 0
2652 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2653
Chris Lattner86102b82005-01-01 16:22:27 +00002654 // and X, X = X
2655 if (Op0 == Op1)
Chris Lattnere6794492002-08-12 21:17:25 +00002656 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002657
Chris Lattner5b2edb12006-02-12 08:02:11 +00002658 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner5997cf92006-02-08 03:25:32 +00002659 // purpose is to compute bits we don't care about.
Chris Lattner0157e7f2006-02-11 09:31:47 +00002660 uint64_t KnownZero, KnownOne;
Chris Lattnerd70d9f52006-03-25 21:58:26 +00002661 if (!isa<PackedType>(I.getType()) &&
2662 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
Chris Lattner0157e7f2006-02-11 09:31:47 +00002663 KnownZero, KnownOne))
Chris Lattner5997cf92006-02-08 03:25:32 +00002664 return &I;
2665
Chris Lattner86102b82005-01-01 16:22:27 +00002666 if (ConstantIntegral *AndRHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00002667 uint64_t AndRHSMask = AndRHS->getZExtValue();
2668 uint64_t TypeMask = Op0->getType()->getIntegralTypeMask();
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00002669 uint64_t NotAndRHS = AndRHSMask^TypeMask;
Chris Lattner86102b82005-01-01 16:22:27 +00002670
Chris Lattnerba1cb382003-09-19 17:17:26 +00002671 // Optimize a variety of ((val OP C1) & C2) combinations...
2672 if (isa<BinaryOperator>(Op0) || isa<ShiftInst>(Op0)) {
2673 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner86102b82005-01-01 16:22:27 +00002674 Value *Op0LHS = Op0I->getOperand(0);
2675 Value *Op0RHS = Op0I->getOperand(1);
2676 switch (Op0I->getOpcode()) {
2677 case Instruction::Xor:
2678 case Instruction::Or:
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00002679 // If the mask is only needed on one incoming arm, push it up.
2680 if (Op0I->hasOneUse()) {
2681 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
2682 // Not masking anything out for the LHS, move to RHS.
2683 Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
2684 Op0RHS->getName()+".masked");
2685 InsertNewInstBefore(NewRHS, I);
2686 return BinaryOperator::create(
2687 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002688 }
Chris Lattnerc3ebf402006-02-07 07:27:52 +00002689 if (!isa<Constant>(Op0RHS) &&
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00002690 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
2691 // Not masking anything out for the RHS, move to LHS.
2692 Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
2693 Op0LHS->getName()+".masked");
2694 InsertNewInstBefore(NewLHS, I);
2695 return BinaryOperator::create(
2696 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
2697 }
2698 }
2699
Chris Lattner86102b82005-01-01 16:22:27 +00002700 break;
Chris Lattneraf517572005-09-18 04:24:45 +00002701 case Instruction::Add:
Chris Lattnerb4b25302005-09-18 07:22:02 +00002702 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
2703 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
2704 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
2705 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
2706 return BinaryOperator::createAnd(V, AndRHS);
2707 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
2708 return BinaryOperator::createAnd(V, AndRHS); // Add commutes
Chris Lattneraf517572005-09-18 04:24:45 +00002709 break;
2710
2711 case Instruction::Sub:
Chris Lattnerb4b25302005-09-18 07:22:02 +00002712 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
2713 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
2714 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
2715 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
2716 return BinaryOperator::createAnd(V, AndRHS);
Chris Lattneraf517572005-09-18 04:24:45 +00002717 break;
Chris Lattner86102b82005-01-01 16:22:27 +00002718 }
2719
Chris Lattner16464b32003-07-23 19:25:52 +00002720 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner86102b82005-01-01 16:22:27 +00002721 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerba1cb382003-09-19 17:17:26 +00002722 return Res;
Chris Lattner86102b82005-01-01 16:22:27 +00002723 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
2724 const Type *SrcTy = CI->getOperand(0)->getType();
2725
Chris Lattner2c14cf72005-08-07 07:03:10 +00002726 // If this is an integer truncation or change from signed-to-unsigned, and
2727 // if the source is an and/or with immediate, transform it. This
2728 // frequently occurs for bitfield accesses.
2729 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
2730 if (SrcTy->getPrimitiveSizeInBits() >=
2731 I.getType()->getPrimitiveSizeInBits() &&
2732 CastOp->getNumOperands() == 2)
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00002733 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1)))
Chris Lattner2c14cf72005-08-07 07:03:10 +00002734 if (CastOp->getOpcode() == Instruction::And) {
2735 // Change: and (cast (and X, C1) to T), C2
2736 // into : and (cast X to T), trunc(C1)&C2
2737 // This will folds the two ands together, which may allow other
2738 // simplifications.
2739 Instruction *NewCast =
2740 new CastInst(CastOp->getOperand(0), I.getType(),
2741 CastOp->getName()+".shrunk");
2742 NewCast = InsertNewInstBefore(NewCast, I);
2743
2744 Constant *C3=ConstantExpr::getCast(AndCI, I.getType());//trunc(C1)
2745 C3 = ConstantExpr::getAnd(C3, AndRHS); // trunc(C1)&C2
2746 return BinaryOperator::createAnd(NewCast, C3);
2747 } else if (CastOp->getOpcode() == Instruction::Or) {
2748 // Change: and (cast (or X, C1) to T), C2
2749 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
2750 Constant *C3=ConstantExpr::getCast(AndCI, I.getType());//trunc(C1)
2751 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
2752 return ReplaceInstUsesWith(I, AndRHS);
2753 }
2754 }
Chris Lattner33217db2003-07-23 19:36:21 +00002755 }
Chris Lattner183b3362004-04-09 19:05:30 +00002756
2757 // Try to fold constant and into select arguments.
2758 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00002759 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00002760 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002761 if (isa<PHINode>(Op0))
2762 if (Instruction *NV = FoldOpIntoPhi(I))
2763 return NV;
Chris Lattner49b47ae2003-07-23 17:57:01 +00002764 }
2765
Chris Lattnerbb74e222003-03-10 23:06:50 +00002766 Value *Op0NotVal = dyn_castNotVal(Op0);
2767 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002768
Chris Lattner023a4832004-06-18 06:07:51 +00002769 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
2770 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2771
Misha Brukman9c003d82004-07-30 12:50:08 +00002772 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattnerbb74e222003-03-10 23:06:50 +00002773 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002774 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
2775 I.getName()+".demorgan");
Chris Lattner49b47ae2003-07-23 17:57:01 +00002776 InsertNewInstBefore(Or, I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002777 return BinaryOperator::createNot(Or);
2778 }
Chris Lattner8b10ab32006-02-13 23:07:23 +00002779
2780 {
2781 Value *A = 0, *B = 0;
2782 ConstantInt *C1 = 0, *C2 = 0;
2783 if (match(Op0, m_Or(m_Value(A), m_Value(B))))
2784 if (A == Op1 || B == Op1) // (A | ?) & A --> A
2785 return ReplaceInstUsesWith(I, Op1);
2786 if (match(Op1, m_Or(m_Value(A), m_Value(B))))
2787 if (A == Op0 || B == Op0) // A & (A | ?) --> A
2788 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerdcd07922006-04-01 08:03:55 +00002789
2790 if (Op0->hasOneUse() &&
2791 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
2792 if (A == Op1) { // (A^B)&A -> A&(A^B)
2793 I.swapOperands(); // Simplify below
2794 std::swap(Op0, Op1);
2795 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
2796 cast<BinaryOperator>(Op0)->swapOperands();
2797 I.swapOperands(); // Simplify below
2798 std::swap(Op0, Op1);
2799 }
2800 }
2801 if (Op1->hasOneUse() &&
2802 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
2803 if (B == Op0) { // B&(A^B) -> B&(B^A)
2804 cast<BinaryOperator>(Op1)->swapOperands();
2805 std::swap(A, B);
2806 }
2807 if (A == Op0) { // A&(A^B) -> A & ~B
2808 Instruction *NotB = BinaryOperator::createNot(B, "tmp");
2809 InsertNewInstBefore(NotB, I);
2810 return BinaryOperator::createAnd(A, NotB);
2811 }
2812 }
Chris Lattner8b10ab32006-02-13 23:07:23 +00002813 }
2814
Chris Lattner3082c5a2003-02-18 19:28:33 +00002815
Chris Lattner623826c2004-09-28 21:48:02 +00002816 if (SetCondInst *RHS = dyn_cast<SetCondInst>(Op1)) {
2817 // (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
Chris Lattner3ac7c262003-08-13 20:16:26 +00002818 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
2819 return R;
2820
Chris Lattner623826c2004-09-28 21:48:02 +00002821 Value *LHSVal, *RHSVal;
2822 ConstantInt *LHSCst, *RHSCst;
2823 Instruction::BinaryOps LHSCC, RHSCC;
2824 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
2825 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
2826 if (LHSVal == RHSVal && // Found (X setcc C1) & (X setcc C2)
2827 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
Misha Brukmanb1c93172005-04-21 23:48:37 +00002828 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
Chris Lattner623826c2004-09-28 21:48:02 +00002829 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
2830 // Ensure that the larger constant is on the RHS.
2831 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
2832 SetCondInst *LHS = cast<SetCondInst>(Op0);
2833 if (cast<ConstantBool>(Cmp)->getValue()) {
2834 std::swap(LHS, RHS);
2835 std::swap(LHSCst, RHSCst);
2836 std::swap(LHSCC, RHSCC);
2837 }
2838
2839 // At this point, we know we have have two setcc instructions
2840 // comparing a value against two constants and and'ing the result
2841 // together. Because of the above check, we know that we only have
2842 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
2843 // FoldSetCCLogical check above), that the two constants are not
2844 // equal.
2845 assert(LHSCst != RHSCst && "Compares not folded above?");
2846
2847 switch (LHSCC) {
2848 default: assert(0 && "Unknown integer condition code!");
2849 case Instruction::SetEQ:
2850 switch (RHSCC) {
2851 default: assert(0 && "Unknown integer condition code!");
2852 case Instruction::SetEQ: // (X == 13 & X == 15) -> false
2853 case Instruction::SetGT: // (X == 13 & X > 15) -> false
Chris Lattner6ab03f62006-09-28 23:35:22 +00002854 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattner623826c2004-09-28 21:48:02 +00002855 case Instruction::SetNE: // (X == 13 & X != 15) -> X == 13
2856 case Instruction::SetLT: // (X == 13 & X < 15) -> X == 13
2857 return ReplaceInstUsesWith(I, LHS);
2858 }
2859 case Instruction::SetNE:
2860 switch (RHSCC) {
2861 default: assert(0 && "Unknown integer condition code!");
2862 case Instruction::SetLT:
2863 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X < 14) -> X < 13
2864 return new SetCondInst(Instruction::SetLT, LHSVal, LHSCst);
2865 break; // (X != 13 & X < 15) -> no change
2866 case Instruction::SetEQ: // (X != 13 & X == 15) -> X == 15
2867 case Instruction::SetGT: // (X != 13 & X > 15) -> X > 15
2868 return ReplaceInstUsesWith(I, RHS);
2869 case Instruction::SetNE:
2870 if (LHSCst == SubOne(RHSCst)) {// (X != 13 & X != 14) -> X-13 >u 1
2871 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
2872 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
2873 LHSVal->getName()+".off");
2874 InsertNewInstBefore(Add, I);
2875 const Type *UnsType = Add->getType()->getUnsignedVersion();
2876 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
2877 AddCST = ConstantExpr::getSub(RHSCst, LHSCst);
2878 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2879 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
2880 }
2881 break; // (X != 13 & X != 15) -> no change
2882 }
2883 break;
2884 case Instruction::SetLT:
2885 switch (RHSCC) {
2886 default: assert(0 && "Unknown integer condition code!");
2887 case Instruction::SetEQ: // (X < 13 & X == 15) -> false
2888 case Instruction::SetGT: // (X < 13 & X > 15) -> false
Chris Lattner6ab03f62006-09-28 23:35:22 +00002889 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattner623826c2004-09-28 21:48:02 +00002890 case Instruction::SetNE: // (X < 13 & X != 15) -> X < 13
2891 case Instruction::SetLT: // (X < 13 & X < 15) -> X < 13
2892 return ReplaceInstUsesWith(I, LHS);
2893 }
2894 case Instruction::SetGT:
2895 switch (RHSCC) {
2896 default: assert(0 && "Unknown integer condition code!");
2897 case Instruction::SetEQ: // (X > 13 & X == 15) -> X > 13
2898 return ReplaceInstUsesWith(I, LHS);
2899 case Instruction::SetGT: // (X > 13 & X > 15) -> X > 15
2900 return ReplaceInstUsesWith(I, RHS);
2901 case Instruction::SetNE:
2902 if (RHSCst == AddOne(LHSCst)) // (X > 13 & X != 14) -> X > 14
2903 return new SetCondInst(Instruction::SetGT, LHSVal, RHSCst);
2904 break; // (X > 13 & X != 15) -> no change
Chris Lattner6862fbd2004-09-29 17:40:11 +00002905 case Instruction::SetLT: // (X > 13 & X < 15) -> (X-14) <u 1
2906 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true, I);
Chris Lattner623826c2004-09-28 21:48:02 +00002907 }
2908 }
2909 }
2910 }
2911
Chris Lattner3af10532006-05-05 06:39:07 +00002912 // fold (and (cast A), (cast B)) -> (cast (and A, B))
2913 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattnere745c7d2006-05-05 20:51:30 +00002914 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner3af10532006-05-05 06:39:07 +00002915 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Chris Lattnere745c7d2006-05-05 20:51:30 +00002916 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegral() &&
Chris Lattner1d441ad2006-05-06 09:00:16 +00002917 // Only do this if the casts both really cause code to be generated.
2918 ValueRequiresCast(Op0C->getOperand(0), I.getType(), TD) &&
2919 ValueRequiresCast(Op1C->getOperand(0), I.getType(), TD)) {
Chris Lattner3af10532006-05-05 06:39:07 +00002920 Instruction *NewOp = BinaryOperator::createAnd(Op0C->getOperand(0),
2921 Op1C->getOperand(0),
2922 I.getName());
2923 InsertNewInstBefore(NewOp, I);
2924 return new CastInst(NewOp, I.getType());
2925 }
2926 }
2927
Chris Lattner113f4f42002-06-25 16:13:24 +00002928 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002929}
2930
Chris Lattnerc482a9e2006-06-15 19:07:26 +00002931/// CollectBSwapParts - Look to see if the specified value defines a single byte
2932/// in the result. If it does, and if the specified byte hasn't been filled in
2933/// yet, fill it in and return false.
2934static bool CollectBSwapParts(Value *V, std::vector<Value*> &ByteValues) {
2935 Instruction *I = dyn_cast<Instruction>(V);
2936 if (I == 0) return true;
2937
2938 // If this is an or instruction, it is an inner node of the bswap.
2939 if (I->getOpcode() == Instruction::Or)
2940 return CollectBSwapParts(I->getOperand(0), ByteValues) ||
2941 CollectBSwapParts(I->getOperand(1), ByteValues);
2942
2943 // If this is a shift by a constant int, and it is "24", then its operand
2944 // defines a byte. We only handle unsigned types here.
2945 if (isa<ShiftInst>(I) && isa<ConstantInt>(I->getOperand(1))) {
2946 // Not shifting the entire input by N-1 bytes?
2947 if (cast<ConstantInt>(I->getOperand(1))->getRawValue() !=
2948 8*(ByteValues.size()-1))
2949 return true;
2950
2951 unsigned DestNo;
2952 if (I->getOpcode() == Instruction::Shl) {
2953 // X << 24 defines the top byte with the lowest of the input bytes.
2954 DestNo = ByteValues.size()-1;
2955 } else {
2956 // X >>u 24 defines the low byte with the highest of the input bytes.
2957 DestNo = 0;
2958 }
2959
2960 // If the destination byte value is already defined, the values are or'd
2961 // together, which isn't a bswap (unless it's an or of the same bits).
2962 if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
2963 return true;
2964 ByteValues[DestNo] = I->getOperand(0);
2965 return false;
2966 }
2967
2968 // Otherwise, we can only handle and(shift X, imm), imm). Bail out of if we
2969 // don't have this.
2970 Value *Shift = 0, *ShiftLHS = 0;
2971 ConstantInt *AndAmt = 0, *ShiftAmt = 0;
2972 if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
2973 !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
2974 return true;
2975 Instruction *SI = cast<Instruction>(Shift);
2976
2977 // Make sure that the shift amount is by a multiple of 8 and isn't too big.
2978 if (ShiftAmt->getRawValue() & 7 ||
2979 ShiftAmt->getRawValue() > 8*ByteValues.size())
2980 return true;
2981
2982 // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
2983 unsigned DestByte;
2984 for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
2985 if (AndAmt->getRawValue() == uint64_t(0xFF) << 8*DestByte)
2986 break;
2987 // Unknown mask for bswap.
2988 if (DestByte == ByteValues.size()) return true;
2989
2990 unsigned ShiftBytes = ShiftAmt->getRawValue()/8;
2991 unsigned SrcByte;
2992 if (SI->getOpcode() == Instruction::Shl)
2993 SrcByte = DestByte - ShiftBytes;
2994 else
2995 SrcByte = DestByte + ShiftBytes;
2996
2997 // If the SrcByte isn't a bswapped value from the DestByte, reject it.
2998 if (SrcByte != ByteValues.size()-DestByte-1)
2999 return true;
3000
3001 // If the destination byte value is already defined, the values are or'd
3002 // together, which isn't a bswap (unless it's an or of the same bits).
3003 if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
3004 return true;
3005 ByteValues[DestByte] = SI->getOperand(0);
3006 return false;
3007}
3008
3009/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
3010/// If so, insert the new bswap intrinsic and return it.
3011Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
3012 // We can only handle bswap of unsigned integers, and cannot bswap one byte.
3013 if (!I.getType()->isUnsigned() || I.getType() == Type::UByteTy)
3014 return 0;
3015
3016 /// ByteValues - For each byte of the result, we keep track of which value
3017 /// defines each byte.
3018 std::vector<Value*> ByteValues;
3019 ByteValues.resize(I.getType()->getPrimitiveSize());
3020
3021 // Try to find all the pieces corresponding to the bswap.
3022 if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
3023 CollectBSwapParts(I.getOperand(1), ByteValues))
3024 return 0;
3025
3026 // Check to see if all of the bytes come from the same value.
3027 Value *V = ByteValues[0];
3028 if (V == 0) return 0; // Didn't find a byte? Must be zero.
3029
3030 // Check to make sure that all of the bytes come from the same value.
3031 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
3032 if (ByteValues[i] != V)
3033 return 0;
3034
3035 // If they do then *success* we can turn this into a bswap. Figure out what
3036 // bswap to make it into.
3037 Module *M = I.getParent()->getParent()->getParent();
Chris Lattner091b6ea2006-07-11 18:31:26 +00003038 const char *FnName = 0;
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003039 if (I.getType() == Type::UShortTy)
3040 FnName = "llvm.bswap.i16";
3041 else if (I.getType() == Type::UIntTy)
3042 FnName = "llvm.bswap.i32";
3043 else if (I.getType() == Type::ULongTy)
3044 FnName = "llvm.bswap.i64";
3045 else
3046 assert(0 && "Unknown integer type!");
3047 Function *F = M->getOrInsertFunction(FnName, I.getType(), I.getType(), NULL);
3048
3049 return new CallInst(F, V);
3050}
3051
3052
Chris Lattner113f4f42002-06-25 16:13:24 +00003053Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003054 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00003055 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003056
Chris Lattner81a7a232004-10-16 18:11:37 +00003057 if (isa<UndefValue>(Op1))
3058 return ReplaceInstUsesWith(I, // X | undef -> -1
3059 ConstantIntegral::getAllOnesValue(I.getType()));
3060
Chris Lattner5b2edb12006-02-12 08:02:11 +00003061 // or X, X = X
3062 if (Op0 == Op1)
Chris Lattnere6794492002-08-12 21:17:25 +00003063 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003064
Chris Lattner5b2edb12006-02-12 08:02:11 +00003065 // See if we can simplify any instructions used by the instruction whose sole
3066 // purpose is to compute bits we don't care about.
3067 uint64_t KnownZero, KnownOne;
Chris Lattnerd70d9f52006-03-25 21:58:26 +00003068 if (!isa<PackedType>(I.getType()) &&
3069 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
Chris Lattner5b2edb12006-02-12 08:02:11 +00003070 KnownZero, KnownOne))
3071 return &I;
3072
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003073 // or X, -1 == -1
Chris Lattner8f0d1562003-07-23 18:29:44 +00003074 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner330628a2006-01-06 17:59:59 +00003075 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00003076 // (X & C1) | C2 --> (X | C2) & (C1|C2)
3077 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Chris Lattnerb62f5082005-05-09 04:58:36 +00003078 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0->getName());
3079 Op0->setName("");
Chris Lattnerd4252a72004-07-30 07:50:03 +00003080 InsertNewInstBefore(Or, I);
3081 return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, C1));
3082 }
Chris Lattner8f0d1562003-07-23 18:29:44 +00003083
Chris Lattnerd4252a72004-07-30 07:50:03 +00003084 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
3085 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
3086 std::string Op0Name = Op0->getName(); Op0->setName("");
3087 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
3088 InsertNewInstBefore(Or, I);
3089 return BinaryOperator::createXor(Or,
3090 ConstantExpr::getAnd(C1, ConstantExpr::getNot(RHS)));
Chris Lattner8f0d1562003-07-23 18:29:44 +00003091 }
Chris Lattner183b3362004-04-09 19:05:30 +00003092
3093 // Try to fold constant and into select arguments.
3094 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00003095 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00003096 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00003097 if (isa<PHINode>(Op0))
3098 if (Instruction *NV = FoldOpIntoPhi(I))
3099 return NV;
Chris Lattner8f0d1562003-07-23 18:29:44 +00003100 }
3101
Chris Lattner330628a2006-01-06 17:59:59 +00003102 Value *A = 0, *B = 0;
3103 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattner4294cec2005-05-07 23:49:08 +00003104
3105 if (match(Op0, m_And(m_Value(A), m_Value(B))))
3106 if (A == Op1 || B == Op1) // (A & ?) | A --> A
3107 return ReplaceInstUsesWith(I, Op1);
3108 if (match(Op1, m_And(m_Value(A), m_Value(B))))
3109 if (A == Op0 || B == Op0) // A | (A & ?) --> A
3110 return ReplaceInstUsesWith(I, Op0);
3111
Chris Lattnerb7845d62006-07-10 20:25:24 +00003112 // (A | B) | C and A | (B | C) -> bswap if possible.
3113 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003114 if (match(Op0, m_Or(m_Value(), m_Value())) ||
Chris Lattnerb7845d62006-07-10 20:25:24 +00003115 match(Op1, m_Or(m_Value(), m_Value())) ||
3116 (match(Op0, m_Shift(m_Value(), m_Value())) &&
3117 match(Op1, m_Shift(m_Value(), m_Value())))) {
Chris Lattnerc482a9e2006-06-15 19:07:26 +00003118 if (Instruction *BSwap = MatchBSwap(I))
3119 return BSwap;
3120 }
3121
Chris Lattnerb62f5082005-05-09 04:58:36 +00003122 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
3123 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003124 MaskedValueIsZero(Op1, C1->getZExtValue())) {
Chris Lattnerb62f5082005-05-09 04:58:36 +00003125 Instruction *NOr = BinaryOperator::createOr(A, Op1, Op0->getName());
3126 Op0->setName("");
3127 return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
3128 }
3129
3130 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
3131 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003132 MaskedValueIsZero(Op0, C1->getZExtValue())) {
Chris Lattnerb62f5082005-05-09 04:58:36 +00003133 Instruction *NOr = BinaryOperator::createOr(A, Op0, Op1->getName());
3134 Op0->setName("");
3135 return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
3136 }
3137
Chris Lattner15212982005-09-18 03:42:07 +00003138 // (A & C1)|(B & C2)
Chris Lattnerd4252a72004-07-30 07:50:03 +00003139 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattner15212982005-09-18 03:42:07 +00003140 match(Op1, m_And(m_Value(B), m_ConstantInt(C2)))) {
3141
3142 if (A == B) // (A & C1)|(A & C2) == A & (C1|C2)
3143 return BinaryOperator::createAnd(A, ConstantExpr::getOr(C1, C2));
3144
3145
Chris Lattner01f56c62005-09-18 06:02:59 +00003146 // If we have: ((V + N) & C1) | (V & C2)
3147 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
3148 // replace with V+N.
3149 if (C1 == ConstantExpr::getNot(C2)) {
Chris Lattner330628a2006-01-06 17:59:59 +00003150 Value *V1 = 0, *V2 = 0;
Chris Lattner01f56c62005-09-18 06:02:59 +00003151 if ((C2->getRawValue() & (C2->getRawValue()+1)) == 0 && // C2 == 0+1+
3152 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
3153 // Add commutes, try both ways.
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003154 if (V1 == B && MaskedValueIsZero(V2, C2->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003155 return ReplaceInstUsesWith(I, A);
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003156 if (V2 == B && MaskedValueIsZero(V1, C2->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003157 return ReplaceInstUsesWith(I, A);
3158 }
3159 // Or commutes, try both ways.
3160 if ((C1->getRawValue() & (C1->getRawValue()+1)) == 0 &&
3161 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
3162 // Add commutes, try both ways.
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003163 if (V1 == A && MaskedValueIsZero(V2, C1->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003164 return ReplaceInstUsesWith(I, B);
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003165 if (V2 == A && MaskedValueIsZero(V1, C1->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003166 return ReplaceInstUsesWith(I, B);
Chris Lattner15212982005-09-18 03:42:07 +00003167 }
3168 }
3169 }
Chris Lattner812aab72003-08-12 19:11:07 +00003170
Chris Lattnerd4252a72004-07-30 07:50:03 +00003171 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
3172 if (A == Op1) // ~A | A == -1
Misha Brukmanb1c93172005-04-21 23:48:37 +00003173 return ReplaceInstUsesWith(I,
Chris Lattnerd4252a72004-07-30 07:50:03 +00003174 ConstantIntegral::getAllOnesValue(I.getType()));
3175 } else {
3176 A = 0;
3177 }
Chris Lattner4294cec2005-05-07 23:49:08 +00003178 // Note, A is still live here!
Chris Lattnerd4252a72004-07-30 07:50:03 +00003179 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
3180 if (Op0 == B)
Misha Brukmanb1c93172005-04-21 23:48:37 +00003181 return ReplaceInstUsesWith(I,
Chris Lattnerd4252a72004-07-30 07:50:03 +00003182 ConstantIntegral::getAllOnesValue(I.getType()));
Chris Lattner3e327a42003-03-10 23:13:59 +00003183
Misha Brukman9c003d82004-07-30 12:50:08 +00003184 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattnerd4252a72004-07-30 07:50:03 +00003185 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3186 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
3187 I.getName()+".demorgan"), I);
3188 return BinaryOperator::createNot(And);
3189 }
Chris Lattner3e327a42003-03-10 23:13:59 +00003190 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00003191
Chris Lattner3ac7c262003-08-13 20:16:26 +00003192 // (setcc1 A, B) | (setcc2 A, B) --> (setcc3 A, B)
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003193 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1))) {
Chris Lattner3ac7c262003-08-13 20:16:26 +00003194 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
3195 return R;
3196
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003197 Value *LHSVal, *RHSVal;
3198 ConstantInt *LHSCst, *RHSCst;
3199 Instruction::BinaryOps LHSCC, RHSCC;
3200 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3201 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3202 if (LHSVal == RHSVal && // Found (X setcc C1) | (X setcc C2)
3203 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
Misha Brukmanb1c93172005-04-21 23:48:37 +00003204 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003205 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
3206 // Ensure that the larger constant is on the RHS.
3207 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
3208 SetCondInst *LHS = cast<SetCondInst>(Op0);
3209 if (cast<ConstantBool>(Cmp)->getValue()) {
3210 std::swap(LHS, RHS);
3211 std::swap(LHSCst, RHSCst);
3212 std::swap(LHSCC, RHSCC);
3213 }
3214
3215 // At this point, we know we have have two setcc instructions
3216 // comparing a value against two constants and or'ing the result
3217 // together. Because of the above check, we know that we only have
3218 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
3219 // FoldSetCCLogical check above), that the two constants are not
3220 // equal.
3221 assert(LHSCst != RHSCst && "Compares not folded above?");
3222
3223 switch (LHSCC) {
3224 default: assert(0 && "Unknown integer condition code!");
3225 case Instruction::SetEQ:
3226 switch (RHSCC) {
3227 default: assert(0 && "Unknown integer condition code!");
3228 case Instruction::SetEQ:
3229 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
3230 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3231 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3232 LHSVal->getName()+".off");
3233 InsertNewInstBefore(Add, I);
3234 const Type *UnsType = Add->getType()->getUnsignedVersion();
3235 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
3236 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
3237 AddCST = ConstantExpr::getCast(AddCST, UnsType);
3238 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
3239 }
3240 break; // (X == 13 | X == 15) -> no change
3241
Chris Lattner5c219462005-04-19 06:04:18 +00003242 case Instruction::SetGT: // (X == 13 | X > 14) -> no change
3243 break;
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003244 case Instruction::SetNE: // (X == 13 | X != 15) -> X != 15
3245 case Instruction::SetLT: // (X == 13 | X < 15) -> X < 15
3246 return ReplaceInstUsesWith(I, RHS);
3247 }
3248 break;
3249 case Instruction::SetNE:
3250 switch (RHSCC) {
3251 default: assert(0 && "Unknown integer condition code!");
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003252 case Instruction::SetEQ: // (X != 13 | X == 15) -> X != 13
3253 case Instruction::SetGT: // (X != 13 | X > 15) -> X != 13
3254 return ReplaceInstUsesWith(I, LHS);
3255 case Instruction::SetNE: // (X != 13 | X != 15) -> true
Chris Lattner2ceb6ee2005-06-17 03:59:17 +00003256 case Instruction::SetLT: // (X != 13 | X < 15) -> true
Chris Lattner6ab03f62006-09-28 23:35:22 +00003257 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003258 }
3259 break;
3260 case Instruction::SetLT:
3261 switch (RHSCC) {
3262 default: assert(0 && "Unknown integer condition code!");
3263 case Instruction::SetEQ: // (X < 13 | X == 14) -> no change
3264 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00003265 case Instruction::SetGT: // (X < 13 | X > 15) -> (X-13) > 2
3266 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false, I);
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003267 case Instruction::SetNE: // (X < 13 | X != 15) -> X != 15
3268 case Instruction::SetLT: // (X < 13 | X < 15) -> X < 15
3269 return ReplaceInstUsesWith(I, RHS);
3270 }
3271 break;
3272 case Instruction::SetGT:
3273 switch (RHSCC) {
3274 default: assert(0 && "Unknown integer condition code!");
3275 case Instruction::SetEQ: // (X > 13 | X == 15) -> X > 13
3276 case Instruction::SetGT: // (X > 13 | X > 15) -> X > 13
3277 return ReplaceInstUsesWith(I, LHS);
3278 case Instruction::SetNE: // (X > 13 | X != 15) -> true
3279 case Instruction::SetLT: // (X > 13 | X < 15) -> true
Chris Lattner6ab03f62006-09-28 23:35:22 +00003280 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003281 }
3282 }
3283 }
3284 }
Chris Lattner3af10532006-05-05 06:39:07 +00003285
3286 // fold (or (cast A), (cast B)) -> (cast (or A, B))
3287 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattnere745c7d2006-05-05 20:51:30 +00003288 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner3af10532006-05-05 06:39:07 +00003289 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Chris Lattnere745c7d2006-05-05 20:51:30 +00003290 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegral() &&
Chris Lattner1d441ad2006-05-06 09:00:16 +00003291 // Only do this if the casts both really cause code to be generated.
3292 ValueRequiresCast(Op0C->getOperand(0), I.getType(), TD) &&
3293 ValueRequiresCast(Op1C->getOperand(0), I.getType(), TD)) {
Chris Lattner3af10532006-05-05 06:39:07 +00003294 Instruction *NewOp = BinaryOperator::createOr(Op0C->getOperand(0),
3295 Op1C->getOperand(0),
3296 I.getName());
3297 InsertNewInstBefore(NewOp, I);
3298 return new CastInst(NewOp, I.getType());
3299 }
3300 }
3301
Chris Lattner15212982005-09-18 03:42:07 +00003302
Chris Lattner113f4f42002-06-25 16:13:24 +00003303 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003304}
3305
Chris Lattnerc2076352004-02-16 01:20:27 +00003306// XorSelf - Implements: X ^ X --> 0
3307struct XorSelf {
3308 Value *RHS;
3309 XorSelf(Value *rhs) : RHS(rhs) {}
3310 bool shouldApply(Value *LHS) const { return LHS == RHS; }
3311 Instruction *apply(BinaryOperator &Xor) const {
3312 return &Xor;
3313 }
3314};
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003315
3316
Chris Lattner113f4f42002-06-25 16:13:24 +00003317Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003318 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00003319 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003320
Chris Lattner81a7a232004-10-16 18:11:37 +00003321 if (isa<UndefValue>(Op1))
3322 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
3323
Chris Lattnerc2076352004-02-16 01:20:27 +00003324 // xor X, X = 0, even if X is nested in a sequence of Xor's.
3325 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
3326 assert(Result == &I && "AssociativeOpt didn't work?");
Chris Lattnere6794492002-08-12 21:17:25 +00003327 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc2076352004-02-16 01:20:27 +00003328 }
Chris Lattner5b2edb12006-02-12 08:02:11 +00003329
3330 // See if we can simplify any instructions used by the instruction whose sole
3331 // purpose is to compute bits we don't care about.
3332 uint64_t KnownZero, KnownOne;
Chris Lattnerd70d9f52006-03-25 21:58:26 +00003333 if (!isa<PackedType>(I.getType()) &&
3334 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
Chris Lattner5b2edb12006-02-12 08:02:11 +00003335 KnownZero, KnownOne))
3336 return &I;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003337
Chris Lattner97638592003-07-23 21:37:07 +00003338 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner97638592003-07-23 21:37:07 +00003339 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerb8d6e402002-08-20 18:24:26 +00003340 // xor (setcc A, B), true = not (setcc A, B) = setncc A, B
Chris Lattner97638592003-07-23 21:37:07 +00003341 if (SetCondInst *SCI = dyn_cast<SetCondInst>(Op0I))
Chris Lattner6ab03f62006-09-28 23:35:22 +00003342 if (RHS == ConstantBool::getTrue() && SCI->hasOneUse())
Chris Lattnerb8d6e402002-08-20 18:24:26 +00003343 return new SetCondInst(SCI->getInverseCondition(),
3344 SCI->getOperand(0), SCI->getOperand(1));
Chris Lattnere5806662003-11-04 23:50:51 +00003345
Chris Lattner8f2f5982003-11-05 01:06:05 +00003346 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003347 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
3348 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003349 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
3350 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003351 ConstantInt::get(I.getType(), 1));
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003352 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003353 }
Chris Lattner023a4832004-06-18 06:07:51 +00003354
3355 // ~(~X & Y) --> (X | ~Y)
3356 if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
3357 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
3358 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
3359 Instruction *NotY =
Misha Brukmanb1c93172005-04-21 23:48:37 +00003360 BinaryOperator::createNot(Op0I->getOperand(1),
Chris Lattner023a4832004-06-18 06:07:51 +00003361 Op0I->getOperand(1)->getName()+".not");
3362 InsertNewInstBefore(NotY, I);
3363 return BinaryOperator::createOr(Op0NotVal, NotY);
3364 }
3365 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003366
Chris Lattner97638592003-07-23 21:37:07 +00003367 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner5b2edb12006-02-12 08:02:11 +00003368 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner0f68fa62003-11-04 23:37:10 +00003369 // ~(X-c) --> (-c-1)-X
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003370 if (RHS->isAllOnesValue()) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003371 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
3372 return BinaryOperator::createSub(
3373 ConstantExpr::getSub(NegOp0CI,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003374 ConstantInt::get(I.getType(), 1)),
Chris Lattner0f68fa62003-11-04 23:37:10 +00003375 Op0I->getOperand(0));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003376 }
Chris Lattnerf78df7c2006-02-26 19:57:54 +00003377 } else if (Op0I->getOpcode() == Instruction::Or) {
3378 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
3379 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getZExtValue())) {
3380 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
3381 // Anything in both C1 and C2 is known to be zero, remove it from
3382 // NewRHS.
3383 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
3384 NewRHS = ConstantExpr::getAnd(NewRHS,
3385 ConstantExpr::getNot(CommonBits));
3386 WorkList.push_back(Op0I);
3387 I.setOperand(0, Op0I->getOperand(0));
3388 I.setOperand(1, NewRHS);
3389 return &I;
3390 }
Chris Lattner97638592003-07-23 21:37:07 +00003391 }
Chris Lattnerb8d6e402002-08-20 18:24:26 +00003392 }
Chris Lattner183b3362004-04-09 19:05:30 +00003393
3394 // Try to fold constant and into select arguments.
3395 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00003396 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00003397 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00003398 if (isa<PHINode>(Op0))
3399 if (Instruction *NV = FoldOpIntoPhi(I))
3400 return NV;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003401 }
3402
Chris Lattnerbb74e222003-03-10 23:06:50 +00003403 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00003404 if (X == Op1)
3405 return ReplaceInstUsesWith(I,
3406 ConstantIntegral::getAllOnesValue(I.getType()));
3407
Chris Lattnerbb74e222003-03-10 23:06:50 +00003408 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00003409 if (X == Op0)
3410 return ReplaceInstUsesWith(I,
3411 ConstantIntegral::getAllOnesValue(I.getType()));
3412
Chris Lattnerdcd07922006-04-01 08:03:55 +00003413 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1))
Chris Lattnerb36d9082004-02-16 03:54:20 +00003414 if (Op1I->getOpcode() == Instruction::Or) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003415 if (Op1I->getOperand(0) == Op0) { // B^(B|A) == (A|B)^B
Chris Lattnerdcd07922006-04-01 08:03:55 +00003416 Op1I->swapOperands();
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003417 I.swapOperands();
3418 std::swap(Op0, Op1);
3419 } else if (Op1I->getOperand(1) == Op0) { // B^(A|B) == (A|B)^B
Chris Lattnerdcd07922006-04-01 08:03:55 +00003420 I.swapOperands(); // Simplified below.
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003421 std::swap(Op0, Op1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003422 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00003423 } else if (Op1I->getOpcode() == Instruction::Xor) {
3424 if (Op0 == Op1I->getOperand(0)) // A^(A^B) == B
3425 return ReplaceInstUsesWith(I, Op1I->getOperand(1));
3426 else if (Op0 == Op1I->getOperand(1)) // A^(B^A) == B
3427 return ReplaceInstUsesWith(I, Op1I->getOperand(0));
Chris Lattnerdcd07922006-04-01 08:03:55 +00003428 } else if (Op1I->getOpcode() == Instruction::And && Op1I->hasOneUse()) {
3429 if (Op1I->getOperand(0) == Op0) // A^(A&B) -> A^(B&A)
3430 Op1I->swapOperands();
3431 if (Op0 == Op1I->getOperand(1)) { // A^(B&A) -> (B&A)^A
3432 I.swapOperands(); // Simplified below.
3433 std::swap(Op0, Op1);
3434 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00003435 }
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003436
Chris Lattnerdcd07922006-04-01 08:03:55 +00003437 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00003438 if (Op0I->getOpcode() == Instruction::Or && Op0I->hasOneUse()) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003439 if (Op0I->getOperand(0) == Op1) // (B|A)^B == (A|B)^B
Chris Lattnerdcd07922006-04-01 08:03:55 +00003440 Op0I->swapOperands();
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003441 if (Op0I->getOperand(1) == Op1) { // (A|B)^B == A & ~B
Chris Lattnerdcd07922006-04-01 08:03:55 +00003442 Instruction *NotB = BinaryOperator::createNot(Op1, "tmp");
3443 InsertNewInstBefore(NotB, I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003444 return BinaryOperator::createAnd(Op0I->getOperand(0), NotB);
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003445 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00003446 } else if (Op0I->getOpcode() == Instruction::Xor) {
3447 if (Op1 == Op0I->getOperand(0)) // (A^B)^A == B
3448 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
3449 else if (Op1 == Op0I->getOperand(1)) // (B^A)^A == B
3450 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattnerdcd07922006-04-01 08:03:55 +00003451 } else if (Op0I->getOpcode() == Instruction::And && Op0I->hasOneUse()) {
3452 if (Op0I->getOperand(0) == Op1) // (A&B)^A -> (B&A)^A
3453 Op0I->swapOperands();
Chris Lattner6cf49142006-04-01 22:05:01 +00003454 if (Op0I->getOperand(1) == Op1 && // (B&A)^A == ~B & A
3455 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattnerdcd07922006-04-01 08:03:55 +00003456 Instruction *N = BinaryOperator::createNot(Op0I->getOperand(0), "tmp");
3457 InsertNewInstBefore(N, I);
3458 return BinaryOperator::createAnd(N, Op1);
3459 }
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003460 }
3461
Chris Lattner3ac7c262003-08-13 20:16:26 +00003462 // (setcc1 A, B) ^ (setcc2 A, B) --> (setcc3 A, B)
3463 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
3464 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
3465 return R;
3466
Chris Lattner3af10532006-05-05 06:39:07 +00003467 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
3468 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattnere745c7d2006-05-05 20:51:30 +00003469 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner3af10532006-05-05 06:39:07 +00003470 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Chris Lattnere745c7d2006-05-05 20:51:30 +00003471 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegral() &&
Chris Lattner1d441ad2006-05-06 09:00:16 +00003472 // Only do this if the casts both really cause code to be generated.
3473 ValueRequiresCast(Op0C->getOperand(0), I.getType(), TD) &&
3474 ValueRequiresCast(Op1C->getOperand(0), I.getType(), TD)) {
Chris Lattner3af10532006-05-05 06:39:07 +00003475 Instruction *NewOp = BinaryOperator::createXor(Op0C->getOperand(0),
3476 Op1C->getOperand(0),
3477 I.getName());
3478 InsertNewInstBefore(NewOp, I);
3479 return new CastInst(NewOp, I.getType());
3480 }
3481 }
3482
Chris Lattner113f4f42002-06-25 16:13:24 +00003483 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003484}
3485
Chris Lattner6862fbd2004-09-29 17:40:11 +00003486/// MulWithOverflow - Compute Result = In1*In2, returning true if the result
3487/// overflowed for this type.
3488static bool MulWithOverflow(ConstantInt *&Result, ConstantInt *In1,
3489 ConstantInt *In2) {
3490 Result = cast<ConstantInt>(ConstantExpr::getMul(In1, In2));
3491 return !In2->isNullValue() && ConstantExpr::getDiv(Result, In2) != In1;
3492}
3493
3494static bool isPositive(ConstantInt *C) {
3495 return cast<ConstantSInt>(C)->getValue() >= 0;
3496}
3497
3498/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
3499/// overflowed for this type.
3500static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
3501 ConstantInt *In2) {
3502 Result = cast<ConstantInt>(ConstantExpr::getAdd(In1, In2));
3503
3504 if (In1->getType()->isUnsigned())
3505 return cast<ConstantUInt>(Result)->getValue() <
3506 cast<ConstantUInt>(In1)->getValue();
3507 if (isPositive(In1) != isPositive(In2))
3508 return false;
3509 if (isPositive(In1))
3510 return cast<ConstantSInt>(Result)->getValue() <
3511 cast<ConstantSInt>(In1)->getValue();
3512 return cast<ConstantSInt>(Result)->getValue() >
3513 cast<ConstantSInt>(In1)->getValue();
3514}
3515
Chris Lattner0798af32005-01-13 20:14:25 +00003516/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
3517/// code necessary to compute the offset from the base pointer (without adding
3518/// in the base pointer). Return the result as a signed integer of intptr size.
3519static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
3520 TargetData &TD = IC.getTargetData();
3521 gep_type_iterator GTI = gep_type_begin(GEP);
3522 const Type *UIntPtrTy = TD.getIntPtrType();
3523 const Type *SIntPtrTy = UIntPtrTy->getSignedVersion();
3524 Value *Result = Constant::getNullValue(SIntPtrTy);
3525
3526 // Build a mask for high order bits.
Chris Lattner77defba2006-02-07 07:00:41 +00003527 uint64_t PtrSizeMask = ~0ULL >> (64-TD.getPointerSize()*8);
Chris Lattner0798af32005-01-13 20:14:25 +00003528
Chris Lattner0798af32005-01-13 20:14:25 +00003529 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
3530 Value *Op = GEP->getOperand(i);
Chris Lattnerd35d2102005-01-13 23:26:48 +00003531 uint64_t Size = TD.getTypeSize(GTI.getIndexedType()) & PtrSizeMask;
Chris Lattner0798af32005-01-13 20:14:25 +00003532 Constant *Scale = ConstantExpr::getCast(ConstantUInt::get(UIntPtrTy, Size),
3533 SIntPtrTy);
3534 if (Constant *OpC = dyn_cast<Constant>(Op)) {
3535 if (!OpC->isNullValue()) {
Chris Lattner4cb9fa32005-01-13 20:40:58 +00003536 OpC = ConstantExpr::getCast(OpC, SIntPtrTy);
Chris Lattner0798af32005-01-13 20:14:25 +00003537 Scale = ConstantExpr::getMul(OpC, Scale);
3538 if (Constant *RC = dyn_cast<Constant>(Result))
3539 Result = ConstantExpr::getAdd(RC, Scale);
3540 else {
3541 // Emit an add instruction.
3542 Result = IC.InsertNewInstBefore(
3543 BinaryOperator::createAdd(Result, Scale,
3544 GEP->getName()+".offs"), I);
3545 }
3546 }
3547 } else {
Chris Lattner7aa41cf2005-01-14 17:17:59 +00003548 // Convert to correct type.
3549 Op = IC.InsertNewInstBefore(new CastInst(Op, SIntPtrTy,
3550 Op->getName()+".c"), I);
3551 if (Size != 1)
Chris Lattner4cb9fa32005-01-13 20:40:58 +00003552 // We'll let instcombine(mul) convert this to a shl if possible.
3553 Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
3554 GEP->getName()+".idx"), I);
Chris Lattner0798af32005-01-13 20:14:25 +00003555
3556 // Emit an add instruction.
Chris Lattner4cb9fa32005-01-13 20:40:58 +00003557 Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
Chris Lattner0798af32005-01-13 20:14:25 +00003558 GEP->getName()+".offs"), I);
3559 }
3560 }
3561 return Result;
3562}
3563
3564/// FoldGEPSetCC - Fold comparisons between a GEP instruction and something
3565/// else. At this point we know that the GEP is on the LHS of the comparison.
3566Instruction *InstCombiner::FoldGEPSetCC(User *GEPLHS, Value *RHS,
3567 Instruction::BinaryOps Cond,
3568 Instruction &I) {
3569 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattner81e84172005-01-13 22:25:21 +00003570
3571 if (CastInst *CI = dyn_cast<CastInst>(RHS))
3572 if (isa<PointerType>(CI->getOperand(0)->getType()))
3573 RHS = CI->getOperand(0);
3574
Chris Lattner0798af32005-01-13 20:14:25 +00003575 Value *PtrBase = GEPLHS->getOperand(0);
3576 if (PtrBase == RHS) {
3577 // As an optimization, we don't actually have to compute the actual value of
3578 // OFFSET if this is a seteq or setne comparison, just return whether each
3579 // index is zero or not.
Chris Lattner81e84172005-01-13 22:25:21 +00003580 if (Cond == Instruction::SetEQ || Cond == Instruction::SetNE) {
3581 Instruction *InVal = 0;
Chris Lattnercd517ff2005-01-28 19:32:01 +00003582 gep_type_iterator GTI = gep_type_begin(GEPLHS);
3583 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i, ++GTI) {
Chris Lattner81e84172005-01-13 22:25:21 +00003584 bool EmitIt = true;
3585 if (Constant *C = dyn_cast<Constant>(GEPLHS->getOperand(i))) {
3586 if (isa<UndefValue>(C)) // undef index -> undef.
3587 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
3588 if (C->isNullValue())
3589 EmitIt = false;
Chris Lattnercd517ff2005-01-28 19:32:01 +00003590 else if (TD->getTypeSize(GTI.getIndexedType()) == 0) {
3591 EmitIt = false; // This is indexing into a zero sized array?
Misha Brukmanb1c93172005-04-21 23:48:37 +00003592 } else if (isa<ConstantInt>(C))
Chris Lattner81e84172005-01-13 22:25:21 +00003593 return ReplaceInstUsesWith(I, // No comparison is needed here.
3594 ConstantBool::get(Cond == Instruction::SetNE));
3595 }
3596
3597 if (EmitIt) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00003598 Instruction *Comp =
Chris Lattner81e84172005-01-13 22:25:21 +00003599 new SetCondInst(Cond, GEPLHS->getOperand(i),
3600 Constant::getNullValue(GEPLHS->getOperand(i)->getType()));
3601 if (InVal == 0)
3602 InVal = Comp;
3603 else {
3604 InVal = InsertNewInstBefore(InVal, I);
3605 InsertNewInstBefore(Comp, I);
3606 if (Cond == Instruction::SetNE) // True if any are unequal
3607 InVal = BinaryOperator::createOr(InVal, Comp);
3608 else // True if all are equal
3609 InVal = BinaryOperator::createAnd(InVal, Comp);
3610 }
3611 }
3612 }
3613
3614 if (InVal)
3615 return InVal;
3616 else
3617 ReplaceInstUsesWith(I, // No comparison is needed here, all indexes = 0
3618 ConstantBool::get(Cond == Instruction::SetEQ));
3619 }
Chris Lattner0798af32005-01-13 20:14:25 +00003620
3621 // Only lower this if the setcc is the only user of the GEP or if we expect
3622 // the result to fold to a constant!
3623 if (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) {
3624 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
3625 Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
3626 return new SetCondInst(Cond, Offset,
3627 Constant::getNullValue(Offset->getType()));
3628 }
3629 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
Chris Lattnera21bf8d2005-04-25 20:17:30 +00003630 // If the base pointers are different, but the indices are the same, just
3631 // compare the base pointer.
3632 if (PtrBase != GEPRHS->getOperand(0)) {
3633 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00003634 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattnerbd43b9d2005-04-26 14:40:41 +00003635 GEPRHS->getOperand(0)->getType();
Chris Lattnera21bf8d2005-04-25 20:17:30 +00003636 if (IndicesTheSame)
3637 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
3638 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
3639 IndicesTheSame = false;
3640 break;
3641 }
3642
3643 // If all indices are the same, just compare the base pointers.
3644 if (IndicesTheSame)
3645 return new SetCondInst(Cond, GEPLHS->getOperand(0),
3646 GEPRHS->getOperand(0));
3647
3648 // Otherwise, the base pointers are different and the indices are
3649 // different, bail out.
Chris Lattner0798af32005-01-13 20:14:25 +00003650 return 0;
Chris Lattnera21bf8d2005-04-25 20:17:30 +00003651 }
Chris Lattner0798af32005-01-13 20:14:25 +00003652
Chris Lattner81e84172005-01-13 22:25:21 +00003653 // If one of the GEPs has all zero indices, recurse.
3654 bool AllZeros = true;
3655 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
3656 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
3657 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
3658 AllZeros = false;
3659 break;
3660 }
3661 if (AllZeros)
3662 return FoldGEPSetCC(GEPRHS, GEPLHS->getOperand(0),
3663 SetCondInst::getSwappedCondition(Cond), I);
Chris Lattner4fa89822005-01-14 00:20:05 +00003664
3665 // If the other GEP has all zero indices, recurse.
Chris Lattner81e84172005-01-13 22:25:21 +00003666 AllZeros = true;
3667 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
3668 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
3669 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
3670 AllZeros = false;
3671 break;
3672 }
3673 if (AllZeros)
3674 return FoldGEPSetCC(GEPLHS, GEPRHS->getOperand(0), Cond, I);
3675
Chris Lattner4fa89822005-01-14 00:20:05 +00003676 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
3677 // If the GEPs only differ by one index, compare it.
3678 unsigned NumDifferences = 0; // Keep track of # differences.
3679 unsigned DiffOperand = 0; // The operand that differs.
3680 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
3681 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003682 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
3683 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattnerfc4429e2005-01-21 23:06:49 +00003684 // Irreconcilable differences.
Chris Lattner4fa89822005-01-14 00:20:05 +00003685 NumDifferences = 2;
3686 break;
3687 } else {
3688 if (NumDifferences++) break;
3689 DiffOperand = i;
3690 }
3691 }
3692
3693 if (NumDifferences == 0) // SAME GEP?
3694 return ReplaceInstUsesWith(I, // No comparison is needed here.
3695 ConstantBool::get(Cond == Instruction::SetEQ));
3696 else if (NumDifferences == 1) {
Chris Lattnerfc4429e2005-01-21 23:06:49 +00003697 Value *LHSV = GEPLHS->getOperand(DiffOperand);
3698 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Chris Lattner247aef82005-07-18 23:07:33 +00003699
3700 // Convert the operands to signed values to make sure to perform a
3701 // signed comparison.
3702 const Type *NewTy = LHSV->getType()->getSignedVersion();
3703 if (LHSV->getType() != NewTy)
3704 LHSV = InsertNewInstBefore(new CastInst(LHSV, NewTy,
3705 LHSV->getName()), I);
3706 if (RHSV->getType() != NewTy)
3707 RHSV = InsertNewInstBefore(new CastInst(RHSV, NewTy,
3708 RHSV->getName()), I);
3709 return new SetCondInst(Cond, LHSV, RHSV);
Chris Lattner4fa89822005-01-14 00:20:05 +00003710 }
3711 }
3712
Chris Lattner0798af32005-01-13 20:14:25 +00003713 // Only lower this if the setcc is the only user of the GEP or if we expect
3714 // the result to fold to a constant!
3715 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
3716 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
3717 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
3718 Value *L = EmitGEPOffset(GEPLHS, I, *this);
3719 Value *R = EmitGEPOffset(GEPRHS, I, *this);
3720 return new SetCondInst(Cond, L, R);
3721 }
3722 }
3723 return 0;
3724}
3725
3726
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003727Instruction *InstCombiner::visitSetCondInst(SetCondInst &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003728 bool Changed = SimplifyCommutative(I);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003729 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3730 const Type *Ty = Op0->getType();
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003731
3732 // setcc X, X
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003733 if (Op0 == Op1)
3734 return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
Chris Lattner1fc23f32002-05-09 20:11:54 +00003735
Chris Lattner81a7a232004-10-16 18:11:37 +00003736 if (isa<UndefValue>(Op1)) // X setcc undef -> undef
3737 return ReplaceInstUsesWith(I, UndefValue::get(Type::BoolTy));
3738
Chris Lattner15ff1e12004-11-14 07:33:16 +00003739 // setcc <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
3740 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanb1c93172005-04-21 23:48:37 +00003741 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
3742 isa<ConstantPointerNull>(Op0)) &&
3743 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner15ff1e12004-11-14 07:33:16 +00003744 isa<ConstantPointerNull>(Op1)))
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003745 return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
3746
3747 // setcc's with boolean values can always be turned into bitwise operations
3748 if (Ty == Type::BoolTy) {
Chris Lattner4456da62004-08-11 00:50:51 +00003749 switch (I.getOpcode()) {
3750 default: assert(0 && "Invalid setcc instruction!");
3751 case Instruction::SetEQ: { // seteq bool %A, %B -> ~(A^B)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003752 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003753 InsertNewInstBefore(Xor, I);
Chris Lattner16930792003-11-03 04:25:02 +00003754 return BinaryOperator::createNot(Xor);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003755 }
Chris Lattner4456da62004-08-11 00:50:51 +00003756 case Instruction::SetNE:
3757 return BinaryOperator::createXor(Op0, Op1);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003758
Chris Lattner4456da62004-08-11 00:50:51 +00003759 case Instruction::SetGT:
3760 std::swap(Op0, Op1); // Change setgt -> setlt
3761 // FALL THROUGH
3762 case Instruction::SetLT: { // setlt bool A, B -> ~X & Y
3763 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
3764 InsertNewInstBefore(Not, I);
3765 return BinaryOperator::createAnd(Not, Op1);
3766 }
3767 case Instruction::SetGE:
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003768 std::swap(Op0, Op1); // Change setge -> setle
Chris Lattner4456da62004-08-11 00:50:51 +00003769 // FALL THROUGH
3770 case Instruction::SetLE: { // setle bool %A, %B -> ~A | B
3771 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
3772 InsertNewInstBefore(Not, I);
3773 return BinaryOperator::createOr(Not, Op1);
3774 }
3775 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003776 }
3777
Chris Lattner2dd01742004-06-09 04:24:29 +00003778 // See if we are doing a comparison between a constant and an instruction that
3779 // can be folded into the comparison.
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003780 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner6862fbd2004-09-29 17:40:11 +00003781 // Check to see if we are comparing against the minimum or maximum value...
3782 if (CI->isMinValue()) {
3783 if (I.getOpcode() == Instruction::SetLT) // A < MIN -> FALSE
Chris Lattner6ab03f62006-09-28 23:35:22 +00003784 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattner6862fbd2004-09-29 17:40:11 +00003785 if (I.getOpcode() == Instruction::SetGE) // A >= MIN -> TRUE
Chris Lattner6ab03f62006-09-28 23:35:22 +00003786 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
Chris Lattner6862fbd2004-09-29 17:40:11 +00003787 if (I.getOpcode() == Instruction::SetLE) // A <= MIN -> A == MIN
3788 return BinaryOperator::createSetEQ(Op0, Op1);
3789 if (I.getOpcode() == Instruction::SetGT) // A > MIN -> A != MIN
3790 return BinaryOperator::createSetNE(Op0, Op1);
3791
3792 } else if (CI->isMaxValue()) {
3793 if (I.getOpcode() == Instruction::SetGT) // A > MAX -> FALSE
Chris Lattner6ab03f62006-09-28 23:35:22 +00003794 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattner6862fbd2004-09-29 17:40:11 +00003795 if (I.getOpcode() == Instruction::SetLE) // A <= MAX -> TRUE
Chris Lattner6ab03f62006-09-28 23:35:22 +00003796 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
Chris Lattner6862fbd2004-09-29 17:40:11 +00003797 if (I.getOpcode() == Instruction::SetGE) // A >= MAX -> A == MAX
3798 return BinaryOperator::createSetEQ(Op0, Op1);
3799 if (I.getOpcode() == Instruction::SetLT) // A < MAX -> A != MAX
3800 return BinaryOperator::createSetNE(Op0, Op1);
3801
3802 // Comparing against a value really close to min or max?
3803 } else if (isMinValuePlusOne(CI)) {
3804 if (I.getOpcode() == Instruction::SetLT) // A < MIN+1 -> A == MIN
3805 return BinaryOperator::createSetEQ(Op0, SubOne(CI));
3806 if (I.getOpcode() == Instruction::SetGE) // A >= MIN-1 -> A != MIN
3807 return BinaryOperator::createSetNE(Op0, SubOne(CI));
3808
3809 } else if (isMaxValueMinusOne(CI)) {
3810 if (I.getOpcode() == Instruction::SetGT) // A > MAX-1 -> A == MAX
3811 return BinaryOperator::createSetEQ(Op0, AddOne(CI));
3812 if (I.getOpcode() == Instruction::SetLE) // A <= MAX-1 -> A != MAX
3813 return BinaryOperator::createSetNE(Op0, AddOne(CI));
3814 }
3815
3816 // If we still have a setle or setge instruction, turn it into the
3817 // appropriate setlt or setgt instruction. Since the border cases have
3818 // already been handled above, this requires little checking.
3819 //
3820 if (I.getOpcode() == Instruction::SetLE)
3821 return BinaryOperator::createSetLT(Op0, AddOne(CI));
3822 if (I.getOpcode() == Instruction::SetGE)
3823 return BinaryOperator::createSetGT(Op0, SubOne(CI));
3824
Chris Lattneree0f2802006-02-12 02:07:56 +00003825
3826 // See if we can fold the comparison based on bits known to be zero or one
3827 // in the input.
3828 uint64_t KnownZero, KnownOne;
3829 if (SimplifyDemandedBits(Op0, Ty->getIntegralTypeMask(),
3830 KnownZero, KnownOne, 0))
3831 return &I;
3832
3833 // Given the known and unknown bits, compute a range that the LHS could be
3834 // in.
3835 if (KnownOne | KnownZero) {
3836 if (Ty->isUnsigned()) { // Unsigned comparison.
3837 uint64_t Min, Max;
3838 uint64_t RHSVal = CI->getZExtValue();
3839 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne,
3840 Min, Max);
3841 switch (I.getOpcode()) { // LE/GE have been folded already.
3842 default: assert(0 && "Unknown setcc opcode!");
3843 case Instruction::SetEQ:
3844 if (Max < RHSVal || Min > RHSVal)
Chris Lattner6ab03f62006-09-28 23:35:22 +00003845 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattneree0f2802006-02-12 02:07:56 +00003846 break;
3847 case Instruction::SetNE:
3848 if (Max < RHSVal || Min > RHSVal)
Chris Lattner6ab03f62006-09-28 23:35:22 +00003849 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
Chris Lattneree0f2802006-02-12 02:07:56 +00003850 break;
3851 case Instruction::SetLT:
Chris Lattner6ab03f62006-09-28 23:35:22 +00003852 if (Max < RHSVal)
3853 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
3854 if (Min > RHSVal)
3855 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattneree0f2802006-02-12 02:07:56 +00003856 break;
3857 case Instruction::SetGT:
Chris Lattner6ab03f62006-09-28 23:35:22 +00003858 if (Min > RHSVal)
3859 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
3860 if (Max < RHSVal)
3861 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattneree0f2802006-02-12 02:07:56 +00003862 break;
3863 }
3864 } else { // Signed comparison.
3865 int64_t Min, Max;
3866 int64_t RHSVal = CI->getSExtValue();
3867 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne,
3868 Min, Max);
3869 switch (I.getOpcode()) { // LE/GE have been folded already.
3870 default: assert(0 && "Unknown setcc opcode!");
3871 case Instruction::SetEQ:
3872 if (Max < RHSVal || Min > RHSVal)
Chris Lattner6ab03f62006-09-28 23:35:22 +00003873 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattneree0f2802006-02-12 02:07:56 +00003874 break;
3875 case Instruction::SetNE:
3876 if (Max < RHSVal || Min > RHSVal)
Chris Lattner6ab03f62006-09-28 23:35:22 +00003877 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
Chris Lattneree0f2802006-02-12 02:07:56 +00003878 break;
3879 case Instruction::SetLT:
Chris Lattner6ab03f62006-09-28 23:35:22 +00003880 if (Max < RHSVal)
3881 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
3882 if (Min > RHSVal)
3883 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattneree0f2802006-02-12 02:07:56 +00003884 break;
3885 case Instruction::SetGT:
Chris Lattner6ab03f62006-09-28 23:35:22 +00003886 if (Min > RHSVal)
3887 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
3888 if (Max < RHSVal)
3889 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattneree0f2802006-02-12 02:07:56 +00003890 break;
3891 }
3892 }
3893 }
3894
3895
Chris Lattnere1e10e12004-05-25 06:32:08 +00003896 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00003897 switch (LHSI->getOpcode()) {
3898 case Instruction::And:
3899 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
3900 LHSI->getOperand(0)->hasOneUse()) {
Chris Lattner4922a0e2006-09-18 05:27:43 +00003901 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
3902
3903 // If an operand is an AND of a truncating cast, we can widen the
3904 // and/compare to be the input width without changing the value
3905 // produced, eliminating a cast.
3906 if (CastInst *Cast = dyn_cast<CastInst>(LHSI->getOperand(0))) {
3907 // We can do this transformation if either the AND constant does not
3908 // have its sign bit set or if it is an equality comparison.
3909 // Extending a relational comparison when we're checking the sign
3910 // bit would not work.
3911 if (Cast->hasOneUse() && Cast->isTruncIntCast() &&
3912 (I.isEquality() ||
3913 (AndCST->getZExtValue() == (uint64_t)AndCST->getSExtValue()) &&
3914 (CI->getZExtValue() == (uint64_t)CI->getSExtValue()))) {
3915 ConstantInt *NewCST;
3916 ConstantInt *NewCI;
3917 if (Cast->getOperand(0)->getType()->isSigned()) {
3918 NewCST = ConstantSInt::get(Cast->getOperand(0)->getType(),
3919 AndCST->getZExtValue());
3920 NewCI = ConstantSInt::get(Cast->getOperand(0)->getType(),
3921 CI->getZExtValue());
3922 } else {
3923 NewCST = ConstantUInt::get(Cast->getOperand(0)->getType(),
3924 AndCST->getZExtValue());
3925 NewCI = ConstantUInt::get(Cast->getOperand(0)->getType(),
3926 CI->getZExtValue());
3927 }
3928 Instruction *NewAnd =
3929 BinaryOperator::createAnd(Cast->getOperand(0), NewCST,
3930 LHSI->getName());
3931 InsertNewInstBefore(NewAnd, I);
3932 return new SetCondInst(I.getOpcode(), NewAnd, NewCI);
3933 }
3934 }
3935
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00003936 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
3937 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
3938 // happens a LOT in code produced by the C front-end, for bitfield
3939 // access.
3940 ShiftInst *Shift = dyn_cast<ShiftInst>(LHSI->getOperand(0));
Chris Lattneree0f2802006-02-12 02:07:56 +00003941
3942 // Check to see if there is a noop-cast between the shift and the and.
3943 if (!Shift) {
3944 if (CastInst *CI = dyn_cast<CastInst>(LHSI->getOperand(0)))
3945 if (CI->getOperand(0)->getType()->isIntegral() &&
3946 CI->getOperand(0)->getType()->getPrimitiveSizeInBits() ==
3947 CI->getType()->getPrimitiveSizeInBits())
3948 Shift = dyn_cast<ShiftInst>(CI->getOperand(0));
3949 }
Chris Lattnerb3f24c92006-09-18 04:22:48 +00003950
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00003951 ConstantUInt *ShAmt;
3952 ShAmt = Shift ? dyn_cast<ConstantUInt>(Shift->getOperand(1)) : 0;
Chris Lattneree0f2802006-02-12 02:07:56 +00003953 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
3954 const Type *AndTy = AndCST->getType(); // Type of the and.
Misha Brukmanb1c93172005-04-21 23:48:37 +00003955
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00003956 // We can fold this as long as we can't shift unknown bits
3957 // into the mask. This can only happen with signed shift
3958 // rights, as they sign-extend.
3959 if (ShAmt) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00003960 bool CanFold = Shift->isLogicalShift();
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00003961 if (!CanFold) {
3962 // To test for the bad case of the signed shr, see if any
3963 // of the bits shifted in could be tested after the mask.
Chris Lattnerc53cb9d2005-06-17 01:29:28 +00003964 int ShAmtVal = Ty->getPrimitiveSizeInBits()-ShAmt->getValue();
3965 if (ShAmtVal < 0) ShAmtVal = 0; // Out of range shift.
3966
3967 Constant *OShAmt = ConstantUInt::get(Type::UByteTy, ShAmtVal);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003968 Constant *ShVal =
Chris Lattneree0f2802006-02-12 02:07:56 +00003969 ConstantExpr::getShl(ConstantInt::getAllOnesValue(AndTy),
3970 OShAmt);
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00003971 if (ConstantExpr::getAnd(ShVal, AndCST)->isNullValue())
3972 CanFold = true;
3973 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003974
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00003975 if (CanFold) {
Chris Lattner6afc02f2004-09-28 17:54:07 +00003976 Constant *NewCst;
3977 if (Shift->getOpcode() == Instruction::Shl)
3978 NewCst = ConstantExpr::getUShr(CI, ShAmt);
3979 else
3980 NewCst = ConstantExpr::getShl(CI, ShAmt);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00003981
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00003982 // Check to see if we are shifting out any of the bits being
3983 // compared.
3984 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != CI){
3985 // If we shifted bits out, the fold is not going to work out.
3986 // As a special case, check to see if this means that the
3987 // result is always true or false now.
3988 if (I.getOpcode() == Instruction::SetEQ)
Chris Lattner6ab03f62006-09-28 23:35:22 +00003989 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00003990 if (I.getOpcode() == Instruction::SetNE)
Chris Lattner6ab03f62006-09-28 23:35:22 +00003991 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00003992 } else {
3993 I.setOperand(1, NewCst);
Chris Lattner6afc02f2004-09-28 17:54:07 +00003994 Constant *NewAndCST;
3995 if (Shift->getOpcode() == Instruction::Shl)
3996 NewAndCST = ConstantExpr::getUShr(AndCST, ShAmt);
3997 else
3998 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
3999 LHSI->setOperand(1, NewAndCST);
Chris Lattneree0f2802006-02-12 02:07:56 +00004000 if (AndTy == Ty)
4001 LHSI->setOperand(0, Shift->getOperand(0));
4002 else {
4003 Value *NewCast = InsertCastBefore(Shift->getOperand(0), AndTy,
4004 *Shift);
4005 LHSI->setOperand(0, NewCast);
4006 }
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004007 WorkList.push_back(Shift); // Shift is dead.
4008 AddUsesToWorkList(I);
4009 return &I;
Chris Lattner1638de42004-07-21 19:50:44 +00004010 }
4011 }
Chris Lattner35167c32004-06-09 07:59:58 +00004012 }
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004013
4014 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
4015 // preferable because it allows the C<<Y expression to be hoisted out
4016 // of a loop if Y is invariant and X is not.
4017 if (Shift && Shift->hasOneUse() && CI->isNullValue() &&
Chris Lattnerde077922006-09-18 18:27:05 +00004018 I.isEquality() && !Shift->isArithmeticShift() &&
4019 isa<Instruction>(Shift->getOperand(0))) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004020 // Compute C << Y.
4021 Value *NS;
4022 if (Shift->getOpcode() == Instruction::Shr) {
4023 NS = new ShiftInst(Instruction::Shl, AndCST, Shift->getOperand(1),
4024 "tmp");
4025 } else {
4026 // Make sure we insert a logical shift.
Chris Lattner4922a0e2006-09-18 05:27:43 +00004027 Constant *NewAndCST = AndCST;
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004028 if (AndCST->getType()->isSigned())
Chris Lattner4922a0e2006-09-18 05:27:43 +00004029 NewAndCST = ConstantExpr::getCast(AndCST,
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004030 AndCST->getType()->getUnsignedVersion());
Chris Lattner4922a0e2006-09-18 05:27:43 +00004031 NS = new ShiftInst(Instruction::Shr, NewAndCST,
4032 Shift->getOperand(1), "tmp");
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004033 }
4034 InsertNewInstBefore(cast<Instruction>(NS), I);
4035
4036 // If C's sign doesn't agree with the and, insert a cast now.
4037 if (NS->getType() != LHSI->getType())
4038 NS = InsertCastBefore(NS, LHSI->getType(), I);
4039
4040 Value *ShiftOp = Shift->getOperand(0);
4041 if (ShiftOp->getType() != LHSI->getType())
4042 ShiftOp = InsertCastBefore(ShiftOp, LHSI->getType(), I);
4043
4044 // Compute X & (C << Y).
4045 Instruction *NewAnd =
4046 BinaryOperator::createAnd(ShiftOp, NS, LHSI->getName());
4047 InsertNewInstBefore(NewAnd, I);
4048
4049 I.setOperand(0, NewAnd);
4050 return &I;
4051 }
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004052 }
4053 break;
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004054
Chris Lattner272d5ca2004-09-28 18:22:15 +00004055 case Instruction::Shl: // (setcc (shl X, ShAmt), CI)
4056 if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004057 if (I.isEquality()) {
Chris Lattner19b57f52005-06-15 20:53:31 +00004058 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
4059
4060 // Check that the shift amount is in range. If not, don't perform
4061 // undefined shifts. When the shift is visited it will be
4062 // simplified.
4063 if (ShAmt->getValue() >= TypeBits)
4064 break;
4065
Chris Lattner272d5ca2004-09-28 18:22:15 +00004066 // If we are comparing against bits always shifted out, the
4067 // comparison cannot succeed.
Misha Brukmanb1c93172005-04-21 23:48:37 +00004068 Constant *Comp =
Chris Lattner272d5ca2004-09-28 18:22:15 +00004069 ConstantExpr::getShl(ConstantExpr::getShr(CI, ShAmt), ShAmt);
4070 if (Comp != CI) {// Comparing against a bit that we know is zero.
4071 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
4072 Constant *Cst = ConstantBool::get(IsSetNE);
4073 return ReplaceInstUsesWith(I, Cst);
4074 }
4075
4076 if (LHSI->hasOneUse()) {
4077 // Otherwise strength reduce the shift into an and.
Chris Lattnerfdfe3e492005-01-08 19:42:22 +00004078 unsigned ShAmtVal = (unsigned)ShAmt->getValue();
Chris Lattner272d5ca2004-09-28 18:22:15 +00004079 uint64_t Val = (1ULL << (TypeBits-ShAmtVal))-1;
4080
4081 Constant *Mask;
4082 if (CI->getType()->isUnsigned()) {
4083 Mask = ConstantUInt::get(CI->getType(), Val);
4084 } else if (ShAmtVal != 0) {
4085 Mask = ConstantSInt::get(CI->getType(), Val);
4086 } else {
4087 Mask = ConstantInt::getAllOnesValue(CI->getType());
4088 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004089
Chris Lattner272d5ca2004-09-28 18:22:15 +00004090 Instruction *AndI =
4091 BinaryOperator::createAnd(LHSI->getOperand(0),
4092 Mask, LHSI->getName()+".mask");
4093 Value *And = InsertNewInstBefore(AndI, I);
4094 return new SetCondInst(I.getOpcode(), And,
4095 ConstantExpr::getUShr(CI, ShAmt));
4096 }
4097 }
Chris Lattner272d5ca2004-09-28 18:22:15 +00004098 }
4099 break;
4100
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004101 case Instruction::Shr: // (setcc (shr X, ShAmt), CI)
Chris Lattner1023b872004-09-27 16:18:50 +00004102 if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004103 if (I.isEquality()) {
Chris Lattner19b57f52005-06-15 20:53:31 +00004104 // Check that the shift amount is in range. If not, don't perform
4105 // undefined shifts. When the shift is visited it will be
4106 // simplified.
Chris Lattner104002b2005-06-16 01:52:07 +00004107 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
Chris Lattner19b57f52005-06-15 20:53:31 +00004108 if (ShAmt->getValue() >= TypeBits)
4109 break;
4110
Chris Lattner1023b872004-09-27 16:18:50 +00004111 // If we are comparing against bits always shifted out, the
4112 // comparison cannot succeed.
Misha Brukmanb1c93172005-04-21 23:48:37 +00004113 Constant *Comp =
Chris Lattner1023b872004-09-27 16:18:50 +00004114 ConstantExpr::getShr(ConstantExpr::getShl(CI, ShAmt), ShAmt);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004115
Chris Lattner1023b872004-09-27 16:18:50 +00004116 if (Comp != CI) {// Comparing against a bit that we know is zero.
4117 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
4118 Constant *Cst = ConstantBool::get(IsSetNE);
4119 return ReplaceInstUsesWith(I, Cst);
4120 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004121
Chris Lattner1023b872004-09-27 16:18:50 +00004122 if (LHSI->hasOneUse() || CI->isNullValue()) {
Chris Lattnerfdfe3e492005-01-08 19:42:22 +00004123 unsigned ShAmtVal = (unsigned)ShAmt->getValue();
Chris Lattner272d5ca2004-09-28 18:22:15 +00004124
Chris Lattner1023b872004-09-27 16:18:50 +00004125 // Otherwise strength reduce the shift into an and.
4126 uint64_t Val = ~0ULL; // All ones.
4127 Val <<= ShAmtVal; // Shift over to the right spot.
4128
4129 Constant *Mask;
4130 if (CI->getType()->isUnsigned()) {
Chris Lattner2f1457f2005-04-24 17:46:05 +00004131 Val &= ~0ULL >> (64-TypeBits);
Chris Lattner1023b872004-09-27 16:18:50 +00004132 Mask = ConstantUInt::get(CI->getType(), Val);
4133 } else {
4134 Mask = ConstantSInt::get(CI->getType(), Val);
4135 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004136
Chris Lattner1023b872004-09-27 16:18:50 +00004137 Instruction *AndI =
4138 BinaryOperator::createAnd(LHSI->getOperand(0),
4139 Mask, LHSI->getName()+".mask");
4140 Value *And = InsertNewInstBefore(AndI, I);
4141 return new SetCondInst(I.getOpcode(), And,
4142 ConstantExpr::getShl(CI, ShAmt));
4143 }
Chris Lattner1023b872004-09-27 16:18:50 +00004144 }
4145 }
4146 break;
Chris Lattner7e794272004-09-24 15:21:34 +00004147
Chris Lattner6862fbd2004-09-29 17:40:11 +00004148 case Instruction::Div:
4149 // Fold: (div X, C1) op C2 -> range check
4150 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
4151 // Fold this div into the comparison, producing a range check.
4152 // Determine, based on the divide type, what the range is being
4153 // checked. If there is an overflow on the low or high side, remember
4154 // it, otherwise compute the range [low, hi) bounding the new value.
4155 bool LoOverflow = false, HiOverflow = 0;
4156 ConstantInt *LoBound = 0, *HiBound = 0;
4157
4158 ConstantInt *Prod;
4159 bool ProdOV = MulWithOverflow(Prod, CI, DivRHS);
4160
Chris Lattnera92af962004-10-11 19:40:04 +00004161 Instruction::BinaryOps Opcode = I.getOpcode();
4162
Chris Lattner6862fbd2004-09-29 17:40:11 +00004163 if (DivRHS->isNullValue()) { // Don't hack on divide by zeros.
4164 } else if (LHSI->getType()->isUnsigned()) { // udiv
4165 LoBound = Prod;
4166 LoOverflow = ProdOV;
4167 HiOverflow = ProdOV || AddWithOverflow(HiBound, LoBound, DivRHS);
4168 } else if (isPositive(DivRHS)) { // Divisor is > 0.
4169 if (CI->isNullValue()) { // (X / pos) op 0
4170 // Can't overflow.
4171 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
4172 HiBound = DivRHS;
4173 } else if (isPositive(CI)) { // (X / pos) op pos
4174 LoBound = Prod;
4175 LoOverflow = ProdOV;
4176 HiOverflow = ProdOV || AddWithOverflow(HiBound, Prod, DivRHS);
4177 } else { // (X / pos) op neg
4178 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
4179 LoOverflow = AddWithOverflow(LoBound, Prod,
4180 cast<ConstantInt>(DivRHSH));
4181 HiBound = Prod;
4182 HiOverflow = ProdOV;
4183 }
4184 } else { // Divisor is < 0.
4185 if (CI->isNullValue()) { // (X / neg) op 0
4186 LoBound = AddOne(DivRHS);
4187 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner73bcba52005-06-17 02:05:55 +00004188 if (HiBound == DivRHS)
4189 LoBound = 0; // - INTMIN = INTMIN
Chris Lattner6862fbd2004-09-29 17:40:11 +00004190 } else if (isPositive(CI)) { // (X / neg) op pos
4191 HiOverflow = LoOverflow = ProdOV;
4192 if (!LoOverflow)
4193 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS));
4194 HiBound = AddOne(Prod);
4195 } else { // (X / neg) op neg
4196 LoBound = Prod;
4197 LoOverflow = HiOverflow = ProdOV;
4198 HiBound = cast<ConstantInt>(ConstantExpr::getSub(Prod, DivRHS));
4199 }
Chris Lattner0b41e862004-10-08 19:15:44 +00004200
Chris Lattnera92af962004-10-11 19:40:04 +00004201 // Dividing by a negate swaps the condition.
4202 Opcode = SetCondInst::getSwappedCondition(Opcode);
Chris Lattner6862fbd2004-09-29 17:40:11 +00004203 }
4204
4205 if (LoBound) {
4206 Value *X = LHSI->getOperand(0);
Chris Lattnera92af962004-10-11 19:40:04 +00004207 switch (Opcode) {
Chris Lattner6862fbd2004-09-29 17:40:11 +00004208 default: assert(0 && "Unhandled setcc opcode!");
4209 case Instruction::SetEQ:
4210 if (LoOverflow && HiOverflow)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004211 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattner6862fbd2004-09-29 17:40:11 +00004212 else if (HiOverflow)
4213 return new SetCondInst(Instruction::SetGE, X, LoBound);
4214 else if (LoOverflow)
4215 return new SetCondInst(Instruction::SetLT, X, HiBound);
4216 else
4217 return InsertRangeTest(X, LoBound, HiBound, true, I);
4218 case Instruction::SetNE:
4219 if (LoOverflow && HiOverflow)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004220 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
Chris Lattner6862fbd2004-09-29 17:40:11 +00004221 else if (HiOverflow)
4222 return new SetCondInst(Instruction::SetLT, X, LoBound);
4223 else if (LoOverflow)
4224 return new SetCondInst(Instruction::SetGE, X, HiBound);
4225 else
4226 return InsertRangeTest(X, LoBound, HiBound, false, I);
4227 case Instruction::SetLT:
4228 if (LoOverflow)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004229 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattner6862fbd2004-09-29 17:40:11 +00004230 return new SetCondInst(Instruction::SetLT, X, LoBound);
4231 case Instruction::SetGT:
4232 if (HiOverflow)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004233 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattner6862fbd2004-09-29 17:40:11 +00004234 return new SetCondInst(Instruction::SetGE, X, HiBound);
4235 }
4236 }
4237 }
4238 break;
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004239 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004240
Chris Lattnerd492a0b2003-07-23 17:02:11 +00004241 // Simplify seteq and setne instructions...
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004242 if (I.isEquality()) {
Chris Lattnerd492a0b2003-07-23 17:02:11 +00004243 bool isSetNE = I.getOpcode() == Instruction::SetNE;
4244
Chris Lattnercfbce7c2003-07-23 17:26:36 +00004245 // If the first operand is (and|or|xor) with a constant, and the second
Chris Lattnerd492a0b2003-07-23 17:02:11 +00004246 // operand is a constant, simplify a bit.
Chris Lattnerc992add2003-08-13 05:33:12 +00004247 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
4248 switch (BO->getOpcode()) {
Chris Lattner23b47b62004-07-06 07:38:18 +00004249 case Instruction::Rem:
4250 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
4251 if (CI->isNullValue() && isa<ConstantSInt>(BO->getOperand(1)) &&
4252 BO->hasOneUse() &&
Chris Lattner22d00a82005-08-02 19:16:58 +00004253 cast<ConstantSInt>(BO->getOperand(1))->getValue() > 1) {
4254 int64_t V = cast<ConstantSInt>(BO->getOperand(1))->getValue();
4255 if (isPowerOf2_64(V)) {
4256 unsigned L2 = Log2_64(V);
Chris Lattner23b47b62004-07-06 07:38:18 +00004257 const Type *UTy = BO->getType()->getUnsignedVersion();
4258 Value *NewX = InsertNewInstBefore(new CastInst(BO->getOperand(0),
4259 UTy, "tmp"), I);
4260 Constant *RHSCst = ConstantUInt::get(UTy, 1ULL << L2);
4261 Value *NewRem =InsertNewInstBefore(BinaryOperator::createRem(NewX,
4262 RHSCst, BO->getName()), I);
4263 return BinaryOperator::create(I.getOpcode(), NewRem,
4264 Constant::getNullValue(UTy));
4265 }
Chris Lattner22d00a82005-08-02 19:16:58 +00004266 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004267 break;
Chris Lattner23b47b62004-07-06 07:38:18 +00004268
Chris Lattnerc992add2003-08-13 05:33:12 +00004269 case Instruction::Add:
Chris Lattner6e079362004-06-27 22:51:36 +00004270 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
4271 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerb121ae12004-09-21 21:35:23 +00004272 if (BO->hasOneUse())
4273 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
4274 ConstantExpr::getSub(CI, BOp1C));
Chris Lattner6e079362004-06-27 22:51:36 +00004275 } else if (CI->isNullValue()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00004276 // Replace ((add A, B) != 0) with (A != -B) if A or B is
4277 // efficiently invertible, or if the add has just this one use.
4278 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004279
Chris Lattnerc992add2003-08-13 05:33:12 +00004280 if (Value *NegVal = dyn_castNegVal(BOp1))
4281 return new SetCondInst(I.getOpcode(), BOp0, NegVal);
4282 else if (Value *NegVal = dyn_castNegVal(BOp0))
4283 return new SetCondInst(I.getOpcode(), NegVal, BOp1);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00004284 else if (BO->hasOneUse()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00004285 Instruction *Neg = BinaryOperator::createNeg(BOp1, BO->getName());
4286 BO->setName("");
4287 InsertNewInstBefore(Neg, I);
4288 return new SetCondInst(I.getOpcode(), BOp0, Neg);
4289 }
4290 }
4291 break;
4292 case Instruction::Xor:
4293 // For the xor case, we can xor two constants together, eliminating
4294 // the explicit xor.
4295 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
4296 return BinaryOperator::create(I.getOpcode(), BO->getOperand(0),
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004297 ConstantExpr::getXor(CI, BOC));
Chris Lattnerc992add2003-08-13 05:33:12 +00004298
4299 // FALLTHROUGH
4300 case Instruction::Sub:
4301 // Replace (([sub|xor] A, B) != 0) with (A != B)
4302 if (CI->isNullValue())
4303 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
4304 BO->getOperand(1));
4305 break;
4306
4307 case Instruction::Or:
4308 // If bits are being or'd in that are not present in the constant we
4309 // are comparing against, then the comparison could never succeed!
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00004310 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Chris Lattnerc8e7e292004-06-10 02:12:35 +00004311 Constant *NotCI = ConstantExpr::getNot(CI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004312 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Chris Lattnerd492a0b2003-07-23 17:02:11 +00004313 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00004314 }
Chris Lattnerc992add2003-08-13 05:33:12 +00004315 break;
4316
4317 case Instruction::And:
4318 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerd492a0b2003-07-23 17:02:11 +00004319 // If bits are being compared against that are and'd out, then the
4320 // comparison can never succeed!
Chris Lattnerc8e7e292004-06-10 02:12:35 +00004321 if (!ConstantExpr::getAnd(CI,
4322 ConstantExpr::getNot(BOC))->isNullValue())
Chris Lattnerd492a0b2003-07-23 17:02:11 +00004323 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattnerc992add2003-08-13 05:33:12 +00004324
Chris Lattner35167c32004-06-09 07:59:58 +00004325 // If we have ((X & C) == C), turn it into ((X & C) != 0).
Chris Lattneree59d4b2004-06-10 02:33:20 +00004326 if (CI == BOC && isOneBitSet(CI))
Chris Lattner35167c32004-06-09 07:59:58 +00004327 return new SetCondInst(isSetNE ? Instruction::SetEQ :
4328 Instruction::SetNE, Op0,
4329 Constant::getNullValue(CI->getType()));
Chris Lattner35167c32004-06-09 07:59:58 +00004330
Chris Lattnerc992add2003-08-13 05:33:12 +00004331 // Replace (and X, (1 << size(X)-1) != 0) with x < 0, converting X
4332 // to be a signed value as appropriate.
4333 if (isSignBit(BOC)) {
4334 Value *X = BO->getOperand(0);
4335 // If 'X' is not signed, insert a cast now...
4336 if (!BOC->getType()->isSigned()) {
Chris Lattner97bfcea2004-06-17 18:16:02 +00004337 const Type *DestTy = BOC->getType()->getSignedVersion();
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004338 X = InsertCastBefore(X, DestTy, I);
Chris Lattnerc992add2003-08-13 05:33:12 +00004339 }
4340 return new SetCondInst(isSetNE ? Instruction::SetLT :
4341 Instruction::SetGE, X,
4342 Constant::getNullValue(X->getType()));
4343 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004344
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004345 // ((X & ~7) == 0) --> X < 8
Chris Lattner8fc5af42004-09-23 21:46:38 +00004346 if (CI->isNullValue() && isHighOnes(BOC)) {
4347 Value *X = BO->getOperand(0);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004348 Constant *NegX = ConstantExpr::getNeg(BOC);
Chris Lattner8fc5af42004-09-23 21:46:38 +00004349
4350 // If 'X' is signed, insert a cast now.
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004351 if (NegX->getType()->isSigned()) {
4352 const Type *DestTy = NegX->getType()->getUnsignedVersion();
4353 X = InsertCastBefore(X, DestTy, I);
4354 NegX = ConstantExpr::getCast(NegX, DestTy);
Chris Lattner8fc5af42004-09-23 21:46:38 +00004355 }
4356
4357 return new SetCondInst(isSetNE ? Instruction::SetGE :
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004358 Instruction::SetLT, X, NegX);
Chris Lattner8fc5af42004-09-23 21:46:38 +00004359 }
4360
Chris Lattnerd492a0b2003-07-23 17:02:11 +00004361 }
Chris Lattnerc992add2003-08-13 05:33:12 +00004362 default: break;
4363 }
4364 }
Chris Lattner2b55ea32004-02-23 07:16:20 +00004365 } else { // Not a SetEQ/SetNE
Misha Brukmanb1c93172005-04-21 23:48:37 +00004366 // If the LHS is a cast from an integral value of the same size,
Chris Lattner2b55ea32004-02-23 07:16:20 +00004367 if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
4368 Value *CastOp = Cast->getOperand(0);
4369 const Type *SrcTy = CastOp->getType();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004370 unsigned SrcTySize = SrcTy->getPrimitiveSizeInBits();
Chris Lattner2b55ea32004-02-23 07:16:20 +00004371 if (SrcTy != Cast->getType() && SrcTy->isInteger() &&
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004372 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00004373 assert((SrcTy->isSigned() ^ Cast->getType()->isSigned()) &&
Chris Lattner2b55ea32004-02-23 07:16:20 +00004374 "Source and destination signednesses should differ!");
4375 if (Cast->getType()->isSigned()) {
4376 // If this is a signed comparison, check for comparisons in the
4377 // vicinity of zero.
4378 if (I.getOpcode() == Instruction::SetLT && CI->isNullValue())
4379 // X < 0 => x > 127
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004380 return BinaryOperator::createSetGT(CastOp,
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004381 ConstantUInt::get(SrcTy, (1ULL << (SrcTySize-1))-1));
Chris Lattner2b55ea32004-02-23 07:16:20 +00004382 else if (I.getOpcode() == Instruction::SetGT &&
4383 cast<ConstantSInt>(CI)->getValue() == -1)
4384 // X > -1 => x < 128
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004385 return BinaryOperator::createSetLT(CastOp,
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004386 ConstantUInt::get(SrcTy, 1ULL << (SrcTySize-1)));
Chris Lattner2b55ea32004-02-23 07:16:20 +00004387 } else {
4388 ConstantUInt *CUI = cast<ConstantUInt>(CI);
4389 if (I.getOpcode() == Instruction::SetLT &&
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004390 CUI->getValue() == 1ULL << (SrcTySize-1))
Chris Lattner2b55ea32004-02-23 07:16:20 +00004391 // X < 128 => X > -1
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004392 return BinaryOperator::createSetGT(CastOp,
4393 ConstantSInt::get(SrcTy, -1));
Chris Lattner2b55ea32004-02-23 07:16:20 +00004394 else if (I.getOpcode() == Instruction::SetGT &&
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004395 CUI->getValue() == (1ULL << (SrcTySize-1))-1)
Chris Lattner2b55ea32004-02-23 07:16:20 +00004396 // X > 127 => X < 0
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004397 return BinaryOperator::createSetLT(CastOp,
4398 Constant::getNullValue(SrcTy));
Chris Lattner2b55ea32004-02-23 07:16:20 +00004399 }
4400 }
4401 }
Chris Lattnere967b342003-06-04 05:10:11 +00004402 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004403 }
4404
Chris Lattner77c32c32005-04-23 15:31:55 +00004405 // Handle setcc with constant RHS's that can be integer, FP or pointer.
4406 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
4407 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4408 switch (LHSI->getOpcode()) {
Chris Lattnera816eee2005-05-01 04:42:15 +00004409 case Instruction::GetElementPtr:
4410 if (RHSC->isNullValue()) {
4411 // Transform setcc GEP P, int 0, int 0, int 0, null -> setcc P, null
4412 bool isAllZeros = true;
4413 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
4414 if (!isa<Constant>(LHSI->getOperand(i)) ||
4415 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
4416 isAllZeros = false;
4417 break;
4418 }
4419 if (isAllZeros)
4420 return new SetCondInst(I.getOpcode(), LHSI->getOperand(0),
4421 Constant::getNullValue(LHSI->getOperand(0)->getType()));
4422 }
4423 break;
4424
Chris Lattner77c32c32005-04-23 15:31:55 +00004425 case Instruction::PHI:
4426 if (Instruction *NV = FoldOpIntoPhi(I))
4427 return NV;
4428 break;
4429 case Instruction::Select:
4430 // If either operand of the select is a constant, we can fold the
4431 // comparison into the select arms, which will cause one to be
4432 // constant folded and the select turned into a bitwise or.
4433 Value *Op1 = 0, *Op2 = 0;
4434 if (LHSI->hasOneUse()) {
4435 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
4436 // Fold the known value into the constant operand.
4437 Op1 = ConstantExpr::get(I.getOpcode(), C, RHSC);
4438 // Insert a new SetCC of the other select operand.
4439 Op2 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
4440 LHSI->getOperand(2), RHSC,
4441 I.getName()), I);
4442 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
4443 // Fold the known value into the constant operand.
4444 Op2 = ConstantExpr::get(I.getOpcode(), C, RHSC);
4445 // Insert a new SetCC of the other select operand.
4446 Op1 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
4447 LHSI->getOperand(1), RHSC,
4448 I.getName()), I);
4449 }
4450 }
Jeff Cohen82639852005-04-23 21:38:35 +00004451
Chris Lattner77c32c32005-04-23 15:31:55 +00004452 if (Op1)
4453 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
4454 break;
4455 }
4456 }
4457
Chris Lattner0798af32005-01-13 20:14:25 +00004458 // If we can optimize a 'setcc GEP, P' or 'setcc P, GEP', do so now.
4459 if (User *GEP = dyn_castGetElementPtr(Op0))
4460 if (Instruction *NI = FoldGEPSetCC(GEP, Op1, I.getOpcode(), I))
4461 return NI;
4462 if (User *GEP = dyn_castGetElementPtr(Op1))
4463 if (Instruction *NI = FoldGEPSetCC(GEP, Op0,
4464 SetCondInst::getSwappedCondition(I.getOpcode()), I))
4465 return NI;
4466
Chris Lattner16930792003-11-03 04:25:02 +00004467 // Test to see if the operands of the setcc are casted versions of other
4468 // values. If the cast can be stripped off both arguments, we do so now.
Chris Lattner6444c372003-11-03 05:17:03 +00004469 if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
4470 Value *CastOp0 = CI->getOperand(0);
4471 if (CastOp0->getType()->isLosslesslyConvertibleTo(CI->getType()) &&
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004472 (isa<Constant>(Op1) || isa<CastInst>(Op1)) && I.isEquality()) {
Chris Lattner16930792003-11-03 04:25:02 +00004473 // We keep moving the cast from the left operand over to the right
4474 // operand, where it can often be eliminated completely.
Chris Lattner6444c372003-11-03 05:17:03 +00004475 Op0 = CastOp0;
Misha Brukmanb1c93172005-04-21 23:48:37 +00004476
Chris Lattner16930792003-11-03 04:25:02 +00004477 // If operand #1 is a cast instruction, see if we can eliminate it as
4478 // well.
Chris Lattner6444c372003-11-03 05:17:03 +00004479 if (CastInst *CI2 = dyn_cast<CastInst>(Op1))
4480 if (CI2->getOperand(0)->getType()->isLosslesslyConvertibleTo(
Chris Lattner16930792003-11-03 04:25:02 +00004481 Op0->getType()))
Chris Lattner6444c372003-11-03 05:17:03 +00004482 Op1 = CI2->getOperand(0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004483
Chris Lattner16930792003-11-03 04:25:02 +00004484 // If Op1 is a constant, we can fold the cast into the constant.
4485 if (Op1->getType() != Op0->getType())
4486 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
4487 Op1 = ConstantExpr::getCast(Op1C, Op0->getType());
4488 } else {
4489 // Otherwise, cast the RHS right before the setcc
4490 Op1 = new CastInst(Op1, Op0->getType(), Op1->getName());
4491 InsertNewInstBefore(cast<Instruction>(Op1), I);
4492 }
4493 return BinaryOperator::create(I.getOpcode(), Op0, Op1);
4494 }
4495
Chris Lattner6444c372003-11-03 05:17:03 +00004496 // Handle the special case of: setcc (cast bool to X), <cst>
4497 // This comes up when you have code like
4498 // int X = A < B;
4499 // if (X) ...
4500 // For generality, we handle any zero-extension of any operand comparison
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004501 // with a constant or another cast from the same type.
4502 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
4503 if (Instruction *R = visitSetCondInstWithCastAndCast(I))
4504 return R;
Chris Lattner6444c372003-11-03 05:17:03 +00004505 }
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00004506
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004507 if (I.isEquality()) {
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00004508 Value *A, *B;
4509 if (match(Op0, m_Xor(m_Value(A), m_Value(B))) &&
4510 (A == Op1 || B == Op1)) {
4511 // (A^B) == A -> B == 0
4512 Value *OtherVal = A == Op1 ? B : A;
4513 return BinaryOperator::create(I.getOpcode(), OtherVal,
4514 Constant::getNullValue(A->getType()));
4515 } else if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
4516 (A == Op0 || B == Op0)) {
4517 // A == (A^B) -> B == 0
4518 Value *OtherVal = A == Op0 ? B : A;
4519 return BinaryOperator::create(I.getOpcode(), OtherVal,
4520 Constant::getNullValue(A->getType()));
4521 } else if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
4522 // (A-B) == A -> B == 0
4523 return BinaryOperator::create(I.getOpcode(), B,
4524 Constant::getNullValue(B->getType()));
4525 } else if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
4526 // A == (A-B) -> B == 0
4527 return BinaryOperator::create(I.getOpcode(), B,
4528 Constant::getNullValue(B->getType()));
4529 }
4530 }
Chris Lattner113f4f42002-06-25 16:13:24 +00004531 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004532}
4533
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004534// visitSetCondInstWithCastAndCast - Handle setcond (cast x to y), (cast/cst).
4535// We only handle extending casts so far.
4536//
4537Instruction *InstCombiner::visitSetCondInstWithCastAndCast(SetCondInst &SCI) {
4538 Value *LHSCIOp = cast<CastInst>(SCI.getOperand(0))->getOperand(0);
4539 const Type *SrcTy = LHSCIOp->getType();
4540 const Type *DestTy = SCI.getOperand(0)->getType();
4541 Value *RHSCIOp;
4542
4543 if (!DestTy->isIntegral() || !SrcTy->isIntegral())
Chris Lattner03f06f12005-01-17 03:20:02 +00004544 return 0;
4545
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004546 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
4547 unsigned DestBits = DestTy->getPrimitiveSizeInBits();
4548 if (SrcBits >= DestBits) return 0; // Only handle extending cast.
4549
4550 // Is this a sign or zero extension?
4551 bool isSignSrc = SrcTy->isSigned();
4552 bool isSignDest = DestTy->isSigned();
4553
4554 if (CastInst *CI = dyn_cast<CastInst>(SCI.getOperand(1))) {
4555 // Not an extension from the same type?
4556 RHSCIOp = CI->getOperand(0);
4557 if (RHSCIOp->getType() != LHSCIOp->getType()) return 0;
4558 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(SCI.getOperand(1))) {
4559 // Compute the constant that would happen if we truncated to SrcTy then
4560 // reextended to DestTy.
4561 Constant *Res = ConstantExpr::getCast(CI, SrcTy);
4562
4563 if (ConstantExpr::getCast(Res, DestTy) == CI) {
4564 RHSCIOp = Res;
4565 } else {
4566 // If the value cannot be represented in the shorter type, we cannot emit
4567 // a simple comparison.
4568 if (SCI.getOpcode() == Instruction::SetEQ)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004569 return ReplaceInstUsesWith(SCI, ConstantBool::getFalse());
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004570 if (SCI.getOpcode() == Instruction::SetNE)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004571 return ReplaceInstUsesWith(SCI, ConstantBool::getTrue());
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004572
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004573 // Evaluate the comparison for LT.
4574 Value *Result;
4575 if (DestTy->isSigned()) {
4576 // We're performing a signed comparison.
4577 if (isSignSrc) {
4578 // Signed extend and signed comparison.
4579 if (cast<ConstantSInt>(CI)->getValue() < 0) // X < (small) --> false
Chris Lattner6ab03f62006-09-28 23:35:22 +00004580 Result = ConstantBool::getFalse();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004581 else
Chris Lattner6ab03f62006-09-28 23:35:22 +00004582 Result = ConstantBool::getTrue(); // X < (large) --> true
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004583 } else {
4584 // Unsigned extend and signed comparison.
4585 if (cast<ConstantSInt>(CI)->getValue() < 0)
Chris Lattner6ab03f62006-09-28 23:35:22 +00004586 Result = ConstantBool::getFalse();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004587 else
Chris Lattner6ab03f62006-09-28 23:35:22 +00004588 Result = ConstantBool::getTrue();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004589 }
4590 } else {
4591 // We're performing an unsigned comparison.
4592 if (!isSignSrc) {
4593 // Unsigned extend & compare -> always true.
Chris Lattner6ab03f62006-09-28 23:35:22 +00004594 Result = ConstantBool::getTrue();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004595 } else {
4596 // We're performing an unsigned comp with a sign extended value.
4597 // This is true if the input is >= 0. [aka >s -1]
4598 Constant *NegOne = ConstantIntegral::getAllOnesValue(SrcTy);
4599 Result = InsertNewInstBefore(BinaryOperator::createSetGT(LHSCIOp,
4600 NegOne, SCI.getName()), SCI);
4601 }
Reid Spencer279fa252004-11-28 21:31:15 +00004602 }
Chris Lattner03f06f12005-01-17 03:20:02 +00004603
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00004604 // Finally, return the value computed.
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004605 if (SCI.getOpcode() == Instruction::SetLT) {
4606 return ReplaceInstUsesWith(SCI, Result);
4607 } else {
4608 assert(SCI.getOpcode()==Instruction::SetGT &&"SetCC should be folded!");
4609 if (Constant *CI = dyn_cast<Constant>(Result))
4610 return ReplaceInstUsesWith(SCI, ConstantExpr::getNot(CI));
4611 else
4612 return BinaryOperator::createNot(Result);
4613 }
Chris Lattner03f06f12005-01-17 03:20:02 +00004614 }
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004615 } else {
4616 return 0;
Reid Spencer279fa252004-11-28 21:31:15 +00004617 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004618
Chris Lattner252a8452005-06-16 03:00:08 +00004619 // Okay, just insert a compare of the reduced operands now!
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004620 return BinaryOperator::create(SCI.getOpcode(), LHSCIOp, RHSCIOp);
4621}
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004622
Chris Lattnere8d6c602003-03-10 19:16:08 +00004623Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +00004624 assert(I.getOperand(1)->getType() == Type::UByteTy);
4625 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00004626 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004627
4628 // shl X, 0 == X and shr X, 0 == X
4629 // shl 0, X == 0 and shr 0, X == 0
4630 if (Op1 == Constant::getNullValue(Type::UByteTy) ||
Chris Lattnere6794492002-08-12 21:17:25 +00004631 Op0 == Constant::getNullValue(Op0->getType()))
4632 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf5b4ef72006-02-12 08:07:37 +00004633
Chris Lattner81a7a232004-10-16 18:11:37 +00004634 if (isa<UndefValue>(Op0)) { // undef >>s X -> undef
4635 if (!isLeftShift && I.getType()->isSigned())
Chris Lattner67f05452004-10-16 23:28:04 +00004636 return ReplaceInstUsesWith(I, Op0);
Chris Lattner81a7a232004-10-16 18:11:37 +00004637 else // undef << X -> 0 AND undef >>u X -> 0
4638 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4639 }
4640 if (isa<UndefValue>(Op1)) {
Chris Lattner18aa4d82005-07-20 18:49:28 +00004641 if (isLeftShift || I.getType()->isUnsigned())// X << undef, X >>u undef -> 0
Chris Lattner81a7a232004-10-16 18:11:37 +00004642 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4643 else
4644 return ReplaceInstUsesWith(I, Op0); // X >>s undef -> X
4645 }
4646
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00004647 // shr int -1, X = -1 (for any arithmetic shift rights of ~0)
4648 if (!isLeftShift)
4649 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
4650 if (CSI->isAllOnesValue())
4651 return ReplaceInstUsesWith(I, CSI);
4652
Chris Lattner183b3362004-04-09 19:05:30 +00004653 // Try to fold constant and into select arguments.
4654 if (isa<Constant>(Op0))
4655 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner86102b82005-01-01 16:22:27 +00004656 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00004657 return R;
4658
Chris Lattnerb18dbbf2005-05-08 17:34:56 +00004659 // See if we can turn a signed shr into an unsigned shr.
Chris Lattnerb3f24c92006-09-18 04:22:48 +00004660 if (I.isArithmeticShift()) {
Chris Lattnerc3ebf402006-02-07 07:27:52 +00004661 if (MaskedValueIsZero(Op0,
4662 1ULL << (I.getType()->getPrimitiveSizeInBits()-1))) {
Chris Lattnerb18dbbf2005-05-08 17:34:56 +00004663 Value *V = InsertCastBefore(Op0, I.getType()->getUnsignedVersion(), I);
4664 V = InsertNewInstBefore(new ShiftInst(Instruction::Shr, V, Op1,
4665 I.getName()), I);
4666 return new CastInst(V, I.getType());
4667 }
4668 }
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00004669
Chris Lattner14553932006-01-06 07:12:35 +00004670 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op1))
4671 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
4672 return Res;
4673 return 0;
4674}
4675
4676Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantUInt *Op1,
4677 ShiftInst &I) {
4678 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattnerb3309392006-01-06 07:22:22 +00004679 bool isSignedShift = Op0->getType()->isSigned();
4680 bool isUnsignedShift = !isSignedShift;
Chris Lattner14553932006-01-06 07:12:35 +00004681
Chris Lattnerf5b4ef72006-02-12 08:07:37 +00004682 // See if we can simplify any instructions used by the instruction whose sole
4683 // purpose is to compute bits we don't care about.
4684 uint64_t KnownZero, KnownOne;
4685 if (SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
4686 KnownZero, KnownOne))
4687 return &I;
4688
Chris Lattner14553932006-01-06 07:12:35 +00004689 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
4690 // of a signed value.
4691 //
4692 unsigned TypeBits = Op0->getType()->getPrimitiveSizeInBits();
4693 if (Op1->getValue() >= TypeBits) {
Chris Lattnerb3309392006-01-06 07:22:22 +00004694 if (isUnsignedShift || isLeftShift)
Chris Lattner14553932006-01-06 07:12:35 +00004695 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
4696 else {
4697 I.setOperand(1, ConstantUInt::get(Type::UByteTy, TypeBits-1));
4698 return &I;
Chris Lattnerf5ce2542004-02-23 20:30:06 +00004699 }
Chris Lattner14553932006-01-06 07:12:35 +00004700 }
4701
4702 // ((X*C1) << C2) == (X * (C1 << C2))
4703 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
4704 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
4705 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
4706 return BinaryOperator::createMul(BO->getOperand(0),
4707 ConstantExpr::getShl(BOOp, Op1));
4708
4709 // Try to fold constant and into select arguments.
4710 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4711 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4712 return R;
4713 if (isa<PHINode>(Op0))
4714 if (Instruction *NV = FoldOpIntoPhi(I))
4715 return NV;
4716
4717 if (Op0->hasOneUse()) {
Chris Lattner14553932006-01-06 07:12:35 +00004718 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
4719 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
4720 Value *V1, *V2;
4721 ConstantInt *CC;
4722 switch (Op0BO->getOpcode()) {
Chris Lattner27cb9db2005-09-18 05:12:10 +00004723 default: break;
4724 case Instruction::Add:
4725 case Instruction::And:
4726 case Instruction::Or:
4727 case Instruction::Xor:
4728 // These operators commute.
4729 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner797dee72005-09-18 06:30:59 +00004730 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
4731 match(Op0BO->getOperand(1),
Chris Lattner14553932006-01-06 07:12:35 +00004732 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Chris Lattner797dee72005-09-18 06:30:59 +00004733 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00004734 Op0BO->getOperand(0), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00004735 Op0BO->getName());
4736 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner24cd2fa2006-02-09 07:41:14 +00004737 Instruction *X =
4738 BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
4739 Op0BO->getOperand(1)->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00004740 InsertNewInstBefore(X, I); // (X + (Y << C))
4741 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
Chris Lattner14553932006-01-06 07:12:35 +00004742 C2 = ConstantExpr::getShl(C2, Op1);
Chris Lattner797dee72005-09-18 06:30:59 +00004743 return BinaryOperator::createAnd(X, C2);
4744 }
Chris Lattner14553932006-01-06 07:12:35 +00004745
Chris Lattner797dee72005-09-18 06:30:59 +00004746 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
4747 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
4748 match(Op0BO->getOperand(1),
4749 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner14553932006-01-06 07:12:35 +00004750 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner24cd2fa2006-02-09 07:41:14 +00004751 cast<BinaryOperator>(Op0BO->getOperand(1))->getOperand(0)->hasOneUse()) {
Chris Lattner797dee72005-09-18 06:30:59 +00004752 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00004753 Op0BO->getOperand(0), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00004754 Op0BO->getName());
4755 InsertNewInstBefore(YS, I); // (Y << C)
4756 Instruction *XM =
Chris Lattner14553932006-01-06 07:12:35 +00004757 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner797dee72005-09-18 06:30:59 +00004758 V1->getName()+".mask");
4759 InsertNewInstBefore(XM, I); // X & (CC << C)
4760
4761 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
4762 }
Chris Lattner14553932006-01-06 07:12:35 +00004763
Chris Lattner797dee72005-09-18 06:30:59 +00004764 // FALL THROUGH.
Chris Lattner27cb9db2005-09-18 05:12:10 +00004765 case Instruction::Sub:
4766 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner797dee72005-09-18 06:30:59 +00004767 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
4768 match(Op0BO->getOperand(0),
Chris Lattner14553932006-01-06 07:12:35 +00004769 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Chris Lattner797dee72005-09-18 06:30:59 +00004770 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00004771 Op0BO->getOperand(1), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00004772 Op0BO->getName());
4773 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner24cd2fa2006-02-09 07:41:14 +00004774 Instruction *X =
Chris Lattner1df0e982006-05-31 21:14:00 +00004775 BinaryOperator::create(Op0BO->getOpcode(), V1, YS,
Chris Lattner24cd2fa2006-02-09 07:41:14 +00004776 Op0BO->getOperand(0)->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00004777 InsertNewInstBefore(X, I); // (X + (Y << C))
4778 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
Chris Lattner14553932006-01-06 07:12:35 +00004779 C2 = ConstantExpr::getShl(C2, Op1);
Chris Lattner797dee72005-09-18 06:30:59 +00004780 return BinaryOperator::createAnd(X, C2);
4781 }
Chris Lattner14553932006-01-06 07:12:35 +00004782
Chris Lattner1df0e982006-05-31 21:14:00 +00004783 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner797dee72005-09-18 06:30:59 +00004784 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
4785 match(Op0BO->getOperand(0),
4786 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner14553932006-01-06 07:12:35 +00004787 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner24cd2fa2006-02-09 07:41:14 +00004788 cast<BinaryOperator>(Op0BO->getOperand(0))
4789 ->getOperand(0)->hasOneUse()) {
Chris Lattner797dee72005-09-18 06:30:59 +00004790 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00004791 Op0BO->getOperand(1), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00004792 Op0BO->getName());
4793 InsertNewInstBefore(YS, I); // (Y << C)
4794 Instruction *XM =
Chris Lattner14553932006-01-06 07:12:35 +00004795 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner797dee72005-09-18 06:30:59 +00004796 V1->getName()+".mask");
4797 InsertNewInstBefore(XM, I); // X & (CC << C)
4798
Chris Lattner1df0e982006-05-31 21:14:00 +00004799 return BinaryOperator::create(Op0BO->getOpcode(), XM, YS);
Chris Lattner797dee72005-09-18 06:30:59 +00004800 }
Chris Lattner14553932006-01-06 07:12:35 +00004801
Chris Lattner27cb9db2005-09-18 05:12:10 +00004802 break;
Chris Lattner14553932006-01-06 07:12:35 +00004803 }
4804
4805
4806 // If the operand is an bitwise operator with a constant RHS, and the
4807 // shift is the only use, we can pull it out of the shift.
4808 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
4809 bool isValid = true; // Valid only for And, Or, Xor
4810 bool highBitSet = false; // Transform if high bit of constant set?
4811
4812 switch (Op0BO->getOpcode()) {
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00004813 default: isValid = false; break; // Do not perform transform!
Chris Lattner44bd3922004-10-08 03:46:20 +00004814 case Instruction::Add:
4815 isValid = isLeftShift;
4816 break;
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00004817 case Instruction::Or:
4818 case Instruction::Xor:
4819 highBitSet = false;
4820 break;
4821 case Instruction::And:
4822 highBitSet = true;
4823 break;
Chris Lattner14553932006-01-06 07:12:35 +00004824 }
4825
4826 // If this is a signed shift right, and the high bit is modified
4827 // by the logical operation, do not perform the transformation.
4828 // The highBitSet boolean indicates the value of the high bit of
4829 // the constant which would cause it to be modified for this
4830 // operation.
4831 //
Chris Lattnerb3309392006-01-06 07:22:22 +00004832 if (isValid && !isLeftShift && isSignedShift) {
Chris Lattner14553932006-01-06 07:12:35 +00004833 uint64_t Val = Op0C->getRawValue();
4834 isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
4835 }
4836
4837 if (isValid) {
4838 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
4839
4840 Instruction *NewShift =
4841 new ShiftInst(I.getOpcode(), Op0BO->getOperand(0), Op1,
4842 Op0BO->getName());
4843 Op0BO->setName("");
4844 InsertNewInstBefore(NewShift, I);
4845
4846 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
4847 NewRHS);
4848 }
4849 }
4850 }
4851 }
4852
Chris Lattnereb372a02006-01-06 07:52:12 +00004853 // Find out if this is a shift of a shift by a constant.
4854 ShiftInst *ShiftOp = 0;
Chris Lattner14553932006-01-06 07:12:35 +00004855 if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0))
Chris Lattnereb372a02006-01-06 07:52:12 +00004856 ShiftOp = Op0SI;
4857 else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
4858 // If this is a noop-integer case of a shift instruction, use the shift.
4859 if (CI->getOperand(0)->getType()->isInteger() &&
4860 CI->getOperand(0)->getType()->getPrimitiveSizeInBits() ==
4861 CI->getType()->getPrimitiveSizeInBits() &&
4862 isa<ShiftInst>(CI->getOperand(0))) {
4863 ShiftOp = cast<ShiftInst>(CI->getOperand(0));
4864 }
4865 }
4866
4867 if (ShiftOp && isa<ConstantUInt>(ShiftOp->getOperand(1))) {
4868 // Find the operands and properties of the input shift. Note that the
4869 // signedness of the input shift may differ from the current shift if there
4870 // is a noop cast between the two.
4871 bool isShiftOfLeftShift = ShiftOp->getOpcode() == Instruction::Shl;
4872 bool isShiftOfSignedShift = ShiftOp->getType()->isSigned();
Chris Lattner9cbfbc22006-01-07 01:32:28 +00004873 bool isShiftOfUnsignedShift = !isShiftOfSignedShift;
Chris Lattnereb372a02006-01-06 07:52:12 +00004874
4875 ConstantUInt *ShiftAmt1C = cast<ConstantUInt>(ShiftOp->getOperand(1));
4876
4877 unsigned ShiftAmt1 = (unsigned)ShiftAmt1C->getValue();
4878 unsigned ShiftAmt2 = (unsigned)Op1->getValue();
4879
4880 // Check for (A << c1) << c2 and (A >> c1) >> c2.
4881 if (isLeftShift == isShiftOfLeftShift) {
4882 // Do not fold these shifts if the first one is signed and the second one
4883 // is unsigned and this is a right shift. Further, don't do any folding
4884 // on them.
4885 if (isShiftOfSignedShift && isUnsignedShift && !isLeftShift)
4886 return 0;
Chris Lattner14553932006-01-06 07:12:35 +00004887
Chris Lattnereb372a02006-01-06 07:52:12 +00004888 unsigned Amt = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
4889 if (Amt > Op0->getType()->getPrimitiveSizeInBits())
4890 Amt = Op0->getType()->getPrimitiveSizeInBits();
Chris Lattner14553932006-01-06 07:12:35 +00004891
Chris Lattnereb372a02006-01-06 07:52:12 +00004892 Value *Op = ShiftOp->getOperand(0);
4893 if (isShiftOfSignedShift != isSignedShift)
4894 Op = InsertNewInstBefore(new CastInst(Op, I.getType(), "tmp"), I);
4895 return new ShiftInst(I.getOpcode(), Op,
4896 ConstantUInt::get(Type::UByteTy, Amt));
4897 }
4898
4899 // Check for (A << c1) >> c2 or (A >> c1) << c2. If we are dealing with
4900 // signed types, we can only support the (A >> c1) << c2 configuration,
4901 // because it can not turn an arbitrary bit of A into a sign bit.
4902 if (isUnsignedShift || isLeftShift) {
4903 // Calculate bitmask for what gets shifted off the edge.
4904 Constant *C = ConstantIntegral::getAllOnesValue(I.getType());
4905 if (isLeftShift)
4906 C = ConstantExpr::getShl(C, ShiftAmt1C);
4907 else
Chris Lattner9cbfbc22006-01-07 01:32:28 +00004908 C = ConstantExpr::getUShr(C, ShiftAmt1C);
Chris Lattnereb372a02006-01-06 07:52:12 +00004909
4910 Value *Op = ShiftOp->getOperand(0);
4911 if (isShiftOfSignedShift != isSignedShift)
4912 Op = InsertNewInstBefore(new CastInst(Op, I.getType(),Op->getName()),I);
4913
4914 Instruction *Mask =
4915 BinaryOperator::createAnd(Op, C, Op->getName()+".mask");
4916 InsertNewInstBefore(Mask, I);
4917
4918 // Figure out what flavor of shift we should use...
Chris Lattner9cbfbc22006-01-07 01:32:28 +00004919 if (ShiftAmt1 == ShiftAmt2) {
Chris Lattnereb372a02006-01-06 07:52:12 +00004920 return ReplaceInstUsesWith(I, Mask); // (A << c) >> c === A & c2
Chris Lattner9cbfbc22006-01-07 01:32:28 +00004921 } else if (ShiftAmt1 < ShiftAmt2) {
Chris Lattnereb372a02006-01-06 07:52:12 +00004922 return new ShiftInst(I.getOpcode(), Mask,
4923 ConstantUInt::get(Type::UByteTy, ShiftAmt2-ShiftAmt1));
Chris Lattner9cbfbc22006-01-07 01:32:28 +00004924 } else if (isShiftOfUnsignedShift || isShiftOfLeftShift) {
4925 if (isShiftOfUnsignedShift && !isShiftOfLeftShift && isSignedShift) {
4926 // Make sure to emit an unsigned shift right, not a signed one.
4927 Mask = InsertNewInstBefore(new CastInst(Mask,
4928 Mask->getType()->getUnsignedVersion(),
4929 Op->getName()), I);
4930 Mask = new ShiftInst(Instruction::Shr, Mask,
Chris Lattnereb372a02006-01-06 07:52:12 +00004931 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
Chris Lattner9cbfbc22006-01-07 01:32:28 +00004932 InsertNewInstBefore(Mask, I);
4933 return new CastInst(Mask, I.getType());
4934 } else {
4935 return new ShiftInst(ShiftOp->getOpcode(), Mask,
4936 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
4937 }
4938 } else {
4939 // (X >>s C1) << C2 where C1 > C2 === (X >>s (C1-C2)) & mask
4940 Op = InsertNewInstBefore(new CastInst(Mask,
4941 I.getType()->getSignedVersion(),
4942 Mask->getName()), I);
4943 Instruction *Shift =
4944 new ShiftInst(ShiftOp->getOpcode(), Op,
4945 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
4946 InsertNewInstBefore(Shift, I);
4947
4948 C = ConstantIntegral::getAllOnesValue(Shift->getType());
4949 C = ConstantExpr::getShl(C, Op1);
4950 Mask = BinaryOperator::createAnd(Shift, C, Op->getName()+".mask");
4951 InsertNewInstBefore(Mask, I);
4952 return new CastInst(Mask, I.getType());
Chris Lattnereb372a02006-01-06 07:52:12 +00004953 }
4954 } else {
Chris Lattner9cbfbc22006-01-07 01:32:28 +00004955 // We can handle signed (X << C1) >>s C2 if it's a sign extend. In
Chris Lattnereb372a02006-01-06 07:52:12 +00004956 // this case, C1 == C2 and C1 is 8, 16, or 32.
4957 if (ShiftAmt1 == ShiftAmt2) {
4958 const Type *SExtType = 0;
Chris Lattner655d08f2006-04-28 22:21:41 +00004959 switch (Op0->getType()->getPrimitiveSizeInBits() - ShiftAmt1) {
Chris Lattnereb372a02006-01-06 07:52:12 +00004960 case 8 : SExtType = Type::SByteTy; break;
4961 case 16: SExtType = Type::ShortTy; break;
4962 case 32: SExtType = Type::IntTy; break;
4963 }
4964
4965 if (SExtType) {
4966 Instruction *NewTrunc = new CastInst(ShiftOp->getOperand(0),
4967 SExtType, "sext");
4968 InsertNewInstBefore(NewTrunc, I);
4969 return new CastInst(NewTrunc, I.getType());
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00004970 }
Chris Lattner27cb9db2005-09-18 05:12:10 +00004971 }
Chris Lattner86102b82005-01-01 16:22:27 +00004972 }
Chris Lattnereb372a02006-01-06 07:52:12 +00004973 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004974 return 0;
4975}
4976
Chris Lattner48a44f72002-05-02 17:06:02 +00004977
Chris Lattner8f663e82005-10-29 04:36:15 +00004978/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
4979/// expression. If so, decompose it, returning some value X, such that Val is
4980/// X*Scale+Offset.
4981///
4982static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
4983 unsigned &Offset) {
4984 assert(Val->getType() == Type::UIntTy && "Unexpected allocation size type!");
4985 if (ConstantUInt *CI = dyn_cast<ConstantUInt>(Val)) {
4986 Offset = CI->getValue();
4987 Scale = 1;
4988 return ConstantUInt::get(Type::UIntTy, 0);
4989 } else if (Instruction *I = dyn_cast<Instruction>(Val)) {
4990 if (I->getNumOperands() == 2) {
4991 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(I->getOperand(1))) {
4992 if (I->getOpcode() == Instruction::Shl) {
4993 // This is a value scaled by '1 << the shift amt'.
4994 Scale = 1U << CUI->getValue();
4995 Offset = 0;
4996 return I->getOperand(0);
4997 } else if (I->getOpcode() == Instruction::Mul) {
4998 // This value is scaled by 'CUI'.
4999 Scale = CUI->getValue();
5000 Offset = 0;
5001 return I->getOperand(0);
5002 } else if (I->getOpcode() == Instruction::Add) {
5003 // We have X+C. Check to see if we really have (X*C2)+C1, where C1 is
5004 // divisible by C2.
5005 unsigned SubScale;
5006 Value *SubVal = DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
5007 Offset);
5008 Offset += CUI->getValue();
5009 if (SubScale > 1 && (Offset % SubScale == 0)) {
5010 Scale = SubScale;
5011 return SubVal;
5012 }
5013 }
5014 }
5015 }
5016 }
5017
5018 // Otherwise, we can't look past this.
5019 Scale = 1;
5020 Offset = 0;
5021 return Val;
5022}
5023
5024
Chris Lattner216be912005-10-24 06:03:58 +00005025/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
5026/// try to eliminate the cast by moving the type information into the alloc.
5027Instruction *InstCombiner::PromoteCastOfAllocation(CastInst &CI,
5028 AllocationInst &AI) {
5029 const PointerType *PTy = dyn_cast<PointerType>(CI.getType());
Chris Lattnerbb171802005-10-27 05:53:56 +00005030 if (!PTy) return 0; // Not casting the allocation to a pointer type.
Chris Lattner216be912005-10-24 06:03:58 +00005031
Chris Lattnerac87beb2005-10-24 06:22:12 +00005032 // Remove any uses of AI that are dead.
5033 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
5034 std::vector<Instruction*> DeadUsers;
5035 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
5036 Instruction *User = cast<Instruction>(*UI++);
5037 if (isInstructionTriviallyDead(User)) {
5038 while (UI != E && *UI == User)
5039 ++UI; // If this instruction uses AI more than once, don't break UI.
5040
5041 // Add operands to the worklist.
5042 AddUsesToWorkList(*User);
5043 ++NumDeadInst;
5044 DEBUG(std::cerr << "IC: DCE: " << *User);
5045
5046 User->eraseFromParent();
5047 removeFromWorkList(User);
5048 }
5049 }
5050
Chris Lattner216be912005-10-24 06:03:58 +00005051 // Get the type really allocated and the type casted to.
5052 const Type *AllocElTy = AI.getAllocatedType();
5053 const Type *CastElTy = PTy->getElementType();
5054 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner355ecc02005-10-24 06:26:18 +00005055
Chris Lattner7d190672006-10-01 19:40:58 +00005056 unsigned AllocElTyAlign = TD->getTypeAlignment(AllocElTy);
5057 unsigned CastElTyAlign = TD->getTypeAlignment(CastElTy);
Chris Lattner355ecc02005-10-24 06:26:18 +00005058 if (CastElTyAlign < AllocElTyAlign) return 0;
5059
Chris Lattner46705b22005-10-24 06:35:18 +00005060 // If the allocation has multiple uses, only promote it if we are strictly
5061 // increasing the alignment of the resultant allocation. If we keep it the
5062 // same, we open the door to infinite loops of various kinds.
5063 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
5064
Chris Lattner216be912005-10-24 06:03:58 +00005065 uint64_t AllocElTySize = TD->getTypeSize(AllocElTy);
5066 uint64_t CastElTySize = TD->getTypeSize(CastElTy);
Chris Lattnerbb171802005-10-27 05:53:56 +00005067 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner355ecc02005-10-24 06:26:18 +00005068
Chris Lattner8270c332005-10-29 03:19:53 +00005069 // See if we can satisfy the modulus by pulling a scale out of the array
5070 // size argument.
Chris Lattner8f663e82005-10-29 04:36:15 +00005071 unsigned ArraySizeScale, ArrayOffset;
5072 Value *NumElements = // See if the array size is a decomposable linear expr.
5073 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
5074
Chris Lattner8270c332005-10-29 03:19:53 +00005075 // If we can now satisfy the modulus, by using a non-1 scale, we really can
5076 // do the xform.
Chris Lattner8f663e82005-10-29 04:36:15 +00005077 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
5078 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattnerb3ecf962005-10-27 06:12:00 +00005079
Chris Lattner8270c332005-10-29 03:19:53 +00005080 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
5081 Value *Amt = 0;
5082 if (Scale == 1) {
5083 Amt = NumElements;
5084 } else {
5085 Amt = ConstantUInt::get(Type::UIntTy, Scale);
5086 if (ConstantUInt *CI = dyn_cast<ConstantUInt>(NumElements))
5087 Amt = ConstantExpr::getMul(CI, cast<ConstantUInt>(Amt));
5088 else if (Scale != 1) {
5089 Instruction *Tmp = BinaryOperator::createMul(Amt, NumElements, "tmp");
5090 Amt = InsertNewInstBefore(Tmp, AI);
Chris Lattnerb3ecf962005-10-27 06:12:00 +00005091 }
Chris Lattnerbb171802005-10-27 05:53:56 +00005092 }
5093
Chris Lattner8f663e82005-10-29 04:36:15 +00005094 if (unsigned Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
5095 Value *Off = ConstantUInt::get(Type::UIntTy, Offset);
5096 Instruction *Tmp = BinaryOperator::createAdd(Amt, Off, "tmp");
5097 Amt = InsertNewInstBefore(Tmp, AI);
5098 }
5099
Chris Lattner216be912005-10-24 06:03:58 +00005100 std::string Name = AI.getName(); AI.setName("");
5101 AllocationInst *New;
5102 if (isa<MallocInst>(AI))
Nate Begeman848622f2005-11-05 09:21:28 +00005103 New = new MallocInst(CastElTy, Amt, AI.getAlignment(), Name);
Chris Lattner216be912005-10-24 06:03:58 +00005104 else
Nate Begeman848622f2005-11-05 09:21:28 +00005105 New = new AllocaInst(CastElTy, Amt, AI.getAlignment(), Name);
Chris Lattner216be912005-10-24 06:03:58 +00005106 InsertNewInstBefore(New, AI);
Chris Lattner46705b22005-10-24 06:35:18 +00005107
5108 // If the allocation has multiple uses, insert a cast and change all things
5109 // that used it to use the new cast. This will also hack on CI, but it will
5110 // die soon.
5111 if (!AI.hasOneUse()) {
5112 AddUsesToWorkList(AI);
5113 CastInst *NewCast = new CastInst(New, AI.getType(), "tmpcast");
5114 InsertNewInstBefore(NewCast, AI);
5115 AI.replaceAllUsesWith(NewCast);
5116 }
Chris Lattner216be912005-10-24 06:03:58 +00005117 return ReplaceInstUsesWith(CI, New);
5118}
5119
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005120/// CanEvaluateInDifferentType - Return true if we can take the specified value
5121/// and return it without inserting any new casts. This is used by code that
5122/// tries to decide whether promoting or shrinking integer operations to wider
5123/// or smaller types will allow us to eliminate a truncate or extend.
5124static bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
5125 int &NumCastsRemoved) {
5126 if (isa<Constant>(V)) return true;
5127
5128 Instruction *I = dyn_cast<Instruction>(V);
5129 if (!I || !I->hasOneUse()) return false;
5130
5131 switch (I->getOpcode()) {
5132 case Instruction::And:
5133 case Instruction::Or:
5134 case Instruction::Xor:
5135 // These operators can all arbitrarily be extended or truncated.
5136 return CanEvaluateInDifferentType(I->getOperand(0), Ty, NumCastsRemoved) &&
5137 CanEvaluateInDifferentType(I->getOperand(1), Ty, NumCastsRemoved);
5138 case Instruction::Cast:
5139 // If this is a cast from the destination type, we can trivially eliminate
5140 // it, and this will remove a cast overall.
5141 if (I->getOperand(0)->getType() == Ty) {
Chris Lattner3fda3862006-06-28 17:34:50 +00005142 // If the first operand is itself a cast, and is eliminable, do not count
5143 // this as an eliminable cast. We would prefer to eliminate those two
5144 // casts first.
5145 if (CastInst *OpCast = dyn_cast<CastInst>(I->getOperand(0)))
5146 return true;
5147
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005148 ++NumCastsRemoved;
5149 return true;
5150 }
5151 // TODO: Can handle more cases here.
5152 break;
5153 }
5154
5155 return false;
5156}
5157
5158/// EvaluateInDifferentType - Given an expression that
5159/// CanEvaluateInDifferentType returns true for, actually insert the code to
5160/// evaluate the expression.
5161Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty) {
5162 if (Constant *C = dyn_cast<Constant>(V))
5163 return ConstantExpr::getCast(C, Ty);
5164
5165 // Otherwise, it must be an instruction.
5166 Instruction *I = cast<Instruction>(V);
Chris Lattnerd0622b62006-05-20 23:14:03 +00005167 Instruction *Res = 0;
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005168 switch (I->getOpcode()) {
5169 case Instruction::And:
5170 case Instruction::Or:
5171 case Instruction::Xor: {
5172 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty);
5173 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty);
5174 Res = BinaryOperator::create((Instruction::BinaryOps)I->getOpcode(),
5175 LHS, RHS, I->getName());
5176 break;
5177 }
5178 case Instruction::Cast:
5179 // If this is a cast from the destination type, return the input.
5180 if (I->getOperand(0)->getType() == Ty)
5181 return I->getOperand(0);
5182
5183 // TODO: Can handle more cases here.
5184 assert(0 && "Unreachable!");
5185 break;
5186 }
5187
5188 return InsertNewInstBefore(Res, *I);
5189}
5190
Chris Lattner216be912005-10-24 06:03:58 +00005191
Chris Lattner48a44f72002-05-02 17:06:02 +00005192// CastInst simplification
Chris Lattner260ab202002-04-18 17:39:14 +00005193//
Chris Lattner113f4f42002-06-25 16:13:24 +00005194Instruction *InstCombiner::visitCastInst(CastInst &CI) {
Chris Lattner55d4bda2003-06-23 21:59:52 +00005195 Value *Src = CI.getOperand(0);
5196
Chris Lattner48a44f72002-05-02 17:06:02 +00005197 // If the user is casting a value to the same type, eliminate this cast
5198 // instruction...
Chris Lattner55d4bda2003-06-23 21:59:52 +00005199 if (CI.getType() == Src->getType())
5200 return ReplaceInstUsesWith(CI, Src);
Chris Lattner48a44f72002-05-02 17:06:02 +00005201
Chris Lattner81a7a232004-10-16 18:11:37 +00005202 if (isa<UndefValue>(Src)) // cast undef -> undef
5203 return ReplaceInstUsesWith(CI, UndefValue::get(CI.getType()));
5204
Chris Lattner48a44f72002-05-02 17:06:02 +00005205 // If casting the result of another cast instruction, try to eliminate this
5206 // one!
5207 //
Chris Lattner86102b82005-01-01 16:22:27 +00005208 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
5209 Value *A = CSrc->getOperand(0);
5210 if (isEliminableCastOfCast(A->getType(), CSrc->getType(),
5211 CI.getType(), TD)) {
Chris Lattner48a44f72002-05-02 17:06:02 +00005212 // This instruction now refers directly to the cast's src operand. This
5213 // has a good chance of making CSrc dead.
Chris Lattner113f4f42002-06-25 16:13:24 +00005214 CI.setOperand(0, CSrc->getOperand(0));
5215 return &CI;
Chris Lattner48a44f72002-05-02 17:06:02 +00005216 }
5217
Chris Lattner650b6da2002-08-02 20:00:25 +00005218 // If this is an A->B->A cast, and we are dealing with integral types, try
5219 // to convert this into a logical 'and' instruction.
5220 //
Misha Brukmanb1c93172005-04-21 23:48:37 +00005221 if (A->getType()->isInteger() &&
Chris Lattnerb0b412e2002-09-03 01:08:28 +00005222 CI.getType()->isInteger() && CSrc->getType()->isInteger() &&
Chris Lattner86102b82005-01-01 16:22:27 +00005223 CSrc->getType()->isUnsigned() && // B->A cast must zero extend
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005224 CSrc->getType()->getPrimitiveSizeInBits() <
5225 CI.getType()->getPrimitiveSizeInBits()&&
5226 A->getType()->getPrimitiveSizeInBits() ==
5227 CI.getType()->getPrimitiveSizeInBits()) {
Chris Lattner650b6da2002-08-02 20:00:25 +00005228 assert(CSrc->getType() != Type::ULongTy &&
5229 "Cannot have type bigger than ulong!");
Chris Lattner77defba2006-02-07 07:00:41 +00005230 uint64_t AndValue = CSrc->getType()->getIntegralTypeMask();
Chris Lattner86102b82005-01-01 16:22:27 +00005231 Constant *AndOp = ConstantUInt::get(A->getType()->getUnsignedVersion(),
5232 AndValue);
5233 AndOp = ConstantExpr::getCast(AndOp, A->getType());
5234 Instruction *And = BinaryOperator::createAnd(CSrc->getOperand(0), AndOp);
5235 if (And->getType() != CI.getType()) {
5236 And->setName(CSrc->getName()+".mask");
5237 InsertNewInstBefore(And, CI);
5238 And = new CastInst(And, CI.getType());
5239 }
5240 return And;
Chris Lattner650b6da2002-08-02 20:00:25 +00005241 }
5242 }
Chris Lattner2590e512006-02-07 06:56:34 +00005243
Chris Lattner03841652004-05-25 04:29:21 +00005244 // If this is a cast to bool, turn it into the appropriate setne instruction.
5245 if (CI.getType() == Type::BoolTy)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00005246 return BinaryOperator::createSetNE(CI.getOperand(0),
Chris Lattner03841652004-05-25 04:29:21 +00005247 Constant::getNullValue(CI.getOperand(0)->getType()));
5248
Chris Lattner2590e512006-02-07 06:56:34 +00005249 // See if we can simplify any instructions used by the LHS whose sole
5250 // purpose is to compute bits we don't care about.
Chris Lattner0157e7f2006-02-11 09:31:47 +00005251 if (CI.getType()->isInteger() && CI.getOperand(0)->getType()->isIntegral()) {
5252 uint64_t KnownZero, KnownOne;
5253 if (SimplifyDemandedBits(&CI, CI.getType()->getIntegralTypeMask(),
5254 KnownZero, KnownOne))
5255 return &CI;
5256 }
Chris Lattner2590e512006-02-07 06:56:34 +00005257
Chris Lattnerd0d51602003-06-21 23:12:02 +00005258 // If casting the result of a getelementptr instruction with no offset, turn
5259 // this into a cast of the original pointer!
5260 //
Chris Lattner55d4bda2003-06-23 21:59:52 +00005261 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattnerd0d51602003-06-21 23:12:02 +00005262 bool AllZeroOperands = true;
5263 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
5264 if (!isa<Constant>(GEP->getOperand(i)) ||
5265 !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
5266 AllZeroOperands = false;
5267 break;
5268 }
5269 if (AllZeroOperands) {
5270 CI.setOperand(0, GEP->getOperand(0));
5271 return &CI;
5272 }
5273 }
5274
Chris Lattnerf4ad1652003-11-02 05:57:39 +00005275 // If we are casting a malloc or alloca to a pointer to a type of the same
5276 // size, rewrite the allocation instruction to allocate the "right" type.
5277 //
5278 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
Chris Lattner216be912005-10-24 06:03:58 +00005279 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
5280 return V;
Chris Lattnerf4ad1652003-11-02 05:57:39 +00005281
Chris Lattner86102b82005-01-01 16:22:27 +00005282 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
5283 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
5284 return NV;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00005285 if (isa<PHINode>(Src))
5286 if (Instruction *NV = FoldOpIntoPhi(CI))
5287 return NV;
Chris Lattnerb19a5c62006-04-12 18:09:35 +00005288
5289 // If the source and destination are pointers, and this cast is equivalent to
5290 // a getelementptr X, 0, 0, 0... turn it into the appropriate getelementptr.
5291 // This can enhance SROA and other transforms that want type-safe pointers.
5292 if (const PointerType *DstPTy = dyn_cast<PointerType>(CI.getType()))
5293 if (const PointerType *SrcPTy = dyn_cast<PointerType>(Src->getType())) {
5294 const Type *DstTy = DstPTy->getElementType();
5295 const Type *SrcTy = SrcPTy->getElementType();
5296
5297 Constant *ZeroUInt = Constant::getNullValue(Type::UIntTy);
5298 unsigned NumZeros = 0;
5299 while (SrcTy != DstTy &&
Chris Lattnerd2862702006-09-11 21:43:16 +00005300 isa<CompositeType>(SrcTy) && !isa<PointerType>(SrcTy) &&
5301 SrcTy->getNumContainedTypes() /* not "{}" */) {
Chris Lattnerb19a5c62006-04-12 18:09:35 +00005302 SrcTy = cast<CompositeType>(SrcTy)->getTypeAtIndex(ZeroUInt);
5303 ++NumZeros;
5304 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00005305
Chris Lattnerb19a5c62006-04-12 18:09:35 +00005306 // If we found a path from the src to dest, create the getelementptr now.
5307 if (SrcTy == DstTy) {
5308 std::vector<Value*> Idxs(NumZeros+1, ZeroUInt);
5309 return new GetElementPtrInst(Src, Idxs);
5310 }
5311 }
5312
Chris Lattnerdfae8be2003-07-24 17:35:25 +00005313 // If the source value is an instruction with only this use, we can attempt to
5314 // propagate the cast into the instruction. Also, only handle integral types
5315 // for now.
Chris Lattner99155be2006-05-25 23:24:33 +00005316 if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
Chris Lattnerf95d9b92003-10-15 16:48:29 +00005317 if (SrcI->hasOneUse() && Src->getType()->isIntegral() &&
Chris Lattnerdfae8be2003-07-24 17:35:25 +00005318 CI.getType()->isInteger()) { // Don't mess with casts to bool here
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005319
5320 int NumCastsRemoved = 0;
5321 if (CanEvaluateInDifferentType(SrcI, CI.getType(), NumCastsRemoved)) {
5322 // If this cast is a truncate, evaluting in a different type always
5323 // eliminates the cast, so it is always a win. If this is a noop-cast
5324 // this just removes a noop cast which isn't pointful, but simplifies
5325 // the code. If this is a zero-extension, we need to do an AND to
5326 // maintain the clear top-part of the computation, so we require that
5327 // the input have eliminated at least one cast. If this is a sign
5328 // extension, we insert two new casts (to do the extension) so we
5329 // require that two casts have been eliminated.
5330 bool DoXForm;
5331 switch (getCastType(Src->getType(), CI.getType())) {
5332 default: assert(0 && "Unknown cast type!");
5333 case Noop:
5334 case Truncate:
5335 DoXForm = true;
5336 break;
5337 case Zeroext:
5338 DoXForm = NumCastsRemoved >= 1;
5339 break;
5340 case Signext:
5341 DoXForm = NumCastsRemoved >= 2;
5342 break;
5343 }
5344
5345 if (DoXForm) {
5346 Value *Res = EvaluateInDifferentType(SrcI, CI.getType());
5347 assert(Res->getType() == CI.getType());
5348 switch (getCastType(Src->getType(), CI.getType())) {
5349 default: assert(0 && "Unknown cast type!");
5350 case Noop:
5351 case Truncate:
5352 // Just replace this cast with the result.
5353 return ReplaceInstUsesWith(CI, Res);
5354 case Zeroext: {
5355 // We need to emit an AND to clear the high bits.
5356 unsigned SrcBitSize = Src->getType()->getPrimitiveSizeInBits();
5357 unsigned DestBitSize = CI.getType()->getPrimitiveSizeInBits();
5358 assert(SrcBitSize < DestBitSize && "Not a zext?");
5359 Constant *C = ConstantUInt::get(Type::ULongTy, (1 << SrcBitSize)-1);
5360 C = ConstantExpr::getCast(C, CI.getType());
5361 return BinaryOperator::createAnd(Res, C);
5362 }
5363 case Signext:
5364 // We need to emit a cast to truncate, then a cast to sext.
5365 return new CastInst(InsertCastBefore(Res, Src->getType(), CI),
5366 CI.getType());
5367 }
5368 }
5369 }
5370
Chris Lattnerdfae8be2003-07-24 17:35:25 +00005371 const Type *DestTy = CI.getType();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005372 unsigned SrcBitSize = Src->getType()->getPrimitiveSizeInBits();
5373 unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
Chris Lattnerdfae8be2003-07-24 17:35:25 +00005374
5375 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
5376 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
5377
5378 switch (SrcI->getOpcode()) {
5379 case Instruction::Add:
5380 case Instruction::Mul:
5381 case Instruction::And:
5382 case Instruction::Or:
5383 case Instruction::Xor:
5384 // If we are discarding information, or just changing the sign, rewrite.
5385 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
5386 // Don't insert two casts if they cannot be eliminated. We allow two
5387 // casts to be inserted if the sizes are the same. This could only be
5388 // converting signedness, which is a noop.
Chris Lattner11ffd592004-07-20 05:21:00 +00005389 if (DestBitSize == SrcBitSize || !ValueRequiresCast(Op1, DestTy,TD) ||
5390 !ValueRequiresCast(Op0, DestTy, TD)) {
Chris Lattnerdfae8be2003-07-24 17:35:25 +00005391 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
5392 Value *Op1c = InsertOperandCastBefore(Op1, DestTy, SrcI);
5393 return BinaryOperator::create(cast<BinaryOperator>(SrcI)
5394 ->getOpcode(), Op0c, Op1c);
5395 }
5396 }
Chris Lattner72086162005-05-06 02:07:39 +00005397
5398 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
5399 if (SrcBitSize == 1 && SrcI->getOpcode() == Instruction::Xor &&
Chris Lattner6ab03f62006-09-28 23:35:22 +00005400 Op1 == ConstantBool::getTrue() &&
Chris Lattner72086162005-05-06 02:07:39 +00005401 (!Op0->hasOneUse() || !isa<SetCondInst>(Op0))) {
5402 Value *New = InsertOperandCastBefore(Op0, DestTy, &CI);
5403 return BinaryOperator::createXor(New,
5404 ConstantInt::get(CI.getType(), 1));
5405 }
Chris Lattnerdfae8be2003-07-24 17:35:25 +00005406 break;
5407 case Instruction::Shl:
5408 // Allow changing the sign of the source operand. Do not allow changing
5409 // the size of the shift, UNLESS the shift amount is a constant. We
5410 // mush not change variable sized shifts to a smaller size, because it
5411 // is undefined to shift more bits out than exist in the value.
5412 if (DestBitSize == SrcBitSize ||
5413 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
5414 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
5415 return new ShiftInst(Instruction::Shl, Op0c, Op1);
5416 }
5417 break;
Chris Lattner87380412005-05-06 04:18:52 +00005418 case Instruction::Shr:
5419 // If this is a signed shr, and if all bits shifted in are about to be
5420 // truncated off, turn it into an unsigned shr to allow greater
5421 // simplifications.
5422 if (DestBitSize < SrcBitSize && Src->getType()->isSigned() &&
5423 isa<ConstantInt>(Op1)) {
5424 unsigned ShiftAmt = cast<ConstantUInt>(Op1)->getValue();
5425 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
5426 // Convert to unsigned.
5427 Value *N1 = InsertOperandCastBefore(Op0,
5428 Op0->getType()->getUnsignedVersion(), &CI);
5429 // Insert the new shift, which is now unsigned.
5430 N1 = InsertNewInstBefore(new ShiftInst(Instruction::Shr, N1,
5431 Op1, Src->getName()), CI);
5432 return new CastInst(N1, CI.getType());
5433 }
5434 }
5435 break;
5436
Chris Lattnerc7bfed02006-02-27 02:38:23 +00005437 case Instruction::SetEQ:
Chris Lattner809dfac2005-05-04 19:10:26 +00005438 case Instruction::SetNE:
Chris Lattnerc7bfed02006-02-27 02:38:23 +00005439 // We if we are just checking for a seteq of a single bit and casting it
5440 // to an integer. If so, shift the bit to the appropriate place then
5441 // cast to integer to avoid the comparison.
Chris Lattner809dfac2005-05-04 19:10:26 +00005442 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerc7bfed02006-02-27 02:38:23 +00005443 uint64_t Op1CV = Op1C->getZExtValue();
5444 // cast (X == 0) to int --> X^1 iff X has only the low bit set.
5445 // cast (X == 0) to int --> (X>>1)^1 iff X has only the 2nd bit set.
5446 // cast (X == 1) to int --> X iff X has only the low bit set.
5447 // cast (X == 2) to int --> X>>1 iff X has only the 2nd bit set.
5448 // cast (X != 0) to int --> X iff X has only the low bit set.
5449 // cast (X != 0) to int --> X>>1 iff X has only the 2nd bit set.
5450 // cast (X != 1) to int --> X^1 iff X has only the low bit set.
5451 // cast (X != 2) to int --> (X>>1)^1 iff X has only the 2nd bit set.
5452 if (Op1CV == 0 || isPowerOf2_64(Op1CV)) {
5453 // If Op1C some other power of two, convert:
5454 uint64_t KnownZero, KnownOne;
5455 uint64_t TypeMask = Op1->getType()->getIntegralTypeMask();
5456 ComputeMaskedBits(Op0, TypeMask, KnownZero, KnownOne);
5457
5458 if (isPowerOf2_64(KnownZero^TypeMask)) { // Exactly one possible 1?
5459 bool isSetNE = SrcI->getOpcode() == Instruction::SetNE;
5460 if (Op1CV && (Op1CV != (KnownZero^TypeMask))) {
5461 // (X&4) == 2 --> false
5462 // (X&4) != 2 --> true
Chris Lattnerc5b6c9a2006-02-28 19:47:20 +00005463 Constant *Res = ConstantBool::get(isSetNE);
5464 Res = ConstantExpr::getCast(Res, CI.getType());
5465 return ReplaceInstUsesWith(CI, Res);
Chris Lattnerc7bfed02006-02-27 02:38:23 +00005466 }
5467
5468 unsigned ShiftAmt = Log2_64(KnownZero^TypeMask);
5469 Value *In = Op0;
5470 if (ShiftAmt) {
Chris Lattner4c2d3782005-05-06 01:53:19 +00005471 // Perform an unsigned shr by shiftamt. Convert input to
5472 // unsigned if it is signed.
Chris Lattner4c2d3782005-05-06 01:53:19 +00005473 if (In->getType()->isSigned())
5474 In = InsertNewInstBefore(new CastInst(In,
5475 In->getType()->getUnsignedVersion(), In->getName()),CI);
5476 // Insert the shift to put the result in the low bit.
5477 In = InsertNewInstBefore(new ShiftInst(Instruction::Shr, In,
Chris Lattnerc7bfed02006-02-27 02:38:23 +00005478 ConstantInt::get(Type::UByteTy, ShiftAmt),
5479 In->getName()+".lobit"), CI);
Chris Lattner4c2d3782005-05-06 01:53:19 +00005480 }
Chris Lattnerc7bfed02006-02-27 02:38:23 +00005481
5482 if ((Op1CV != 0) == isSetNE) { // Toggle the low bit.
5483 Constant *One = ConstantInt::get(In->getType(), 1);
5484 In = BinaryOperator::createXor(In, One, "tmp");
5485 InsertNewInstBefore(cast<Instruction>(In), CI);
Chris Lattner4c2d3782005-05-06 01:53:19 +00005486 }
Chris Lattnerc7bfed02006-02-27 02:38:23 +00005487
5488 if (CI.getType() == In->getType())
5489 return ReplaceInstUsesWith(CI, In);
5490 else
5491 return new CastInst(In, CI.getType());
Chris Lattner4c2d3782005-05-06 01:53:19 +00005492 }
Chris Lattner809dfac2005-05-04 19:10:26 +00005493 }
5494 }
5495 break;
Chris Lattnerdfae8be2003-07-24 17:35:25 +00005496 }
5497 }
Chris Lattner99155be2006-05-25 23:24:33 +00005498
5499 if (SrcI->hasOneUse()) {
5500 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(SrcI)) {
5501 // Okay, we have (cast (shuffle ..)). We know this cast is a bitconvert
5502 // because the inputs are known to be a vector. Check to see if this is
5503 // a cast to a vector with the same # elts.
5504 if (isa<PackedType>(CI.getType()) &&
5505 cast<PackedType>(CI.getType())->getNumElements() ==
5506 SVI->getType()->getNumElements()) {
5507 CastInst *Tmp;
5508 // If either of the operands is a cast from CI.getType(), then
5509 // evaluating the shuffle in the casted destination's type will allow
5510 // us to eliminate at least one cast.
5511 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
5512 Tmp->getOperand(0)->getType() == CI.getType()) ||
5513 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
Chris Lattner95cebb02006-06-06 22:26:02 +00005514 Tmp->getOperand(0)->getType() == CI.getType())) {
Chris Lattner99155be2006-05-25 23:24:33 +00005515 Value *LHS = InsertOperandCastBefore(SVI->getOperand(0),
5516 CI.getType(), &CI);
5517 Value *RHS = InsertOperandCastBefore(SVI->getOperand(1),
5518 CI.getType(), &CI);
5519 // Return a new shuffle vector. Use the same element ID's, as we
5520 // know the vector types match #elts.
5521 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
5522 }
5523 }
5524 }
5525 }
5526 }
Chris Lattnerbb171802005-10-27 05:53:56 +00005527
Chris Lattner260ab202002-04-18 17:39:14 +00005528 return 0;
Chris Lattnerca081252001-12-14 16:52:21 +00005529}
5530
Chris Lattner56e4d3d2004-04-09 23:46:01 +00005531/// GetSelectFoldableOperands - We want to turn code that looks like this:
5532/// %C = or %A, %B
5533/// %D = select %cond, %C, %A
5534/// into:
5535/// %C = select %cond, %B, 0
5536/// %D = or %A, %C
5537///
5538/// Assuming that the specified instruction is an operand to the select, return
5539/// a bitmask indicating which operands of this instruction are foldable if they
5540/// equal the other incoming value of the select.
5541///
5542static unsigned GetSelectFoldableOperands(Instruction *I) {
5543 switch (I->getOpcode()) {
5544 case Instruction::Add:
5545 case Instruction::Mul:
5546 case Instruction::And:
5547 case Instruction::Or:
5548 case Instruction::Xor:
5549 return 3; // Can fold through either operand.
5550 case Instruction::Sub: // Can only fold on the amount subtracted.
5551 case Instruction::Shl: // Can only fold on the shift amount.
5552 case Instruction::Shr:
Misha Brukmanb1c93172005-04-21 23:48:37 +00005553 return 1;
Chris Lattner56e4d3d2004-04-09 23:46:01 +00005554 default:
5555 return 0; // Cannot fold
5556 }
5557}
5558
5559/// GetSelectFoldableConstant - For the same transformation as the previous
5560/// function, return the identity constant that goes into the select.
5561static Constant *GetSelectFoldableConstant(Instruction *I) {
5562 switch (I->getOpcode()) {
5563 default: assert(0 && "This cannot happen!"); abort();
5564 case Instruction::Add:
5565 case Instruction::Sub:
5566 case Instruction::Or:
5567 case Instruction::Xor:
5568 return Constant::getNullValue(I->getType());
5569 case Instruction::Shl:
5570 case Instruction::Shr:
5571 return Constant::getNullValue(Type::UByteTy);
5572 case Instruction::And:
5573 return ConstantInt::getAllOnesValue(I->getType());
5574 case Instruction::Mul:
5575 return ConstantInt::get(I->getType(), 1);
5576 }
5577}
5578
Chris Lattner411336f2005-01-19 21:50:18 +00005579/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
5580/// have the same opcode and only one use each. Try to simplify this.
5581Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
5582 Instruction *FI) {
5583 if (TI->getNumOperands() == 1) {
5584 // If this is a non-volatile load or a cast from the same type,
5585 // merge.
5586 if (TI->getOpcode() == Instruction::Cast) {
5587 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
5588 return 0;
5589 } else {
5590 return 0; // unknown unary op.
5591 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00005592
Chris Lattner411336f2005-01-19 21:50:18 +00005593 // Fold this by inserting a select from the input values.
5594 SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
5595 FI->getOperand(0), SI.getName()+".v");
5596 InsertNewInstBefore(NewSI, SI);
5597 return new CastInst(NewSI, TI->getType());
5598 }
5599
5600 // Only handle binary operators here.
5601 if (!isa<ShiftInst>(TI) && !isa<BinaryOperator>(TI))
5602 return 0;
5603
5604 // Figure out if the operations have any operands in common.
5605 Value *MatchOp, *OtherOpT, *OtherOpF;
5606 bool MatchIsOpZero;
5607 if (TI->getOperand(0) == FI->getOperand(0)) {
5608 MatchOp = TI->getOperand(0);
5609 OtherOpT = TI->getOperand(1);
5610 OtherOpF = FI->getOperand(1);
5611 MatchIsOpZero = true;
5612 } else if (TI->getOperand(1) == FI->getOperand(1)) {
5613 MatchOp = TI->getOperand(1);
5614 OtherOpT = TI->getOperand(0);
5615 OtherOpF = FI->getOperand(0);
5616 MatchIsOpZero = false;
5617 } else if (!TI->isCommutative()) {
5618 return 0;
5619 } else if (TI->getOperand(0) == FI->getOperand(1)) {
5620 MatchOp = TI->getOperand(0);
5621 OtherOpT = TI->getOperand(1);
5622 OtherOpF = FI->getOperand(0);
5623 MatchIsOpZero = true;
5624 } else if (TI->getOperand(1) == FI->getOperand(0)) {
5625 MatchOp = TI->getOperand(1);
5626 OtherOpT = TI->getOperand(0);
5627 OtherOpF = FI->getOperand(1);
5628 MatchIsOpZero = true;
5629 } else {
5630 return 0;
5631 }
5632
5633 // If we reach here, they do have operations in common.
5634 SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
5635 OtherOpF, SI.getName()+".v");
5636 InsertNewInstBefore(NewSI, SI);
5637
5638 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
5639 if (MatchIsOpZero)
5640 return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
5641 else
5642 return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
5643 } else {
5644 if (MatchIsOpZero)
5645 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), MatchOp, NewSI);
5646 else
5647 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), NewSI, MatchOp);
5648 }
5649}
5650
Chris Lattnerb909e8b2004-03-12 05:52:32 +00005651Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattner533bc492004-03-30 19:37:13 +00005652 Value *CondVal = SI.getCondition();
5653 Value *TrueVal = SI.getTrueValue();
5654 Value *FalseVal = SI.getFalseValue();
5655
5656 // select true, X, Y -> X
5657 // select false, X, Y -> Y
5658 if (ConstantBool *C = dyn_cast<ConstantBool>(CondVal))
Chris Lattner6ab03f62006-09-28 23:35:22 +00005659 return ReplaceInstUsesWith(SI, C->getValue() ? TrueVal : FalseVal);
Chris Lattner533bc492004-03-30 19:37:13 +00005660
5661 // select C, X, X -> X
5662 if (TrueVal == FalseVal)
5663 return ReplaceInstUsesWith(SI, TrueVal);
5664
Chris Lattner81a7a232004-10-16 18:11:37 +00005665 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
5666 return ReplaceInstUsesWith(SI, FalseVal);
5667 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
5668 return ReplaceInstUsesWith(SI, TrueVal);
5669 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
5670 if (isa<Constant>(TrueVal))
5671 return ReplaceInstUsesWith(SI, TrueVal);
5672 else
5673 return ReplaceInstUsesWith(SI, FalseVal);
5674 }
5675
Chris Lattner1c631e82004-04-08 04:43:23 +00005676 if (SI.getType() == Type::BoolTy)
5677 if (ConstantBool *C = dyn_cast<ConstantBool>(TrueVal)) {
Chris Lattner6ab03f62006-09-28 23:35:22 +00005678 if (C->getValue()) {
Chris Lattner1c631e82004-04-08 04:43:23 +00005679 // Change: A = select B, true, C --> A = or B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00005680 return BinaryOperator::createOr(CondVal, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00005681 } else {
5682 // Change: A = select B, false, C --> A = and !B, C
5683 Value *NotCond =
5684 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
5685 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00005686 return BinaryOperator::createAnd(NotCond, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00005687 }
5688 } else if (ConstantBool *C = dyn_cast<ConstantBool>(FalseVal)) {
Chris Lattner6ab03f62006-09-28 23:35:22 +00005689 if (C->getValue() == false) {
Chris Lattner1c631e82004-04-08 04:43:23 +00005690 // Change: A = select B, C, false --> A = and B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00005691 return BinaryOperator::createAnd(CondVal, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00005692 } else {
5693 // Change: A = select B, C, true --> A = or !B, C
5694 Value *NotCond =
5695 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
5696 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00005697 return BinaryOperator::createOr(NotCond, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00005698 }
5699 }
5700
Chris Lattner183b3362004-04-09 19:05:30 +00005701 // Selecting between two integer constants?
5702 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
5703 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
5704 // select C, 1, 0 -> cast C to int
5705 if (FalseValC->isNullValue() && TrueValC->getRawValue() == 1) {
5706 return new CastInst(CondVal, SI.getType());
5707 } else if (TrueValC->isNullValue() && FalseValC->getRawValue() == 1) {
5708 // select C, 0, 1 -> cast !C to int
5709 Value *NotCond =
5710 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
Chris Lattnercf7baf32004-04-09 18:19:44 +00005711 "not."+CondVal->getName()), SI);
Chris Lattner183b3362004-04-09 19:05:30 +00005712 return new CastInst(NotCond, SI.getType());
Chris Lattnercf7baf32004-04-09 18:19:44 +00005713 }
Chris Lattner35167c32004-06-09 07:59:58 +00005714
Chris Lattner380c7e92006-09-20 04:44:59 +00005715 if (SetCondInst *IC = dyn_cast<SetCondInst>(SI.getCondition())) {
5716
5717 // (x <s 0) ? -1 : 0 -> sra x, 31
5718 // (x >u 2147483647) ? -1 : 0 -> sra x, 31
5719 if (TrueValC->isAllOnesValue() && FalseValC->isNullValue())
5720 if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
5721 bool CanXForm = false;
5722 if (CmpCst->getType()->isSigned())
5723 CanXForm = CmpCst->isNullValue() &&
5724 IC->getOpcode() == Instruction::SetLT;
5725 else {
5726 unsigned Bits = CmpCst->getType()->getPrimitiveSizeInBits();
5727 CanXForm = (CmpCst->getRawValue() == ~0ULL >> (64-Bits+1)) &&
5728 IC->getOpcode() == Instruction::SetGT;
5729 }
5730
5731 if (CanXForm) {
5732 // The comparison constant and the result are not neccessarily the
5733 // same width. In any case, the first step to do is make sure
5734 // that X is signed.
5735 Value *X = IC->getOperand(0);
5736 if (!X->getType()->isSigned())
5737 X = InsertCastBefore(X, X->getType()->getSignedVersion(), SI);
5738
5739 // Now that X is signed, we have to make the all ones value. Do
5740 // this by inserting a new SRA.
5741 unsigned Bits = X->getType()->getPrimitiveSizeInBits();
5742 Constant *ShAmt = ConstantUInt::get(Type::UByteTy, Bits-1);
5743 Instruction *SRA = new ShiftInst(Instruction::Shr, X,
5744 ShAmt, "ones");
5745 InsertNewInstBefore(SRA, SI);
5746
5747 // Finally, convert to the type of the select RHS. If this is
5748 // smaller than the compare value, it will truncate the ones to
5749 // fit. If it is larger, it will sext the ones to fit.
5750 return new CastInst(SRA, SI.getType());
5751 }
5752 }
5753
5754
5755 // If one of the constants is zero (we know they can't both be) and we
5756 // have a setcc instruction with zero, and we have an 'and' with the
5757 // non-constant value, eliminate this whole mess. This corresponds to
5758 // cases like this: ((X & 27) ? 27 : 0)
5759 if (TrueValC->isNullValue() || FalseValC->isNullValue())
Chris Lattnerb3f24c92006-09-18 04:22:48 +00005760 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner35167c32004-06-09 07:59:58 +00005761 cast<Constant>(IC->getOperand(1))->isNullValue())
5762 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
5763 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00005764 isa<ConstantInt>(ICA->getOperand(1)) &&
5765 (ICA->getOperand(1) == TrueValC ||
5766 ICA->getOperand(1) == FalseValC) &&
Chris Lattner35167c32004-06-09 07:59:58 +00005767 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
5768 // Okay, now we know that everything is set up, we just don't
5769 // know whether we have a setne or seteq and whether the true or
5770 // false val is the zero.
5771 bool ShouldNotVal = !TrueValC->isNullValue();
5772 ShouldNotVal ^= IC->getOpcode() == Instruction::SetNE;
5773 Value *V = ICA;
5774 if (ShouldNotVal)
5775 V = InsertNewInstBefore(BinaryOperator::create(
5776 Instruction::Xor, V, ICA->getOperand(1)), SI);
5777 return ReplaceInstUsesWith(SI, V);
5778 }
Chris Lattner380c7e92006-09-20 04:44:59 +00005779 }
Chris Lattner533bc492004-03-30 19:37:13 +00005780 }
Chris Lattner623fba12004-04-10 22:21:27 +00005781
5782 // See if we are selecting two values based on a comparison of the two values.
5783 if (SetCondInst *SCI = dyn_cast<SetCondInst>(CondVal)) {
5784 if (SCI->getOperand(0) == TrueVal && SCI->getOperand(1) == FalseVal) {
5785 // Transform (X == Y) ? X : Y -> Y
5786 if (SCI->getOpcode() == Instruction::SetEQ)
5787 return ReplaceInstUsesWith(SI, FalseVal);
5788 // Transform (X != Y) ? X : Y -> X
5789 if (SCI->getOpcode() == Instruction::SetNE)
5790 return ReplaceInstUsesWith(SI, TrueVal);
5791 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
5792
5793 } else if (SCI->getOperand(0) == FalseVal && SCI->getOperand(1) == TrueVal){
5794 // Transform (X == Y) ? Y : X -> X
5795 if (SCI->getOpcode() == Instruction::SetEQ)
Chris Lattner24cf0202004-04-11 01:39:19 +00005796 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattner623fba12004-04-10 22:21:27 +00005797 // Transform (X != Y) ? Y : X -> Y
5798 if (SCI->getOpcode() == Instruction::SetNE)
Chris Lattner24cf0202004-04-11 01:39:19 +00005799 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattner623fba12004-04-10 22:21:27 +00005800 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
5801 }
5802 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00005803
Chris Lattnera04c9042005-01-13 22:52:24 +00005804 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
5805 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
5806 if (TI->hasOneUse() && FI->hasOneUse()) {
5807 bool isInverse = false;
5808 Instruction *AddOp = 0, *SubOp = 0;
5809
Chris Lattner411336f2005-01-19 21:50:18 +00005810 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
5811 if (TI->getOpcode() == FI->getOpcode())
5812 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
5813 return IV;
5814
5815 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
5816 // even legal for FP.
Chris Lattnera04c9042005-01-13 22:52:24 +00005817 if (TI->getOpcode() == Instruction::Sub &&
5818 FI->getOpcode() == Instruction::Add) {
5819 AddOp = FI; SubOp = TI;
5820 } else if (FI->getOpcode() == Instruction::Sub &&
5821 TI->getOpcode() == Instruction::Add) {
5822 AddOp = TI; SubOp = FI;
5823 }
5824
5825 if (AddOp) {
5826 Value *OtherAddOp = 0;
5827 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
5828 OtherAddOp = AddOp->getOperand(1);
5829 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
5830 OtherAddOp = AddOp->getOperand(0);
5831 }
5832
5833 if (OtherAddOp) {
Chris Lattnerb580d262006-02-24 18:05:58 +00005834 // So at this point we know we have (Y -> OtherAddOp):
5835 // select C, (add X, Y), (sub X, Z)
5836 Value *NegVal; // Compute -Z
5837 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
5838 NegVal = ConstantExpr::getNeg(C);
5839 } else {
5840 NegVal = InsertNewInstBefore(
5841 BinaryOperator::createNeg(SubOp->getOperand(1), "tmp"), SI);
Chris Lattnera04c9042005-01-13 22:52:24 +00005842 }
Chris Lattnerb580d262006-02-24 18:05:58 +00005843
5844 Value *NewTrueOp = OtherAddOp;
5845 Value *NewFalseOp = NegVal;
5846 if (AddOp != TI)
5847 std::swap(NewTrueOp, NewFalseOp);
5848 Instruction *NewSel =
5849 new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
5850
5851 NewSel = InsertNewInstBefore(NewSel, SI);
5852 return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
Chris Lattnera04c9042005-01-13 22:52:24 +00005853 }
5854 }
5855 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00005856
Chris Lattner56e4d3d2004-04-09 23:46:01 +00005857 // See if we can fold the select into one of our operands.
5858 if (SI.getType()->isInteger()) {
5859 // See the comment above GetSelectFoldableOperands for a description of the
5860 // transformation we are doing here.
5861 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
5862 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
5863 !isa<Constant>(FalseVal))
5864 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
5865 unsigned OpToFold = 0;
5866 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
5867 OpToFold = 1;
5868 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
5869 OpToFold = 2;
5870 }
5871
5872 if (OpToFold) {
5873 Constant *C = GetSelectFoldableConstant(TVI);
5874 std::string Name = TVI->getName(); TVI->setName("");
5875 Instruction *NewSel =
5876 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C,
5877 Name);
5878 InsertNewInstBefore(NewSel, SI);
5879 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
5880 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
5881 else if (ShiftInst *SI = dyn_cast<ShiftInst>(TVI))
5882 return new ShiftInst(SI->getOpcode(), FalseVal, NewSel);
5883 else {
5884 assert(0 && "Unknown instruction!!");
5885 }
5886 }
5887 }
Chris Lattner6862fbd2004-09-29 17:40:11 +00005888
Chris Lattner56e4d3d2004-04-09 23:46:01 +00005889 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
5890 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
5891 !isa<Constant>(TrueVal))
5892 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
5893 unsigned OpToFold = 0;
5894 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
5895 OpToFold = 1;
5896 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
5897 OpToFold = 2;
5898 }
5899
5900 if (OpToFold) {
5901 Constant *C = GetSelectFoldableConstant(FVI);
5902 std::string Name = FVI->getName(); FVI->setName("");
5903 Instruction *NewSel =
5904 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold),
5905 Name);
5906 InsertNewInstBefore(NewSel, SI);
5907 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
5908 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
5909 else if (ShiftInst *SI = dyn_cast<ShiftInst>(FVI))
5910 return new ShiftInst(SI->getOpcode(), TrueVal, NewSel);
5911 else {
5912 assert(0 && "Unknown instruction!!");
5913 }
5914 }
5915 }
5916 }
Chris Lattnerd6f636a2005-04-24 07:30:14 +00005917
5918 if (BinaryOperator::isNot(CondVal)) {
5919 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
5920 SI.setOperand(1, FalseVal);
5921 SI.setOperand(2, TrueVal);
5922 return &SI;
5923 }
5924
Chris Lattnerb909e8b2004-03-12 05:52:32 +00005925 return 0;
5926}
5927
Chris Lattner82f2ef22006-03-06 20:18:44 +00005928/// GetKnownAlignment - If the specified pointer has an alignment that we can
5929/// determine, return it, otherwise return 0.
5930static unsigned GetKnownAlignment(Value *V, TargetData *TD) {
5931 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
5932 unsigned Align = GV->getAlignment();
5933 if (Align == 0 && TD)
5934 Align = TD->getTypeAlignment(GV->getType()->getElementType());
5935 return Align;
5936 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
5937 unsigned Align = AI->getAlignment();
5938 if (Align == 0 && TD) {
5939 if (isa<AllocaInst>(AI))
5940 Align = TD->getTypeAlignment(AI->getType()->getElementType());
5941 else if (isa<MallocInst>(AI)) {
5942 // Malloc returns maximally aligned memory.
5943 Align = TD->getTypeAlignment(AI->getType()->getElementType());
5944 Align = std::max(Align, (unsigned)TD->getTypeAlignment(Type::DoubleTy));
5945 Align = std::max(Align, (unsigned)TD->getTypeAlignment(Type::LongTy));
5946 }
5947 }
5948 return Align;
Chris Lattner53ef5a02006-03-07 01:28:57 +00005949 } else if (isa<CastInst>(V) ||
5950 (isa<ConstantExpr>(V) &&
5951 cast<ConstantExpr>(V)->getOpcode() == Instruction::Cast)) {
5952 User *CI = cast<User>(V);
Chris Lattner82f2ef22006-03-06 20:18:44 +00005953 if (isa<PointerType>(CI->getOperand(0)->getType()))
5954 return GetKnownAlignment(CI->getOperand(0), TD);
5955 return 0;
Chris Lattner53ef5a02006-03-07 01:28:57 +00005956 } else if (isa<GetElementPtrInst>(V) ||
5957 (isa<ConstantExpr>(V) &&
5958 cast<ConstantExpr>(V)->getOpcode()==Instruction::GetElementPtr)) {
5959 User *GEPI = cast<User>(V);
Chris Lattner82f2ef22006-03-06 20:18:44 +00005960 unsigned BaseAlignment = GetKnownAlignment(GEPI->getOperand(0), TD);
5961 if (BaseAlignment == 0) return 0;
5962
5963 // If all indexes are zero, it is just the alignment of the base pointer.
5964 bool AllZeroOperands = true;
5965 for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
5966 if (!isa<Constant>(GEPI->getOperand(i)) ||
5967 !cast<Constant>(GEPI->getOperand(i))->isNullValue()) {
5968 AllZeroOperands = false;
5969 break;
5970 }
5971 if (AllZeroOperands)
5972 return BaseAlignment;
5973
5974 // Otherwise, if the base alignment is >= the alignment we expect for the
5975 // base pointer type, then we know that the resultant pointer is aligned at
5976 // least as much as its type requires.
5977 if (!TD) return 0;
5978
5979 const Type *BasePtrTy = GEPI->getOperand(0)->getType();
5980 if (TD->getTypeAlignment(cast<PointerType>(BasePtrTy)->getElementType())
Chris Lattner53ef5a02006-03-07 01:28:57 +00005981 <= BaseAlignment) {
5982 const Type *GEPTy = GEPI->getType();
5983 return TD->getTypeAlignment(cast<PointerType>(GEPTy)->getElementType());
5984 }
Chris Lattner82f2ef22006-03-06 20:18:44 +00005985 return 0;
5986 }
5987 return 0;
5988}
5989
Chris Lattnerb909e8b2004-03-12 05:52:32 +00005990
Chris Lattnerc66b2232006-01-13 20:11:04 +00005991/// visitCallInst - CallInst simplification. This mostly only handles folding
5992/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
5993/// the heavy lifting.
5994///
Chris Lattner970c33a2003-06-19 17:00:31 +00005995Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattnerc66b2232006-01-13 20:11:04 +00005996 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
5997 if (!II) return visitCallSite(&CI);
5998
Chris Lattner51ea1272004-02-28 05:22:00 +00005999 // Intrinsics cannot occur in an invoke, so handle them here instead of in
6000 // visitCallSite.
Chris Lattnerc66b2232006-01-13 20:11:04 +00006001 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner00648e12004-10-12 04:52:52 +00006002 bool Changed = false;
6003
6004 // memmove/cpy/set of zero bytes is a noop.
6005 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
6006 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
6007
Chris Lattner00648e12004-10-12 04:52:52 +00006008 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
6009 if (CI->getRawValue() == 1) {
6010 // Replace the instruction with just byte operations. We would
6011 // transform other cases to loads/stores, but we don't know if
6012 // alignment is sufficient.
6013 }
Chris Lattner51ea1272004-02-28 05:22:00 +00006014 }
6015
Chris Lattner00648e12004-10-12 04:52:52 +00006016 // If we have a memmove and the source operation is a constant global,
6017 // then the source and dest pointers can't alias, so we can change this
6018 // into a call to memcpy.
Chris Lattner82f2ef22006-03-06 20:18:44 +00006019 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(II)) {
Chris Lattner00648e12004-10-12 04:52:52 +00006020 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
6021 if (GVSrc->isConstant()) {
6022 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner681ef2f2006-03-03 01:34:17 +00006023 const char *Name;
6024 if (CI.getCalledFunction()->getFunctionType()->getParamType(3) ==
6025 Type::UIntTy)
6026 Name = "llvm.memcpy.i32";
6027 else
6028 Name = "llvm.memcpy.i64";
6029 Function *MemCpy = M->getOrInsertFunction(Name,
Chris Lattner00648e12004-10-12 04:52:52 +00006030 CI.getCalledFunction()->getFunctionType());
6031 CI.setOperand(0, MemCpy);
6032 Changed = true;
6033 }
Chris Lattner82f2ef22006-03-06 20:18:44 +00006034 }
Chris Lattner00648e12004-10-12 04:52:52 +00006035
Chris Lattner82f2ef22006-03-06 20:18:44 +00006036 // If we can determine a pointer alignment that is bigger than currently
6037 // set, update the alignment.
6038 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
6039 unsigned Alignment1 = GetKnownAlignment(MI->getOperand(1), TD);
6040 unsigned Alignment2 = GetKnownAlignment(MI->getOperand(2), TD);
6041 unsigned Align = std::min(Alignment1, Alignment2);
6042 if (MI->getAlignment()->getRawValue() < Align) {
6043 MI->setAlignment(ConstantUInt::get(Type::UIntTy, Align));
6044 Changed = true;
6045 }
6046 } else if (isa<MemSetInst>(MI)) {
6047 unsigned Alignment = GetKnownAlignment(MI->getDest(), TD);
6048 if (MI->getAlignment()->getRawValue() < Alignment) {
6049 MI->setAlignment(ConstantUInt::get(Type::UIntTy, Alignment));
6050 Changed = true;
6051 }
6052 }
6053
Chris Lattnerc66b2232006-01-13 20:11:04 +00006054 if (Changed) return II;
Chris Lattner503221f2006-01-13 21:28:09 +00006055 } else {
6056 switch (II->getIntrinsicID()) {
6057 default: break;
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00006058 case Intrinsic::ppc_altivec_lvx:
6059 case Intrinsic::ppc_altivec_lvxl:
Chris Lattner36dd7c92006-04-17 22:26:56 +00006060 case Intrinsic::x86_sse_loadu_ps:
6061 case Intrinsic::x86_sse2_loadu_pd:
6062 case Intrinsic::x86_sse2_loadu_dq:
6063 // Turn PPC lvx -> load if the pointer is known aligned.
6064 // Turn X86 loadups -> load if the pointer is known aligned.
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00006065 if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
Chris Lattnere79d2492006-04-06 19:19:17 +00006066 Value *Ptr = InsertCastBefore(II->getOperand(1),
6067 PointerType::get(II->getType()), CI);
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00006068 return new LoadInst(Ptr);
6069 }
6070 break;
6071 case Intrinsic::ppc_altivec_stvx:
6072 case Intrinsic::ppc_altivec_stvxl:
6073 // Turn stvx -> store if the pointer is known aligned.
6074 if (GetKnownAlignment(II->getOperand(2), TD) >= 16) {
Chris Lattnere79d2492006-04-06 19:19:17 +00006075 const Type *OpPtrTy = PointerType::get(II->getOperand(1)->getType());
6076 Value *Ptr = InsertCastBefore(II->getOperand(2), OpPtrTy, CI);
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00006077 return new StoreInst(II->getOperand(1), Ptr);
6078 }
6079 break;
Chris Lattner36dd7c92006-04-17 22:26:56 +00006080 case Intrinsic::x86_sse_storeu_ps:
6081 case Intrinsic::x86_sse2_storeu_pd:
6082 case Intrinsic::x86_sse2_storeu_dq:
6083 case Intrinsic::x86_sse2_storel_dq:
6084 // Turn X86 storeu -> store if the pointer is known aligned.
6085 if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
6086 const Type *OpPtrTy = PointerType::get(II->getOperand(2)->getType());
6087 Value *Ptr = InsertCastBefore(II->getOperand(1), OpPtrTy, CI);
6088 return new StoreInst(II->getOperand(2), Ptr);
6089 }
6090 break;
Chris Lattnere79d2492006-04-06 19:19:17 +00006091 case Intrinsic::ppc_altivec_vperm:
6092 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
6093 if (ConstantPacked *Mask = dyn_cast<ConstantPacked>(II->getOperand(3))) {
6094 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
6095
6096 // Check that all of the elements are integer constants or undefs.
6097 bool AllEltsOk = true;
6098 for (unsigned i = 0; i != 16; ++i) {
6099 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
6100 !isa<UndefValue>(Mask->getOperand(i))) {
6101 AllEltsOk = false;
6102 break;
6103 }
6104 }
6105
6106 if (AllEltsOk) {
6107 // Cast the input vectors to byte vectors.
6108 Value *Op0 = InsertCastBefore(II->getOperand(1), Mask->getType(), CI);
6109 Value *Op1 = InsertCastBefore(II->getOperand(2), Mask->getType(), CI);
6110 Value *Result = UndefValue::get(Op0->getType());
6111
6112 // Only extract each element once.
6113 Value *ExtractedElts[32];
6114 memset(ExtractedElts, 0, sizeof(ExtractedElts));
6115
6116 for (unsigned i = 0; i != 16; ++i) {
6117 if (isa<UndefValue>(Mask->getOperand(i)))
6118 continue;
6119 unsigned Idx =cast<ConstantInt>(Mask->getOperand(i))->getRawValue();
6120 Idx &= 31; // Match the hardware behavior.
6121
6122 if (ExtractedElts[Idx] == 0) {
6123 Instruction *Elt =
6124 new ExtractElementInst(Idx < 16 ? Op0 : Op1,
6125 ConstantUInt::get(Type::UIntTy, Idx&15),
6126 "tmp");
6127 InsertNewInstBefore(Elt, CI);
6128 ExtractedElts[Idx] = Elt;
6129 }
6130
6131 // Insert this value into the result vector.
6132 Result = new InsertElementInst(Result, ExtractedElts[Idx],
6133 ConstantUInt::get(Type::UIntTy, i),
6134 "tmp");
6135 InsertNewInstBefore(cast<Instruction>(Result), CI);
6136 }
6137 return new CastInst(Result, CI.getType());
6138 }
6139 }
6140 break;
6141
Chris Lattner503221f2006-01-13 21:28:09 +00006142 case Intrinsic::stackrestore: {
6143 // If the save is right next to the restore, remove the restore. This can
6144 // happen when variable allocas are DCE'd.
6145 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
6146 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
6147 BasicBlock::iterator BI = SS;
6148 if (&*++BI == II)
6149 return EraseInstFromFunction(CI);
6150 }
6151 }
6152
6153 // If the stack restore is in a return/unwind block and if there are no
6154 // allocas or calls between the restore and the return, nuke the restore.
6155 TerminatorInst *TI = II->getParent()->getTerminator();
6156 if (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)) {
6157 BasicBlock::iterator BI = II;
6158 bool CannotRemove = false;
6159 for (++BI; &*BI != TI; ++BI) {
6160 if (isa<AllocaInst>(BI) ||
6161 (isa<CallInst>(BI) && !isa<IntrinsicInst>(BI))) {
6162 CannotRemove = true;
6163 break;
6164 }
6165 }
6166 if (!CannotRemove)
6167 return EraseInstFromFunction(CI);
6168 }
6169 break;
6170 }
6171 }
Chris Lattner00648e12004-10-12 04:52:52 +00006172 }
6173
Chris Lattnerc66b2232006-01-13 20:11:04 +00006174 return visitCallSite(II);
Chris Lattner970c33a2003-06-19 17:00:31 +00006175}
6176
6177// InvokeInst simplification
6178//
6179Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattneraec3d942003-10-07 22:32:43 +00006180 return visitCallSite(&II);
Chris Lattner970c33a2003-06-19 17:00:31 +00006181}
6182
Chris Lattneraec3d942003-10-07 22:32:43 +00006183// visitCallSite - Improvements for call and invoke instructions.
6184//
6185Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner75b4d1d2003-10-07 22:54:13 +00006186 bool Changed = false;
6187
6188 // If the callee is a constexpr cast of a function, attempt to move the cast
6189 // to the arguments of the call/invoke.
Chris Lattneraec3d942003-10-07 22:32:43 +00006190 if (transformConstExprCastCall(CS)) return 0;
6191
Chris Lattner75b4d1d2003-10-07 22:54:13 +00006192 Value *Callee = CS.getCalledValue();
Chris Lattner81a7a232004-10-16 18:11:37 +00006193
Chris Lattner61d9d812005-05-13 07:09:09 +00006194 if (Function *CalleeF = dyn_cast<Function>(Callee))
6195 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
6196 Instruction *OldCall = CS.getInstruction();
6197 // If the call and callee calling conventions don't match, this call must
6198 // be unreachable, as the call is undefined.
Chris Lattner6ab03f62006-09-28 23:35:22 +00006199 new StoreInst(ConstantBool::getTrue(),
Chris Lattner61d9d812005-05-13 07:09:09 +00006200 UndefValue::get(PointerType::get(Type::BoolTy)), OldCall);
6201 if (!OldCall->use_empty())
6202 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
6203 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
6204 return EraseInstFromFunction(*OldCall);
6205 return 0;
6206 }
6207
Chris Lattner8ba9ec92004-10-18 02:59:09 +00006208 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
6209 // This instruction is not reachable, just remove it. We insert a store to
6210 // undef so that we know that this code is not reachable, despite the fact
6211 // that we can't modify the CFG here.
Chris Lattner6ab03f62006-09-28 23:35:22 +00006212 new StoreInst(ConstantBool::getTrue(),
Chris Lattner8ba9ec92004-10-18 02:59:09 +00006213 UndefValue::get(PointerType::get(Type::BoolTy)),
6214 CS.getInstruction());
6215
6216 if (!CS.getInstruction()->use_empty())
6217 CS.getInstruction()->
6218 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
6219
6220 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
6221 // Don't break the CFG, insert a dummy cond branch.
6222 new BranchInst(II->getNormalDest(), II->getUnwindDest(),
Chris Lattner6ab03f62006-09-28 23:35:22 +00006223 ConstantBool::getTrue(), II);
Chris Lattner81a7a232004-10-16 18:11:37 +00006224 }
Chris Lattner8ba9ec92004-10-18 02:59:09 +00006225 return EraseInstFromFunction(*CS.getInstruction());
6226 }
Chris Lattner81a7a232004-10-16 18:11:37 +00006227
Chris Lattner75b4d1d2003-10-07 22:54:13 +00006228 const PointerType *PTy = cast<PointerType>(Callee->getType());
6229 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
6230 if (FTy->isVarArg()) {
6231 // See if we can optimize any arguments passed through the varargs area of
6232 // the call.
6233 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
6234 E = CS.arg_end(); I != E; ++I)
6235 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
6236 // If this cast does not effect the value passed through the varargs
6237 // area, we can eliminate the use of the cast.
6238 Value *Op = CI->getOperand(0);
6239 if (CI->getType()->isLosslesslyConvertibleTo(Op->getType())) {
6240 *I = Op;
6241 Changed = true;
6242 }
6243 }
6244 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00006245
Chris Lattner75b4d1d2003-10-07 22:54:13 +00006246 return Changed ? CS.getInstruction() : 0;
Chris Lattneraec3d942003-10-07 22:32:43 +00006247}
6248
Chris Lattner970c33a2003-06-19 17:00:31 +00006249// transformConstExprCastCall - If the callee is a constexpr cast of a function,
6250// attempt to move the cast to the arguments of the call/invoke.
6251//
6252bool InstCombiner::transformConstExprCastCall(CallSite CS) {
6253 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
6254 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Chris Lattnerf3edc492004-07-18 18:59:44 +00006255 if (CE->getOpcode() != Instruction::Cast || !isa<Function>(CE->getOperand(0)))
Chris Lattner970c33a2003-06-19 17:00:31 +00006256 return false;
Reid Spencer87436872004-07-18 00:38:32 +00006257 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner970c33a2003-06-19 17:00:31 +00006258 Instruction *Caller = CS.getInstruction();
6259
6260 // Okay, this is a cast from a function to a different type. Unless doing so
6261 // would cause a type conversion of one of our arguments, change this call to
6262 // be a direct call with arguments casted to the appropriate types.
6263 //
6264 const FunctionType *FT = Callee->getFunctionType();
6265 const Type *OldRetTy = Caller->getType();
6266
Chris Lattner1f7942f2004-01-14 06:06:08 +00006267 // Check to see if we are changing the return type...
6268 if (OldRetTy != FT->getReturnType()) {
6269 if (Callee->isExternal() &&
Andrew Lenharth61eae292006-04-20 14:56:47 +00006270 !(OldRetTy->isLosslesslyConvertibleTo(FT->getReturnType()) ||
6271 (isa<PointerType>(FT->getReturnType()) &&
Andrew Lenharthf89e6302006-04-20 15:41:37 +00006272 TD->getIntPtrType()->isLosslesslyConvertibleTo(OldRetTy)))
Andrew Lenharth61eae292006-04-20 14:56:47 +00006273 && !Caller->use_empty())
Chris Lattner1f7942f2004-01-14 06:06:08 +00006274 return false; // Cannot transform this return value...
6275
6276 // If the callsite is an invoke instruction, and the return value is used by
6277 // a PHI node in a successor, we cannot change the return type of the call
6278 // because there is no place to put the cast instruction (without breaking
6279 // the critical edge). Bail out in this case.
6280 if (!Caller->use_empty())
6281 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
6282 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
6283 UI != E; ++UI)
6284 if (PHINode *PN = dyn_cast<PHINode>(*UI))
6285 if (PN->getParent() == II->getNormalDest() ||
Chris Lattnerfae8ab32004-02-08 21:44:31 +00006286 PN->getParent() == II->getUnwindDest())
Chris Lattner1f7942f2004-01-14 06:06:08 +00006287 return false;
6288 }
Chris Lattner970c33a2003-06-19 17:00:31 +00006289
6290 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
6291 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanb1c93172005-04-21 23:48:37 +00006292
Chris Lattner970c33a2003-06-19 17:00:31 +00006293 CallSite::arg_iterator AI = CS.arg_begin();
6294 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
6295 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthebfa24e2006-06-28 01:01:52 +00006296 const Type *ActTy = (*AI)->getType();
6297 ConstantSInt* c = dyn_cast<ConstantSInt>(*AI);
6298 //Either we can cast directly, or we can upconvert the argument
6299 bool isConvertible = ActTy->isLosslesslyConvertibleTo(ParamTy) ||
6300 (ParamTy->isIntegral() && ActTy->isIntegral() &&
6301 ParamTy->isSigned() == ActTy->isSigned() &&
6302 ParamTy->getPrimitiveSize() >= ActTy->getPrimitiveSize()) ||
6303 (c && ParamTy->getPrimitiveSize() >= ActTy->getPrimitiveSize() &&
6304 c->getValue() > 0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00006305 if (Callee->isExternal() && !isConvertible) return false;
Chris Lattner970c33a2003-06-19 17:00:31 +00006306 }
6307
6308 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
6309 Callee->isExternal())
6310 return false; // Do not delete arguments unless we have a function body...
6311
6312 // Okay, we decided that this is a safe thing to do: go ahead and start
6313 // inserting cast instructions as necessary...
6314 std::vector<Value*> Args;
6315 Args.reserve(NumActualArgs);
6316
6317 AI = CS.arg_begin();
6318 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
6319 const Type *ParamTy = FT->getParamType(i);
6320 if ((*AI)->getType() == ParamTy) {
6321 Args.push_back(*AI);
6322 } else {
Chris Lattner1c631e82004-04-08 04:43:23 +00006323 Args.push_back(InsertNewInstBefore(new CastInst(*AI, ParamTy, "tmp"),
6324 *Caller));
Chris Lattner970c33a2003-06-19 17:00:31 +00006325 }
6326 }
6327
6328 // If the function takes more arguments than the call was taking, add them
6329 // now...
6330 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
6331 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
6332
6333 // If we are removing arguments to the function, emit an obnoxious warning...
6334 if (FT->getNumParams() < NumActualArgs)
6335 if (!FT->isVarArg()) {
6336 std::cerr << "WARNING: While resolving call to function '"
6337 << Callee->getName() << "' arguments were dropped!\n";
6338 } else {
6339 // Add all of the arguments in their promoted form to the arg list...
6340 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
6341 const Type *PTy = getPromotedType((*AI)->getType());
6342 if (PTy != (*AI)->getType()) {
6343 // Must promote to pass through va_arg area!
6344 Instruction *Cast = new CastInst(*AI, PTy, "tmp");
6345 InsertNewInstBefore(Cast, *Caller);
6346 Args.push_back(Cast);
6347 } else {
6348 Args.push_back(*AI);
6349 }
6350 }
6351 }
6352
6353 if (FT->getReturnType() == Type::VoidTy)
6354 Caller->setName(""); // Void type should not have a name...
6355
6356 Instruction *NC;
6357 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Chris Lattnerfae8ab32004-02-08 21:44:31 +00006358 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
Chris Lattner970c33a2003-06-19 17:00:31 +00006359 Args, Caller->getName(), Caller);
Chris Lattner05c703e2005-05-14 12:25:32 +00006360 cast<InvokeInst>(II)->setCallingConv(II->getCallingConv());
Chris Lattner970c33a2003-06-19 17:00:31 +00006361 } else {
6362 NC = new CallInst(Callee, Args, Caller->getName(), Caller);
Chris Lattner6aacb0f2005-05-06 06:48:21 +00006363 if (cast<CallInst>(Caller)->isTailCall())
6364 cast<CallInst>(NC)->setTailCall();
Chris Lattner05c703e2005-05-14 12:25:32 +00006365 cast<CallInst>(NC)->setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Chris Lattner970c33a2003-06-19 17:00:31 +00006366 }
6367
6368 // Insert a cast of the return type as necessary...
6369 Value *NV = NC;
6370 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
6371 if (NV->getType() != Type::VoidTy) {
6372 NV = NC = new CastInst(NC, Caller->getType(), "tmp");
Chris Lattner686767f2003-10-30 00:46:41 +00006373
6374 // If this is an invoke instruction, we should insert it after the first
6375 // non-phi, instruction in the normal successor block.
6376 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
6377 BasicBlock::iterator I = II->getNormalDest()->begin();
6378 while (isa<PHINode>(I)) ++I;
6379 InsertNewInstBefore(NC, *I);
6380 } else {
6381 // Otherwise, it's a call, just insert cast right after the call instr
6382 InsertNewInstBefore(NC, *Caller);
6383 }
Chris Lattner51ea1272004-02-28 05:22:00 +00006384 AddUsersToWorkList(*Caller);
Chris Lattner970c33a2003-06-19 17:00:31 +00006385 } else {
Chris Lattnere29d6342004-10-17 21:22:38 +00006386 NV = UndefValue::get(Caller->getType());
Chris Lattner970c33a2003-06-19 17:00:31 +00006387 }
6388 }
6389
6390 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
6391 Caller->replaceAllUsesWith(NV);
6392 Caller->getParent()->getInstList().erase(Caller);
6393 removeFromWorkList(Caller);
6394 return true;
6395}
6396
6397
Chris Lattner7515cab2004-11-14 19:13:23 +00006398// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
6399// operator and they all are only used by the PHI, PHI together their
6400// inputs, and do the operation once, to the result of the PHI.
6401Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
6402 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
6403
6404 // Scan the instruction, looking for input operations that can be folded away.
6405 // If all input operands to the phi are the same instruction (e.g. a cast from
6406 // the same type or "+42") we can pull the operation through the PHI, reducing
6407 // code size and simplifying code.
6408 Constant *ConstantOp = 0;
6409 const Type *CastSrcTy = 0;
6410 if (isa<CastInst>(FirstInst)) {
6411 CastSrcTy = FirstInst->getOperand(0)->getType();
6412 } else if (isa<BinaryOperator>(FirstInst) || isa<ShiftInst>(FirstInst)) {
6413 // Can fold binop or shift if the RHS is a constant.
6414 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
6415 if (ConstantOp == 0) return 0;
6416 } else {
6417 return 0; // Cannot fold this operation.
6418 }
6419
6420 // Check to see if all arguments are the same operation.
6421 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
6422 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
6423 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
6424 if (!I->hasOneUse() || I->getOpcode() != FirstInst->getOpcode())
6425 return 0;
6426 if (CastSrcTy) {
6427 if (I->getOperand(0)->getType() != CastSrcTy)
6428 return 0; // Cast operation must match.
6429 } else if (I->getOperand(1) != ConstantOp) {
6430 return 0;
6431 }
6432 }
6433
6434 // Okay, they are all the same operation. Create a new PHI node of the
6435 // correct type, and PHI together all of the LHS's of the instructions.
6436 PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
6437 PN.getName()+".in");
Chris Lattnerd8e20182005-01-29 00:39:08 +00006438 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattner46dd5a62004-11-14 19:29:34 +00006439
6440 Value *InVal = FirstInst->getOperand(0);
6441 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattner7515cab2004-11-14 19:13:23 +00006442
6443 // Add all operands to the new PHI.
Chris Lattner46dd5a62004-11-14 19:29:34 +00006444 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
6445 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
6446 if (NewInVal != InVal)
6447 InVal = 0;
6448 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
6449 }
6450
6451 Value *PhiVal;
6452 if (InVal) {
6453 // The new PHI unions all of the same values together. This is really
6454 // common, so we handle it intelligently here for compile-time speed.
6455 PhiVal = InVal;
6456 delete NewPN;
6457 } else {
6458 InsertNewInstBefore(NewPN, PN);
6459 PhiVal = NewPN;
6460 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00006461
Chris Lattner7515cab2004-11-14 19:13:23 +00006462 // Insert and return the new operation.
6463 if (isa<CastInst>(FirstInst))
Chris Lattner46dd5a62004-11-14 19:29:34 +00006464 return new CastInst(PhiVal, PN.getType());
Chris Lattner7515cab2004-11-14 19:13:23 +00006465 else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattner46dd5a62004-11-14 19:29:34 +00006466 return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattner7515cab2004-11-14 19:13:23 +00006467 else
6468 return new ShiftInst(cast<ShiftInst>(FirstInst)->getOpcode(),
Chris Lattner46dd5a62004-11-14 19:29:34 +00006469 PhiVal, ConstantOp);
Chris Lattner7515cab2004-11-14 19:13:23 +00006470}
Chris Lattner48a44f72002-05-02 17:06:02 +00006471
Chris Lattner71536432005-01-17 05:10:15 +00006472/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
6473/// that is dead.
6474static bool DeadPHICycle(PHINode *PN, std::set<PHINode*> &PotentiallyDeadPHIs) {
6475 if (PN->use_empty()) return true;
6476 if (!PN->hasOneUse()) return false;
6477
6478 // Remember this node, and if we find the cycle, return.
6479 if (!PotentiallyDeadPHIs.insert(PN).second)
6480 return true;
6481
6482 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
6483 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanb1c93172005-04-21 23:48:37 +00006484
Chris Lattner71536432005-01-17 05:10:15 +00006485 return false;
6486}
6487
Chris Lattnerbbbdd852002-05-06 18:06:38 +00006488// PHINode simplification
6489//
Chris Lattner113f4f42002-06-25 16:13:24 +00006490Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonbbf89902006-07-10 22:15:25 +00006491 // If LCSSA is around, don't mess with Phi nodes
6492 if (mustPreserveAnalysisID(LCSSAID)) return 0;
Owen Andersona6968f82006-07-10 19:03:49 +00006493
Owen Andersonae8aa642006-07-10 22:03:18 +00006494 if (Value *V = PN.hasConstantValue())
6495 return ReplaceInstUsesWith(PN, V);
6496
6497 // If the only user of this instruction is a cast instruction, and all of the
6498 // incoming values are constants, change this PHI to merge together the casted
6499 // constants.
6500 if (PN.hasOneUse())
6501 if (CastInst *CI = dyn_cast<CastInst>(PN.use_back()))
6502 if (CI->getType() != PN.getType()) { // noop casts will be folded
6503 bool AllConstant = true;
6504 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
6505 if (!isa<Constant>(PN.getIncomingValue(i))) {
6506 AllConstant = false;
6507 break;
6508 }
6509 if (AllConstant) {
6510 // Make a new PHI with all casted values.
6511 PHINode *New = new PHINode(CI->getType(), PN.getName(), &PN);
6512 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
6513 Constant *OldArg = cast<Constant>(PN.getIncomingValue(i));
6514 New->addIncoming(ConstantExpr::getCast(OldArg, New->getType()),
6515 PN.getIncomingBlock(i));
6516 }
6517
6518 // Update the cast instruction.
6519 CI->setOperand(0, New);
6520 WorkList.push_back(CI); // revisit the cast instruction to fold.
6521 WorkList.push_back(New); // Make sure to revisit the new Phi
6522 return &PN; // PN is now dead!
6523 }
6524 }
6525
6526 // If all PHI operands are the same operation, pull them through the PHI,
6527 // reducing code size.
6528 if (isa<Instruction>(PN.getIncomingValue(0)) &&
6529 PN.getIncomingValue(0)->hasOneUse())
6530 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
6531 return Result;
6532
6533 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
6534 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
6535 // PHI)... break the cycle.
6536 if (PN.hasOneUse())
6537 if (PHINode *PU = dyn_cast<PHINode>(PN.use_back())) {
6538 std::set<PHINode*> PotentiallyDeadPHIs;
6539 PotentiallyDeadPHIs.insert(&PN);
6540 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
6541 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
6542 }
6543
Chris Lattner91daeb52003-12-19 05:58:40 +00006544 return 0;
Chris Lattnerbbbdd852002-05-06 18:06:38 +00006545}
6546
Chris Lattner69193f92004-04-05 01:30:19 +00006547static Value *InsertSignExtendToPtrTy(Value *V, const Type *DTy,
6548 Instruction *InsertPoint,
6549 InstCombiner *IC) {
6550 unsigned PS = IC->getTargetData().getPointerSize();
6551 const Type *VTy = V->getType();
Chris Lattner69193f92004-04-05 01:30:19 +00006552 if (!VTy->isSigned() && VTy->getPrimitiveSize() < PS)
6553 // We must insert a cast to ensure we sign-extend.
6554 V = IC->InsertNewInstBefore(new CastInst(V, VTy->getSignedVersion(),
6555 V->getName()), *InsertPoint);
6556 return IC->InsertNewInstBefore(new CastInst(V, DTy, V->getName()),
6557 *InsertPoint);
6558}
6559
Chris Lattner48a44f72002-05-02 17:06:02 +00006560
Chris Lattner113f4f42002-06-25 16:13:24 +00006561Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner5f667a62004-05-07 22:09:22 +00006562 Value *PtrOp = GEP.getOperand(0);
Chris Lattner471bd762003-05-22 19:07:21 +00006563 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
Chris Lattner113f4f42002-06-25 16:13:24 +00006564 // If so, eliminate the noop.
Chris Lattner8d0bacb2004-02-22 05:25:17 +00006565 if (GEP.getNumOperands() == 1)
Chris Lattner5f667a62004-05-07 22:09:22 +00006566 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner8d0bacb2004-02-22 05:25:17 +00006567
Chris Lattner81a7a232004-10-16 18:11:37 +00006568 if (isa<UndefValue>(GEP.getOperand(0)))
6569 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
6570
Chris Lattner8d0bacb2004-02-22 05:25:17 +00006571 bool HasZeroPointerIndex = false;
6572 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
6573 HasZeroPointerIndex = C->isNullValue();
6574
6575 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner5f667a62004-05-07 22:09:22 +00006576 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner48a44f72002-05-02 17:06:02 +00006577
Chris Lattner69193f92004-04-05 01:30:19 +00006578 // Eliminate unneeded casts for indices.
6579 bool MadeChange = false;
Chris Lattner2b2412d2004-04-07 18:38:20 +00006580 gep_type_iterator GTI = gep_type_begin(GEP);
6581 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI)
6582 if (isa<SequentialType>(*GTI)) {
6583 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
6584 Value *Src = CI->getOperand(0);
6585 const Type *SrcTy = Src->getType();
6586 const Type *DestTy = CI->getType();
6587 if (Src->getType()->isInteger()) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00006588 if (SrcTy->getPrimitiveSizeInBits() ==
6589 DestTy->getPrimitiveSizeInBits()) {
Chris Lattner2b2412d2004-04-07 18:38:20 +00006590 // We can always eliminate a cast from ulong or long to the other.
6591 // We can always eliminate a cast from uint to int or the other on
6592 // 32-bit pointer platforms.
Chris Lattnerd1f46d32005-04-24 06:59:08 +00006593 if (DestTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()){
Chris Lattner2b2412d2004-04-07 18:38:20 +00006594 MadeChange = true;
6595 GEP.setOperand(i, Src);
6596 }
6597 } else if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
6598 SrcTy->getPrimitiveSize() == 4) {
6599 // We can always eliminate a cast from int to [u]long. We can
6600 // eliminate a cast from uint to [u]long iff the target is a 32-bit
6601 // pointer target.
Misha Brukmanb1c93172005-04-21 23:48:37 +00006602 if (SrcTy->isSigned() ||
Chris Lattnerd1f46d32005-04-24 06:59:08 +00006603 SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
Chris Lattner2b2412d2004-04-07 18:38:20 +00006604 MadeChange = true;
6605 GEP.setOperand(i, Src);
6606 }
Chris Lattner69193f92004-04-05 01:30:19 +00006607 }
6608 }
6609 }
Chris Lattner2b2412d2004-04-07 18:38:20 +00006610 // If we are using a wider index than needed for this platform, shrink it
6611 // to what we need. If the incoming value needs a cast instruction,
6612 // insert it. This explicit cast can make subsequent optimizations more
6613 // obvious.
6614 Value *Op = GEP.getOperand(i);
6615 if (Op->getType()->getPrimitiveSize() > TD->getPointerSize())
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00006616 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner44d0b952004-07-20 01:48:15 +00006617 GEP.setOperand(i, ConstantExpr::getCast(C,
6618 TD->getIntPtrType()->getSignedVersion()));
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00006619 MadeChange = true;
6620 } else {
Chris Lattner2b2412d2004-04-07 18:38:20 +00006621 Op = InsertNewInstBefore(new CastInst(Op, TD->getIntPtrType(),
6622 Op->getName()), GEP);
6623 GEP.setOperand(i, Op);
6624 MadeChange = true;
6625 }
Chris Lattner44d0b952004-07-20 01:48:15 +00006626
6627 // If this is a constant idx, make sure to canonicalize it to be a signed
6628 // operand, otherwise CSE and other optimizations are pessimized.
6629 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op)) {
6630 GEP.setOperand(i, ConstantExpr::getCast(CUI,
6631 CUI->getType()->getSignedVersion()));
6632 MadeChange = true;
6633 }
Chris Lattner69193f92004-04-05 01:30:19 +00006634 }
6635 if (MadeChange) return &GEP;
6636
Chris Lattnerae7a0d32002-08-02 19:29:35 +00006637 // Combine Indices - If the source pointer to this getelementptr instruction
6638 // is a getelementptr instruction, combine the indices of the two
6639 // getelementptr instructions into a single instruction.
6640 //
Chris Lattner57c67b02004-03-25 22:59:29 +00006641 std::vector<Value*> SrcGEPOperands;
Chris Lattner0798af32005-01-13 20:14:25 +00006642 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattner57c67b02004-03-25 22:59:29 +00006643 SrcGEPOperands.assign(Src->op_begin(), Src->op_end());
Chris Lattner57c67b02004-03-25 22:59:29 +00006644
6645 if (!SrcGEPOperands.empty()) {
Chris Lattner5f667a62004-05-07 22:09:22 +00006646 // Note that if our source is a gep chain itself that we wait for that
6647 // chain to be resolved before we perform this transformation. This
6648 // avoids us creating a TON of code in some cases.
6649 //
6650 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
6651 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
6652 return 0; // Wait until our source is folded to completion.
6653
Chris Lattnerae7a0d32002-08-02 19:29:35 +00006654 std::vector<Value *> Indices;
Chris Lattner5f667a62004-05-07 22:09:22 +00006655
6656 // Find out whether the last index in the source GEP is a sequential idx.
6657 bool EndsWithSequential = false;
6658 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
6659 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattner8ec5f882004-05-08 22:41:42 +00006660 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00006661
Chris Lattnerae7a0d32002-08-02 19:29:35 +00006662 // Can we combine the two pointer arithmetics offsets?
Chris Lattner5f667a62004-05-07 22:09:22 +00006663 if (EndsWithSequential) {
Chris Lattner235af562003-03-05 22:33:14 +00006664 // Replace: gep (gep %P, long B), long A, ...
6665 // With: T = long A+B; gep %P, T, ...
6666 //
Chris Lattner5f667a62004-05-07 22:09:22 +00006667 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner69193f92004-04-05 01:30:19 +00006668 if (SO1 == Constant::getNullValue(SO1->getType())) {
6669 Sum = GO1;
6670 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
6671 Sum = SO1;
6672 } else {
6673 // If they aren't the same type, convert both to an integer of the
6674 // target's pointer size.
6675 if (SO1->getType() != GO1->getType()) {
6676 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
6677 SO1 = ConstantExpr::getCast(SO1C, GO1->getType());
6678 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
6679 GO1 = ConstantExpr::getCast(GO1C, SO1->getType());
6680 } else {
6681 unsigned PS = TD->getPointerSize();
Chris Lattner69193f92004-04-05 01:30:19 +00006682 if (SO1->getType()->getPrimitiveSize() == PS) {
6683 // Convert GO1 to SO1's type.
6684 GO1 = InsertSignExtendToPtrTy(GO1, SO1->getType(), &GEP, this);
6685
6686 } else if (GO1->getType()->getPrimitiveSize() == PS) {
6687 // Convert SO1 to GO1's type.
6688 SO1 = InsertSignExtendToPtrTy(SO1, GO1->getType(), &GEP, this);
6689 } else {
6690 const Type *PT = TD->getIntPtrType();
6691 SO1 = InsertSignExtendToPtrTy(SO1, PT, &GEP, this);
6692 GO1 = InsertSignExtendToPtrTy(GO1, PT, &GEP, this);
6693 }
6694 }
6695 }
Chris Lattner5f667a62004-05-07 22:09:22 +00006696 if (isa<Constant>(SO1) && isa<Constant>(GO1))
6697 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
6698 else {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00006699 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
6700 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner5f667a62004-05-07 22:09:22 +00006701 }
Chris Lattner69193f92004-04-05 01:30:19 +00006702 }
Chris Lattner5f667a62004-05-07 22:09:22 +00006703
6704 // Recycle the GEP we already have if possible.
6705 if (SrcGEPOperands.size() == 2) {
6706 GEP.setOperand(0, SrcGEPOperands[0]);
6707 GEP.setOperand(1, Sum);
6708 return &GEP;
6709 } else {
6710 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
6711 SrcGEPOperands.end()-1);
6712 Indices.push_back(Sum);
6713 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
6714 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00006715 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner69193f92004-04-05 01:30:19 +00006716 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00006717 SrcGEPOperands.size() != 1) {
Chris Lattnerae7a0d32002-08-02 19:29:35 +00006718 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattner57c67b02004-03-25 22:59:29 +00006719 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
6720 SrcGEPOperands.end());
Chris Lattnerae7a0d32002-08-02 19:29:35 +00006721 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
6722 }
6723
6724 if (!Indices.empty())
Chris Lattner57c67b02004-03-25 22:59:29 +00006725 return new GetElementPtrInst(SrcGEPOperands[0], Indices, GEP.getName());
Chris Lattnerc59af1d2002-08-17 22:21:59 +00006726
Chris Lattner5f667a62004-05-07 22:09:22 +00006727 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattnerc59af1d2002-08-17 22:21:59 +00006728 // GEP of global variable. If all of the indices for this GEP are
6729 // constants, we can promote this to a constexpr instead of an instruction.
6730
6731 // Scan for nonconstants...
6732 std::vector<Constant*> Indices;
6733 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
6734 for (; I != E && isa<Constant>(*I); ++I)
6735 Indices.push_back(cast<Constant>(*I));
6736
6737 if (I == E) { // If they are all constants...
Chris Lattnerf3edc492004-07-18 18:59:44 +00006738 Constant *CE = ConstantExpr::getGetElementPtr(GV, Indices);
Chris Lattnerc59af1d2002-08-17 22:21:59 +00006739
6740 // Replace all uses of the GEP with the new constexpr...
6741 return ReplaceInstUsesWith(GEP, CE);
6742 }
Chris Lattner567b81f2005-09-13 00:40:14 +00006743 } else if (Value *X = isCast(PtrOp)) { // Is the operand a cast?
6744 if (!isa<PointerType>(X->getType())) {
6745 // Not interesting. Source pointer must be a cast from pointer.
6746 } else if (HasZeroPointerIndex) {
6747 // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
6748 // into : GEP [10 x ubyte]* X, long 0, ...
6749 //
6750 // This occurs when the program declares an array extern like "int X[];"
6751 //
6752 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
6753 const PointerType *XTy = cast<PointerType>(X->getType());
6754 if (const ArrayType *XATy =
6755 dyn_cast<ArrayType>(XTy->getElementType()))
6756 if (const ArrayType *CATy =
6757 dyn_cast<ArrayType>(CPTy->getElementType()))
6758 if (CATy->getElementType() == XATy->getElementType()) {
6759 // At this point, we know that the cast source type is a pointer
6760 // to an array of the same type as the destination pointer
6761 // array. Because the array type is never stepped over (there
6762 // is a leading zero) we can fold the cast into this GEP.
6763 GEP.setOperand(0, X);
6764 return &GEP;
6765 }
6766 } else if (GEP.getNumOperands() == 2) {
6767 // Transform things like:
Chris Lattner2a893292005-09-13 18:36:04 +00006768 // %t = getelementptr ubyte* cast ([2 x int]* %str to uint*), uint %V
6769 // into: %t1 = getelementptr [2 x int*]* %str, int 0, uint %V; cast
Chris Lattner567b81f2005-09-13 00:40:14 +00006770 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
6771 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
6772 if (isa<ArrayType>(SrcElTy) &&
6773 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
6774 TD->getTypeSize(ResElTy)) {
6775 Value *V = InsertNewInstBefore(
6776 new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
6777 GEP.getOperand(1), GEP.getName()), GEP);
6778 return new CastInst(V, GEP.getType());
Chris Lattner8d0bacb2004-02-22 05:25:17 +00006779 }
Chris Lattner2a893292005-09-13 18:36:04 +00006780
6781 // Transform things like:
6782 // getelementptr sbyte* cast ([100 x double]* X to sbyte*), int %tmp
6783 // (where tmp = 8*tmp2) into:
6784 // getelementptr [100 x double]* %arr, int 0, int %tmp.2
6785
6786 if (isa<ArrayType>(SrcElTy) &&
6787 (ResElTy == Type::SByteTy || ResElTy == Type::UByteTy)) {
6788 uint64_t ArrayEltSize =
6789 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType());
6790
6791 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
6792 // allow either a mul, shift, or constant here.
6793 Value *NewIdx = 0;
6794 ConstantInt *Scale = 0;
6795 if (ArrayEltSize == 1) {
6796 NewIdx = GEP.getOperand(1);
6797 Scale = ConstantInt::get(NewIdx->getType(), 1);
6798 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Chris Lattnera393e4d2005-09-14 17:32:56 +00006799 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner2a893292005-09-13 18:36:04 +00006800 Scale = CI;
6801 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
6802 if (Inst->getOpcode() == Instruction::Shl &&
6803 isa<ConstantInt>(Inst->getOperand(1))) {
6804 unsigned ShAmt =cast<ConstantUInt>(Inst->getOperand(1))->getValue();
6805 if (Inst->getType()->isSigned())
6806 Scale = ConstantSInt::get(Inst->getType(), 1ULL << ShAmt);
6807 else
6808 Scale = ConstantUInt::get(Inst->getType(), 1ULL << ShAmt);
6809 NewIdx = Inst->getOperand(0);
6810 } else if (Inst->getOpcode() == Instruction::Mul &&
6811 isa<ConstantInt>(Inst->getOperand(1))) {
6812 Scale = cast<ConstantInt>(Inst->getOperand(1));
6813 NewIdx = Inst->getOperand(0);
6814 }
6815 }
6816
6817 // If the index will be to exactly the right offset with the scale taken
6818 // out, perform the transformation.
6819 if (Scale && Scale->getRawValue() % ArrayEltSize == 0) {
6820 if (ConstantSInt *C = dyn_cast<ConstantSInt>(Scale))
6821 Scale = ConstantSInt::get(C->getType(),
Chris Lattnera393e4d2005-09-14 17:32:56 +00006822 (int64_t)C->getRawValue() /
6823 (int64_t)ArrayEltSize);
Chris Lattner2a893292005-09-13 18:36:04 +00006824 else
6825 Scale = ConstantUInt::get(Scale->getType(),
6826 Scale->getRawValue() / ArrayEltSize);
6827 if (Scale->getRawValue() != 1) {
6828 Constant *C = ConstantExpr::getCast(Scale, NewIdx->getType());
6829 Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
6830 NewIdx = InsertNewInstBefore(Sc, GEP);
6831 }
6832
6833 // Insert the new GEP instruction.
6834 Instruction *Idx =
6835 new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
6836 NewIdx, GEP.getName());
6837 Idx = InsertNewInstBefore(Idx, GEP);
6838 return new CastInst(Idx, GEP.getType());
6839 }
6840 }
Chris Lattner8d0bacb2004-02-22 05:25:17 +00006841 }
Chris Lattnerca081252001-12-14 16:52:21 +00006842 }
6843
Chris Lattnerca081252001-12-14 16:52:21 +00006844 return 0;
6845}
6846
Chris Lattner1085bdf2002-11-04 16:18:53 +00006847Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
6848 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
6849 if (AI.isArrayAllocation()) // Check C != 1
6850 if (const ConstantUInt *C = dyn_cast<ConstantUInt>(AI.getArraySize())) {
6851 const Type *NewTy = ArrayType::get(AI.getAllocatedType(), C->getValue());
Chris Lattnera2620ac2002-11-09 00:49:43 +00006852 AllocationInst *New = 0;
Chris Lattner1085bdf2002-11-04 16:18:53 +00006853
6854 // Create and insert the replacement instruction...
6855 if (isa<MallocInst>(AI))
Nate Begeman848622f2005-11-05 09:21:28 +00006856 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00006857 else {
6858 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Nate Begeman848622f2005-11-05 09:21:28 +00006859 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00006860 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00006861
6862 InsertNewInstBefore(New, AI);
Misha Brukmanb1c93172005-04-21 23:48:37 +00006863
Chris Lattner1085bdf2002-11-04 16:18:53 +00006864 // Scan to the end of the allocation instructions, to skip over a block of
6865 // allocas if possible...
6866 //
6867 BasicBlock::iterator It = New;
6868 while (isa<AllocationInst>(*It)) ++It;
6869
6870 // Now that I is pointing to the first non-allocation-inst in the block,
6871 // insert our getelementptr instruction...
6872 //
Chris Lattner809dfac2005-05-04 19:10:26 +00006873 Value *NullIdx = Constant::getNullValue(Type::IntTy);
6874 Value *V = new GetElementPtrInst(New, NullIdx, NullIdx,
6875 New->getName()+".sub", It);
Chris Lattner1085bdf2002-11-04 16:18:53 +00006876
6877 // Now make everything use the getelementptr instead of the original
6878 // allocation.
Chris Lattnerabb77c92004-03-19 06:08:10 +00006879 return ReplaceInstUsesWith(AI, V);
Chris Lattner81a7a232004-10-16 18:11:37 +00006880 } else if (isa<UndefValue>(AI.getArraySize())) {
6881 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner1085bdf2002-11-04 16:18:53 +00006882 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00006883
6884 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
6885 // Note that we only do this for alloca's, because malloc should allocate and
6886 // return a unique pointer, even for a zero byte allocation.
Misha Brukmanb1c93172005-04-21 23:48:37 +00006887 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
Chris Lattner49df6ce2004-07-02 22:55:47 +00006888 TD->getTypeSize(AI.getAllocatedType()) == 0)
Chris Lattnerabb77c92004-03-19 06:08:10 +00006889 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
6890
Chris Lattner1085bdf2002-11-04 16:18:53 +00006891 return 0;
6892}
6893
Chris Lattner8427bff2003-12-07 01:24:23 +00006894Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
6895 Value *Op = FI.getOperand(0);
6896
6897 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
6898 if (CastInst *CI = dyn_cast<CastInst>(Op))
6899 if (isa<PointerType>(CI->getOperand(0)->getType())) {
6900 FI.setOperand(0, CI->getOperand(0));
6901 return &FI;
6902 }
6903
Chris Lattner8ba9ec92004-10-18 02:59:09 +00006904 // free undef -> unreachable.
6905 if (isa<UndefValue>(Op)) {
6906 // Insert a new store to null because we cannot modify the CFG here.
Chris Lattner6ab03f62006-09-28 23:35:22 +00006907 new StoreInst(ConstantBool::getTrue(),
Chris Lattner8ba9ec92004-10-18 02:59:09 +00006908 UndefValue::get(PointerType::get(Type::BoolTy)), &FI);
6909 return EraseInstFromFunction(FI);
6910 }
6911
Chris Lattnerf3a36602004-02-28 04:57:37 +00006912 // If we have 'free null' delete the instruction. This can happen in stl code
6913 // when lots of inlining happens.
Chris Lattner8ba9ec92004-10-18 02:59:09 +00006914 if (isa<ConstantPointerNull>(Op))
Chris Lattner51ea1272004-02-28 05:22:00 +00006915 return EraseInstFromFunction(FI);
Chris Lattnerf3a36602004-02-28 04:57:37 +00006916
Chris Lattner8427bff2003-12-07 01:24:23 +00006917 return 0;
6918}
6919
6920
Chris Lattner72684fe2005-01-31 05:51:45 +00006921/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Chris Lattner35e24772004-07-13 01:49:43 +00006922static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
6923 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00006924 Value *CastOp = CI->getOperand(0);
Chris Lattner35e24772004-07-13 01:49:43 +00006925
6926 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00006927 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Chris Lattner35e24772004-07-13 01:49:43 +00006928 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00006929
Chris Lattnerebca4762006-04-02 05:37:12 +00006930 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
6931 isa<PackedType>(DestPTy)) {
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00006932 // If the source is an array, the code below will not succeed. Check to
6933 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
6934 // constants.
6935 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
6936 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
6937 if (ASrcTy->getNumElements() != 0) {
6938 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
6939 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
6940 SrcTy = cast<PointerType>(CastOp->getType());
6941 SrcPTy = SrcTy->getElementType();
6942 }
6943
Chris Lattnerebca4762006-04-02 05:37:12 +00006944 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
6945 isa<PackedType>(SrcPTy)) &&
Chris Lattnerecfa9b52005-03-29 06:37:47 +00006946 // Do not allow turning this into a load of an integer, which is then
6947 // casted to a pointer, this pessimizes pointer analysis a lot.
6948 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00006949 IC.getTargetData().getTypeSize(SrcPTy) ==
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00006950 IC.getTargetData().getTypeSize(DestPTy)) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00006951
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00006952 // Okay, we are casting from one integer or pointer type to another of
6953 // the same size. Instead of casting the pointer before the load, cast
6954 // the result of the loaded value.
6955 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
6956 CI->getName(),
6957 LI.isVolatile()),LI);
6958 // Now cast the result of the load.
6959 return new CastInst(NewLoad, LI.getType());
6960 }
Chris Lattner35e24772004-07-13 01:49:43 +00006961 }
6962 }
6963 return 0;
6964}
6965
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00006966/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattnere6f13092004-09-19 19:18:10 +00006967/// from this value cannot trap. If it is not obviously safe to load from the
6968/// specified pointer, we do a quick local scan of the basic block containing
6969/// ScanFrom, to determine if the address is already accessed.
6970static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
6971 // If it is an alloca or global variable, it is always safe to load from.
6972 if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
6973
6974 // Otherwise, be a little bit agressive by scanning the local block where we
6975 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00006976 // from/to. If so, the previous load or store would have already trapped,
6977 // so there is no harm doing an extra load (also, CSE will later eliminate
6978 // the load entirely).
Chris Lattnere6f13092004-09-19 19:18:10 +00006979 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
6980
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00006981 while (BBI != E) {
Chris Lattnere6f13092004-09-19 19:18:10 +00006982 --BBI;
6983
6984 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
6985 if (LI->getOperand(0) == V) return true;
6986 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
6987 if (SI->getOperand(1) == V) return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +00006988
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00006989 }
Chris Lattnere6f13092004-09-19 19:18:10 +00006990 return false;
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00006991}
6992
Chris Lattner0f1d8a32003-06-26 05:06:25 +00006993Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
6994 Value *Op = LI.getOperand(0);
Chris Lattner7e8af382004-01-12 04:13:56 +00006995
Chris Lattnera9d84e32005-05-01 04:24:53 +00006996 // load (cast X) --> cast (load X) iff safe
6997 if (CastInst *CI = dyn_cast<CastInst>(Op))
6998 if (Instruction *Res = InstCombineLoadCast(*this, LI))
6999 return Res;
7000
7001 // None of the following transforms are legal for volatile loads.
7002 if (LI.isVolatile()) return 0;
Chris Lattnerb990f7d2005-09-12 22:00:15 +00007003
Chris Lattnerb990f7d2005-09-12 22:00:15 +00007004 if (&LI.getParent()->front() != &LI) {
7005 BasicBlock::iterator BBI = &LI; --BBI;
Chris Lattnere0bfdf12005-09-12 22:21:03 +00007006 // If the instruction immediately before this is a store to the same
7007 // address, do a simple form of store->load forwarding.
Chris Lattnerb990f7d2005-09-12 22:00:15 +00007008 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
7009 if (SI->getOperand(1) == LI.getOperand(0))
7010 return ReplaceInstUsesWith(LI, SI->getOperand(0));
Chris Lattnere0bfdf12005-09-12 22:21:03 +00007011 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
7012 if (LIB->getOperand(0) == LI.getOperand(0))
7013 return ReplaceInstUsesWith(LI, LIB);
Chris Lattnerb990f7d2005-09-12 22:00:15 +00007014 }
Chris Lattnera9d84e32005-05-01 04:24:53 +00007015
7016 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op))
7017 if (isa<ConstantPointerNull>(GEPI->getOperand(0)) ||
7018 isa<UndefValue>(GEPI->getOperand(0))) {
7019 // Insert a new store to null instruction before the load to indicate
7020 // that this code is not reachable. We do this instead of inserting
7021 // an unreachable instruction directly because we cannot modify the
7022 // CFG.
7023 new StoreInst(UndefValue::get(LI.getType()),
7024 Constant::getNullValue(Op->getType()), &LI);
7025 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
7026 }
7027
Chris Lattner81a7a232004-10-16 18:11:37 +00007028 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattnera9d84e32005-05-01 04:24:53 +00007029 // load null/undef -> undef
7030 if ((C->isNullValue() || isa<UndefValue>(C))) {
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007031 // Insert a new store to null instruction before the load to indicate that
7032 // this code is not reachable. We do this instead of inserting an
7033 // unreachable instruction directly because we cannot modify the CFG.
Chris Lattnera9d84e32005-05-01 04:24:53 +00007034 new StoreInst(UndefValue::get(LI.getType()),
7035 Constant::getNullValue(Op->getType()), &LI);
Chris Lattner81a7a232004-10-16 18:11:37 +00007036 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner8ba9ec92004-10-18 02:59:09 +00007037 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00007038
Chris Lattner81a7a232004-10-16 18:11:37 +00007039 // Instcombine load (constant global) into the value loaded.
7040 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
7041 if (GV->isConstant() && !GV->isExternal())
7042 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanb1c93172005-04-21 23:48:37 +00007043
Chris Lattner81a7a232004-10-16 18:11:37 +00007044 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
7045 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
7046 if (CE->getOpcode() == Instruction::GetElementPtr) {
7047 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
7048 if (GV->isConstant() && !GV->isExternal())
Chris Lattner0b011ec2005-09-26 05:28:06 +00007049 if (Constant *V =
7050 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
Chris Lattner81a7a232004-10-16 18:11:37 +00007051 return ReplaceInstUsesWith(LI, V);
Chris Lattnera9d84e32005-05-01 04:24:53 +00007052 if (CE->getOperand(0)->isNullValue()) {
7053 // Insert a new store to null instruction before the load to indicate
7054 // that this code is not reachable. We do this instead of inserting
7055 // an unreachable instruction directly because we cannot modify the
7056 // CFG.
7057 new StoreInst(UndefValue::get(LI.getType()),
7058 Constant::getNullValue(Op->getType()), &LI);
7059 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
7060 }
7061
Chris Lattner81a7a232004-10-16 18:11:37 +00007062 } else if (CE->getOpcode() == Instruction::Cast) {
7063 if (Instruction *Res = InstCombineLoadCast(*this, LI))
7064 return Res;
7065 }
7066 }
Chris Lattnere228ee52004-04-08 20:39:49 +00007067
Chris Lattnera9d84e32005-05-01 04:24:53 +00007068 if (Op->hasOneUse()) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00007069 // Change select and PHI nodes to select values instead of addresses: this
7070 // helps alias analysis out a lot, allows many others simplifications, and
7071 // exposes redundancy in the code.
7072 //
7073 // Note that we cannot do the transformation unless we know that the
7074 // introduced loads cannot trap! Something like this is valid as long as
7075 // the condition is always false: load (select bool %C, int* null, int* %G),
7076 // but it would not be valid if we transformed it to load from null
7077 // unconditionally.
7078 //
7079 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
7080 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattnere6f13092004-09-19 19:18:10 +00007081 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
7082 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00007083 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner42618552004-09-20 10:15:10 +00007084 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00007085 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner42618552004-09-20 10:15:10 +00007086 SI->getOperand(2)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00007087 return new SelectInst(SI->getCondition(), V1, V2);
7088 }
7089
Chris Lattnerbdcf41a2004-09-23 15:46:00 +00007090 // load (select (cond, null, P)) -> load P
7091 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
7092 if (C->isNullValue()) {
7093 LI.setOperand(0, SI->getOperand(2));
7094 return &LI;
7095 }
7096
7097 // load (select (cond, P, null)) -> load P
7098 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
7099 if (C->isNullValue()) {
7100 LI.setOperand(0, SI->getOperand(1));
7101 return &LI;
7102 }
7103
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00007104 } else if (PHINode *PN = dyn_cast<PHINode>(Op)) {
7105 // load (phi (&V1, &V2, &V3)) --> phi(load &V1, load &V2, load &V3)
Chris Lattner42618552004-09-20 10:15:10 +00007106 bool Safe = PN->getParent() == LI.getParent();
7107
7108 // Scan all of the instructions between the PHI and the load to make
7109 // sure there are no instructions that might possibly alter the value
7110 // loaded from the PHI.
7111 if (Safe) {
7112 BasicBlock::iterator I = &LI;
7113 for (--I; !isa<PHINode>(I); --I)
7114 if (isa<StoreInst>(I) || isa<CallInst>(I)) {
7115 Safe = false;
7116 break;
7117 }
7118 }
7119
7120 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e && Safe; ++i)
Chris Lattnere6f13092004-09-19 19:18:10 +00007121 if (!isSafeToLoadUnconditionally(PN->getIncomingValue(i),
Chris Lattner42618552004-09-20 10:15:10 +00007122 PN->getIncomingBlock(i)->getTerminator()))
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00007123 Safe = false;
Chris Lattner42618552004-09-20 10:15:10 +00007124
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00007125 if (Safe) {
7126 // Create the PHI.
7127 PHINode *NewPN = new PHINode(LI.getType(), PN->getName());
7128 InsertNewInstBefore(NewPN, *PN);
7129 std::map<BasicBlock*,Value*> LoadMap; // Don't insert duplicate loads
7130
7131 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
7132 BasicBlock *BB = PN->getIncomingBlock(i);
7133 Value *&TheLoad = LoadMap[BB];
7134 if (TheLoad == 0) {
7135 Value *InVal = PN->getIncomingValue(i);
7136 TheLoad = InsertNewInstBefore(new LoadInst(InVal,
7137 InVal->getName()+".val"),
7138 *BB->getTerminator());
7139 }
7140 NewPN->addIncoming(TheLoad, BB);
7141 }
7142 return ReplaceInstUsesWith(LI, NewPN);
7143 }
7144 }
7145 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00007146 return 0;
7147}
7148
Chris Lattner72684fe2005-01-31 05:51:45 +00007149/// InstCombineStoreToCast - Fold 'store V, (cast P)' -> store (cast V), P'
7150/// when possible.
7151static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
7152 User *CI = cast<User>(SI.getOperand(1));
7153 Value *CastOp = CI->getOperand(0);
7154
7155 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
7156 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
7157 const Type *SrcPTy = SrcTy->getElementType();
7158
7159 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
7160 // If the source is an array, the code below will not succeed. Check to
7161 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
7162 // constants.
7163 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
7164 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
7165 if (ASrcTy->getNumElements() != 0) {
7166 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
7167 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
7168 SrcTy = cast<PointerType>(CastOp->getType());
7169 SrcPTy = SrcTy->getElementType();
7170 }
7171
7172 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00007173 IC.getTargetData().getTypeSize(SrcPTy) ==
Chris Lattner72684fe2005-01-31 05:51:45 +00007174 IC.getTargetData().getTypeSize(DestPTy)) {
7175
7176 // Okay, we are casting from one integer or pointer type to another of
7177 // the same size. Instead of casting the pointer before the store, cast
7178 // the value to be stored.
7179 Value *NewCast;
7180 if (Constant *C = dyn_cast<Constant>(SI.getOperand(0)))
7181 NewCast = ConstantExpr::getCast(C, SrcPTy);
7182 else
7183 NewCast = IC.InsertNewInstBefore(new CastInst(SI.getOperand(0),
7184 SrcPTy,
7185 SI.getOperand(0)->getName()+".c"), SI);
7186
7187 return new StoreInst(NewCast, CastOp);
7188 }
7189 }
7190 }
7191 return 0;
7192}
7193
Chris Lattner31f486c2005-01-31 05:36:43 +00007194Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
7195 Value *Val = SI.getOperand(0);
7196 Value *Ptr = SI.getOperand(1);
7197
7198 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner5997cf92006-02-08 03:25:32 +00007199 EraseInstFromFunction(SI);
Chris Lattner31f486c2005-01-31 05:36:43 +00007200 ++NumCombined;
7201 return 0;
7202 }
7203
Chris Lattner5997cf92006-02-08 03:25:32 +00007204 // Do really simple DSE, to catch cases where there are several consequtive
7205 // stores to the same location, separated by a few arithmetic operations. This
7206 // situation often occurs with bitfield accesses.
7207 BasicBlock::iterator BBI = &SI;
7208 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
7209 --ScanInsts) {
7210 --BBI;
7211
7212 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
7213 // Prev store isn't volatile, and stores to the same location?
7214 if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
7215 ++NumDeadStore;
7216 ++BBI;
7217 EraseInstFromFunction(*PrevSI);
7218 continue;
7219 }
7220 break;
7221 }
7222
Chris Lattnerdab43b22006-05-26 19:19:20 +00007223 // If this is a load, we have to stop. However, if the loaded value is from
7224 // the pointer we're loading and is producing the pointer we're storing,
7225 // then *this* store is dead (X = load P; store X -> P).
7226 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
7227 if (LI == Val && LI->getOperand(0) == Ptr) {
7228 EraseInstFromFunction(SI);
7229 ++NumCombined;
7230 return 0;
7231 }
7232 // Otherwise, this is a load from some other location. Stores before it
7233 // may not be dead.
7234 break;
7235 }
7236
Chris Lattner5997cf92006-02-08 03:25:32 +00007237 // Don't skip over loads or things that can modify memory.
Chris Lattnerdab43b22006-05-26 19:19:20 +00007238 if (BBI->mayWriteToMemory())
Chris Lattner5997cf92006-02-08 03:25:32 +00007239 break;
7240 }
7241
7242
7243 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner31f486c2005-01-31 05:36:43 +00007244
7245 // store X, null -> turns into 'unreachable' in SimplifyCFG
7246 if (isa<ConstantPointerNull>(Ptr)) {
7247 if (!isa<UndefValue>(Val)) {
7248 SI.setOperand(0, UndefValue::get(Val->getType()));
7249 if (Instruction *U = dyn_cast<Instruction>(Val))
7250 WorkList.push_back(U); // Dropped a use.
7251 ++NumCombined;
7252 }
7253 return 0; // Do not modify these!
7254 }
7255
7256 // store undef, Ptr -> noop
7257 if (isa<UndefValue>(Val)) {
Chris Lattner5997cf92006-02-08 03:25:32 +00007258 EraseInstFromFunction(SI);
Chris Lattner31f486c2005-01-31 05:36:43 +00007259 ++NumCombined;
7260 return 0;
7261 }
7262
Chris Lattner72684fe2005-01-31 05:51:45 +00007263 // If the pointer destination is a cast, see if we can fold the cast into the
7264 // source instead.
7265 if (CastInst *CI = dyn_cast<CastInst>(Ptr))
7266 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
7267 return Res;
7268 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
7269 if (CE->getOpcode() == Instruction::Cast)
7270 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
7271 return Res;
7272
Chris Lattner219175c2005-09-12 23:23:25 +00007273
7274 // If this store is the last instruction in the basic block, and if the block
7275 // ends with an unconditional branch, try to move it to the successor block.
Chris Lattner5997cf92006-02-08 03:25:32 +00007276 BBI = &SI; ++BBI;
Chris Lattner219175c2005-09-12 23:23:25 +00007277 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
7278 if (BI->isUnconditional()) {
7279 // Check to see if the successor block has exactly two incoming edges. If
7280 // so, see if the other predecessor contains a store to the same location.
7281 // if so, insert a PHI node (if needed) and move the stores down.
7282 BasicBlock *Dest = BI->getSuccessor(0);
7283
7284 pred_iterator PI = pred_begin(Dest);
7285 BasicBlock *Other = 0;
7286 if (*PI != BI->getParent())
7287 Other = *PI;
7288 ++PI;
7289 if (PI != pred_end(Dest)) {
7290 if (*PI != BI->getParent())
7291 if (Other)
7292 Other = 0;
7293 else
7294 Other = *PI;
7295 if (++PI != pred_end(Dest))
7296 Other = 0;
7297 }
7298 if (Other) { // If only one other pred...
7299 BBI = Other->getTerminator();
7300 // Make sure this other block ends in an unconditional branch and that
7301 // there is an instruction before the branch.
7302 if (isa<BranchInst>(BBI) && cast<BranchInst>(BBI)->isUnconditional() &&
7303 BBI != Other->begin()) {
7304 --BBI;
7305 StoreInst *OtherStore = dyn_cast<StoreInst>(BBI);
7306
7307 // If this instruction is a store to the same location.
7308 if (OtherStore && OtherStore->getOperand(1) == SI.getOperand(1)) {
7309 // Okay, we know we can perform this transformation. Insert a PHI
7310 // node now if we need it.
7311 Value *MergedVal = OtherStore->getOperand(0);
7312 if (MergedVal != SI.getOperand(0)) {
7313 PHINode *PN = new PHINode(MergedVal->getType(), "storemerge");
7314 PN->reserveOperandSpace(2);
7315 PN->addIncoming(SI.getOperand(0), SI.getParent());
7316 PN->addIncoming(OtherStore->getOperand(0), Other);
7317 MergedVal = InsertNewInstBefore(PN, Dest->front());
7318 }
7319
7320 // Advance to a place where it is safe to insert the new store and
7321 // insert it.
7322 BBI = Dest->begin();
7323 while (isa<PHINode>(BBI)) ++BBI;
7324 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
7325 OtherStore->isVolatile()), *BBI);
7326
7327 // Nuke the old stores.
Chris Lattner5997cf92006-02-08 03:25:32 +00007328 EraseInstFromFunction(SI);
7329 EraseInstFromFunction(*OtherStore);
Chris Lattner219175c2005-09-12 23:23:25 +00007330 ++NumCombined;
7331 return 0;
7332 }
7333 }
7334 }
7335 }
7336
Chris Lattner31f486c2005-01-31 05:36:43 +00007337 return 0;
7338}
7339
7340
Chris Lattner9eef8a72003-06-04 04:46:00 +00007341Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
7342 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4fdd96c2005-06-18 17:37:34 +00007343 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00007344 BasicBlock *TrueDest;
7345 BasicBlock *FalseDest;
7346 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
7347 !isa<Constant>(X)) {
7348 // Swap Destinations and condition...
7349 BI.setCondition(X);
7350 BI.setSuccessor(0, FalseDest);
7351 BI.setSuccessor(1, TrueDest);
7352 return &BI;
7353 }
7354
7355 // Cannonicalize setne -> seteq
7356 Instruction::BinaryOps Op; Value *Y;
7357 if (match(&BI, m_Br(m_SetCond(Op, m_Value(X), m_Value(Y)),
7358 TrueDest, FalseDest)))
7359 if ((Op == Instruction::SetNE || Op == Instruction::SetLE ||
7360 Op == Instruction::SetGE) && BI.getCondition()->hasOneUse()) {
7361 SetCondInst *I = cast<SetCondInst>(BI.getCondition());
7362 std::string Name = I->getName(); I->setName("");
7363 Instruction::BinaryOps NewOpcode = SetCondInst::getInverseCondition(Op);
7364 Value *NewSCC = BinaryOperator::create(NewOpcode, X, Y, Name, I);
Chris Lattnere967b342003-06-04 05:10:11 +00007365 // Swap Destinations and condition...
Chris Lattnerd4252a72004-07-30 07:50:03 +00007366 BI.setCondition(NewSCC);
Chris Lattnere967b342003-06-04 05:10:11 +00007367 BI.setSuccessor(0, FalseDest);
7368 BI.setSuccessor(1, TrueDest);
Chris Lattnerd4252a72004-07-30 07:50:03 +00007369 removeFromWorkList(I);
7370 I->getParent()->getInstList().erase(I);
7371 WorkList.push_back(cast<Instruction>(NewSCC));
Chris Lattnere967b342003-06-04 05:10:11 +00007372 return &BI;
7373 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00007374
Chris Lattner9eef8a72003-06-04 04:46:00 +00007375 return 0;
7376}
Chris Lattner1085bdf2002-11-04 16:18:53 +00007377
Chris Lattner4c9c20a2004-07-03 00:26:11 +00007378Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
7379 Value *Cond = SI.getCondition();
7380 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
7381 if (I->getOpcode() == Instruction::Add)
7382 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7383 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
7384 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattner81a7a232004-10-16 18:11:37 +00007385 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner4c9c20a2004-07-03 00:26:11 +00007386 AddRHS));
7387 SI.setOperand(0, I->getOperand(0));
7388 WorkList.push_back(I);
7389 return &SI;
7390 }
7391 }
7392 return 0;
7393}
7394
Chris Lattner6bc98652006-03-05 00:22:33 +00007395/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
7396/// is to leave as a vector operation.
7397static bool CheapToScalarize(Value *V, bool isConstant) {
7398 if (isa<ConstantAggregateZero>(V))
7399 return true;
7400 if (ConstantPacked *C = dyn_cast<ConstantPacked>(V)) {
7401 if (isConstant) return true;
7402 // If all elts are the same, we can extract.
7403 Constant *Op0 = C->getOperand(0);
7404 for (unsigned i = 1; i < C->getNumOperands(); ++i)
7405 if (C->getOperand(i) != Op0)
7406 return false;
7407 return true;
7408 }
7409 Instruction *I = dyn_cast<Instruction>(V);
7410 if (!I) return false;
7411
7412 // Insert element gets simplified to the inserted element or is deleted if
7413 // this is constant idx extract element and its a constant idx insertelt.
7414 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
7415 isa<ConstantInt>(I->getOperand(2)))
7416 return true;
7417 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
7418 return true;
7419 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
7420 if (BO->hasOneUse() &&
7421 (CheapToScalarize(BO->getOperand(0), isConstant) ||
7422 CheapToScalarize(BO->getOperand(1), isConstant)))
7423 return true;
7424
7425 return false;
7426}
7427
Chris Lattner12249be2006-05-25 23:48:38 +00007428/// getShuffleMask - Read and decode a shufflevector mask. It turns undef
7429/// elements into values that are larger than the #elts in the input.
7430static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
7431 unsigned NElts = SVI->getType()->getNumElements();
7432 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
7433 return std::vector<unsigned>(NElts, 0);
7434 if (isa<UndefValue>(SVI->getOperand(2)))
7435 return std::vector<unsigned>(NElts, 2*NElts);
7436
7437 std::vector<unsigned> Result;
7438 const ConstantPacked *CP = cast<ConstantPacked>(SVI->getOperand(2));
7439 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
7440 if (isa<UndefValue>(CP->getOperand(i)))
7441 Result.push_back(NElts*2); // undef -> 8
7442 else
7443 Result.push_back(cast<ConstantUInt>(CP->getOperand(i))->getValue());
7444 return Result;
7445}
7446
Chris Lattner8d1d8d32006-03-31 23:01:56 +00007447/// FindScalarElement - Given a vector and an element number, see if the scalar
7448/// value is already around as a register, for example if it were inserted then
7449/// extracted from the vector.
7450static Value *FindScalarElement(Value *V, unsigned EltNo) {
7451 assert(isa<PackedType>(V->getType()) && "Not looking at a vector?");
7452 const PackedType *PTy = cast<PackedType>(V->getType());
Chris Lattner2d37f922006-04-10 23:06:36 +00007453 unsigned Width = PTy->getNumElements();
7454 if (EltNo >= Width) // Out of range access.
Chris Lattner8d1d8d32006-03-31 23:01:56 +00007455 return UndefValue::get(PTy->getElementType());
7456
7457 if (isa<UndefValue>(V))
7458 return UndefValue::get(PTy->getElementType());
7459 else if (isa<ConstantAggregateZero>(V))
7460 return Constant::getNullValue(PTy->getElementType());
7461 else if (ConstantPacked *CP = dyn_cast<ConstantPacked>(V))
7462 return CP->getOperand(EltNo);
7463 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
7464 // If this is an insert to a variable element, we don't know what it is.
7465 if (!isa<ConstantUInt>(III->getOperand(2))) return 0;
7466 unsigned IIElt = cast<ConstantUInt>(III->getOperand(2))->getValue();
7467
7468 // If this is an insert to the element we are looking for, return the
7469 // inserted value.
7470 if (EltNo == IIElt) return III->getOperand(1);
7471
7472 // Otherwise, the insertelement doesn't modify the value, recurse on its
7473 // vector input.
7474 return FindScalarElement(III->getOperand(0), EltNo);
Chris Lattner2d37f922006-04-10 23:06:36 +00007475 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Chris Lattner12249be2006-05-25 23:48:38 +00007476 unsigned InEl = getShuffleMask(SVI)[EltNo];
7477 if (InEl < Width)
7478 return FindScalarElement(SVI->getOperand(0), InEl);
7479 else if (InEl < Width*2)
7480 return FindScalarElement(SVI->getOperand(1), InEl - Width);
7481 else
7482 return UndefValue::get(PTy->getElementType());
Chris Lattner8d1d8d32006-03-31 23:01:56 +00007483 }
7484
7485 // Otherwise, we don't know.
7486 return 0;
7487}
7488
Robert Bocchinoa8352962006-01-13 22:48:06 +00007489Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Chris Lattner8d1d8d32006-03-31 23:01:56 +00007490
Chris Lattner92346c32006-03-31 18:25:14 +00007491 // If packed val is undef, replace extract with scalar undef.
7492 if (isa<UndefValue>(EI.getOperand(0)))
7493 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
7494
7495 // If packed val is constant 0, replace extract with scalar 0.
7496 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
7497 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
7498
Robert Bocchinoa8352962006-01-13 22:48:06 +00007499 if (ConstantPacked *C = dyn_cast<ConstantPacked>(EI.getOperand(0))) {
7500 // If packed val is constant with uniform operands, replace EI
7501 // with that operand
Chris Lattner6bc98652006-03-05 00:22:33 +00007502 Constant *op0 = C->getOperand(0);
Robert Bocchinoa8352962006-01-13 22:48:06 +00007503 for (unsigned i = 1; i < C->getNumOperands(); ++i)
Chris Lattner6bc98652006-03-05 00:22:33 +00007504 if (C->getOperand(i) != op0) {
7505 op0 = 0;
7506 break;
7507 }
7508 if (op0)
7509 return ReplaceInstUsesWith(EI, op0);
Robert Bocchinoa8352962006-01-13 22:48:06 +00007510 }
Chris Lattner6bc98652006-03-05 00:22:33 +00007511
Chris Lattner8d1d8d32006-03-31 23:01:56 +00007512 // If extracting a specified index from the vector, see if we can recursively
7513 // find a previously computed scalar that was inserted into the vector.
Chris Lattner2d37f922006-04-10 23:06:36 +00007514 if (ConstantUInt *IdxC = dyn_cast<ConstantUInt>(EI.getOperand(1))) {
Chris Lattner8d1d8d32006-03-31 23:01:56 +00007515 if (Value *Elt = FindScalarElement(EI.getOperand(0), IdxC->getValue()))
7516 return ReplaceInstUsesWith(EI, Elt);
Chris Lattner2d37f922006-04-10 23:06:36 +00007517 }
Chris Lattner8d1d8d32006-03-31 23:01:56 +00007518
Chris Lattner83f65782006-05-25 22:53:38 +00007519 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Robert Bocchinoa8352962006-01-13 22:48:06 +00007520 if (I->hasOneUse()) {
7521 // Push extractelement into predecessor operation if legal and
7522 // profitable to do so
7523 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Chris Lattner6bc98652006-03-05 00:22:33 +00007524 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
7525 if (CheapToScalarize(BO, isConstantElt)) {
7526 ExtractElementInst *newEI0 =
7527 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
7528 EI.getName()+".lhs");
7529 ExtractElementInst *newEI1 =
7530 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
7531 EI.getName()+".rhs");
7532 InsertNewInstBefore(newEI0, EI);
7533 InsertNewInstBefore(newEI1, EI);
7534 return BinaryOperator::create(BO->getOpcode(), newEI0, newEI1);
7535 }
7536 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Robert Bocchinoa8352962006-01-13 22:48:06 +00007537 Value *Ptr = InsertCastBefore(I->getOperand(0),
7538 PointerType::get(EI.getType()), EI);
7539 GetElementPtrInst *GEP =
7540 new GetElementPtrInst(Ptr, EI.getOperand(1),
7541 I->getName() + ".gep");
7542 InsertNewInstBefore(GEP, EI);
7543 return new LoadInst(GEP);
Chris Lattner83f65782006-05-25 22:53:38 +00007544 }
7545 }
7546 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
7547 // Extracting the inserted element?
7548 if (IE->getOperand(2) == EI.getOperand(1))
7549 return ReplaceInstUsesWith(EI, IE->getOperand(1));
7550 // If the inserted and extracted elements are constants, they must not
7551 // be the same value, extract from the pre-inserted value instead.
7552 if (isa<Constant>(IE->getOperand(2)) &&
7553 isa<Constant>(EI.getOperand(1))) {
7554 AddUsesToWorkList(EI);
7555 EI.setOperand(0, IE->getOperand(0));
7556 return &EI;
7557 }
7558 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
7559 // If this is extracting an element from a shufflevector, figure out where
7560 // it came from and extract from the appropriate input element instead.
7561 if (ConstantUInt *Elt = dyn_cast<ConstantUInt>(EI.getOperand(1))) {
Chris Lattner12249be2006-05-25 23:48:38 +00007562 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getValue()];
7563 Value *Src;
7564 if (SrcIdx < SVI->getType()->getNumElements())
7565 Src = SVI->getOperand(0);
7566 else if (SrcIdx < SVI->getType()->getNumElements()*2) {
7567 SrcIdx -= SVI->getType()->getNumElements();
7568 Src = SVI->getOperand(1);
7569 } else {
7570 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattner612fa8e2006-03-30 22:02:40 +00007571 }
Chris Lattner12249be2006-05-25 23:48:38 +00007572 return new ExtractElementInst(Src,
7573 ConstantUInt::get(Type::UIntTy, SrcIdx));
Robert Bocchinoa8352962006-01-13 22:48:06 +00007574 }
7575 }
Chris Lattner83f65782006-05-25 22:53:38 +00007576 }
Robert Bocchinoa8352962006-01-13 22:48:06 +00007577 return 0;
7578}
7579
Chris Lattner90951862006-04-16 00:51:47 +00007580/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
7581/// elements from either LHS or RHS, return the shuffle mask and true.
7582/// Otherwise, return false.
7583static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
7584 std::vector<Constant*> &Mask) {
7585 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
7586 "Invalid CollectSingleShuffleElements");
7587 unsigned NumElts = cast<PackedType>(V->getType())->getNumElements();
7588
7589 if (isa<UndefValue>(V)) {
7590 Mask.assign(NumElts, UndefValue::get(Type::UIntTy));
7591 return true;
7592 } else if (V == LHS) {
7593 for (unsigned i = 0; i != NumElts; ++i)
7594 Mask.push_back(ConstantUInt::get(Type::UIntTy, i));
7595 return true;
7596 } else if (V == RHS) {
7597 for (unsigned i = 0; i != NumElts; ++i)
7598 Mask.push_back(ConstantUInt::get(Type::UIntTy, i+NumElts));
7599 return true;
7600 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
7601 // If this is an insert of an extract from some other vector, include it.
7602 Value *VecOp = IEI->getOperand(0);
7603 Value *ScalarOp = IEI->getOperand(1);
7604 Value *IdxOp = IEI->getOperand(2);
7605
Chris Lattnerb6cb64b2006-04-27 21:14:21 +00007606 if (!isa<ConstantInt>(IdxOp))
7607 return false;
7608 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getRawValue();
7609
7610 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
7611 // Okay, we can handle this if the vector we are insertinting into is
7612 // transitively ok.
7613 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
7614 // If so, update the mask to reflect the inserted undef.
7615 Mask[InsertedIdx] = UndefValue::get(Type::UIntTy);
7616 return true;
7617 }
7618 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
7619 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner90951862006-04-16 00:51:47 +00007620 EI->getOperand(0)->getType() == V->getType()) {
7621 unsigned ExtractedIdx =
7622 cast<ConstantInt>(EI->getOperand(1))->getRawValue();
Chris Lattner90951862006-04-16 00:51:47 +00007623
7624 // This must be extracting from either LHS or RHS.
7625 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
7626 // Okay, we can handle this if the vector we are insertinting into is
7627 // transitively ok.
7628 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
7629 // If so, update the mask to reflect the inserted value.
7630 if (EI->getOperand(0) == LHS) {
7631 Mask[InsertedIdx & (NumElts-1)] =
7632 ConstantUInt::get(Type::UIntTy, ExtractedIdx);
7633 } else {
7634 assert(EI->getOperand(0) == RHS);
7635 Mask[InsertedIdx & (NumElts-1)] =
7636 ConstantUInt::get(Type::UIntTy, ExtractedIdx+NumElts);
7637
7638 }
7639 return true;
7640 }
7641 }
7642 }
7643 }
7644 }
7645 // TODO: Handle shufflevector here!
7646
7647 return false;
7648}
7649
7650/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
7651/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
7652/// that computes V and the LHS value of the shuffle.
Chris Lattner39fac442006-04-15 01:39:45 +00007653static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Chris Lattner90951862006-04-16 00:51:47 +00007654 Value *&RHS) {
7655 assert(isa<PackedType>(V->getType()) &&
7656 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattner39fac442006-04-15 01:39:45 +00007657 "Invalid shuffle!");
7658 unsigned NumElts = cast<PackedType>(V->getType())->getNumElements();
7659
7660 if (isa<UndefValue>(V)) {
7661 Mask.assign(NumElts, UndefValue::get(Type::UIntTy));
7662 return V;
7663 } else if (isa<ConstantAggregateZero>(V)) {
7664 Mask.assign(NumElts, ConstantUInt::get(Type::UIntTy, 0));
7665 return V;
7666 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
7667 // If this is an insert of an extract from some other vector, include it.
7668 Value *VecOp = IEI->getOperand(0);
7669 Value *ScalarOp = IEI->getOperand(1);
7670 Value *IdxOp = IEI->getOperand(2);
7671
7672 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
7673 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
7674 EI->getOperand(0)->getType() == V->getType()) {
7675 unsigned ExtractedIdx =
7676 cast<ConstantInt>(EI->getOperand(1))->getRawValue();
7677 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getRawValue();
7678
7679 // Either the extracted from or inserted into vector must be RHSVec,
7680 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner90951862006-04-16 00:51:47 +00007681 if (EI->getOperand(0) == RHS || RHS == 0) {
7682 RHS = EI->getOperand(0);
7683 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
Chris Lattner39fac442006-04-15 01:39:45 +00007684 Mask[InsertedIdx & (NumElts-1)] =
7685 ConstantUInt::get(Type::UIntTy, NumElts+ExtractedIdx);
7686 return V;
7687 }
7688
Chris Lattner90951862006-04-16 00:51:47 +00007689 if (VecOp == RHS) {
7690 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
Chris Lattner39fac442006-04-15 01:39:45 +00007691 // Everything but the extracted element is replaced with the RHS.
7692 for (unsigned i = 0; i != NumElts; ++i) {
7693 if (i != InsertedIdx)
7694 Mask[i] = ConstantUInt::get(Type::UIntTy, NumElts+i);
7695 }
7696 return V;
7697 }
Chris Lattner90951862006-04-16 00:51:47 +00007698
7699 // If this insertelement is a chain that comes from exactly these two
7700 // vectors, return the vector and the effective shuffle.
7701 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
7702 return EI->getOperand(0);
7703
Chris Lattner39fac442006-04-15 01:39:45 +00007704 }
7705 }
7706 }
Chris Lattner90951862006-04-16 00:51:47 +00007707 // TODO: Handle shufflevector here!
Chris Lattner39fac442006-04-15 01:39:45 +00007708
7709 // Otherwise, can't do anything fancy. Return an identity vector.
7710 for (unsigned i = 0; i != NumElts; ++i)
7711 Mask.push_back(ConstantUInt::get(Type::UIntTy, i));
7712 return V;
7713}
7714
7715Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
7716 Value *VecOp = IE.getOperand(0);
7717 Value *ScalarOp = IE.getOperand(1);
7718 Value *IdxOp = IE.getOperand(2);
7719
7720 // If the inserted element was extracted from some other vector, and if the
7721 // indexes are constant, try to turn this into a shufflevector operation.
7722 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
7723 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
7724 EI->getOperand(0)->getType() == IE.getType()) {
7725 unsigned NumVectorElts = IE.getType()->getNumElements();
7726 unsigned ExtractedIdx=cast<ConstantInt>(EI->getOperand(1))->getRawValue();
7727 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getRawValue();
7728
7729 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
7730 return ReplaceInstUsesWith(IE, VecOp);
7731
7732 if (InsertedIdx >= NumVectorElts) // Out of range insert.
7733 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
7734
7735 // If we are extracting a value from a vector, then inserting it right
7736 // back into the same place, just use the input vector.
7737 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
7738 return ReplaceInstUsesWith(IE, VecOp);
7739
7740 // We could theoretically do this for ANY input. However, doing so could
7741 // turn chains of insertelement instructions into a chain of shufflevector
7742 // instructions, and right now we do not merge shufflevectors. As such,
7743 // only do this in a situation where it is clear that there is benefit.
7744 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
7745 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
7746 // the values of VecOp, except then one read from EIOp0.
7747 // Build a new shuffle mask.
7748 std::vector<Constant*> Mask;
7749 if (isa<UndefValue>(VecOp))
7750 Mask.assign(NumVectorElts, UndefValue::get(Type::UIntTy));
7751 else {
7752 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
7753 Mask.assign(NumVectorElts, ConstantUInt::get(Type::UIntTy,
7754 NumVectorElts));
7755 }
7756 Mask[InsertedIdx] = ConstantUInt::get(Type::UIntTy, ExtractedIdx);
7757 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
7758 ConstantPacked::get(Mask));
7759 }
7760
7761 // If this insertelement isn't used by some other insertelement, turn it
7762 // (and any insertelements it points to), into one big shuffle.
7763 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
7764 std::vector<Constant*> Mask;
Chris Lattner90951862006-04-16 00:51:47 +00007765 Value *RHS = 0;
7766 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
7767 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
7768 // We now have a shuffle of LHS, RHS, Mask.
7769 return new ShuffleVectorInst(LHS, RHS, ConstantPacked::get(Mask));
Chris Lattner39fac442006-04-15 01:39:45 +00007770 }
7771 }
7772 }
7773
7774 return 0;
7775}
7776
7777
Chris Lattnerfbb77a42006-04-10 22:45:52 +00007778Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
7779 Value *LHS = SVI.getOperand(0);
7780 Value *RHS = SVI.getOperand(1);
Chris Lattner12249be2006-05-25 23:48:38 +00007781 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnerfbb77a42006-04-10 22:45:52 +00007782
7783 bool MadeChange = false;
7784
Chris Lattner12249be2006-05-25 23:48:38 +00007785 if (isa<UndefValue>(SVI.getOperand(2)))
Chris Lattnerfbb77a42006-04-10 22:45:52 +00007786 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
7787
Chris Lattner39fac442006-04-15 01:39:45 +00007788 // TODO: If we have shuffle(x, undef, mask) and any elements of mask refer to
7789 // the undef, change them to undefs.
7790
Chris Lattner12249be2006-05-25 23:48:38 +00007791 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
7792 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
7793 if (LHS == RHS || isa<UndefValue>(LHS)) {
7794 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnerfbb77a42006-04-10 22:45:52 +00007795 // shuffle(undef,undef,mask) -> undef.
7796 return ReplaceInstUsesWith(SVI, LHS);
7797 }
7798
Chris Lattner12249be2006-05-25 23:48:38 +00007799 // Remap any references to RHS to use LHS.
7800 std::vector<Constant*> Elts;
7801 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner0e477162006-05-26 00:29:06 +00007802 if (Mask[i] >= 2*e)
Chris Lattner12249be2006-05-25 23:48:38 +00007803 Elts.push_back(UndefValue::get(Type::UIntTy));
Chris Lattner0e477162006-05-26 00:29:06 +00007804 else {
7805 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
7806 (Mask[i] < e && isa<UndefValue>(LHS)))
7807 Mask[i] = 2*e; // Turn into undef.
7808 else
7809 Mask[i] &= (e-1); // Force to LHS.
7810 Elts.push_back(ConstantUInt::get(Type::UIntTy, Mask[i]));
7811 }
Chris Lattnerfbb77a42006-04-10 22:45:52 +00007812 }
Chris Lattner12249be2006-05-25 23:48:38 +00007813 SVI.setOperand(0, SVI.getOperand(1));
Chris Lattnerfbb77a42006-04-10 22:45:52 +00007814 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Chris Lattner12249be2006-05-25 23:48:38 +00007815 SVI.setOperand(2, ConstantPacked::get(Elts));
Chris Lattner0e477162006-05-26 00:29:06 +00007816 LHS = SVI.getOperand(0);
7817 RHS = SVI.getOperand(1);
Chris Lattnerfbb77a42006-04-10 22:45:52 +00007818 MadeChange = true;
7819 }
7820
Chris Lattner0e477162006-05-26 00:29:06 +00007821 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner12249be2006-05-25 23:48:38 +00007822 bool isLHSID = true, isRHSID = true;
Chris Lattner34cebe72006-04-16 00:03:56 +00007823
Chris Lattner12249be2006-05-25 23:48:38 +00007824 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
7825 if (Mask[i] >= e*2) continue; // Ignore undef values.
7826 // Is this an identity shuffle of the LHS value?
7827 isLHSID &= (Mask[i] == i);
7828
7829 // Is this an identity shuffle of the RHS value?
7830 isRHSID &= (Mask[i]-e == i);
Chris Lattner34cebe72006-04-16 00:03:56 +00007831 }
Chris Lattnerfbb77a42006-04-10 22:45:52 +00007832
Chris Lattner12249be2006-05-25 23:48:38 +00007833 // Eliminate identity shuffles.
7834 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
7835 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnerfbb77a42006-04-10 22:45:52 +00007836
Chris Lattner0e477162006-05-26 00:29:06 +00007837 // If the LHS is a shufflevector itself, see if we can combine it with this
7838 // one without producing an unusual shuffle. Here we are really conservative:
7839 // we are absolutely afraid of producing a shuffle mask not in the input
7840 // program, because the code gen may not be smart enough to turn a merged
7841 // shuffle into two specific shuffles: it may produce worse code. As such,
7842 // we only merge two shuffles if the result is one of the two input shuffle
7843 // masks. In this case, merging the shuffles just removes one instruction,
7844 // which we know is safe. This is good for things like turning:
7845 // (splat(splat)) -> splat.
7846 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
7847 if (isa<UndefValue>(RHS)) {
7848 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
7849
7850 std::vector<unsigned> NewMask;
7851 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
7852 if (Mask[i] >= 2*e)
7853 NewMask.push_back(2*e);
7854 else
7855 NewMask.push_back(LHSMask[Mask[i]]);
7856
7857 // If the result mask is equal to the src shuffle or this shuffle mask, do
7858 // the replacement.
7859 if (NewMask == LHSMask || NewMask == Mask) {
7860 std::vector<Constant*> Elts;
7861 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
7862 if (NewMask[i] >= e*2) {
7863 Elts.push_back(UndefValue::get(Type::UIntTy));
7864 } else {
7865 Elts.push_back(ConstantUInt::get(Type::UIntTy, NewMask[i]));
7866 }
7867 }
7868 return new ShuffleVectorInst(LHSSVI->getOperand(0),
7869 LHSSVI->getOperand(1),
7870 ConstantPacked::get(Elts));
7871 }
7872 }
7873 }
7874
Chris Lattnerfbb77a42006-04-10 22:45:52 +00007875 return MadeChange ? &SVI : 0;
7876}
7877
7878
Robert Bocchinoa8352962006-01-13 22:48:06 +00007879
Chris Lattner99f48c62002-09-02 04:59:56 +00007880void InstCombiner::removeFromWorkList(Instruction *I) {
7881 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
7882 WorkList.end());
7883}
7884
Chris Lattner39c98bb2004-12-08 23:43:58 +00007885
7886/// TryToSinkInstruction - Try to move the specified instruction from its
7887/// current block into the beginning of DestBlock, which can only happen if it's
7888/// safe to move the instruction past all of the instructions between it and the
7889/// end of its block.
7890static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
7891 assert(I->hasOneUse() && "Invariants didn't hold!");
7892
Chris Lattnerc4f67e62005-10-27 17:13:11 +00007893 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
7894 if (isa<PHINode>(I) || I->mayWriteToMemory()) return false;
Misha Brukmanb1c93172005-04-21 23:48:37 +00007895
Chris Lattner39c98bb2004-12-08 23:43:58 +00007896 // Do not sink alloca instructions out of the entry block.
7897 if (isa<AllocaInst>(I) && I->getParent() == &DestBlock->getParent()->front())
7898 return false;
7899
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00007900 // We can only sink load instructions if there is nothing between the load and
7901 // the end of block that could change the value.
7902 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00007903 for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
7904 Scan != E; ++Scan)
7905 if (Scan->mayWriteToMemory())
7906 return false;
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00007907 }
Chris Lattner39c98bb2004-12-08 23:43:58 +00007908
7909 BasicBlock::iterator InsertPos = DestBlock->begin();
7910 while (isa<PHINode>(InsertPos)) ++InsertPos;
7911
Chris Lattner9f269e42005-08-08 19:11:57 +00007912 I->moveBefore(InsertPos);
Chris Lattner39c98bb2004-12-08 23:43:58 +00007913 ++NumSunkInst;
7914 return true;
7915}
7916
Chris Lattner1443bc52006-05-11 17:11:52 +00007917/// OptimizeConstantExpr - Given a constant expression and target data layout
7918/// information, symbolically evaluation the constant expr to something simpler
7919/// if possible.
7920static Constant *OptimizeConstantExpr(ConstantExpr *CE, const TargetData *TD) {
7921 if (!TD) return CE;
7922
7923 Constant *Ptr = CE->getOperand(0);
7924 if (CE->getOpcode() == Instruction::GetElementPtr && Ptr->isNullValue() &&
7925 cast<PointerType>(Ptr->getType())->getElementType()->isSized()) {
7926 // If this is a constant expr gep that is effectively computing an
7927 // "offsetof", fold it into 'cast int Size to T*' instead of 'gep 0, 0, 12'
7928 bool isFoldableGEP = true;
7929 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
7930 if (!isa<ConstantInt>(CE->getOperand(i)))
7931 isFoldableGEP = false;
7932 if (isFoldableGEP) {
7933 std::vector<Value*> Ops(CE->op_begin()+1, CE->op_end());
7934 uint64_t Offset = TD->getIndexedOffset(Ptr->getType(), Ops);
7935 Constant *C = ConstantUInt::get(Type::ULongTy, Offset);
7936 C = ConstantExpr::getCast(C, TD->getIntPtrType());
7937 return ConstantExpr::getCast(C, CE->getType());
7938 }
7939 }
7940
7941 return CE;
7942}
7943
Chris Lattnera36ee4e2006-05-10 19:00:36 +00007944
7945/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
7946/// all reachable code to the worklist.
7947///
7948/// This has a couple of tricks to make the code faster and more powerful. In
7949/// particular, we constant fold and DCE instructions as we go, to avoid adding
7950/// them to the worklist (this significantly speeds up instcombine on code where
7951/// many instructions are dead or constant). Additionally, if we find a branch
7952/// whose condition is a known constant, we only visit the reachable successors.
7953///
7954static void AddReachableCodeToWorklist(BasicBlock *BB,
7955 std::set<BasicBlock*> &Visited,
Chris Lattner1443bc52006-05-11 17:11:52 +00007956 std::vector<Instruction*> &WorkList,
7957 const TargetData *TD) {
Chris Lattnera36ee4e2006-05-10 19:00:36 +00007958 // We have now visited this block! If we've already been here, bail out.
7959 if (!Visited.insert(BB).second) return;
7960
7961 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
7962 Instruction *Inst = BBI++;
7963
7964 // DCE instruction if trivially dead.
7965 if (isInstructionTriviallyDead(Inst)) {
7966 ++NumDeadInst;
7967 DEBUG(std::cerr << "IC: DCE: " << *Inst);
7968 Inst->eraseFromParent();
7969 continue;
7970 }
7971
7972 // ConstantProp instruction if trivially constant.
7973 if (Constant *C = ConstantFoldInstruction(Inst)) {
Chris Lattner1443bc52006-05-11 17:11:52 +00007974 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
7975 C = OptimizeConstantExpr(CE, TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00007976 DEBUG(std::cerr << "IC: ConstFold to: " << *C << " from: " << *Inst);
7977 Inst->replaceAllUsesWith(C);
7978 ++NumConstProp;
7979 Inst->eraseFromParent();
7980 continue;
7981 }
7982
7983 WorkList.push_back(Inst);
7984 }
7985
7986 // Recursively visit successors. If this is a branch or switch on a constant,
7987 // only visit the reachable successor.
7988 TerminatorInst *TI = BB->getTerminator();
7989 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
7990 if (BI->isConditional() && isa<ConstantBool>(BI->getCondition())) {
7991 bool CondVal = cast<ConstantBool>(BI->getCondition())->getValue();
Chris Lattner1443bc52006-05-11 17:11:52 +00007992 AddReachableCodeToWorklist(BI->getSuccessor(!CondVal), Visited, WorkList,
7993 TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00007994 return;
7995 }
7996 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
7997 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
7998 // See if this is an explicit destination.
7999 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
8000 if (SI->getCaseValue(i) == Cond) {
Chris Lattner1443bc52006-05-11 17:11:52 +00008001 AddReachableCodeToWorklist(SI->getSuccessor(i), Visited, WorkList,TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00008002 return;
8003 }
8004
8005 // Otherwise it is the default destination.
Chris Lattner1443bc52006-05-11 17:11:52 +00008006 AddReachableCodeToWorklist(SI->getSuccessor(0), Visited, WorkList, TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00008007 return;
8008 }
8009 }
8010
8011 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
Chris Lattner1443bc52006-05-11 17:11:52 +00008012 AddReachableCodeToWorklist(TI->getSuccessor(i), Visited, WorkList, TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00008013}
8014
Chris Lattner113f4f42002-06-25 16:13:24 +00008015bool InstCombiner::runOnFunction(Function &F) {
Chris Lattner260ab202002-04-18 17:39:14 +00008016 bool Changed = false;
Chris Lattnerf4ad1652003-11-02 05:57:39 +00008017 TD = &getAnalysis<TargetData>();
Chris Lattnerca081252001-12-14 16:52:21 +00008018
Chris Lattner4ed40f72005-07-07 20:40:38 +00008019 {
Chris Lattnera36ee4e2006-05-10 19:00:36 +00008020 // Do a depth-first traversal of the function, populate the worklist with
8021 // the reachable instructions. Ignore blocks that are not reachable. Keep
8022 // track of which blocks we visit.
Chris Lattner4ed40f72005-07-07 20:40:38 +00008023 std::set<BasicBlock*> Visited;
Chris Lattner1443bc52006-05-11 17:11:52 +00008024 AddReachableCodeToWorklist(F.begin(), Visited, WorkList, TD);
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00008025
Chris Lattner4ed40f72005-07-07 20:40:38 +00008026 // Do a quick scan over the function. If we find any blocks that are
8027 // unreachable, remove any instructions inside of them. This prevents
8028 // the instcombine code from having to deal with some bad special cases.
8029 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
8030 if (!Visited.count(BB)) {
8031 Instruction *Term = BB->getTerminator();
8032 while (Term != BB->begin()) { // Remove instrs bottom-up
8033 BasicBlock::iterator I = Term; --I;
Chris Lattner2d3a7a62004-04-27 15:13:33 +00008034
Chris Lattner4ed40f72005-07-07 20:40:38 +00008035 DEBUG(std::cerr << "IC: DCE: " << *I);
8036 ++NumDeadInst;
8037
8038 if (!I->use_empty())
8039 I->replaceAllUsesWith(UndefValue::get(I->getType()));
8040 I->eraseFromParent();
8041 }
8042 }
8043 }
Chris Lattnerca081252001-12-14 16:52:21 +00008044
8045 while (!WorkList.empty()) {
8046 Instruction *I = WorkList.back(); // Get an instruction from the worklist
8047 WorkList.pop_back();
8048
Chris Lattner1443bc52006-05-11 17:11:52 +00008049 // Check to see if we can DCE the instruction.
Chris Lattner99f48c62002-09-02 04:59:56 +00008050 if (isInstructionTriviallyDead(I)) {
Chris Lattner1443bc52006-05-11 17:11:52 +00008051 // Add operands to the worklist.
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00008052 if (I->getNumOperands() < 4)
Chris Lattner51ea1272004-02-28 05:22:00 +00008053 AddUsesToWorkList(*I);
Chris Lattner99f48c62002-09-02 04:59:56 +00008054 ++NumDeadInst;
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00008055
Chris Lattnercd517ff2005-01-28 19:32:01 +00008056 DEBUG(std::cerr << "IC: DCE: " << *I);
8057
8058 I->eraseFromParent();
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00008059 removeFromWorkList(I);
8060 continue;
8061 }
Chris Lattner99f48c62002-09-02 04:59:56 +00008062
Chris Lattner1443bc52006-05-11 17:11:52 +00008063 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattner99f48c62002-09-02 04:59:56 +00008064 if (Constant *C = ConstantFoldInstruction(I)) {
Chris Lattner1443bc52006-05-11 17:11:52 +00008065 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
8066 C = OptimizeConstantExpr(CE, TD);
Chris Lattnercd517ff2005-01-28 19:32:01 +00008067 DEBUG(std::cerr << "IC: ConstFold to: " << *C << " from: " << *I);
8068
Chris Lattner1443bc52006-05-11 17:11:52 +00008069 // Add operands to the worklist.
Chris Lattner51ea1272004-02-28 05:22:00 +00008070 AddUsesToWorkList(*I);
Chris Lattnerc6509f42002-12-05 22:41:53 +00008071 ReplaceInstUsesWith(*I, C);
8072
Chris Lattner99f48c62002-09-02 04:59:56 +00008073 ++NumConstProp;
Chris Lattnera36ee4e2006-05-10 19:00:36 +00008074 I->eraseFromParent();
Chris Lattner800aaaf2003-10-07 15:17:02 +00008075 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00008076 continue;
Chris Lattner99f48c62002-09-02 04:59:56 +00008077 }
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00008078
Chris Lattner39c98bb2004-12-08 23:43:58 +00008079 // See if we can trivially sink this instruction to a successor basic block.
8080 if (I->hasOneUse()) {
8081 BasicBlock *BB = I->getParent();
8082 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
8083 if (UserParent != BB) {
8084 bool UserIsSuccessor = false;
8085 // See if the user is one of our successors.
8086 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
8087 if (*SI == UserParent) {
8088 UserIsSuccessor = true;
8089 break;
8090 }
8091
8092 // If the user is one of our immediate successors, and if that successor
8093 // only has us as a predecessors (we'd have to split the critical edge
8094 // otherwise), we can keep going.
8095 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
8096 next(pred_begin(UserParent)) == pred_end(UserParent))
8097 // Okay, the CFG is simple enough, try to sink this instruction.
8098 Changed |= TryToSinkInstruction(I, UserParent);
8099 }
8100 }
8101
Chris Lattnerca081252001-12-14 16:52:21 +00008102 // Now that we have an instruction, try combining it to simplify it...
Chris Lattnerae7a0d32002-08-02 19:29:35 +00008103 if (Instruction *Result = visit(*I)) {
Chris Lattner0b18c1d2002-05-10 15:38:35 +00008104 ++NumCombined;
Chris Lattner260ab202002-04-18 17:39:14 +00008105 // Should we replace the old instruction with a new one?
Chris Lattner053c0932002-05-14 15:24:07 +00008106 if (Result != I) {
Chris Lattner7d2a5392004-03-13 23:54:27 +00008107 DEBUG(std::cerr << "IC: Old = " << *I
8108 << " New = " << *Result);
8109
Chris Lattner396dbfe2004-06-09 05:08:07 +00008110 // Everything uses the new instruction now.
8111 I->replaceAllUsesWith(Result);
8112
8113 // Push the new instruction and any users onto the worklist.
8114 WorkList.push_back(Result);
8115 AddUsersToWorkList(*Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00008116
8117 // Move the name to the new instruction first...
8118 std::string OldName = I->getName(); I->setName("");
Chris Lattner950fc782003-10-07 22:58:41 +00008119 Result->setName(OldName);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00008120
8121 // Insert the new instruction into the basic block...
8122 BasicBlock *InstParent = I->getParent();
Chris Lattner7515cab2004-11-14 19:13:23 +00008123 BasicBlock::iterator InsertPos = I;
8124
8125 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
8126 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
8127 ++InsertPos;
8128
8129 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00008130
Chris Lattner63d75af2004-05-01 23:27:23 +00008131 // Make sure that we reprocess all operands now that we reduced their
8132 // use counts.
Chris Lattnerb643a9e2004-05-01 23:19:52 +00008133 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
8134 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
8135 WorkList.push_back(OpI);
8136
Chris Lattner396dbfe2004-06-09 05:08:07 +00008137 // Instructions can end up on the worklist more than once. Make sure
8138 // we do not process an instruction that has been deleted.
8139 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00008140
8141 // Erase the old instruction.
8142 InstParent->getInstList().erase(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00008143 } else {
Chris Lattner7d2a5392004-03-13 23:54:27 +00008144 DEBUG(std::cerr << "IC: MOD = " << *I);
8145
Chris Lattnerae7a0d32002-08-02 19:29:35 +00008146 // If the instruction was modified, it's possible that it is now dead.
8147 // if so, remove it.
Chris Lattner63d75af2004-05-01 23:27:23 +00008148 if (isInstructionTriviallyDead(I)) {
8149 // Make sure we process all operands now that we are reducing their
8150 // use counts.
8151 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
8152 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
8153 WorkList.push_back(OpI);
Misha Brukmanb1c93172005-04-21 23:48:37 +00008154
Chris Lattner63d75af2004-05-01 23:27:23 +00008155 // Instructions may end up in the worklist more than once. Erase all
Robert Bocchinoa8352962006-01-13 22:48:06 +00008156 // occurrences of this instruction.
Chris Lattner99f48c62002-09-02 04:59:56 +00008157 removeFromWorkList(I);
Chris Lattner31f486c2005-01-31 05:36:43 +00008158 I->eraseFromParent();
Chris Lattner396dbfe2004-06-09 05:08:07 +00008159 } else {
8160 WorkList.push_back(Result);
8161 AddUsersToWorkList(*Result);
Chris Lattnerae7a0d32002-08-02 19:29:35 +00008162 }
Chris Lattner053c0932002-05-14 15:24:07 +00008163 }
Chris Lattner260ab202002-04-18 17:39:14 +00008164 Changed = true;
Chris Lattnerca081252001-12-14 16:52:21 +00008165 }
8166 }
8167
Chris Lattner260ab202002-04-18 17:39:14 +00008168 return Changed;
Chris Lattner04805fa2002-02-26 21:46:54 +00008169}
8170
Brian Gaeke38b79e82004-07-27 17:43:21 +00008171FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattner260ab202002-04-18 17:39:14 +00008172 return new InstCombiner();
Chris Lattner04805fa2002-02-26 21:46:54 +00008173}
Brian Gaeke960707c2003-11-11 22:41:34 +00008174